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 `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
93 pub array_constructor: Option<Gc<JsObject>>,
94 /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
95 pub promise_constructor: Option<Gc<JsObject>>,
96 /// Reference cells for globals declared by the script.
97 ///
98 /// A declared global is read with `get_var` (by name) but written with
99 /// `put_var_ref` (through the cell), so the cell is what makes a function
100 /// declaration and its uses agree on one binding.
101 pub globals: BTreeMap<String, Gc<Cell>>,
102 /// Names of the globals that came from a *declaration*, which are
103 /// non-configurable properties of the global object.
104 pub declared: Vec<String>,
105 /// Names among the lexical globals that are `const`.
106 ///
107 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
108 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
109 /// path does not carry, so a store through it would look like a plain `let`. The
110 /// realm records it once, at declaration, and answers for every reader.
111 pub lexical_consts: BTreeSet<String>,
112 /// The error constructors by class name, so a runtime error can throw a real
113 /// `TypeError` instance rather than a look-alike object.
114 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
115 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
116 pub string_proto: Option<Gc<JsObject>>,
117 /// `Number.prototype`.
118 pub number_proto: Option<Gc<JsObject>>,
119 /// `Boolean.prototype`.
120 pub boolean_proto: Option<Gc<JsObject>>,
121 /// `BigInt.prototype`.
122 pub bigint_proto: Option<Gc<JsObject>>,
123 /// `Error.prototype`, the prototype of every error instance.
124 pub error_proto: Gc<JsObject>,
125 /// `Date.prototype`, so the constructor can build an instance in the
126 /// function-call form (`Date()` returns a string) without going through `new`.
127 pub date_proto: Gc<JsObject>,
128 /// `%ThrowTypeError%`, the single frozen thrower behind every restricted property.
129 ///
130 /// §10.2.4 makes it *one* object per realm, and the identity is observable: test262's
131 /// whole `ThrowTypeError/` directory finds it through
132 /// `Object.getOwnPropertyDescriptor(function(){"use strict"; return arguments;}(),
133 /// "callee").get` and then asserts on its `length`, `name`, prototype and frozenness.
134 /// Creating a fresh one per property would make
135 /// `getOwnPropertyDescriptor(Function.prototype, "caller").get ===
136 /// getOwnPropertyDescriptor(Function.prototype, "arguments").get` false.
137 pub throw_type_error: Option<Gc<JsObject>>,
138 /// `%GeneratorPrototype%`, the prototype of every generator object.
139 pub generator_proto: Gc<JsObject>,
140 /// `Promise.prototype`, the prototype of every promise.
141 pub promise_proto: Option<Gc<JsObject>>,
142 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
143 pub async_generator_proto: Option<Gc<JsObject>>,
144 /// `%AsyncIteratorPrototype%`, the prototype of `%AsyncGeneratorPrototype%`.
145 ///
146 /// It carries exactly two methods — `@@asyncIterator` and `@@asyncDispose` — and is the
147 /// object test262 reaches through
148 /// `Object.getPrototypeOf(Object.getPrototypeOf(generator.prototype))`.
149 pub async_iterator_proto: Option<Gc<JsObject>>,
150 /// `Symbol.prototype`.
151 pub symbol_proto: Option<Gc<JsObject>>,
152 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
153 /// `_date_value`.
154 ///
155 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
156 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
157 /// language does not have and `new Error()` listed `_class` beside `message` and
158 /// `stack` — and a caller that copies every own property (which
159 /// `Object.create(null, props)` effectively does) tried to write an internal name and
160 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
161 /// and `JSON.stringify`, while remaining an ordinary traced property.
162 ///
163 /// `RefCell` because interning is memoisation rather than observable state: filling the
164 /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
165 /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
166 /// built while reporting a failure must not require an exclusive borrow.
167 pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
168
169 /// The `Symbol.for` registry: `key -> symbol`.
170 ///
171 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
172 /// symbol every time within one script while a fresh realm starts empty.
173 pub symbol_registry: BTreeMap<String, Value>,
174 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
175 pub regexp_proto: Option<Gc<JsObject>>,
176 /// The `RegExp` constructor.
177 pub regexp_ctor: Option<Gc<JsObject>>,
178 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
179 ///
180 /// The prototype rather than the constructor on purpose: a script that replaces
181 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
182 /// error wrapping, which the `using` test suite checks explicitly.
183 pub suppressed_error_proto: Option<Gc<JsObject>>,
184 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
185 pub disposable_stack_proto: Option<Gc<JsObject>>,
186 /// `Map.prototype`.
187 pub map_proto: Option<Gc<JsObject>>,
188 /// `Set.prototype`.
189 pub set_proto: Option<Gc<JsObject>>,
190 /// Every live `FinalizationRegistry`, held weakly.
191 ///
192 /// The cleanup callback has to run from a *safe point* — a place where script is not
193 /// already executing and no engine borrow is held — and the collector cannot enumerate
194 /// heap objects by type. Registering each registry here gives the drain a list to walk.
195 ///
196 /// The handles are weak on purpose: a registry the script dropped must be collectable,
197 /// and it must not be resurrected merely because the drain knew about it. Entries whose
198 /// target has expired are swept out as the drain walks, so the vector does not grow
199 /// without bound in a program that creates many short-lived registries.
200 pub finalization_registries: Vec<WeakGc<JsObject>>,
201 /// `ArrayBuffer.prototype`.
202 pub array_buffer_proto: Option<Gc<JsObject>>,
203 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
204 pub typed_array_proto: Option<Gc<JsObject>>,
205 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
206 ///
207 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
208 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
209 /// `"Object"` and `r instanceof Int32Array` is false.
210 pub typed_array_protos: Vec<Gc<JsObject>>,
211 /// `DataView.prototype`.
212 pub data_view_proto: Option<Gc<JsObject>>,
213 /// The `AsyncDisposableStack` prototype.
214 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
215 /// `Iterator.prototype`.
216 pub iterator_proto: Option<Gc<JsObject>>,
217 /// The `Iterator` constructor itself.
218 ///
219 /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
220 /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
221 /// place it can live is the realm.
222 pub iterator_ctor: Option<Gc<JsObject>>,
223 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
224 ///
225 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
226 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
227 /// `[object Iterator Helper]`).
228 pub iterator_helper_proto: Option<Gc<JsObject>>,
229 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
230 /// that was not already an `Iterator`.
231 ///
232 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
233 /// untouched and does *not* override `@@toStringTag`, so
234 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
235 pub iterator_wrap_proto: Option<Gc<JsObject>>,
236 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
237 pub generator_function_proto: Option<Gc<JsObject>>,
238 /// `%AsyncFunction.prototype%`.
239 pub async_function_proto: Option<Gc<JsObject>>,
240 /// `%AsyncGeneratorFunction.prototype%`.
241 pub async_generator_function_proto: Option<Gc<JsObject>>,
242 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
243 ///
244 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
245 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
246 /// prototype per iterator made every array iterator's prototype distinct.
247 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
248 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
249 ///
250 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
251 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
252 /// both faster and impossible to break from a script.
253 well_known_symbols: WellKnownSymbols,
254 /// The classes the host registered, and the prototype each one hands its instances.
255 pub host_classes: HostClasses,
256}
257
258/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
259///
260/// One per realm, because a class id is only meaningful within the runtime that handed it
261/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
262/// a host class cannot collide.
263pub struct HostClasses {
264 /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
265 /// `JS_GetOpaque(val, 0)` has to match nothing.
266 next_id: u32,
267 /// What each registered class does.
268 defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
269 /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
270 ///
271 /// A strong reference, so the prototype a host installed outlives every script
272 /// reference to it — which is what `JS_SetClassProto` promises.
273 protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
274}
275
276impl HostClasses {
277 fn new() -> HostClasses {
278 HostClasses {
279 next_id: 1,
280 defs: std::collections::BTreeMap::new(),
281 protos: std::collections::BTreeMap::new(),
282 }
283 }
284
285 /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
286 pub fn register(&mut self, def: ClassDef) -> ClassId {
287 let id = ClassId::from_raw(self.next_id);
288 self.next_id += 1;
289 self.defs.insert(id, std::rc::Rc::new(def));
290 id
291 }
292
293 /// Register `def` under an id the caller already has (`JS_NewClass`).
294 ///
295 /// The C API splits "get an id" from "register a class" because a module may be
296 /// initialised lazily; registering twice under one id replaces the definition, and an
297 /// object created under the old one keeps the old behaviour, since it carries its own
298 /// reference.
299 pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
300 if !id.is_valid() {
301 return false;
302 }
303 // Keep the counter past any id handed out explicitly, so a later `register` cannot
304 // reuse one.
305 self.next_id = self.next_id.max(id.get() + 1);
306 self.defs.insert(id, std::rc::Rc::new(def));
307 true
308 }
309
310 /// What `id` was registered with.
311 pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
312 self.defs.get(&id).cloned()
313 }
314
315 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
316 pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
317 self.protos.insert(id, proto);
318 }
319
320 /// The prototype installed for `id`, if the host installed one.
321 pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
322 self.protos.get(&id).cloned()
323 }
324
325 /// How many classes the host registered.
326 pub fn len(&self) -> usize {
327 self.defs.len()
328 }
329
330 /// Whether no class has been registered.
331 pub fn is_empty(&self) -> bool {
332 self.defs.is_empty()
333 }
334}
335
336impl Default for HostClasses {
337 fn default() -> HostClasses {
338 HostClasses::new()
339 }
340}
341
342/// One binding of the frame that called `eval`, so the eval'd code can read and
343/// write it by name.
344struct EvalBinding {
345 /// The name it was declared with.
346 name: String,
347 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
348 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
349 /// a function that declares `a` must find that `a`.
350 frame: usize,
351 /// Which table of that frame it lives in.
352 slot: EvalSlot,
353 /// The slot index within that table.
354 index: usize,
355}
356
357/// Which table of a frame an [`EvalBinding`] indexes.
358#[derive(Clone, Copy)]
359enum EvalSlot {
360 Arg,
361 Local,
362}
363
364/// One activation record.
365struct Frame {
366 /// The bytecode being run.
367 code: Gc<CompiledCode>,
368 /// The cells this closure captured.
369 env: Gc<ClosureEnv>,
370 /// The `this` binding.
371 this: Value,
372 /// Argument slots, sized to the declared parameter count.
373 args: Vec<Value>,
374 /// How many values the caller actually passed, which is what `arguments.length`
375 /// reports and what `...rest` slices from.
376 passed_count: usize,
377 /// The passed values, **only when they do not fit in [`Self::args`]**.
378 ///
379 /// `args` is sized to the declared parameters, so a call that passes no more than
380 /// that already holds every passed value in its first `passed_count` slots — copying
381 /// them here as well was two writes and a buffer per call, on the hottest path in
382 /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
383 /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
384 /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
385 /// its own copy.
386 ///
387 /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
388 /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
389 /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
390 /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
391 /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
392 /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
393 #[allow(clippy::box_collection)]
394 passed_overflow: Option<Box<Vec<Value>>>,
395 /// Local slots.
396 locals: Vec<Value>,
397 /// Reference cells for this frame's own captured bindings.
398 cells: Vec<Gc<Cell>>,
399 /// The operand stack.
400 stack: Vec<Value>,
401 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
402 local_vars: Option<Gc<LocalVars>>,
403
404 /// Index of the next instruction, not a byte offset.
405 ///
406 /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
407 /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
408 /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
409 /// `Frame`, and `frames.push` copies the whole struct on every call.
410 pc: usize,
411 /// Byte offset of the instruction being executed, which is what a stack trace
412 /// reports. `pc` has already moved past it by the time an instruction runs.
413 ///
414 /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
415 at: usize,
416 /// The callee, so a native builtin can tell which constructor it is.
417 callee: Value,
418 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
419 new_target: Value,
420 /// What this frame costs against [`Interp::stack_limit`], in bytes.
421 ///
422 /// Cached rather than recomputed because it is charged on every call and a call is the
423 /// hottest thing in the interpreter.
424 cost: usize,
425 /// [`Interp::stack_used`] before this frame was pushed.
426 ///
427 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
428 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
429 /// leave the counter wrong. There are eight places that drop frames; one subtraction
430 /// forgotten in any of them would leak budget until the depth limit moved.
431 stack_base: usize,
432 /// Whether this frame's body ended in a `tail_call`.
433 ///
434 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
435 /// with its own frame just like `call` does and only skips storing the result
436 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
437 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
438 /// pushed as usual, and this marker makes its return value the *caller's* return
439 /// value without running the instructions after the call.
440 tail: bool,
441}
442
443impl Frame {
444 /// Read a local slot, taking the frame as `self`.
445 ///
446 /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
447 /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
448 /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
449 /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
450 /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
451 #[inline]
452 fn read_loc(&self, slot: usize) -> Value {
453 let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
454 if cell == -1 {
455 return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
456 }
457 match self.cells.get(cell as usize) {
458 Some(cell) => cell.get(),
459 None => Value::Undefined,
460 }
461 }
462
463 /// [`Self::read_loc`] for an argument slot.
464 #[inline]
465 fn read_arg(&self, slot: usize) -> Value {
466 let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
467 if cell == -1 {
468 return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
469 }
470 match self.cells.get(cell as usize) {
471 Some(cell) => cell.get(),
472 None => Value::Undefined,
473 }
474 }
475
476 /// The values the caller actually passed, which is what `arguments` exposes.
477 ///
478 /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
479 fn passed(&self) -> &[Value] {
480 match &self.passed_overflow {
481 Some(values) => values,
482 None => &self.args[..self.passed_count],
483 }
484 }
485
486 /// The decoded instructions of the function this frame runs.
487 ///
488 /// A method rather than `frame.code.insns` at the call site so that the borrow is
489 /// obviously of the frame — the dispatch loop holds one across a `get`.
490 fn insns(&self) -> &[crate::insn::Insn] {
491 &self.code.insns
492 }
493}
494
495impl js_gc::Trace for Frame {
496 fn trace(&self, tracer: &mut js_gc::Tracer) {
497 self.code.trace(tracer);
498 self.env.trace(tracer);
499 self.this.trace(tracer);
500 for value in &self.args {
501 value.trace(tracer);
502 }
503 for value in self.passed() {
504 value.trace(tracer);
505 }
506 for value in &self.locals {
507 value.trace(tracer);
508 }
509 for cell in &self.cells {
510 cell.trace(tracer);
511 }
512 if let Some(local_vars) = &self.local_vars {
513 tracer.visit(local_vars);
514 }
515 for value in &self.stack {
516 value.trace(tracer);
517 }
518 self.callee.trace(tracer);
519 self.new_target.trace(tracer);
520 }
521}
522
523/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
524/// emitted `if_false` treats as "keep going".
525/// How many finished frames' value buffers are kept for reuse.
526const RECYCLE_SLOTS: usize = 8;
527
528/// The largest buffer worth keeping. See [`Interp::free_values`].
529const RECYCLE_MAX_CAPACITY: usize = 4096;
530
531const RESUME_NEXT: i32 = 0;
532/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
533/// generator fall into its `return_async`.
534const RESUME_RETURN: i32 = 1;
535/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
536/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
537/// must forward the exception into the inner iterator rather than finish.
538const RESUME_THROW: i32 = 2;
539
540/// One microtask.
541///
542/// The queue holds *data* rather than closures because its contents are GC values: a
543/// closure would be invisible to the collector, and a pending reaction is exactly the
544/// kind of thing that must keep its handlers and its promise alive.
545pub enum Job {
546 /// A `then` reaction about to run.
547 Reaction {
548 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
549 handler: Option<Value>,
550 /// The value or reason to call it with.
551 argument: Value,
552 /// Whether the source promise rejected, which decides the pass-through kind.
553 rejected: bool,
554 /// The promise the answer settles.
555 promise: Gc<JsObject>,
556 },
557 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
558 Thenable {
559 /// The `then` that was found on the value.
560 then: Value,
561 /// The thenable itself, which becomes `then`'s `this`.
562 value: Value,
563 /// The promise being resolved.
564 promise: Gc<JsObject>,
565 },
566 /// A pending `import(specifier)`.
567 Import {
568 /// The specifier, already converted to a string.
569 specifier: String,
570 /// The module that asked, which the specifier resolves against.
571 referrer: String,
572 /// The promise `import()` handed back.
573 promise: Gc<JsObject>,
574 },
575 /// An async generator resuming after the value it awaited settled.
576 GeneratorResume {
577 /// The async generator to continue.
578 generator: Gc<JsObject>,
579 /// The promise the pending method returned.
580 promise: Gc<JsObject>,
581 /// Whether this delivers the value or raises the reason.
582 kind: ResumeKind,
583 /// The settled value, or the rejection reason.
584 value: Value,
585 },
586 /// An async function resuming after the value it awaited settled.
587 Resume {
588 /// The body, parked in a coroutine.
589 coroutine: Gc<JsObject>,
590 /// The promise the async function handed its caller.
591 promise: Gc<JsObject>,
592 /// Whether this resumption delivers a value or raises one.
593 kind: ResumeKind,
594 /// The settled value, or the rejection reason.
595 value: Value,
596 },
597}
598
599/// One macro-task: work the event loop owes the script but has not run yet.
600///
601/// The microtask queue ([`Job`]) is different: those run before the host regains control.
602/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
603/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
604/// logic: the engine decides *what* is due, the host decides *how to wait*.
605///
606/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
607/// reference counting even though nothing else references it — the same rule the `HostFn`
608/// documentation states from the other side (a host closure must not hold a `Gc`, so the
609/// `Gc` lives here instead).
610pub enum Task {
611 /// A `setTimeout` that is due at `due_at`.
612 ///
613 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
614 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
615 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
616 /// would give this engine a timer the reference cannot produce, with nothing to
617 /// compare it against.
618 Timer {
619 /// The id `setTimeout` returned, for `clearTimeout`.
620 id: i32,
621 /// What to call when it fires.
622 callback: Value,
623 /// When it becomes runnable, as a monotonic instant.
624 due_at: std::time::Instant,
625 },
626}
627
628/// A descriptor the host has to poll, and which directions have a handler.
629///
630/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
631/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
632/// blocks on it, and the host reports back through [`Interp::fire_fd`].
633#[derive(Debug, Clone, Copy, PartialEq, Eq)]
634pub struct FdInterest {
635 /// The descriptor to watch.
636 pub fd: i32,
637 /// Whether `os.setReadHandler` registered a callback.
638 pub read: bool,
639 /// Whether `os.setWriteHandler` registered a callback.
640 pub write: bool,
641}
642
643/// The callbacks registered for one descriptor, per direction.
644#[derive(Default)]
645pub(crate) struct FdHandlers {
646 /// `os.setReadHandler`'s callback.
647 pub read: Option<Value>,
648 /// `os.setWriteHandler`'s callback.
649 pub write: Option<Value>,
650}
651
652/// The file name `eval` reports, which the reference does not inherit from the caller.
653///
654/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
655/// reference and the names show up in stack traces.
656/// The description of the private symbol a class brand is made from.
657///
658/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
659/// place no script can reach, since no expression can name a private symbol.
660const BRAND_DESCRIPTION: &str = "brand";
661
662/// One validated property lookup.
663///
664/// Covers both own-property hits and prototype hits. The second kind was deliberately left
665/// uncached at first ("a prototype hit depends on more than the object and the name"), and
666/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
667/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
668/// names on every iteration (measured: 100 ns per call over an empty loop).
669pub struct FieldCache {
670 /// The name, so two different properties of one object do not collide.
671 key: PropertyKey,
672 /// Where the value was found, relative to the chain below.
673 index: usize,
674 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
675 level: u8,
676 /// The receiver and every prototype down to (and including) the level that answered,
677 /// each with the length of its property table at the time.
678 ///
679 /// That length is the whole guard, and it is sufficient for the ways the answer can
680 /// change without a lookup: adding or deleting any property moves it, and a
681 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
682 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
683 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
684 /// the one that was cached.
685 ///
686 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
687 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
688 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
689}
690
691/// How many links of a prototype chain a [`FieldCache`] remembers.
692///
693/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
694/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
695/// at three.
696const MAX_CACHED_CHAIN: usize = 3;
697
698/// A remembered global-variable lookup.
699///
700/// A `var` global is an ordinary property of the global object, so reading one walks the
701/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
702/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
703/// fixed by the bytecode, and the slot in the object's table only changes if the global
704/// object is mutated, which the index-and-name check below catches.
705pub struct GlobalCache {
706 /// The global object the lookup was resolved on, weakly.
707 object: js_gc::WeakGc<JsObject>,
708 /// Index of the data property in the global object's table.
709 index: usize,
710}
711
712/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
713const GLOBAL_CACHE_SLOTS: usize = 1024;
714
715/// How many property lookups are remembered.
716///
717/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
718/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
719/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
720/// lookup itself. Making it bigger stops helping: the working set of a real program's
721/// property sites is bounded by its code size.
722const FIELD_CACHE_SLOTS: usize = 4096;
723
724/// How much the heap may grow past the last `out of memory` before saying it again.
725///
726/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
727/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
728/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
729/// because it looks like it works. The reference gets this for free: it fails inside
730/// `js_malloc`, and its printing path happens not to allocate.
731///
732/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
733/// allocating is stopped within a rounding error of the limit) and far above what a
734/// handler needs.
735const OOM_HYSTERESIS: usize = 64 * 1024;
736
737/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
738pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
739
740/// How many instructions run between polls of [`Interp::interrupt`].
741///
742/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
743/// order of magnitude on both implementations — which is what lets a C driver compare its
744/// output byte for byte (see `scripts/m15-capi.sh --embed`).
745pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
746
747/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
748///
749/// Chosen so that the byte budget is what actually decides for every ordinary
750/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
751/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
752/// millions of frames.
753pub const MAX_FRAMES: usize = 200_000;
754
755const EVAL_FILE: &str = "<input>";
756
757/// The file name `std.evalScript` reports.
758const EVAL_SCRIPT_FILE: &str = "<evalScript>";
759
760/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
761///
762/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
763/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
764fn clamp_delay(delay_ms: f64) -> std::time::Duration {
765 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
766 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
767 // non-positive delay mean "due now".
768 if delay_ms.is_nan() || delay_ms <= 0.0 {
769 return std::time::Duration::ZERO;
770 }
771 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
772}
773
774impl js_gc::Trace for Task {
775 fn trace(&self, tracer: &mut js_gc::Tracer) {
776 let Task::Timer { callback, .. } = self;
777 callback.trace(tracer);
778 }
779}
780
781/// What one turn of the event loop did, so the caller cannot spin by accident.
782///
783/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
784/// core until the timer is due. Naming the three cases makes the wait explicit.
785#[derive(Debug, Clone, Copy, PartialEq, Eq)]
786pub enum Turn {
787 /// Something ran. Call again immediately — there may be more ready work.
788 Ran,
789 /// Nothing is runnable, but descriptors are registered: the host must poll
790 /// [`Interp::pending_fds`] for at most this long, then report readiness with
791 /// [`Interp::fire_fd`].
792 ///
793 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
794 /// the failure this project treats as worst — a handler that silently never fires —
795 /// so the two cannot be confused by accident.
796 Poll(std::time::Duration),
797 /// Nothing is runnable yet, but something is pending. Block at most this long, then
798 /// call again.
799 Wait(std::time::Duration),
800 /// Nothing is pending at all: the loop is done.
801 Done,
802}
803
804impl js_gc::Trace for Job {
805 fn trace(&self, tracer: &mut js_gc::Tracer) {
806 match self {
807 Job::Reaction {
808 handler,
809 argument,
810 promise,
811 ..
812 } => {
813 if let Some(handler) = handler {
814 handler.trace(tracer);
815 }
816 argument.trace(tracer);
817 tracer.visit(promise);
818 }
819 Job::Thenable {
820 then,
821 value,
822 promise,
823 } => {
824 then.trace(tracer);
825 value.trace(tracer);
826 tracer.visit(promise);
827 }
828 Job::Resume {
829 coroutine,
830 promise,
831 value,
832 ..
833 } => {
834 tracer.visit(coroutine);
835 tracer.visit(promise);
836 value.trace(tracer);
837 }
838 Job::Import { promise, .. } => tracer.visit(promise),
839 Job::GeneratorResume {
840 generator,
841 promise,
842 value,
843 ..
844 } => {
845 tracer.visit(generator);
846 tracer.visit(promise);
847 value.trace(tracer);
848 }
849 }
850 }
851}
852
853/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
854#[derive(Debug, Clone, Copy, PartialEq, Eq)]
855pub enum ResumeKind {
856 /// The generator was just created and is being run to its first suspension.
857 Start,
858 /// `next(v)`.
859 Next,
860 /// `return(v)`.
861 Return,
862 /// `throw(e)`.
863 Throw,
864}
865
866/// A generator object's saved execution.
867///
868/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
869/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
870/// separately allocated buffers.
871pub struct GeneratorState {
872 /// The detached frame, or `None` once the generator has finished or while it runs.
873 frame: Option<Frame>,
874 /// How far it got.
875 phase: GeneratorPhase,
876 /// Whether the last suspension was an `await` rather than a `yield`.
877 ///
878 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
879 /// value and a magic number, because the emitted code branches on which method
880 /// resumed it, while an `await` simply continues with its value. Getting this wrong
881 /// leaves an extra value on the operand stack that the next instruction then
882 /// consumes — a wrong answer rather than a crash.
883 parked_on_await: bool,
884 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
885 ///
886 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
887 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
888 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
889 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
890 /// delegating. Tracking it as part of the phase, the way the reference splits
891 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
892 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
893 /// exception and never reached `xs.throw`.
894 parked_on_yield_star: bool,
895 /// Pending `next`/`return`/`throw` calls, oldest first.
896 ///
897 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
898 /// called back to back must answer in that order, with the second call's value
899 /// arriving at the *second* `yield`. Running each call straight into the body — which
900 /// is what this engine did before — delivered the last queued value to whichever
901 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
902 /// `a === b ===` the final argument.
903 ///
904 /// The front entry is the one being served; it stays there (with `async_busy` set)
905 /// until its promise settles, because an `await` inside the body is a suspension of
906 /// the *driver*, not the end of the request.
907 requests: std::collections::VecDeque<AsyncRequest>,
908 /// Whether the front request is in flight.
909 async_busy: bool,
910 /// Whether this came from an `async function*`.
911 ///
912 /// A sync generator and an async one share `ObjectKind::Generator`, so without this
913 /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
914 /// `AsyncGeneratorValidate` has to tell them apart
915 /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
916 pub is_async: bool,
917}
918
919/// How one async-generator request ended.
920enum AsyncOutcome {
921 /// The method answered this `{value, done}`.
922 Value(Value),
923 /// The body threw.
924 Error(Value),
925}
926
927/// One queued `next`/`return`/`throw` on an async generator: the reference's
928/// `JSAsyncGeneratorRequest`.
929pub struct AsyncRequest {
930 /// Which method was called.
931 kind: ResumeKind,
932 /// Its argument.
933 value: Value,
934 /// The promise the method answered.
935 promise: Gc<JsObject>,
936}
937
938/// Which of §27.5.3.3's states a generator is in.
939#[derive(Debug, Clone, Copy, PartialEq, Eq)]
940enum GeneratorPhase {
941 /// Created, `initial_yield` reached, body not entered.
942 SuspendedStart,
943 /// Parked at a `yield`.
944 SuspendedYield,
945 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
946 Executing,
947 /// Finished; the frame is gone.
948 Completed,
949}
950
951impl js_gc::Trace for GeneratorState {
952 fn trace(&self, tracer: &mut js_gc::Tracer) {
953 if let Some(frame) = &self.frame {
954 frame.trace(tracer);
955 }
956 for request in &self.requests {
957 request.value.trace(tracer);
958 tracer.visit(&request.promise);
959 }
960 }
961}
962
963/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
964/// them in.
965///
966/// Each is a field rather than a map entry because the runtime reads them on hot paths
967/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
968/// failure — reaching a default here means the builtin did not install, and every
969/// accessor panics rather than silently answering `undefined`.
970///
971/// [`builtins::symbol`]: crate::builtins::symbol
972#[derive(Default)]
973pub struct WellKnownSymbols {
974 /// The symbol values, positionally. Empty until `Symbol` installs.
975 symbols: Vec<Value>,
976}
977
978/// Which well-known symbol a caller wants.
979///
980/// A typed accessor beats passing a name around: a typo is a compile error rather than
981/// an `undefined` key that quietly matches nothing.
982#[derive(Debug, Clone, Copy, PartialEq, Eq)]
983pub enum WellKnown {
984 /// `Symbol.toPrimitive`.
985 ToPrimitive,
986 /// `Symbol.iterator`.
987 Iterator,
988 /// `Symbol.match`.
989 Match,
990 /// `Symbol.matchAll`.
991 MatchAll,
992 /// `Symbol.replace`.
993 Replace,
994 /// `Symbol.search`.
995 Search,
996 /// `Symbol.split`.
997 Split,
998 /// `Symbol.toStringTag`.
999 ToStringTag,
1000 /// `Symbol.isConcatSpreadable`.
1001 IsConcatSpreadable,
1002 /// `Symbol.hasInstance`.
1003 HasInstance,
1004 /// `Symbol.species`.
1005 Species,
1006 /// `Symbol.unscopables`.
1007 Unscopables,
1008 /// `Symbol.asyncIterator`.
1009 AsyncIterator,
1010 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1011 Disposable,
1012 /// `Symbol.asyncDispose` — the awaited form.
1013 AsyncDisposable,
1014}
1015
1016impl WellKnown {
1017 /// The index `Symbol`'s installer creates this symbol at.
1018 fn index(self) -> usize {
1019 match self {
1020 WellKnown::ToPrimitive => 0,
1021 WellKnown::Iterator => 1,
1022 WellKnown::Match => 2,
1023 WellKnown::MatchAll => 3,
1024 WellKnown::Replace => 4,
1025 WellKnown::Search => 5,
1026 WellKnown::Split => 6,
1027 WellKnown::ToStringTag => 7,
1028 WellKnown::IsConcatSpreadable => 8,
1029 WellKnown::HasInstance => 9,
1030 WellKnown::Species => 10,
1031 WellKnown::Unscopables => 11,
1032 WellKnown::AsyncIterator => 12,
1033 WellKnown::Disposable => 13,
1034 WellKnown::AsyncDisposable => 14,
1035 }
1036 }
1037}
1038
1039impl Realm {
1040 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1041 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1042 self.well_known_symbols.symbols = symbols;
1043 }
1044
1045 /// A well-known symbol.
1046 pub fn well_known(&self, which: WellKnown) -> Value {
1047 self.well_known_symbols
1048 .symbols
1049 .get(which.index())
1050 .cloned()
1051 .unwrap_or(Value::Undefined)
1052 }
1053
1054 /// The well-known symbol as a property key.
1055 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1056 match self.well_known(which) {
1057 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1058 // Unreachable once `Symbol` has installed; an empty string key matches
1059 // nothing, which degrades to "the object has no such method".
1060 _ => PropertyKey::from(String::new()),
1061 }
1062 }
1063}
1064
1065/// The interpreter: a realm plus a frame stack.
1066pub struct Interp<'a> {
1067 /// The heap everything is allocated on.
1068 pub heap: &'a Heap,
1069 /// The realm.
1070 pub realm: Realm,
1071 /// Active frames, outermost first.
1072 frames: Vec<Frame>,
1073 /// Value buffers from frames that have finished, reused by the next call.
1074 ///
1075 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1076 /// the locals and the operand stack — and free all four on return. `call:recursion`
1077 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1078 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1079 ///
1080 /// Bounded in both directions: a few buffers per kind, and none larger than
1081 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1082 /// and keeping its buffer would pin that memory for the rest of the run.
1083 free_values: Vec<Vec<Value>>,
1084 /// A strict-mode `eval`'s own variable scope, while its script runs.
1085 ///
1086 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1087 /// become a global. Name lookups still fall through to the realm, which is why
1088 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1089 eval_scope: Option<BTreeMap<String, Value>>,
1090 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1091 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1092 eval_depth: usize,
1093 /// The calling frame's own bindings, which the running `eval` can read and write.
1094 ///
1095 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1096 /// come from the frame, and a write is applied back to the frame (or to the cell
1097 /// the frame captured) when the eval finishes. That is what makes
1098 /// `f("a = 3")` visible to the caller as `a === 3`.
1099 eval_bindings: Vec<EvalBinding>,
1100 /// The calling frame's `arguments`, while an `eval` runs.
1101 ///
1102 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1103 /// own yet still has to see the caller's `arguments`.
1104 eval_arguments: Option<Value>,
1105 /// The `with` objects live at the moment the running `eval` started, innermost first.
1106 ///
1107 /// `None` outside an eval, which is what keeps a finished block's object from
1108 /// shadowing ordinary bytecode reads.
1109 eval_with: Option<Vec<Gc<JsObject>>>,
1110 /// The bindings the running direct `eval` makes visible, as name → cell.
1111 ///
1112 /// Set for the duration of an eval and then restored, but every closure created
1113 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1114 /// `eval("f = () => i")` work after the eval has returned.
1115 active_eval_scope: Option<Gc<EvalScope>>,
1116 /// The frame that called the direct `eval` currently running, if any.
1117 ///
1118 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1119 /// on the global object, which is what keeps
1120 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1121 /// gives each call its own `x`.
1122 eval_caller: Option<Option<usize>>,
1123 /// The caller's `new.target`, while an `eval` runs.
1124 ///
1125 /// The eval'd code is a script with no constructor of its own, so it inherits the
1126 /// one the enclosing function was called with.
1127 eval_new_target: Option<Value>,
1128 /// `new.target` for the frame about to be pushed.
1129 ///
1130 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1131 /// value reaches the frame without threading a parameter through every call site.
1132 ///
1133 /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1134 /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1135 /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1136 /// value was parked for the outer call and never consumed.
1137 pending_new_target: Option<Value>,
1138 /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1139 ///
1140 /// `undefined` outside a `new` call.
1141 active_new_target: Value,
1142 /// Names of the native functions currently executing, outermost first.
1143 ///
1144 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1145 /// trace still names it with `(native)` instead of a position, so the names are
1146 /// tracked separately and stitched into [`Interp::stack_trace`].
1147 ///
1148 /// The third field is how many bytecode frames were live when the native was entered,
1149 /// which is what places it *among* them rather than before all of them. Native
1150 /// functions used to be emitted up front on the grounds that they never re-enter
1151 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1152 /// The natives currently running, innermost last: the function object and the
1153 /// depth it was entered at.
1154 ///
1155 /// The *name* is deliberately not stored. It used to be, read with
1156 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1157 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1158 /// benchmark. A stack trace is built rarely; it can read the name then.
1159 native_frames: Vec<(Gc<JsObject>, usize)>,
1160 /// The native function currently executing, for the ones that have to know *which*
1161 /// function they are — a typed-array constructor reads its element type off itself.
1162 ///
1163 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1164 /// reports whatever the enclosing bytecode frame was called with.
1165 current_native: Option<Gc<JsObject>>,
1166 /// Text written by `print` and friends, in order.
1167 ///
1168 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1169 /// once at the end, which is also when upstream's line buffering becomes
1170 /// visible for the cases compared here.
1171 pub output: String,
1172 /// Where `print` also writes, as it goes. `output` keeps the full log for
1173 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1174 ///
1175 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1176 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1177 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1178 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1179 /// would show a script's output all at once when it finished.
1180 pub output_sink: Option<Box<dyn std::io::Write>>,
1181 /// Where recent property reads found their value.
1182 ///
1183 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1184 /// table remembering *which object* and *which entry of its property table* answered a
1185 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1186 /// can move; the property can become an accessor), which is what makes a stale entry a
1187 /// miss rather than a wrong answer.
1188 ///
1189 /// The object is held weakly: a cache that held it strongly would keep up to
1190 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1191 /// program cannot see and cannot work around.
1192 pub field_cache: Vec<Option<FieldCache>>,
1193 /// Global lookups, by binding slot. See [`GlobalCache`].
1194 global_cache: Vec<Option<GlobalCache>>,
1195 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1196 /// under its limit. See [`Interp::check_memory`].
1197 pub oom_reported_at: usize,
1198 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1199 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1200 ///
1201 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1202 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1203 /// host that wants to stop a runaway script must not have to wait for it to return.
1204 ///
1205 /// Two things this cannot do, both of them differences a host can observe:
1206 ///
1207 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1208 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1209 /// needs a signal that the `catch` machinery does not see, which is a change to
1210 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1211 /// a host that stops the script itself.
1212 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1213 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1214 /// both, so the difference is when the counter hits zero, not whether it will.
1215 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1216 /// Instructions until the next [`Interp::interrupt`] poll.
1217 pub interrupt_counter: u32,
1218 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1219 ///
1220 /// A separate field from [`Interp::uncatchable`] because the two live for different
1221 /// spans. This one is the host's standing request; it survives the start of an
1222 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1223 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1224 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1225 /// cleared it before the script it was set for had a chance to throw.
1226 pub uncatchable_next: bool,
1227 /// Whether the exception now unwinding may be caught by a `catch`.
1228 ///
1229 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1230 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1231 /// a host stopping a runaway loop is not fought by the loop.
1232 ///
1233 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1234 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1235 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1236 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1237 pub uncatchable: bool,
1238 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1239 ///
1240 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1241 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1242 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1243 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1244 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1245 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1246 ///
1247 /// The numbers come out close for the same reason a C frame and a heap frame of this
1248 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1249 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1250 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1251 /// `crates/quickjs-cli/tests/limits.rs`.
1252 pub stack_limit: usize,
1253 /// The most frames that may be live at once, whatever the byte budget says.
1254 ///
1255 /// A second bound for a reason the reference does not have: our frames cost less than
1256 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1257 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1258 /// `--stack-size 1G` from being a memory bomb.
1259 pub max_frames: usize,
1260 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1261 ///
1262 /// Script execution does not return until this has drained, which is what makes
1263 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1264 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1265 /// not a `for`.
1266 pub(crate) jobs: std::collections::VecDeque<Job>,
1267 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1268 ///
1269 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1270 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1271 pub(crate) tasks: Vec<Task>,
1272 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1273 /// barrier'd evaluation started.
1274 ///
1275 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1276 /// lets a REPL report an error from the line it just evaluated without also reporting
1277 /// its own readline loop.
1278 trace_barriers: Vec<usize>,
1279 /// `os.signal` handlers, keyed by signal number.
1280 ///
1281 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1282 /// a handler cannot be freed while it is still registered.
1283 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1284 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1285 ///
1286 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1287 /// that is only reachable from a host closure could be freed while still registered.
1288 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1289 /// The next timer id.
1290 ///
1291 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1292 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1293 next_timer_id: i32,
1294 /// Errors thrown by timer callbacks, already rendered.
1295 ///
1296 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1297 /// that throws has no promise behind it. Both are reported by the host at the end of
1298 /// the loop, but only one is fixed up by a later `.catch`.
1299 timer_errors: Vec<String>,
1300 /// The module registry, keyed by canonical name.
1301 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1302 /// How the host turns a specifier into bytes.
1303 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1304 /// The module the host was asked to run, for `import.meta.main`.
1305 pub main_module_name: Option<String>,
1306 /// Module bodies currently running, innermost last.
1307 ///
1308 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1309 /// this is the only place that knows which module that is.
1310 pub module_stack: Vec<String>,
1311 /// Rejections that no handler has claimed, with the promise they belong to.
1312 ///
1313 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1314 /// reason alone cannot say whether somebody eventually listened.
1315 unhandled: Vec<(Gc<JsObject>, Value)>,
1316}
1317
1318impl<'a> Interp<'a> {
1319 /// Build an interpreter over `heap`, with a fresh realm.
1320 pub fn new(heap: &'a Heap) -> Interp<'a> {
1321 let object_proto = JsObject::ordinary(heap, None);
1322 let function_proto = JsObject::function(
1323 heap,
1324 Some(object_proto.clone()),
1325 Callable::Native {
1326 func: |_, _, _| Ok(Value::Undefined),
1327 own_instance: false,
1328 },
1329 );
1330 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1331 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1332 let mut interp = Interp {
1333 heap,
1334 realm: Realm {
1335 global,
1336 object_proto,
1337 function_proto,
1338 array_proto,
1339 array_constructor: None,
1340 promise_constructor: None,
1341 globals: BTreeMap::new(),
1342 declared: Vec::new(),
1343 lexical_consts: BTreeSet::new(),
1344 errors: BTreeMap::new(),
1345 string_proto: None,
1346 number_proto: None,
1347 boolean_proto: None,
1348 bigint_proto: None,
1349 error_proto: JsObject::ordinary(heap, None),
1350 date_proto: JsObject::ordinary(heap, None),
1351 throw_type_error: None,
1352 generator_proto: JsObject::ordinary(heap, None),
1353 promise_proto: None,
1354 async_generator_proto: None,
1355 async_iterator_proto: None,
1356 symbol_proto: None,
1357 symbol_registry: BTreeMap::new(),
1358 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1359 regexp_proto: None,
1360 regexp_ctor: None,
1361 suppressed_error_proto: None,
1362 disposable_stack_proto: None,
1363 map_proto: None,
1364 set_proto: None,
1365 finalization_registries: Vec::new(),
1366 array_buffer_proto: None,
1367 typed_array_proto: None,
1368 typed_array_protos: Vec::new(),
1369 data_view_proto: None,
1370 async_disposable_stack_proto: None,
1371 iterator_proto: None,
1372 iterator_ctor: None,
1373 iterator_helper_proto: None,
1374 iterator_wrap_proto: None,
1375 generator_function_proto: None,
1376 async_function_proto: None,
1377 async_generator_function_proto: None,
1378 iterator_protos: std::collections::BTreeMap::new(),
1379 well_known_symbols: WellKnownSymbols::default(),
1380 host_classes: HostClasses::new(),
1381 },
1382 frames: Vec::new(),
1383 free_values: Vec::new(),
1384 global_cache: {
1385 let mut cache = Vec::new();
1386 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1387 cache
1388 },
1389 eval_scope: None,
1390 eval_depth: 0,
1391 eval_bindings: Vec::new(),
1392 eval_arguments: None,
1393 eval_with: None,
1394 active_eval_scope: None,
1395 eval_caller: None,
1396 pending_new_target: None,
1397 active_new_target: Value::Undefined,
1398 eval_new_target: None,
1399 native_frames: Vec::new(),
1400 current_native: None,
1401 output: String::new(),
1402 output_sink: None,
1403 field_cache: {
1404 let mut cache = Vec::new();
1405 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1406 cache
1407 },
1408 oom_reported_at: 0,
1409 interrupt: None,
1410 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1411 uncatchable_next: false,
1412 uncatchable: false,
1413 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1414 // absent.
1415 stack_limit: DEFAULT_STACK_SIZE,
1416 max_frames: MAX_FRAMES,
1417 jobs: std::collections::VecDeque::new(),
1418 tasks: Vec::new(),
1419 trace_barriers: Vec::new(),
1420 signal_handlers: std::collections::BTreeMap::new(),
1421 fd_handlers: std::collections::BTreeMap::new(),
1422 next_timer_id: 1,
1423 timer_errors: Vec::new(),
1424 modules: std::collections::BTreeMap::new(),
1425 module_loader: None,
1426 main_module_name: None,
1427 module_stack: Vec::new(),
1428 unhandled: Vec::new(),
1429 };
1430 crate::builtins::install(&mut interp);
1431 interp
1432 }
1433
1434 // -- allocation helpers -------------------------------------------------
1435
1436 /// A new string value.
1437 /// A `BigInt` value from a computed big integer.
1438 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1439 Value::BigInt(Gc::new(self.heap, value))
1440 }
1441
1442 /// A string value from bytes that are already WTF-8, which is how a string with an
1443 /// unpaired surrogate reaches a `Value`.
1444 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1445 Value::string_wtf8(self.heap, text)
1446 }
1447
1448 /// A new string value, from text that is valid UTF-8.
1449 pub fn string(&self, text: impl Into<String>) -> Value {
1450 Value::string(self.heap, text)
1451 }
1452
1453 /// A new ordinary object with the given prototype.
1454 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1455 JsObject::ordinary(self.heap, proto)
1456 }
1457
1458 // -- host classes -------------------------------------------------------
1459
1460 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1461 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1462 self.realm.host_classes.register(def)
1463 }
1464
1465 /// Register `def` under an id the host already holds (`JS_NewClass`).
1466 ///
1467 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1468 /// `JS_NewClass`.
1469 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1470 self.realm.host_classes.define(id, def)
1471 }
1472
1473 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1474 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1475 self.realm.host_classes.set_proto(id, proto);
1476 }
1477
1478 /// The prototype installed for `id`, if any.
1479 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1480 self.realm.host_classes.proto(id)
1481 }
1482
1483 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1484 ///
1485 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1486 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1487 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1488 /// host installed none.
1489 ///
1490 /// Answers `None` for an id that was never registered: the C API would return an
1491 /// exception, and silently making an ordinary object instead would move the failure to
1492 /// the first `JS_GetOpaque` that no longer matches.
1493 pub fn new_host_object(
1494 &mut self,
1495 proto: Option<Gc<JsObject>>,
1496 class_id: ClassId,
1497 ) -> Option<Gc<JsObject>> {
1498 let class = self.realm.host_classes.def(class_id)?;
1499 let proto = proto
1500 .or_else(|| self.realm.host_classes.proto(class_id))
1501 .or_else(|| Some(self.realm.object_proto.clone()));
1502 Some(JsObject::host_object(self.heap, proto, class_id, class))
1503 }
1504
1505 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1506 ///
1507 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1508 /// object, it is an object of another class, or the class never got a payload. A host
1509 /// that has to tell them apart uses [`JsObject::host_class_id`].
1510 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1511 let object = value.as_object()?;
1512 if object.host_class_id()? != class_id {
1513 return None;
1514 }
1515 object.host_opaque()
1516 }
1517
1518 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1519 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1520 match value.as_object() {
1521 Some(object) => object.set_host_opaque(opaque),
1522 None => false,
1523 }
1524 }
1525
1526 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1527 ///
1528 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1529 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1530 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1531 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1532 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1533 /// said `[object Object]` instead of `[object Array Iterator]`.
1534 ///
1535 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1536 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1537 /// its own.
1538 pub fn new_iterator_prototype(
1539 &mut self,
1540 tag: &str,
1541 next: crate::object::NativeFn,
1542 ) -> Gc<JsObject> {
1543 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1544 return existing.clone();
1545 }
1546 let parent = self.realm.iterator_proto.clone();
1547 let proto = self.new_object(parent);
1548 let next = self.new_native("next", 0, next);
1549 proto.define(
1550 "next",
1551 Property::with_attributes(Value::Object(next), true, false),
1552 );
1553 let key = self.realm.well_known_key(WellKnown::Iterator);
1554 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1555 proto.define_key(
1556 &key,
1557 Property::with_attributes(Value::Object(identity), true, false),
1558 );
1559 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1560 let tag_value = self.string(tag);
1561 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1562 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1563 // checks it.
1564 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1565 self.realm
1566 .iterator_protos
1567 .insert(tag.to_string(), proto.clone());
1568 proto
1569 }
1570
1571 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1572 ///
1573 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1574 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1575 /// produced. That is why the two branches are not merged.
1576 pub fn object_own_property_keys(
1577 &mut self,
1578 object: &Gc<JsObject>,
1579 ) -> JsResult<Vec<PropertyKey>> {
1580 if let Some(keys) = self.proxy_own_keys(object)? {
1581 return Ok(keys);
1582 }
1583 // Integer-like keys ascending, then the string keys in insertion order, then the
1584 // symbols — the order every schema that walks an object expects.
1585 let entries = object.property_entries();
1586 let mut numeric: Vec<u32> = Vec::new();
1587 // An integer-indexed exotic object reports its indices as own keys even though they
1588 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1589 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1590 // order). The length is asked per call, so a resizable buffer's view reports the
1591 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1592 if object.typed_array_parts().is_some() {
1593 for index in 0..object.typed_array_length().unwrap_or(0) {
1594 // `u32::try_from` cannot fail for a real length, but the length is a
1595 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1596 // as an array index and one element beyond is not.
1597 match u32::try_from(index) {
1598 Ok(index) => numeric.push(index),
1599 Err(_) => break,
1600 }
1601 }
1602 }
1603 let mut strings: Vec<PropertyKey> = Vec::new();
1604 let mut symbols: Vec<PropertyKey> = Vec::new();
1605 for (key, _) in entries {
1606 match &key {
1607 // A class-private name is never reported by any enumeration: that is the
1608 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1609 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1610 // symbol skip, `Object.assign`) therefore cannot see it.
1611 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1612 PropertyKey::Symbol(_) => symbols.push(key),
1613 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1614 Some(index) => {
1615 if !numeric.contains(&index) {
1616 numeric.push(index);
1617 }
1618 }
1619 None => strings.push(key),
1620 },
1621 }
1622 }
1623 numeric.sort_unstable();
1624 let mut keys: Vec<PropertyKey> = numeric
1625 .into_iter()
1626 .map(|index| PropertyKey::from(index.to_string()))
1627 .collect();
1628 keys.extend(strings);
1629 keys.extend(symbols);
1630 Ok(keys)
1631 }
1632
1633 /// The state behind a promise object, or `None` when `object` is not one.
1634 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1635 object.with(|data| match &data.kind {
1636 ObjectKind::Promise(state) => Some(state.clone()),
1637 _ => None,
1638 })
1639 }
1640
1641 /// A new pending promise.
1642 pub fn new_promise(&mut self) -> Gc<JsObject> {
1643 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1644 // the one place every promise is built, and a subclass that builds its instances
1645 // somewhere else would be invisible to `instanceof`.
1646 let default = self.realm.promise_proto.clone();
1647 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1648 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1649 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1650 // `prototype` getter therefore still gets a working promise; the alternative is a
1651 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1652 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1653 let promise = JsObject::ordinary(self.heap, proto);
1654 promise.with_mut(|data| {
1655 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1656 crate::object::PromiseState::default(),
1657 )));
1658 });
1659 promise
1660 }
1661
1662 /// Fulfil `promise`, unless it has already settled.
1663 ///
1664 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1665 /// after `reject`, changes nothing.
1666 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1667 let Some(state) = self.promise_state(promise) else {
1668 return;
1669 };
1670 let reactions = {
1671 let mut state = state.borrow_mut();
1672 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1673 return;
1674 }
1675 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1676 std::mem::take(&mut state.reactions)
1677 };
1678 self.queue_reactions(reactions, value, false);
1679 }
1680
1681 /// Reject `promise`, unless it has already settled.
1682 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1683 let Some(state) = self.promise_state(promise) else {
1684 return;
1685 };
1686 let reactions = {
1687 let mut state = state.borrow_mut();
1688 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1689 return;
1690 }
1691 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1692 std::mem::take(&mut state.reactions)
1693 };
1694 // Remember it only when nothing is listening *now*; a `then` registered later
1695 // prunes the entry in `perform_then`.
1696 if reactions.is_empty() {
1697 self.unhandled.push((promise.clone(), reason.clone()));
1698 }
1699 self.queue_reactions(reactions, reason, true);
1700 }
1701
1702 /// Queue one job per reaction.
1703 ///
1704 /// This is what makes `then` asynchronous even on an already-settled promise:
1705 /// `p.then(f); g()` calls `g` first.
1706 fn queue_reactions(
1707 &mut self,
1708 reactions: Vec<crate::object::PromiseReaction>,
1709 argument: Value,
1710 rejected: bool,
1711 ) {
1712 for reaction in reactions {
1713 let handler = if rejected {
1714 reaction.on_rejected.clone()
1715 } else {
1716 reaction.on_fulfilled.clone()
1717 };
1718 self.jobs.push_back(Job::Reaction {
1719 handler,
1720 argument: argument.clone(),
1721 rejected,
1722 promise: reaction.promise,
1723 });
1724 }
1725 }
1726
1727 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1728 /// resolve/reject pair.
1729 ///
1730 /// The pair are callable objects rather than Rust closures, because the script gets
1731 /// them and may stash them for later.
1732 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1733 let promise = self.new_promise();
1734 // Both handlers are built-ins with an empty name and length 1, in
1735 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1736 // off `Object.getOwnPropertyNames`.
1737 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1738 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1739 (promise, Value::Object(resolve), Value::Object(reject))
1740 }
1741
1742 /// §27.2.1.5 `NewPromiseCapability(C)`.
1743 ///
1744 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1745 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1746 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1747 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1748 /// silently ignored argument.
1749 ///
1750 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1751 /// the engine's own executor is exactly what `new_promise_capability` builds.
1752 pub fn new_promise_capability_for(
1753 &mut self,
1754 constructor: &Value,
1755 ) -> JsResult<(Value, Value, Value)> {
1756 let Some(object) = constructor.as_object().cloned() else {
1757 return Err(self.type_error("promise constructor is not a constructor"));
1758 };
1759 if !object.is_constructor() {
1760 return Err(self.type_error("promise constructor is not a constructor"));
1761 }
1762 if self
1763 .realm
1764 .promise_constructor
1765 .as_ref()
1766 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1767 {
1768 let (promise, resolve, reject) = self.new_promise_capability();
1769 return Ok((Value::Object(promise), resolve, reject));
1770 }
1771 let state = self.new_object(Some(self.realm.object_proto.clone()));
1772 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1773 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1774 // which only a *custom* constructor can observe, and none of the combinator tests
1775 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1776 let executor = self.builtin_function(
1777 "",
1778 2,
1779 Callable::CapabilityExecutor {
1780 state: state.clone(),
1781 },
1782 );
1783 let promise = self.construct(
1784 Value::Object(object.clone()),
1785 Value::Object(object),
1786 vec![Value::Object(executor)],
1787 )?;
1788 // The pair is read *after* the constructor returns, so a constructor that never
1789 // called its executor, or called it with non-callables, is the spec's step 11
1790 // `TypeError` — not something the engine can paper over.
1791 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1792 return Err(self.type_error("promise executor never ran"));
1793 };
1794 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1795 return Err(self.type_error("promise executor never ran"));
1796 };
1797 for handler in [&resolve, &reject] {
1798 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1799 return Err(self.type_error("promise capability handler is not callable"));
1800 }
1801 }
1802 Ok((promise, resolve, reject))
1803 }
1804
1805 /// §27.2.3.1 `PromiseResolve(C, x)`.
1806 ///
1807 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1808 /// an `x` that is already a promise of exactly this constructor is handed back
1809 /// unchanged, and anything else gets a fresh capability from `C`.
1810 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1811 if let Value::Object(object) = &value
1812 && self.promise_state(object).is_some()
1813 {
1814 // `x.constructor === C` means "already the right kind", so no capability is
1815 // built — which is observable through a `resolve` that counts its calls.
1816 let x_constructor = self.get_property(object, "constructor")?;
1817 let same = match (
1818 x_constructor.as_ref().and_then(Value::as_object),
1819 constructor.as_object(),
1820 ) {
1821 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1822 _ => false,
1823 };
1824 if same {
1825 return Ok(value);
1826 }
1827 }
1828 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1829 self.call_value(resolve, Value::Undefined, vec![value])?;
1830 Ok(promise)
1831 }
1832
1833 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1834 /// promise, as `{ value: completion }`.
1835 ///
1836 /// The three cases are the reference's, and they differ on purpose:
1837 ///
1838 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1839 /// exception before any promise exists;
1840 /// * a **runtime** error rejects the returned promise;
1841 /// * success resolves it with `{ value }`, where the value is the script's completion
1842 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1843 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1844 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1845 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1846 ///
1847 /// # What this does not do
1848 ///
1849 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1850 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1851 /// the parser and the suspension machinery to accept a suspended top-level script, and
1852 /// is not implemented — such source is a syntax error here. Everything else about the
1853 /// flag is reproduced.
1854 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1855 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1856 // too, and the reference truncates that one at the same place as a runtime failure.
1857 if barrier {
1858 let depth = self.frames.len();
1859 self.trace_barriers.push(depth);
1860 }
1861 // Compiled before the promise exists, so a parse failure propagates as a throw
1862 // instead of being folded into a rejection.
1863 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1864 Ok(compiled) => compiled,
1865 Err(error) => {
1866 if barrier {
1867 self.trace_barriers.pop();
1868 }
1869 return Err(error);
1870 }
1871 };
1872 // An async body answers its own promise, and that promise is what the reference
1873 // hands back — the same object, not a wrapper around it. Its resolution value is
1874 // the `{value}` object the compiled epilogue built.
1875 if compiled.kind.is_async() {
1876 let strict = compiled.strict;
1877 let promise = self.run_eval_script(compiled, strict)?;
1878 if barrier {
1879 self.trace_barriers.pop();
1880 }
1881 return Ok(promise);
1882 }
1883 let (promise, resolve, reject) = self.new_promise_capability();
1884 let strict = compiled.strict;
1885 match self.run_eval_script(compiled, strict) {
1886 Ok(value) => {
1887 // `{ value }` is a plain object, so resolving with it adopts nothing even
1888 // when the completion value is itself a promise.
1889 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1890 self.set_property(&wrapped, "value", value)?;
1891 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1892 }
1893 Err(Signal::Throw(error)) => {
1894 self.call_value(reject, Value::Undefined, vec![error])?;
1895 }
1896 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1897 }
1898 if barrier {
1899 self.trace_barriers.pop();
1900 }
1901 Ok(Value::Object(promise))
1902 }
1903
1904 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1905 ///
1906 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1907 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1908 /// timer table, where the collector already scans it.
1909 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1910 let (promise, resolve, _reject) = self.new_promise_capability();
1911 let resolve = self.new_host_function(
1912 "resolve",
1913 1,
1914 Box::new(
1915 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1916 let value = args.first().cloned().unwrap_or(Value::Undefined);
1917 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1918 },
1919 ),
1920 );
1921 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1922 // timer table is part of what the collector walks.
1923 self.schedule_timer(Value::Object(resolve), delay_ms);
1924 Ok(Value::Object(promise))
1925 }
1926
1927 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1928 /// new promise resolved with it.
1929 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1930 if let Value::Object(object) = &value
1931 && self.promise_state(object).is_some()
1932 {
1933 return Ok(value);
1934 }
1935 let promise = self.new_promise();
1936 self.resolve_promise_with(&promise, value)?;
1937 Ok(Value::Object(promise))
1938 }
1939
1940 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
1941 ///
1942 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
1943 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
1944 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
1945 /// therefore observable — which is exactly what
1946 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
1947 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
1948 /// shortcut.
1949 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
1950 if let Value::Object(object) = &value
1951 && self.promise_state(object).is_some()
1952 {
1953 let constructor = self.get_property(object, "constructor")?;
1954 let same = match (&constructor, &self.realm.promise_constructor) {
1955 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
1956 _ => false,
1957 };
1958 if same {
1959 return Ok(value);
1960 }
1961 }
1962 let promise = self.new_promise();
1963 self.resolve_promise_with(&promise, value)?;
1964 Ok(Value::Object(promise))
1965 }
1966
1967 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1968 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1969 // Resolving a promise with itself is a `TypeError`. The check exists because the
1970 // alternative is a chain of self-reactions that never settles.
1971 if let Value::Object(object) = &value
1972 && object.ptr_eq(promise)
1973 {
1974 // The spec rejects *and* throws, so both the promise and the caller see it.
1975 let thrown = self.type_error("cannot resolve a promise with itself");
1976 let Signal::Throw(error) = thrown.clone() else {
1977 unreachable!("type_error always throws")
1978 };
1979 self.reject_promise(promise, error);
1980 return Err(thrown);
1981 }
1982 let then = match &value {
1983 Value::Object(object) => self.get_property(object, "then")?,
1984 _ => None,
1985 };
1986 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1987 if !callable_then {
1988 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1989 self.fulfill_promise(promise, value);
1990 return Ok(());
1991 }
1992 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1993 // inside `resolve`, so a script cannot make a promise settle synchronously.
1994 self.jobs.push_back(Job::Thenable {
1995 then: then.expect("checked callable"),
1996 value,
1997 promise: promise.clone(),
1998 });
1999 Ok(())
2000 }
2001
2002 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2003 ///
2004 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2005 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2006 ///
2007 /// The property read is **not** short-circuitable even for a real promise: the spec says
2008 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2009 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2010 /// the combinator's loop infinite — the test's iterator never sets `done`.
2011 pub fn invoke_then(
2012 &mut self,
2013 thenable: Value,
2014 on_fulfilled: Value,
2015 on_rejected: Value,
2016 ) -> JsResult<()> {
2017 let then = match &thenable {
2018 Value::Object(object) => self.get_property(object, "then")?,
2019 primitive => {
2020 let boxed = self.object_from(primitive)?;
2021 self.get_property(&boxed, "then")?
2022 }
2023 };
2024 let Some(then) = then else {
2025 return Err(self.type_error("thenable has no then method"));
2026 };
2027 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2028 return Err(self.type_error("then is not a function"));
2029 }
2030 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2031 Ok(())
2032 }
2033
2034 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2035 ///
2036 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2037 /// promise.
2038 pub fn perform_then(
2039 &mut self,
2040 promise: &Gc<JsObject>,
2041 on_fulfilled: Option<Value>,
2042 on_rejected: Option<Value>,
2043 ) -> JsResult<Value> {
2044 let Some(state) = self.promise_state(promise) else {
2045 return Err(self.type_error("not a promise"));
2046 };
2047 // Whether a rejection handler is being attached decides whether a recorded
2048 // rejection stops being unhandled, so it is read before the values are moved.
2049 let has_rejection_handler = on_rejected.is_some();
2050 let derived = self.new_promise();
2051 let reaction = crate::object::PromiseReaction {
2052 on_fulfilled,
2053 on_rejected,
2054 promise: derived.clone(),
2055 };
2056 let settled = {
2057 let mut state = state.borrow_mut();
2058 // A rejection somebody reacts to is no longer unhandled.
2059 state.handled = true;
2060 match &state.status {
2061 crate::object::PromiseStatus::Pending => {
2062 state.reactions.push(reaction.clone());
2063 None
2064 }
2065 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2066 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2067 }
2068 };
2069 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2070 // later, means somebody is listening after all.
2071 if has_rejection_handler {
2072 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2073 }
2074 if let Some((argument, rejected)) = settled {
2075 let handler = if rejected {
2076 reaction.on_rejected
2077 } else {
2078 reaction.on_fulfilled
2079 };
2080 self.jobs.push_back(Job::Reaction {
2081 handler,
2082 argument,
2083 rejected,
2084 promise: reaction.promise,
2085 });
2086 }
2087 Ok(Value::Object(derived))
2088 }
2089
2090 /// The rejections nobody listened to, formatted the way the reference reports them.
2091 ///
2092 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2093 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2094 /// unhandled at the point the queue drains, because a `then` may still be attached
2095 /// before the host acts on it.
2096 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2097 let entries = std::mem::take(&mut self.unhandled);
2098 // Somebody may have attached a handler after the rejection was recorded, so the
2099 // promise is the authority rather than the list.
2100 let still_unhandled: Vec<Value> = entries
2101 .into_iter()
2102 .filter_map(|(promise, reason)| {
2103 let handled = self
2104 .promise_state(&promise)
2105 .map(|state| state.borrow().handled)
2106 .unwrap_or(true);
2107 (!handled).then_some(reason)
2108 })
2109 .collect();
2110 still_unhandled
2111 .into_iter()
2112 .map(|reason| {
2113 let text = self.describe_exception(&reason);
2114 let stack = match &reason {
2115 Value::Object(object) => self
2116 .get_property(object, "stack")
2117 .ok()
2118 .flatten()
2119 .map(|value| value.to_js_string())
2120 // `stack` carries a trailing newline of its own, which would leave
2121 // a blank line between two reported rejections.
2122 .map(|text| text.trim_end().to_string())
2123 .unwrap_or_default(),
2124 _ => String::new(),
2125 };
2126 if stack.is_empty() {
2127 format!("Possibly unhandled promise rejection: {text}")
2128 } else {
2129 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2130 }
2131 })
2132 .collect()
2133 }
2134
2135 /// Run the microtask queue to exhaustion.
2136 ///
2137 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2138 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2139 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2140 ///
2141 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2142 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2143 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2144 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2145 crate::builtins::json::parse_text(self, text, true)
2146 }
2147
2148 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2149 ///
2150 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2151 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2152 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2153 ///
2154 /// The callback is called with **no arguments**. The reference stores only the function
2155 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2156 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2157 /// extra arguments arrive as `undefined`.
2158 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2159 let id = self.next_timer_id;
2160 // Wrap rather than grow: the id reaches the script as an `Int32`.
2161 self.next_timer_id = if self.next_timer_id == i32::MAX {
2162 1
2163 } else {
2164 self.next_timer_id + 1
2165 };
2166 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2167 self.tasks.push(Task::Timer {
2168 id,
2169 callback,
2170 due_at,
2171 });
2172 id
2173 }
2174
2175 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2176 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2177 pub fn cancel_timer(&mut self, id: i32) -> bool {
2178 let before = self.tasks.len();
2179 self.tasks.retain(|task| match task {
2180 Task::Timer { id: task_id, .. } => *task_id != id,
2181 });
2182 self.tasks.len() != before
2183 }
2184
2185 /// How long until the earliest pending timer, or `None` when none is pending.
2186 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2187 let now = std::time::Instant::now();
2188 self.tasks
2189 .iter()
2190 .map(|task| match task {
2191 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2192 })
2193 .min()
2194 }
2195
2196 /// Run one turn of the event loop.
2197 ///
2198 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2199 /// run at most one due timer, then drain again. The blocking belongs to the caller
2200 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2201 /// is how it asks.
2202 ///
2203 /// One timer per turn rather than all of them: a timer callback may schedule another
2204 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2205 /// starve the microtask queue.
2206 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2207 self.drain_jobs()?;
2208 let now = std::time::Instant::now();
2209 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2210 // followed by `setTimeout(g, 1)` must run `g` first.
2211 let due = self
2212 .tasks
2213 .iter()
2214 .enumerate()
2215 .filter(|(_, task)| match task {
2216 Task::Timer { due_at, .. } => *due_at <= now,
2217 })
2218 .min_by_key(|(_, task)| match task {
2219 Task::Timer { due_at, .. } => *due_at,
2220 })
2221 .map(|(index, _)| index);
2222 let Some(index) = due else {
2223 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2224 // descriptor is registered but no timer is closer, so a script that never
2225 // touches the descriptor still gets control back. Without a cap a handler on a
2226 // descriptor that is never ready would block for as long as the host allows.
2227 let timeout = self
2228 .next_timeout()
2229 .unwrap_or(std::time::Duration::from_secs(10))
2230 .min(std::time::Duration::from_secs(10));
2231 if !self.fd_handlers.is_empty() {
2232 // Blocking on a timer while descriptors are registered would starve them,
2233 // and blocking on the descriptors while a timer is due would delay it; the
2234 // host polls with the earlier of the two deadlines, which this timeout is.
2235 return Ok(Turn::Poll(timeout));
2236 }
2237 return Ok(match self.next_timeout() {
2238 Some(wait) => Turn::Wait(wait),
2239 None => Turn::Done,
2240 });
2241 };
2242 let Task::Timer { callback, .. } = self.tasks.remove(index);
2243 let this = Value::Undefined;
2244 // A throwing timer callback must not stop the loop: the reference reports it and
2245 // keeps going, because the alternative is that one bad timer silently stops every
2246 // later one.
2247 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2248 match self.call_value(callback, this, Vec::new()) {
2249 Ok(_) => {}
2250 Err(Signal::Throw(value)) => {
2251 let text = self.describe_exception(&value);
2252 self.timer_errors.push(text);
2253 }
2254 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2255 }
2256 self.drain_jobs()?;
2257 Ok(Turn::Ran)
2258 }
2259
2260 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2261 ///
2262 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2263 /// left is removed — the reference does the same, so a script can rely on
2264 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2265 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2266 let entry = self.fd_handlers.entry(fd).or_default();
2267 if readable {
2268 entry.read = callback;
2269 } else {
2270 entry.write = callback;
2271 }
2272 if entry.read.is_none() && entry.write.is_none() {
2273 self.fd_handlers.remove(&fd);
2274 }
2275 }
2276
2277 /// Register or clear an `os.signal` handler.
2278 ///
2279 /// `None` removes it; the host separately restores the default disposition or sets
2280 /// ignore, because which of those happened is the script's choice (`null` versus
2281 /// `undefined`) and not something this table can express.
2282 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2283 match handler {
2284 Some(handler) => {
2285 self.signal_handlers.insert(signal, handler);
2286 }
2287 None => {
2288 self.signal_handlers.remove(&signal);
2289 }
2290 }
2291 }
2292
2293 /// Run the handler for `signal`, reporting whether one ran.
2294 ///
2295 /// A throwing handler is reported and the loop continues, like a timer's.
2296 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2297 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2298 return Ok(false);
2299 };
2300 match self.call_value(handler, Value::Undefined, Vec::new()) {
2301 Ok(_) => {}
2302 Err(Signal::Throw(value)) => {
2303 let text = self.describe_exception(&value);
2304 self.timer_errors.push(text);
2305 }
2306 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2307 }
2308 self.drain_jobs()?;
2309 Ok(true)
2310 }
2311
2312 /// The descriptors the host has to poll, and in which direction.
2313 ///
2314 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2315 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2316 /// `os_poll` asks for.
2317 pub fn pending_fds(&self) -> Vec<FdInterest> {
2318 self.fd_handlers
2319 .iter()
2320 .map(|(fd, entry)| FdInterest {
2321 fd: *fd,
2322 read: entry.read.is_some(),
2323 write: entry.write.is_some(),
2324 })
2325 .collect()
2326 }
2327
2328 /// Call the handler registered for `fd`, reporting whether one ran.
2329 ///
2330 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2331 /// poll iteration and then restarts the loop, because the handler may have changed the
2332 /// registration list underneath it; doing the same here keeps a handler that
2333 /// unregisters itself from being called with stale state.
2334 ///
2335 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2336 /// every later one, exactly as with timers.
2337 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2338 let Some(entry) = self.fd_handlers.get(&fd) else {
2339 return Ok(false);
2340 };
2341 let callback = if readable {
2342 entry.read.clone()
2343 } else if writable {
2344 entry.write.clone()
2345 } else {
2346 None
2347 };
2348 let Some(callback) = callback else {
2349 return Ok(false);
2350 };
2351 self.drain_jobs()?;
2352 match self.call_value(callback, Value::Undefined, Vec::new()) {
2353 Ok(_) => {}
2354 Err(Signal::Throw(value)) => {
2355 let text = self.describe_exception(&value);
2356 self.timer_errors.push(text);
2357 }
2358 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2359 }
2360 self.drain_jobs()?;
2361 Ok(true)
2362 }
2363
2364 /// Take the errors timer callbacks threw, leaving the list empty.
2365 pub fn take_timer_errors(&mut self) -> Vec<String> {
2366 std::mem::take(&mut self.timer_errors)
2367 }
2368
2369 /// Whether anything is still pending: a microtask or a timer.
2370 pub fn has_pending_work(&self) -> bool {
2371 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2372 }
2373
2374 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2375 pub fn has_pending_timers_or_jobs(&self) -> bool {
2376 !self.jobs.is_empty() || !self.tasks.is_empty()
2377 }
2378
2379 /// Run every queued microtask, including ones queued while draining.
2380 pub fn drain_jobs(&mut self) -> JsResult<()> {
2381 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2382 // would spin forever, so the drain is bounded the way the call stack is.
2383 let mut budget = 1_000_000usize;
2384 while let Some(job) = self.jobs.pop_front() {
2385 if budget == 0 {
2386 return Err(Signal::Throw(
2387 self.make_error("InternalError", "promise job queue did not drain"),
2388 ));
2389 }
2390 budget -= 1;
2391 self.run_job(job)?;
2392 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2393 // engine may run script that the script itself did not ask for. Doing it here
2394 // rather than from a drop hook is what keeps the callback out of arbitrary
2395 // engine bookkeeping — see `builtins::weak`'s header.
2396 crate::builtins::weak::drain_finalizers(self)?;
2397 }
2398 // A script that queued no jobs may still have dropped targets, so the checkpoint
2399 // runs once more after the queue empties.
2400 crate::builtins::weak::drain_finalizers(self)?;
2401 Ok(())
2402 }
2403
2404 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2405 ///
2406 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2407 /// `None` and is swept out here. This is also where the realm learns that a registry
2408 /// died, which is why it is a mutation rather than a read.
2409 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2410 let handles = std::mem::take(&mut self.realm.finalization_registries);
2411 let mut live = Vec::with_capacity(handles.len());
2412 for handle in handles {
2413 let Some(object) = handle.upgrade() else {
2414 continue;
2415 };
2416 let Some(state) = object.finalization_state() else {
2417 continue;
2418 };
2419 live.push((object.clone(), *state));
2420 self.realm.finalization_registries.push(object.downgrade());
2421 }
2422 live
2423 }
2424
2425 /// Run one microtask.
2426 fn run_job(&mut self, job: Job) -> JsResult<()> {
2427 match job {
2428 Job::Reaction {
2429 handler: None,
2430 argument,
2431 rejected,
2432 promise,
2433 } => {
2434 // No handler: the settlement passes straight through to the derived
2435 // promise, which is why `p.catch(f)` ignores fulfilments.
2436 if rejected {
2437 self.reject_promise(&promise, argument);
2438 } else {
2439 self.fulfill_promise(&promise, argument);
2440 }
2441 Ok(())
2442 }
2443 Job::Reaction {
2444 handler: Some(handler),
2445 argument,
2446 promise,
2447 ..
2448 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2449 Ok(answer) => {
2450 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2451 self.reject_promise(&promise, error);
2452 }
2453 Ok(())
2454 }
2455 Err(Signal::Throw(reason)) => {
2456 self.reject_promise(&promise, reason);
2457 Ok(())
2458 }
2459 Err(other) => Err(other),
2460 },
2461 Job::Thenable {
2462 then,
2463 value,
2464 promise,
2465 } => {
2466 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2467 // the value it produces settles `promise`.
2468 // The thenable's `then` gets this promise's own pair, so whatever it
2469 // produces settles `promise`.
2470 let resolve = JsObject::function(
2471 self.heap,
2472 Some(self.realm.function_proto.clone()),
2473 Callable::PromiseResolve(promise.clone()),
2474 );
2475 let reject = JsObject::function(
2476 self.heap,
2477 Some(self.realm.function_proto.clone()),
2478 Callable::PromiseReject(promise.clone()),
2479 );
2480 match self.call_value(
2481 then,
2482 value,
2483 vec![Value::Object(resolve), Value::Object(reject)],
2484 ) {
2485 Ok(_) => Ok(()),
2486 Err(Signal::Throw(reason)) => {
2487 self.reject_promise(&promise, reason);
2488 Ok(())
2489 }
2490 Err(other) => Err(other),
2491 }
2492 }
2493 Job::Resume {
2494 coroutine,
2495 promise,
2496 kind,
2497 value,
2498 } => self.drive_async(&coroutine, &promise, kind, value),
2499 Job::GeneratorResume {
2500 generator,
2501 promise,
2502 kind,
2503 value,
2504 } => self.step_async_generator(&generator, &promise, kind, value),
2505 Job::Import {
2506 specifier,
2507 referrer,
2508 promise,
2509 } => {
2510 self.run_dynamic_import(&specifier, &referrer, &promise);
2511 Ok(())
2512 }
2513 }
2514 }
2515
2516 /// One element of a `Promise` combinator settled.
2517 ///
2518 /// The shared state object holds the result array, the number still outstanding, and
2519 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2520 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2521 /// to settle, only whatever `Sub` said a capability is.
2522 ///
2523 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2524 /// and `any` must ignore every later settlement, and `all` must not report a second
2525 /// rejection after the first.
2526 fn settle_combinator(
2527 &mut self,
2528 state: &Gc<JsObject>,
2529 index: usize,
2530 fulfilled: bool,
2531 value: Value,
2532 ) -> JsResult<()> {
2533 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2534 // Each element settles at most once: a thenable may call `onFulfilled` twice
2535 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2536 // call a no-op. Without it the second call decremented `remaining` again and settled
2537 // `all` with a short values array (`call-resolve-element-items`).
2538 let done = field("done");
2539 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2540 let settled = field("settled").is_some_and(|value| value.to_boolean());
2541 if settled {
2542 return Ok(());
2543 }
2544 if let Some(Value::Object(done)) = &done {
2545 if done
2546 .array_get(index)
2547 .is_some_and(|value| value.to_boolean())
2548 {
2549 return Ok(());
2550 }
2551 done.array_set(self.heap, index, Value::Bool(true));
2552 }
2553 let resolve = field("resolve");
2554 let reject = field("reject");
2555 let keys = field("keys");
2556 let results = field("results").and_then(|value| value.as_object().cloned());
2557 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2558 // promise: the handler is a plain function the constructor chose.
2559 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2560 if let Some(handler) = handler {
2561 interp.call_value(handler, Value::Undefined, vec![value])?;
2562 }
2563 Ok(())
2564 };
2565 match kind {
2566 // `race`: the first settlement wins and stops the rest.
2567 3 => {
2568 state.define_data("settled", Value::Bool(true));
2569 let handler = if fulfilled { resolve } else { reject };
2570 settle_with(self, handler, value)?;
2571 return Ok(());
2572 }
2573 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2574 // the first rejection wins outright.
2575 0 | 4 if !fulfilled => {
2576 state.define_data("settled", Value::Bool(true));
2577 settle_with(self, reject, value)?;
2578 return Ok(());
2579 }
2580 // `any`: the first fulfilment wins.
2581 2 if fulfilled => {
2582 state.define_data("settled", Value::Bool(true));
2583 settle_with(self, resolve, value)?;
2584 return Ok(());
2585 }
2586 _ => {}
2587 }
2588 let Some(results) = &results else {
2589 return Ok(());
2590 };
2591 match kind {
2592 4 => {
2593 results.array_set(self.heap, index, value);
2594 }
2595 0 => {
2596 results.array_set(self.heap, index, value);
2597 }
2598 // `allSettled` (and its keyed twin) never rejects; each slot records what
2599 // happened.
2600 1 | 5 => {
2601 let record = self.new_object(Some(self.realm.object_proto.clone()));
2602 if fulfilled {
2603 record.define_data("status", self.string("fulfilled"));
2604 record.define_data("value", value);
2605 } else {
2606 record.define_data("status", self.string("rejected"));
2607 record.define_data("reason", value);
2608 }
2609 results.array_set(self.heap, index, Value::Object(record));
2610 }
2611 // `any`: a rejection is parked in the errors array and the sweep continues.
2612 2 => {
2613 results.array_set(self.heap, index, value);
2614 }
2615 _ => {}
2616 }
2617 let remaining = field("remaining")
2618 .map(|value| value.to_int32())
2619 .unwrap_or(0);
2620 let left = remaining - 1;
2621 state.define_data("remaining", Value::Int(left));
2622 if left != 0 {
2623 return Ok(());
2624 }
2625 state.define_data("settled", Value::Bool(true));
2626 match kind {
2627 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2628 // The keyed result: an ordinary object with a **null** prototype, holding the
2629 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2630 4 | 5 => {
2631 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2632 settle_with(self, resolve, keyed)?;
2633 }
2634 2 => {
2635 // The rejection is an `AggregateError` whose `errors` is the results array
2636 // itself — the slots are the reasons, in input order.
2637 let errors = results.array_elements().unwrap_or_default();
2638 let error = self.aggregate_error(errors, "all promises were rejected");
2639 settle_with(self, reject, error)?;
2640 }
2641 _ => {}
2642 }
2643 Ok(())
2644 }
2645
2646 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2647 ///
2648 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2649 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2650 /// prototype is load-bearing in both directions: a key called `toString` must not
2651 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2652 /// (`resolves-empty-object.js`).
2653 pub(crate) fn keyed_result_object(
2654 &mut self,
2655 keys: Option<&Value>,
2656 values: &Gc<JsObject>,
2657 ) -> JsResult<Value> {
2658 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2659 return Ok(Value::Object(self.new_object(None)));
2660 };
2661 let result = self.new_object(None);
2662 let count = values.array_length().unwrap_or(0);
2663 for index in 0..count {
2664 let Some(key) = keys.array_get(index) else {
2665 continue;
2666 };
2667 let Some(value) = values.array_get(index) else {
2668 continue;
2669 };
2670 let property = Property::with_attributes(value, true, true);
2671 match &key {
2672 Value::Symbol(symbol) => {
2673 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2674 }
2675 other => {
2676 let text = self.to_js_string(other)?;
2677 result.define_key(&PropertyKey::from(text.as_str()), property);
2678 }
2679 }
2680 }
2681 Ok(Value::Object(result))
2682 }
2683
2684 /// Build an async function's result: a promise whose body runs as a coroutine.
2685 pub fn new_async_function(
2686 &mut self,
2687 function: Value,
2688 this: Value,
2689 args: Vec<Value>,
2690 ) -> JsResult<Value> {
2691 let promise = self.new_promise();
2692 let coroutine = self.new_coroutine(function, this, args)?;
2693 if let Err(Signal::Throw(reason)) =
2694 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2695 {
2696 self.reject_promise(&promise, reason);
2697 }
2698 Ok(Value::Object(promise))
2699 }
2700
2701 /// The coroutine an async body runs in.
2702 ///
2703 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2704 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2705 /// than growing a second state machine. The difference is only in the ending — a
2706 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2707 /// Run `code` as an async function body, answering the promise it settles.
2708 ///
2709 /// Used for a module with top-level `await`: its body is an async function whose
2710 /// caller is the host, so there is no function object to pass through
2711 /// [`Interp::new_async_function`].
2712 pub fn run_async_body(
2713 &mut self,
2714 code: Gc<CompiledCode>,
2715 env: Gc<ClosureEnv>,
2716 this: Value,
2717 ) -> JsResult<Value> {
2718 let promise = self.new_promise();
2719 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2720 if let Err(Signal::Throw(reason)) =
2721 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2722 {
2723 self.reject_promise(&promise, reason);
2724 }
2725 Ok(Value::Object(promise))
2726 }
2727
2728 fn new_coroutine(
2729 &mut self,
2730 function: Value,
2731 this: Value,
2732 args: Vec<Value>,
2733 ) -> JsResult<Gc<JsObject>> {
2734 let Some(object) = function.as_object().cloned() else {
2735 return Err(self.type_error("not a function"));
2736 };
2737 let Some((code, env)) = bytecode_of(&object) else {
2738 return Err(self.type_error("not a function"));
2739 };
2740 self.new_coroutine_from(code, env, this, args)
2741 }
2742
2743 /// Build a coroutine over an already-resolved body.
2744 fn new_coroutine_from(
2745 &mut self,
2746 code: Gc<CompiledCode>,
2747 env: Gc<ClosureEnv>,
2748 this: Value,
2749 args: Vec<Value>,
2750 ) -> JsResult<Gc<JsObject>> {
2751 let function = Value::Undefined;
2752 self.push_frame(code, env, this, args, function)?;
2753 let frame = self.frames.pop().expect("push_frame just pushed it");
2754 let state = GeneratorState {
2755 frame: Some(frame),
2756 phase: GeneratorPhase::SuspendedStart,
2757 parked_on_await: false,
2758 parked_on_yield_star: false,
2759 requests: std::collections::VecDeque::new(),
2760 async_busy: false,
2761 // An `async function` body is driven by `drive_async`, never by the generator
2762 // protocol, and the object is not reachable from script.
2763 is_async: false,
2764 };
2765 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2766 coroutine.with_mut(|data| {
2767 data.kind = ObjectKind::Generator(Box::new(state));
2768 });
2769 Ok(coroutine)
2770 }
2771
2772 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2773 /// `await` and `value` is what it awaited.
2774 fn resume_coroutine(
2775 &mut self,
2776 coroutine: &Gc<JsObject>,
2777 kind: ResumeKind,
2778 value: Value,
2779 ) -> JsResult<(Value, bool)> {
2780 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2781 ObjectKind::Generator(state) => {
2782 let is_async = state.is_async;
2783 Some(std::mem::replace(
2784 state.as_mut(),
2785 GeneratorState {
2786 frame: None,
2787 phase: GeneratorPhase::Executing,
2788 parked_on_await: false,
2789 parked_on_yield_star: false,
2790 requests: std::collections::VecDeque::new(),
2791 async_busy: false,
2792 is_async,
2793 },
2794 ))
2795 }
2796 _ => None,
2797 }) else {
2798 return Err(self.type_error("not a coroutine"));
2799 };
2800 let result = self.step_generator(&mut state, kind, value);
2801 coroutine.with_mut(|data| {
2802 data.kind = ObjectKind::Generator(Box::new(state));
2803 });
2804 let (value, done, _ready, _reason) = result?;
2805 Ok((value, done))
2806 }
2807
2808 /// Advance an async body and settle its promise with the outcome.
2809 fn drive_async(
2810 &mut self,
2811 coroutine: &Gc<JsObject>,
2812 promise: &Gc<JsObject>,
2813 kind: ResumeKind,
2814 value: Value,
2815 ) -> JsResult<()> {
2816 match self.resume_coroutine(coroutine, kind, value) {
2817 Ok((value, true)) => {
2818 // `Ok` with `done` means the body finished *normally*, even when it was
2819 // resumed by a `throw` — `try { await p } catch {}` completes by
2820 // returning. Only the `Err` arm below is a rejection.
2821 //
2822 // Resolving rather than fulfilling matters: `return promise` in an async
2823 // body adopts the inner promise, so `async function f(){ return
2824 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2825 // promise.
2826 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2827 self.reject_promise(promise, reason);
2828 }
2829 Ok(())
2830 }
2831 Ok((value, false)) => {
2832 // Parked on `await`: follow what it awaited and resume with the outcome.
2833 let awaited = match self.promise_resolve_value(value) {
2834 Ok(awaited) => awaited,
2835 Err(Signal::Throw(error)) => {
2836 self.reject_promise(promise, error);
2837 return Ok(());
2838 }
2839 Err(other) => return Err(other),
2840 };
2841 self.hook_await(awaited, coroutine, promise)
2842 }
2843 Err(Signal::Throw(reason)) => {
2844 self.reject_promise(promise, reason);
2845 Ok(())
2846 }
2847 Err(other) => Err(other),
2848 }
2849 }
2850
2851 /// Arrange for `coroutine` to resume when `awaited` settles.
2852 fn hook_await(
2853 &mut self,
2854 awaited: Value,
2855 coroutine: &Gc<JsObject>,
2856 promise: &Gc<JsObject>,
2857 ) -> JsResult<()> {
2858 let resumed = JsObject::function(
2859 self.heap,
2860 Some(self.realm.function_proto.clone()),
2861 Callable::AwaitResume {
2862 coroutine: coroutine.clone(),
2863 promise: promise.clone(),
2864 kind: ResumeKind::Next,
2865 },
2866 );
2867 let raised = JsObject::function(
2868 self.heap,
2869 Some(self.realm.function_proto.clone()),
2870 Callable::AwaitResume {
2871 coroutine: coroutine.clone(),
2872 promise: promise.clone(),
2873 kind: ResumeKind::Throw,
2874 },
2875 );
2876 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2877 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2878 let Value::Object(awaited) = &awaited else {
2879 self.jobs.push_back(Job::Resume {
2880 coroutine: coroutine.clone(),
2881 promise: promise.clone(),
2882 kind: ResumeKind::Next,
2883 value: awaited,
2884 });
2885 return Ok(());
2886 };
2887 self.perform_then(
2888 awaited,
2889 Some(Value::Object(resumed)),
2890 Some(Value::Object(raised)),
2891 )?;
2892 Ok(())
2893 }
2894
2895 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2896 /// things an engine keeps outside it — array elements and an array's `length`.
2897 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2898 if let Some(property) = object.own_property_key(key) {
2899 return Some(property);
2900 }
2901 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2902 // be synthesized too — and every one of them is a plain writable, enumerable,
2903 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2904 // `undefined` before this, which made `key-is-numericindex` fail on its own
2905 // side effect check.
2906 //
2907 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2908 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2909 // likewise not elements however numeric they look.
2910 if object.typed_array_element_type().is_some()
2911 && let Some(numeric) = canonical_numeric_index(key)
2912 && numeric.is_finite()
2913 && numeric.fract() == 0.0
2914 && !(numeric == 0.0 && numeric.is_sign_negative())
2915 && numeric >= 0.0
2916 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
2917 {
2918 let value = object.typed_array_element(numeric as usize)?;
2919 return Some(Property::data(value));
2920 }
2921 // An array's elements live in their own vector rather than the property table, so
2922 // a descriptor for one has to be synthesized — with the attributes an element has.
2923 if let Some(index) = key.as_str().and_then(array_index)
2924 && let Some(value) = object.array_get(index as usize)
2925 && !matches!(value, Value::Hole)
2926 {
2927 return Some(Property::data(value));
2928 }
2929 // `length` is an own property of an array that is not in its property table
2930 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2931 // and non-enumerable.
2932 if key.as_str() == Some("length")
2933 && let Some(length) = object.array_length()
2934 {
2935 return Some(Property {
2936 value: Some(crate::object::length_value(length)),
2937 writable: object.length_writable(),
2938 enumerable: false,
2939 configurable: false,
2940 getter: None,
2941 setter: None,
2942 descriptor_fields: None,
2943 });
2944 }
2945 None
2946 }
2947
2948 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2949 pub fn object_get_own_property(
2950 &mut self,
2951 object: &Gc<JsObject>,
2952 key: &PropertyKey,
2953 ) -> JsResult<Option<Property>> {
2954 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2955 return Ok(answer);
2956 }
2957 if let Some(exotic) = object.exotic()
2958 && let Some(answer) = exotic.get_own_property(self, object, key)?
2959 {
2960 return Ok(answer);
2961 }
2962 // A mapped `arguments` index is a data property as far as script can see: the
2963 // accessor pair that aliases the parameter is plumbing, and exposing it would
2964 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2965 // report a `get` where the spec has a `[[Value]]`.
2966 if let Some(index) = key.as_str().and_then(crate::object::array_index)
2967 && let Some(cell) = object.mapped_argument_cell(index as usize)
2968 {
2969 // Non-configurable is *not* the default: an ordinary mapped index is
2970 // configurable, and only becomes non-configurable once something
2971 // redefines it. Preserve whatever the property table currently says.
2972 // The attributes come from whatever the property table holds, because they
2973 // can be changed independently of the mapping; only the *value* and the
2974 // data-property *kind* are the accessor's secret.
2975 let flags = Self::ordinary_own_property(object, key);
2976 if let Some(existing) = &flags
2977 && !existing.is_accessor()
2978 {
2979 // Already demapped: the table entry is the answer, not the cell.
2980 return Ok(flags);
2981 }
2982 return Ok(Some(Property {
2983 value: Some(cell.get()),
2984 writable: true,
2985 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2986 configurable: flags.as_ref().is_some_and(|p| p.configurable),
2987 ..Property::default()
2988 }));
2989 }
2990 Ok(Self::ordinary_own_property(object, key))
2991 }
2992
2993 /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
2994 ///
2995 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
2996 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
2997 /// abstract operation here rather than a private helper in `error.rs`.
2998 ///
2999 /// The name is the whole point: the setter must behave as if the prototype were not
3000 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3001 /// the accessor for every error object in the realm. Everything below follows from that:
3002 ///
3003 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3004 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3005 /// accessor's own home an error rather than a self-shadow.
3006 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3007 /// either has a string or has made a mistake.
3008 /// 4. An existing *own* property decides the path — an own setter is called, an own
3009 /// non-writable data property is a `TypeError` — and only a missing own property
3010 /// falls through to defining one.
3011 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3012 /// traps and a non-extensible receiver is a `TypeError`.
3013 ///
3014 /// The installed shape is writable + configurable, not enumerable.
3015 pub fn setter_that_ignores_prototype_properties(
3016 &mut self,
3017 this_value: Value,
3018 home: &Gc<JsObject>,
3019 property_key: &str,
3020 args: &[Value],
3021 ) -> JsResult<Value> {
3022 let Some(receiver) = this_value.as_object().cloned() else {
3023 return Err(self.type_error("setter called on a non-object"));
3024 };
3025 if Gc::ptr_eq(&receiver, home) {
3026 return Err(self.type_error("cannot assign to the accessor's own home object"));
3027 }
3028 // No type check here: §7.3.40 takes an arbitrary `v`, and
3029 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3030 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3031 // before calling this.
3032 let value = args.first().cloned().unwrap_or(Value::Undefined);
3033 let key = PropertyKey::from(property_key);
3034 // Step 4: an own property on the receiver changes what happens, and there are three
3035 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3036 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3037 // `Set` with `throw = true`, and a test exists for each.
3038 if let Some(existing) = self.object_get_own_property(&receiver, &key)? {
3039 if existing.is_accessor() && existing.setter.is_none() {
3040 // A getter-only own accessor cannot be written through.
3041 return Err(self.type_error("no setter for the own property"));
3042 }
3043 // Everything else — an own data property, or an own accessor *with* a setter —
3044 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3045 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3046 // an own user setter receives the value (`setter-own-accessor`), because
3047 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3048 // setter directly is the difference between one code path and two that can
3049 // disagree.
3050 self.set_property(&receiver, property_key, value.clone())?;
3051 return Ok(Value::Undefined);
3052 }
3053 let property = Property {
3054 value: Some(value.clone()),
3055 writable: true,
3056 // Enumerable, despite the accessor it shadows not being. The reference installs
3057 // it that way and six cases check it (`setter-creates-own-property` and friends).
3058 enumerable: true,
3059 configurable: true,
3060 ..Property::default()
3061 };
3062 if !self.object_define_own_property(&receiver, &key, property)? {
3063 return Err(self.type_error("the receiver refused the definition"));
3064 }
3065 Ok(Value::Undefined)
3066 }
3067
3068 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3069 ///
3070 /// The indices of a typed array are not properties at all — they are bytes in the
3071 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3072 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3073 /// enumerable and configurable, so a definition can only ever change the *value*, and
3074 /// every other descriptor is refused rather than applied.
3075 ///
3076 /// The order of the checks is the spec's, and two of them are load-bearing:
3077 ///
3078 /// * the index is validated **before** the value is converted, because the conversion
3079 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3080 /// detaches from a `valueOf` and still expects `true` with no store, which only
3081 /// happens when the index was valid on the way in;
3082 /// * the store is attempted even when the index has gone out of bounds by the time the
3083 /// conversion finishes, because the store is a silent no-op rather than a failure —
3084 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3085 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3086 ///
3087 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3088 /// the existing element, which is harmless here: every valid index is already
3089 /// writable, enumerable and configurable, so a `false` in the merged property can only
3090 /// have come from the descriptor having named `false`.
3091 fn integer_indexed_define_own_property(
3092 &mut self,
3093 object: &Gc<JsObject>,
3094 numeric: f64,
3095 property: &Property,
3096 ) -> JsResult<bool> {
3097 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3098 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3099 if !typed_array_index_is_valid(object, numeric) {
3100 return Ok(false);
3101 }
3102 // Step 6: the indices are data properties, so an accessor descriptor is refused
3103 // rather than converted. `Object.defineProperty` turns the `false` into a
3104 // `TypeError`; `Reflect.defineProperty` reports it.
3105 if property.is_accessor() {
3106 return Ok(false);
3107 }
3108 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3109 // definition that asks for anything else cannot be honoured.
3110 if !property.writable || !property.enumerable || !property.configurable {
3111 return Ok(false);
3112 }
3113 // Step 10: only a descriptor that names a value stores anything.
3114 let Some(value) = property.value.clone() else {
3115 return Ok(true);
3116 };
3117 let Some(element) = object.typed_array_element_type() else {
3118 return Ok(false);
3119 };
3120 let stored = self.element_value(element, value)?;
3121 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3122 return Err(self.type_error(reason));
3123 }
3124 Ok(true)
3125 }
3126
3127 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3128 pub fn object_define_own_property(
3129 &mut self,
3130 object: &Gc<JsObject>,
3131 key: &PropertyKey,
3132 property: Property,
3133 ) -> JsResult<bool> {
3134 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3135 return Ok(accepted);
3136 }
3137 // A proxy always answers above — with `Some` from its trap, or with `None` when
3138 // the trap is absent, and then the definition belongs to the **target**
3139 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3140 // when there is no trap). Falling through to the ordinary path here defined the
3141 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3142 // property the target never saw.
3143 if object.proxy_state().is_some() {
3144 let Some((target, _handler)) = self.proxy_parts(object)? else {
3145 return Err(self.type_error("cannot use a proxy that has been revoked"));
3146 };
3147 return self.object_define_own_property(&target, key, property);
3148 }
3149 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3150 // they accept exactly one descriptor shape. This has to happen before the
3151 // ordinary path, which would happily store a data property next to the buffer —
3152 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3153 // and `TypedArray/prototype/set` are about this section.
3154 if object.typed_array_element_type().is_some()
3155 && let Some(index) = canonical_numeric_index(key)
3156 {
3157 return self.integer_indexed_define_own_property(object, index, &property);
3158 }
3159 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3160 // non-extensible object. The check lives here rather than in the callers because
3161 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3162 // `Array.prototype.filter` uses to store its result, and a species object made
3163 // non-extensible by its own constructor must make that a `TypeError`
3164 // (`target-array-non-extensible`).
3165 // Note the `is_none()`: an already-present property may still be **redefined** on a
3166 // non-extensible object, and only *adding* one is refused (as Distinct from
3167 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3168 // properties — testing extensibility before looking for the property made every
3169 // `Object.freeze` of an ordinary object refuse its own second step).
3170 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3171 return Ok(false);
3172 }
3173 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3174 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3175 // an omitted field is left alone). Merging here rather than at each call site is
3176 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3177 // the value and `enumerable` in place.
3178 //
3179 // The merge is a no-op when the property is absent: there is nothing to keep.
3180 let was_partial = property.descriptor_fields.is_some();
3181 let property = match property.descriptor_fields {
3182 None => property,
3183 Some(fields) => {
3184 let base = self.object_get_own_property(object, key)?;
3185 let mut merged = base.clone().unwrap_or_default();
3186 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3187 // descriptor names, and switching kind discards the other half —
3188 // `{set: f}` on a data property is an accessor with no getter, not a data
3189 // property whose `get` happens to be absent.
3190 let wants_accessor = fields.get || fields.set;
3191 let wants_data = fields.value || fields.writable;
3192 if wants_accessor {
3193 merged.value = None;
3194 merged.writable = false;
3195 merged.getter = property.getter.clone();
3196 merged.setter = property.setter.clone();
3197 } else if wants_data {
3198 merged.getter = None;
3199 merged.setter = None;
3200 if fields.value {
3201 merged.value = property.value.clone();
3202 }
3203 if fields.writable {
3204 merged.writable = property.writable;
3205 }
3206 }
3207 if fields.enumerable {
3208 merged.enumerable = property.enumerable;
3209 }
3210 if fields.configurable {
3211 merged.configurable = property.configurable;
3212 }
3213 merged.descriptor_fields = None;
3214 merged
3215 }
3216 };
3217 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3218 // descriptor. `define_property_on` runs the same check before it calls here, so an
3219 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3220 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3221 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3222 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3223 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3224 // own define would have refused.
3225 //
3226 // Only partial descriptors are validated here. A whole `Property` passed by an
3227 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3228 // what the descriptor "named", and those callers rely on the write landing.
3229 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3230 // Every branch below is gated on `!existing.configurable`: a *configurable*
3231 // property may be reshaped however the descriptor likes, which is why an
3232 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3233 // must succeed. Testing only `writable` refused that and broke
3234 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3235 let same_kind = existing.is_accessor() == property.is_accessor();
3236 if !same_kind {
3237 // Step 4: a non-configurable property may not change kind.
3238 if !existing.configurable {
3239 return Ok(false);
3240 }
3241 } else if existing.is_accessor() {
3242 // Step 6: an accessor's halves are its value.
3243 if !existing.configurable
3244 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3245 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3246 {
3247 return Ok(false);
3248 }
3249 } else if !existing.configurable && !existing.writable {
3250 // Step 7: a non-configurable *and* non-writable data property's value is
3251 // fixed, and it may not become writable again.
3252 if property.writable {
3253 return Ok(false);
3254 }
3255 let current = existing.value.clone().unwrap_or(Value::Undefined);
3256 let requested = property.value.clone().unwrap_or(Value::Undefined);
3257 if !current.same_value(&requested) {
3258 return Ok(false);
3259 }
3260 }
3261 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3262 // is frozen with it.
3263 if !existing.configurable
3264 && (property.configurable || property.enumerable != existing.enumerable)
3265 {
3266 return Ok(false);
3267 }
3268 }
3269 // A host class that intercepts definitions owns the attributes of the properties it
3270 // defines: `_class`-style storage on the native side is the usual reason.
3271 if let Some(exotic) = object.exotic()
3272 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3273 {
3274 return Ok(accepted);
3275 }
3276 // An array index is stored in the element vector, which can hold a plain value and
3277 // nothing else. An accessor — or a data property with non-default attributes —
3278 // therefore has to live in the property table, and the element slot is blanked so
3279 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3280 // {get})` stored the accessor where no read ever looked, and the array kept
3281 // answering its old value.
3282 // An array's `length` is not stored in the property table, so defining it has to
3283 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3284 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3285 // {value: 1})` reported success and changed nothing.
3286 if key.as_str() == Some("length") && object.is_array() {
3287 // `{writable: false}` on `length` does not change the length, but it does make
3288 // it read-only — after which neither a later `{writable: true}` nor a store
3289 // past the end may succeed.
3290 if property.value.is_none() {
3291 if !object.length_writable() && property.writable {
3292 return Ok(false);
3293 }
3294 object.set_length_writable(property.writable);
3295 return Ok(true);
3296 }
3297 if !object.length_writable() {
3298 return Ok(false);
3299 }
3300 }
3301 if key.as_str() == Some("length")
3302 && object.is_array()
3303 && let Some(value) = property.value.clone()
3304 {
3305 let requested = value.to_number();
3306 let valid = requested.is_finite()
3307 && requested >= 0.0
3308 && requested.fract() == 0.0
3309 && requested <= u32::MAX as f64;
3310 if !valid {
3311 return Err(self.range_error("invalid array length"));
3312 }
3313 // Truncating deletes the elements above the new length, and a non-configurable
3314 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3315 // makes `a.length = 2` fail rather than quietly drop it.
3316 let current = object.array_length().unwrap_or(0);
3317 let requested = requested as usize;
3318 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3319 return Ok(false);
3320 }
3321 object.array_set_length(self.heap, requested);
3322 return Ok(true);
3323 }
3324 let plain = property.writable
3325 && property.enumerable
3326 && property.configurable
3327 && !property.is_accessor();
3328 if let Some(index) = key.as_str().and_then(array_index)
3329 && object.is_array()
3330 {
3331 // Growing the array needs a writable `length`: after
3332 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3333 // be added.
3334 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3335 return Ok(false);
3336 }
3337 if plain && property.value.is_some() {
3338 // An ordinary element: the vector is where a read looks first, so it has
3339 // to be the vector that changes — unless the index is too far out to be
3340 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3341 // one property, because past its own limit it stores the index as an
3342 // ordinary key. Falling through to `define_key` below is the same choice,
3343 // and the alternative was worse: the store used to be *dropped* and the
3344 // length left at 0, which is a silent wrong answer.
3345 let value = property.value.clone().unwrap_or(Value::Undefined);
3346 object.delete_key(key);
3347 if object.array_set(self.heap, index as usize, value) {
3348 return Ok(true);
3349 }
3350 // Past the dense limit the element lives in the table like any property.
3351 object.note_element_descriptor();
3352 object.define_key(key, property);
3353 // A sparse store past the dense limit still extends `length`, which is what
3354 // `a[a.length] = v` relies on — but only extends: shortening would delete
3355 // the sparse properties above the index, including this one.
3356 if index as usize + 1 > object.array_length().unwrap_or(0) {
3357 object.array_set_length(self.heap, index as usize + 1);
3358 }
3359 return Ok(true);
3360 }
3361 // A non-plain element — an accessor, or an attribute that is not the default —
3362 // lives in the table while the slot becomes a hole. Recording it keeps every
3363 // later `a[i] = v` off the dense path, where the write would have shadowed the
3364 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3365 // replace the accessor with a plain data property.
3366 object.note_element_descriptor();
3367 object.define_key(key, property);
3368 // The slot stays, so `length` does not shrink; a hole is not an element, so
3369 // the table entry is now what a read finds.
3370 object.array_set(self.heap, index as usize, Value::Hole);
3371 return Ok(true);
3372 }
3373 object.define_key(key, property);
3374 Ok(true)
3375 }
3376
3377 /// Build a proxy object over `target`, with its traps read from `handler`.
3378 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3379 JsObject::proxy(self.heap, target, handler)
3380 }
3381
3382 /// The `revoke` function for a proxy's slots.
3383 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3384 let revoke = JsObject::function(
3385 self.heap,
3386 Some(self.realm.function_proto.clone()),
3387 Callable::Revoker(slots),
3388 );
3389 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3390 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3391 // inherited from `Function.prototype` reads the same but fails the three cases that
3392 // check the own-property list (`revocation-function-{length,name,property-order}`).
3393 revoke.define("length", Property::name_or_length(Value::Int(0)));
3394 revoke.define("name", Property::name_or_length(self.string("")));
3395 revoke
3396 }
3397
3398 /// A new array.
3399 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3400 let array = JsObject::array(
3401 self.heap,
3402 Some(self.realm.array_proto.clone()),
3403 elements.len(),
3404 );
3405 for (index, element) in elements.into_iter().enumerate() {
3406 array.array_set(self.heap, index, element);
3407 }
3408 array
3409 }
3410
3411 /// A new native function object.
3412 ///
3413 /// The observable `name` and `length` are installed as properties here, which is
3414 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3415 /// so `f.name = "x"` behaves like the writable property it is.
3416 /// A native constructor that builds its own instance after validating its arguments.
3417 ///
3418 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3419 /// check runs before `new.target.prototype` is read.
3420 pub fn new_native_ctor(
3421 &self,
3422 name: impl Into<String>,
3423 length: u32,
3424 func: NativeFn,
3425 ) -> Gc<JsObject> {
3426 let function = JsObject::function(
3427 self.heap,
3428 Some(self.realm.function_proto.clone()),
3429 Callable::Native {
3430 func,
3431 own_instance: true,
3432 },
3433 );
3434 function.set_constructible(true);
3435 function.define(
3436 "length",
3437 Property::name_or_length(Value::Int(length as i32)),
3438 );
3439 function.define("name", Property::name_or_length(self.string(name)));
3440 function
3441 }
3442
3443 /// A native constructor that lets `new` build the instance first.
3444 ///
3445 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3446 /// validation that must precede reading `new.target.prototype`, so the object can be
3447 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3448 /// which makes a *method* and therefore not a constructor at all.
3449 pub fn new_native_constructor(
3450 &self,
3451 name: impl Into<String>,
3452 length: u32,
3453 func: NativeFn,
3454 ) -> Gc<JsObject> {
3455 let function = self.new_native(name, length, func);
3456 function.set_constructible(true);
3457 function
3458 }
3459
3460 /// A new host function object: a native closure that carries its own state.
3461 ///
3462 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3463 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3464 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3465 /// this safe: the closure must not capture a `Gc`.
3466 pub fn new_host_function(
3467 &self,
3468 name: impl Into<String>,
3469 length: u32,
3470 func: crate::object::HostFn,
3471 ) -> Gc<JsObject> {
3472 self.new_host_inner(name.into(), length, func, false)
3473 }
3474
3475 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3476 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3477 pub fn new_host_ctor(
3478 &self,
3479 name: impl Into<String>,
3480 length: u32,
3481 func: crate::object::HostFn,
3482 ) -> Gc<JsObject> {
3483 let function = self.new_host_inner(name.into(), length, func, true);
3484 function.set_constructible(true);
3485 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3486 // installs its own methods on it, so it starts as a plain object.
3487 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3488 function.define(
3489 "prototype",
3490 Property {
3491 value: Some(Value::Object(proto)),
3492 writable: true,
3493 enumerable: false,
3494 configurable: false,
3495 ..Property::default()
3496 },
3497 );
3498 function
3499 }
3500
3501 fn new_host_inner(
3502 &self,
3503 name: String,
3504 length: u32,
3505 func: crate::object::HostFn,
3506 own_instance: bool,
3507 ) -> Gc<JsObject> {
3508 let function = JsObject::function(
3509 self.heap,
3510 Some(self.realm.function_proto.clone()),
3511 Callable::Host {
3512 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3513 own_instance,
3514 },
3515 );
3516 function.define(
3517 "length",
3518 Property::name_or_length(Value::Int(length as i32)),
3519 );
3520 function.define("name", Property::name_or_length(self.string(name)));
3521 function
3522 }
3523
3524 /// A callable object with the `length`/`name` a built-in function has, in that order.
3525 ///
3526 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3527 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3528 /// [`JsObject::function`] defines neither, which is why every capability helper built
3529 /// with it reported no own `length` and no own `name` at all.
3530 ///
3531 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3532 /// configurable.
3533 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3534 let function =
3535 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3536 function.define(
3537 "length",
3538 Property::name_or_length(Value::Int(length as i32)),
3539 );
3540 function.define("name", Property::name_or_length(self.string(name)));
3541 function
3542 }
3543
3544 /// A new native function object.
3545 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3546 let function = JsObject::function(
3547 self.heap,
3548 Some(self.realm.function_proto.clone()),
3549 Callable::Native {
3550 func,
3551 own_instance: false,
3552 },
3553 );
3554 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3555 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3556 // `length,name` and this listed `name,length`. A bytecode function already gets it
3557 // the right way round; only native ones were built backwards.
3558 function.define(
3559 "length",
3560 Property::name_or_length(Value::Int(length as i32)),
3561 );
3562 function.define("name", Property::name_or_length(self.string(name)));
3563 function
3564 }
3565
3566 /// A new bound function.
3567 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3568 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3569 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3570 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3571 let constructible = target
3572 .as_object()
3573 .is_some_and(|target| target.is_constructor());
3574 let bound = JsObject::function(
3575 self.heap,
3576 Some(self.realm.function_proto.clone()),
3577 Callable::Bound { target, this, args },
3578 );
3579 bound.set_constructible(constructible);
3580 bound
3581 }
3582
3583 /// A new reference cell.
3584 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3585 Gc::new(self.heap, Cell::new(value))
3586 }
3587
3588 // -- running ------------------------------------------------------------
3589
3590 /// Evaluate `code` as a script body and return its completion value.
3591 /// Compile and run `source` for the engine's own use, returning its completion value.
3592 ///
3593 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3594 /// needs to be a real async function, and the engine already runs those as coroutines,
3595 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3596 ///
3597 /// Differences from [`Self::eval_in_global`], both deliberate:
3598 ///
3599 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3600 /// being built, and the source is an IIFE that only constructs a closure, so there
3601 /// is nothing to drain — and draining here would run script-queued jobs in the
3602 /// middle of `install`.
3603 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3604 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3605 /// and it should not look like the user wrote something wrong.
3606 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3607 let program = match js_parse::parse_script(source) {
3608 Ok(program) => program,
3609 Err(error) => {
3610 let message = format!("builtin source does not parse: {error}");
3611 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3612 }
3613 };
3614 let mut code = match js_compile::compile_script_with_source(&program, source) {
3615 Ok(code) => code,
3616 Err(error) => {
3617 let message = format!("builtin source does not compile: {}", error.message);
3618 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3619 }
3620 };
3621 // The frame has to name something, and `<builtin>` is what a stack trace through
3622 // this code should say.
3623 code.set_filename("<builtin>");
3624 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3625 let closure_vars = compiled.code.closure_vars.clone();
3626 let env = self.global_env(&closure_vars);
3627 let this = Value::Object(self.realm.global.clone());
3628 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3629 }
3630
3631 /// Run an already-parsed script and drain the microtasks it queued.
3632 ///
3633 /// The drain is what lets an `async` function's body advance past its first `await`
3634 /// before the host sees the result: nothing else pumps the job queue.
3635 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3636 let this = Value::Object(self.realm.global.clone());
3637 self.run_script_with_this(code, this)
3638 }
3639
3640 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3641 ///
3642 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3643 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3644 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3645 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3646 /// state the next script evaluation tripped over.
3647 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3648 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3649 let closure_vars = compiled.code.closure_vars.clone();
3650 let env = self.global_env(&closure_vars);
3651 let callee = Value::Undefined;
3652 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3653 // The script is done, so the microtasks it queued run before the host sees the
3654 // result. Without this an `async` function's body would never advance past its
3655 // first `await`, because nothing else drains the queue.
3656 self.drain_jobs()?;
3657 Ok(result)
3658 }
3659
3660 /// Compile and run `source` in global scope, returning its completion value.
3661 ///
3662 /// This is what `eval` and `new Function` use. Running it as a script means it
3663 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3664 /// for a `Function` body; a *direct* eval that reads a local variable would need
3665 /// the compiler to hand its variable environment over, which is not implemented.
3666 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3667 self.eval_in_global_named(source, EVAL_FILE, false)
3668 }
3669
3670 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3671 ///
3672 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3673 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3674 /// through the code, so they cannot share one constant.
3675 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3676 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3677 }
3678
3679 /// Evaluate `source` as a global script, reported under `file`.
3680 ///
3681 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3682 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3683 /// from inside a C callback, where the interpreter is the running one rather than a
3684 /// context's own.
3685 pub fn eval_in_global_named(
3686 &mut self,
3687 source: &str,
3688 file: &str,
3689 barrier: bool,
3690 ) -> JsResult<Value> {
3691 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3692 // eval-created global binding — configurable, unlike a script's own `var`.
3693 self.eval_depth += 1;
3694 if barrier {
3695 let depth = self.frames.len();
3696 self.trace_barriers.push(depth);
3697 }
3698 let result = self.eval_in_global_inner(source, file);
3699 if barrier {
3700 self.trace_barriers.pop();
3701 }
3702 self.eval_depth -= 1;
3703 result
3704 }
3705
3706 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3707 let compiled = self.compile_global_script(source, file, false)?;
3708 let strict = compiled.strict;
3709 self.run_eval_script(compiled, strict)
3710 }
3711
3712 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3713 ///
3714 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3715 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3716 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3717 /// direct eval's is.
3718 pub fn eval_script_with_this(
3719 &mut self,
3720 source: &str,
3721 file: &str,
3722 this: Value,
3723 ) -> JsResult<Value> {
3724 let program = match js_parse::parse_script(source) {
3725 Ok(program) => program,
3726 Err(error) => {
3727 return Err(Signal::Throw(self.syntax_error_at(
3728 file,
3729 error.span.start.line,
3730 error.span.start.column,
3731 &error.message,
3732 )));
3733 }
3734 };
3735 let mut compiled = match js_compile::compile_script(&program) {
3736 Ok(compiled) => compiled,
3737 Err(error) => {
3738 return Err(Signal::Throw(self.syntax_error_at(
3739 file,
3740 error.span.start.line,
3741 error.span.start.column,
3742 &error.message,
3743 )));
3744 }
3745 };
3746 compiled.set_filename(file);
3747 self.run_script_with_this(compiled, this)
3748 }
3749
3750 /// Parse and compile `source` as a global script, without running it.
3751 ///
3752 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3753 /// before a promise exists to reject — while still evaluating in the same eval context
3754 /// (direct-eval strictness, `new.target`, `super`).
3755 fn compile_global_script(
3756 &mut self,
3757 source: &str,
3758 file: &str,
3759 async_body: bool,
3760 ) -> JsResult<CompiledFunction> {
3761 // A *direct* eval inherits the strictness of the code that called it, which is
3762 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3763 // implicit global. The caller's frame is the innermost one here, because a
3764 // native function does not push a frame of its own.
3765 let strict = self.current_strict();
3766 // `eval` runs in the caller's function context, so `new.target` is legal here
3767 // even though the source is a bare script — and so is `super.x` when the caller
3768 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3769 // caller's, which is what `special_object 4` already does.
3770 let context = js_parse::EvalContext {
3771 in_method: self.enclosing_home_object().is_some(),
3772 // `super()` belongs to a derived constructor, and an eval'd body is not a
3773 // constructor at all: the caller frame's `this` is already built.
3774 in_derived_constructor: false,
3775 };
3776 // A *global* eval is not a function body: `new.target` and `super` are out of
3777 // reach there. Its `{async: true}` form differs in the other direction — the body
3778 // may `await` — so the two flags are independent and the reference sets both from
3779 // the eval type rather than from the caller.
3780 let parsed = if async_body {
3781 js_parse::parse_suspensible_global_eval(source, strict)
3782 } else {
3783 js_parse::parse_eval_script_in(source, strict, context)
3784 };
3785 let program = match parsed {
3786 Ok(program) => program,
3787 Err(error) => {
3788 // The message is bare: the position lives in `fileName`,
3789 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3790 // the reference puts it. An `invalid source: L:C: ` prefix made
3791 // `e.message` differ from the reference while the stack already agreed.
3792 return Err(Signal::Throw(self.syntax_error_at(
3793 file,
3794 error.span.start.line,
3795 error.span.start.column,
3796 &error.message,
3797 )));
3798 }
3799 };
3800 let mut compiled = match if async_body {
3801 js_compile::compile_script_suspensible(&program)
3802 } else {
3803 js_compile::compile_script(&program)
3804 } {
3805 Ok(compiled) => compiled,
3806 // A construct the compiler does not handle yet is reported the same way a
3807 // parse error is: it happens before anything runs, so the trace is the
3808 // position in the source followed by the caller.
3809 Err(error) => {
3810 return Err(Signal::Throw(self.syntax_error_at(
3811 file,
3812 error.span.start.line,
3813 error.span.start.column,
3814 &error.message,
3815 )));
3816 }
3817 };
3818 compiled.set_filename(file);
3819 Ok(compiled)
3820 }
3821
3822 /// Run an `eval`'d script in the caller's scope.
3823 ///
3824 /// Three things have to come from the calling frame, because the eval'd code is a
3825 /// script and would otherwise see only the global object:
3826 ///
3827 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3828 /// * `arguments`, exposed as a binding of the eval's own scope, so
3829 /// `f("arguments.length", 1)` sees the caller's arguments;
3830 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3831 /// `eval("var v = 1")` into the global object.
3832 ///
3833 /// Locals of the calling function are *not* reachable: that needs the compiler to
3834 /// hand its variable environment over, which this milestone does not do.
3835 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3836 // `this` and `arguments` come from the innermost frame only — those are not
3837 // lexical — while the name bindings come from the whole chain of frames, part
3838 // of it being ordinary scope resolution.
3839 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3840 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3841 // read from its closure.
3842 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3843 // variable environment is the innermost frame of all: an arrow's own body is where
3844 // `var`s declared by an `eval` inside it belong.
3845 let caller_index = self
3846 .frames
3847 .iter()
3848 .rposition(|frame| !frame.code.code.is_arrow)
3849 .or_else(|| self.frames.len().checked_sub(1));
3850 let env_index = self.frames.len().checked_sub(1);
3851 let caller = caller_index.and_then(|index| self.frames.get(index));
3852 let (this, passed) = match caller {
3853 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3854 // No frame at all: the eval is running at the top level, so there is
3855 // nothing to inherit and the global receiver is right.
3856 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3857 };
3858 // Innermost frame first, so the first binding found for a name is the one that
3859 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3860 let mut bindings: Vec<EvalBinding> = Vec::new();
3861 // The calling function's own bindings, resolved by the compiler at the call
3862 // site. That table is the only reliable answer when a name is declared twice in
3863 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3864 // body means, and guessing by declaration order picks the wrong one as soon as
3865 // two loops in a row use the same name.
3866 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3867 // every direct call — a bare `eval(...)` callee — so finding one at the current
3868 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3869 // callee to a value first and leave no site behind.
3870 let mut direct = false;
3871 let mut resolved_here = false;
3872 if let Some(frame) = self.frames.last() {
3873 let (line, column) = frame
3874 .code
3875 .code
3876 .position_at(frame.at as u32)
3877 .unwrap_or_default();
3878 // The nearest site at or before the current position, not an exact match:
3879 // the recorded position of the `call` instruction is the callee's, which
3880 // sits a few columns inside the call expression the compiler recorded. A
3881 // site is unique per call, so "the closest one behind us" identifies it.
3882 if let Some(site) = frame
3883 .code
3884 .code
3885 .eval_sites
3886 .iter()
3887 .filter(|site| (site.line, site.column) <= (line, column))
3888 .max_by_key(|site| (site.line, site.column))
3889 {
3890 direct = true;
3891 resolved_here = true;
3892 for binding in &site.bindings {
3893 // An enclosing function's frame sits `owner` levels below the one
3894 // running the call.
3895 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3896 else {
3897 continue;
3898 };
3899 bindings.push(EvalBinding {
3900 name: binding.name.clone(),
3901 frame,
3902 slot: if binding.is_arg {
3903 EvalSlot::Arg
3904 } else {
3905 EvalSlot::Local
3906 },
3907 index: binding.index as usize,
3908 });
3909 }
3910 }
3911 }
3912 for frame_index in (0..self.frames.len()).rev() {
3913 // Skip the innermost frame's flat scan when the compiler already answered
3914 // for it; an enclosing frame still needs one, because the eval resolves
3915 // those names dynamically.
3916 if resolved_here && frame_index == self.frames.len() - 1 {
3917 continue;
3918 }
3919 let frame = &self.frames[frame_index];
3920 for (index, arg) in frame.code.code.args.iter().enumerate() {
3921 bindings.push(EvalBinding {
3922 name: arg.name.clone(),
3923 frame: frame_index,
3924 slot: EvalSlot::Arg,
3925 index,
3926 });
3927 }
3928 for (index, local) in frame.code.code.vars.iter().enumerate() {
3929 bindings.push(EvalBinding {
3930 name: local.name.clone(),
3931 frame: frame_index,
3932 slot: EvalSlot::Local,
3933 index,
3934 });
3935 }
3936 }
3937 let mut seen = BTreeSet::new();
3938 bindings.retain(|binding| seen.insert(binding.name.clone()));
3939
3940 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3941 // elements is all the spec's ordinary uses need.
3942 //
3943 // Known divergence: this is bound for a *global* eval too, where there is no
3944 // caller and the reference throws `'arguments' is not defined`. Deciding properly
3945 // needs "does the calling frame have an `arguments` of its own", which is not
3946 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3947 // script or eval body does not, and `eval(b)` passes the callee as a value so even
3948 // the call-site detection does not answer it. Modelled as a binding in the caller's
3949 // variable environment, this would fall out; that is a larger change than the one
3950 // this comment is attached to.
3951 let arguments = Value::Object(self.new_array(passed));
3952
3953 // Only a *strict* eval gets a variable environment of its own. A sloppy one
3954 // declares its `var`s in the caller's — which for a top-level eval is the global
3955 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3956 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3957 // vanish into a scope nobody reads back from.
3958 let previous_scope = if code_strict {
3959 self.eval_scope.replace(BTreeMap::new())
3960 } else {
3961 None
3962 };
3963 let previous_arguments = self.eval_arguments.replace(arguments);
3964 let previous_with = self.eval_with.replace(self.with_objects());
3965 let inherited_new_target = self
3966 .frames
3967 .iter()
3968 .rev()
3969 .find(|frame| !frame.code.code.is_arrow)
3970 .map(|frame| frame.new_target.clone());
3971 let previous_new_target = self
3972 .eval_new_target
3973 .replace(inherited_new_target.unwrap_or(Value::Undefined));
3974 let eval_cells = self.eval_cells_for(&bindings);
3975 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3976 // A sloppy direct eval declares its `var`s in the caller's variable environment;
3977 // `declare_eval_local` needs to know which frame that is.
3978 // An indirect eval gets the global environment, so nothing of the caller's is
3979 // recorded as the place its `var`s belong.
3980 let previous_caller = self
3981 .eval_caller
3982 .replace(if direct { env_index } else { None });
3983 // The cell-based view of the same bindings, which is what a closure created
3984 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3985 // whose compiler did not put a binding in a cell simply does not appear here —
3986 // reads and writes still work through `eval_bindings`, they just cannot outlive
3987 // the eval.
3988 let previous_eval_scope = self
3989 .active_eval_scope
3990 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3991 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3992 let closure_vars = compiled.code.closure_vars.clone();
3993 let env = self.global_env(&closure_vars);
3994 let callee = Value::Undefined;
3995 // An async body does not run here: it becomes a coroutine and answers a promise,
3996 // which is what makes `await` legal in it. `this` still has to be the caller's
3997 // (for a global eval, the global object), because `this` is not part of `await`.
3998 let result = if compiled.code.kind.is_async() {
3999 self.run_async_body(compiled, env, this)
4000 } else {
4001 self.execute(compiled, env, this, Vec::new(), callee)
4002 };
4003 self.eval_scope = previous_scope;
4004 self.eval_arguments = previous_arguments;
4005 self.eval_with = previous_with;
4006 self.eval_new_target = previous_new_target;
4007 self.eval_bindings = previous_bindings;
4008 self.eval_caller = previous_caller;
4009 self.active_eval_scope = previous_eval_scope;
4010 result
4011 }
4012
4013 /// The cell-backed subset of `bindings`, in the same priority order.
4014 ///
4015 /// Both lookup routes have to agree — the eval's own reads go through
4016 /// [`Interp::eval_binding_value`] and the closures it builds go through
4017 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4018 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4019 /// is not in a cell simply does not appear: reads and writes still work, they just
4020 /// cannot be handed to a closure that outlives the eval.
4021 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4022 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4023 for binding in bindings {
4024 let Some(frame) = self.frames.get(binding.frame) else {
4025 continue;
4026 };
4027 let cell = match binding.slot {
4028 EvalSlot::Arg => frame
4029 .code
4030 .arg_cell
4031 .get(binding.index)
4032 .copied()
4033 .unwrap_or(-1),
4034 EvalSlot::Local => frame
4035 .code
4036 .loc_cell
4037 .get(binding.index)
4038 .copied()
4039 .unwrap_or(-1),
4040 };
4041 if cell < 0 {
4042 continue;
4043 }
4044 if let Some(cell) = frame.cells.get(cell as usize) {
4045 names.push((binding.name.clone(), cell.clone()));
4046 }
4047 }
4048 names
4049 }
4050
4051 /// A `SyntaxError` that reports where in the source it happened.
4052 ///
4053 /// Compile-time failures never run, so they have no frame of their own; the
4054 /// reference still puts the position first in the trace, with no function name and
4055 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4056 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4057 /// reference borrows), which is how a script reads the position without parsing
4058 /// the trace.
4059 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4060 ///
4061 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4062 /// `columnNumber`, which is how the reference prints one. A positionless error
4063 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4064 /// the reference raises it from `js_resolve_module`, where there is no position.
4065 pub(crate) fn syntax_error_plain(
4066 &mut self,
4067 error: &js_parse::SyntaxError,
4068 file: &str,
4069 ) -> Value {
4070 if error.positionless {
4071 return self.make_error("SyntaxError", &error.message);
4072 }
4073 self.syntax_error_at(
4074 file,
4075 error.span.start.line,
4076 error.span.start.column,
4077 &error.message,
4078 )
4079 }
4080
4081 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4082 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4083 let value = self.make_error("SyntaxError", message);
4084 if let Value::Object(object) = &value {
4085 let text = self.string(blamed);
4086 // `stack` is an own data property, and the reference keeps it
4087 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4088 object.define("stack", Property::with_attributes(text, true, false));
4089 let name = self.string(file);
4090 object.define("fileName", Property::with_attributes(name, true, true));
4091 object.define(
4092 "lineNumber",
4093 Property::with_attributes(Value::Int(line as i32), true, true),
4094 );
4095 object.define(
4096 "columnNumber",
4097 Property::with_attributes(Value::Int(column as i32), true, true),
4098 );
4099 }
4100 value
4101 }
4102
4103 /// Run a compiled script whose completion value is a function, returning it.
4104 ///
4105 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4106 /// get the closure out, which keeps the constant-pool plumbing in one place.
4107 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4108 self.run_script(code)
4109 }
4110
4111 /// The environment of a script or of any function compiled at global scope:
4112 /// every entry is a global binding, so each one resolves to the realm's cell.
4113 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4114 let mut cells = Vec::with_capacity(closure_vars.len());
4115 for closure_var in closure_vars {
4116 let cell = match closure_var.closure_type {
4117 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4118 if closure_var.is_lexical =>
4119 {
4120 // A lexical declaration: the cell is created here holding the
4121 // dead-zone marker, which is what makes the binding exist and
4122 // unreadable before its initialiser runs.
4123 self.declare_global(&closure_var.name, closure_var.is_const);
4124 self.realm.globals[&closure_var.name].clone()
4125 }
4126 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4127 // A `var` or function declaration becomes a property of the global
4128 // object, and it exists from here on — which is why
4129 // `print(v); var v = 1` prints `undefined` instead of raising.
4130 // Declaring it at instantiation time (rather than at the
4131 // initialiser) is also what makes it non-configurable: the store
4132 // then lands on an existing property instead of creating one.
4133 self.declare_var_global(&closure_var.name);
4134 // The cell is a placeholder that nothing indexes; it cannot be
4135 // omitted because the slot has to hold something.
4136 self.new_cell(Value::Undefined)
4137 }
4138 _ => {
4139 // An undeclared global is read by name; the cell is a
4140 // placeholder that nothing indexes.
4141 self.new_cell(Value::Undefined)
4142 }
4143 };
4144 cells.push(cell);
4145 }
4146 Gc::new(
4147 self.heap,
4148 ClosureEnv {
4149 cells,
4150 eval_scope: None,
4151 local_vars: None,
4152 local_phase: 1,
4153 },
4154 )
4155 }
4156
4157 /// Push a frame and run until it returns.
4158 pub(crate) fn execute(
4159 &mut self,
4160 code: Gc<CompiledCode>,
4161 env: Gc<ClosureEnv>,
4162 this: Value,
4163 args: Vec<Value>,
4164 callee: Value,
4165 ) -> JsResult<Value> {
4166 let depth = self.frames.len();
4167 if depth == 0 {
4168 // A throw that reached the host ends the *active* mode: the next one is catchable
4169 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4170 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4171 // for the throw that evaluation will raise.
4172 self.uncatchable = false;
4173 }
4174 self.push_frame(code, env, this, args, callee)?;
4175 loop {
4176 // The fast loop first: it runs whole runs of records with `pc` in a register.
4177 //
4178 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4179 // reads it again — a store, a load and two bounds checks that a loop body does
4180 // not need, because nothing outside the loop can run in between. This is the
4181 // classic split: advance a register, and only spill it when leaving.
4182 //
4183 // `Some(value)` means the function ended by running off the end of its
4184 // instruction array, which is a normal return.
4185 let step = match self.run_fast() {
4186 Ok(Some(value)) => Ok(Step::Return(value)),
4187 Ok(None) => self.step(),
4188 Err(signal) => Err(signal),
4189 };
4190 match step {
4191 Ok(Step::Continue) => {}
4192 Ok(Step::Return(value)) => {
4193 self.pop_frame();
4194 // A frame that ended in a `tail_call` hands its value straight to
4195 // its caller: nothing after the call can run, so every frame above
4196 // the callee unwinds with the same value. See [`Frame::tail`] —
4197 // the reference does not reuse frames either, so recursion depth
4198 // and the stack-overflow limit behave the same way.
4199 while self.frames.len() > depth && self.frame().tail {
4200 self.pop_frame();
4201 }
4202 if self.frames.len() == depth {
4203 return Ok(value);
4204 }
4205 // The caller resumes with the value on its stack.
4206 self.frames
4207 .last_mut()
4208 .expect("a caller is live")
4209 .stack
4210 .push(value);
4211 }
4212 Err(Signal::Throw(value)) => {
4213 // The host's standing request becomes the active mode for this unwind,
4214 // and is consumed here so it does not leak into the next throw.
4215 if self.uncatchable_next {
4216 self.uncatchable_next = false;
4217 self.uncatchable = true;
4218 }
4219 // An uncatchable throw walks past every `catch` on the way out. The
4220 // frames are still popped, because the values they hold have to be
4221 // dropped — only the search for a handler is skipped.
4222 if self.uncatchable {
4223 while self.frames.len() > depth {
4224 self.frames.pop();
4225 }
4226 return Err(Signal::Throw(value));
4227 }
4228 // A handler lives on the stack of the frame that is throwing —
4229 // `catch` pushed it there — so this frame gets the first chance
4230 // to catch before it is popped.
4231 let value = value;
4232 loop {
4233 if self.frames.len() <= depth {
4234 return Err(Signal::Throw(value));
4235 }
4236 if self.catch_here(value.clone()).is_some() {
4237 break;
4238 }
4239 self.frames.pop();
4240 }
4241 }
4242 // A `yield` in a frame that `execute` is running directly means a
4243 // generator body was entered as an ordinary call, which only happens if
4244 // the generator check in `call_or_push` was bypassed.
4245 Ok(Step::Suspend(_)) => {
4246 return Err(Signal::Throw(self.make_error(
4247 "InternalError",
4248 "a generator body ran as an ordinary call",
4249 )));
4250 }
4251 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4252 }
4253 }
4254 }
4255
4256 /// Install a handler for `value` if this frame has one, resuming at it.
4257 ///
4258 /// The scan is the reference's: walk the frame's stack downwards looking for the
4259 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4260 /// `0` is an enumerator marker rather than a handler — it exists so that a
4261 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4262 /// here and the unwinding continues.
4263 fn catch_here(&mut self, value: Value) -> Option<()> {
4264 let frame = self.frames.last_mut()?;
4265 while let Some(top) = frame.stack.pop() {
4266 if let Value::CatchOffset(offset) = top {
4267 if offset == 0 {
4268 continue;
4269 }
4270 frame.stack.push(value);
4271 frame.pc = offset as usize;
4272 return Some(());
4273 }
4274 }
4275 None
4276 }
4277
4278 fn push_frame(
4279 &mut self,
4280 code: Gc<CompiledCode>,
4281 env: Gc<ClosureEnv>,
4282 this: Value,
4283 mut args: Vec<Value>,
4284 callee: Value,
4285 ) -> JsResult<()> {
4286 // Two bounds, and the byte budget is the one that decides in practice. The
4287 // reference's message is `stack overflow` on an `InternalError`, not V8's
4288 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4289 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4290 let frame_cost = Self::frame_cost(&code);
4291 let stack_base = self.stack_used();
4292 if self.frames.len() >= self.max_frames
4293 || stack_base.saturating_add(frame_cost) > self.stack_limit
4294 {
4295 return Err(Signal::Throw(
4296 self.make_error("InternalError", "stack overflow"),
4297 ));
4298 }
4299 let arg_count = code.code.args.len();
4300 // How many were actually passed, which `arguments.length` reports and
4301 // `assert(x)` depends on: a call with one argument must not look like a call
4302 // with one argument and an explicit `undefined`.
4303 let passed = args.len();
4304 // Missing arguments are `undefined` in their slots; extra ones are dropped
4305 // from the slots but still reachable through `arguments`.
4306 //
4307 // A call that passes no more than the declared parameters needs **no** copy:
4308 // after the resize below, `args[..passed]` *is* the passed values. Only the
4309 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4310 // the rare case. This used to copy every call: one `Value` clone per argument
4311 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4312 let passed_overflow = (passed > arg_count).then(|| {
4313 let mut values = self.take_values(passed, Value::Undefined);
4314 values[..passed].clone_from_slice(&args[..passed]);
4315 values
4316 });
4317 // Only when the counts differ, which for the overwhelmingly common call — as many
4318 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4319 // lengths is two length compares and nothing else, but this is the hottest few
4320 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4321 if passed != arg_count {
4322 args.resize(arg_count, Value::Undefined);
4323 args.truncate(arg_count);
4324 }
4325 let cell_count = code.code.var_ref_count as usize;
4326 let mut cells = Vec::with_capacity(cell_count);
4327 for _ in 0..cell_count {
4328 cells.push(self.new_cell(Value::Undefined));
4329 }
4330 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4331 // A captured argument lives in its cell, not in the argument slot, so the
4332 // incoming value has to be moved there before the body runs.
4333 for (slot, cell) in code.arg_cell.iter().enumerate() {
4334 if *cell >= 0
4335 && let Some(value) = args.get(slot).cloned()
4336 {
4337 cells[*cell as usize].set(value);
4338 }
4339 }
4340 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4341 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4342 // reports `object`. Strict mode passes the value through untouched.
4343 let this = if code.code.strict {
4344 this
4345 } else if this.is_nullish() {
4346 Value::Object(self.realm.global.clone())
4347 } else if matches!(this, Value::Object(_)) {
4348 this
4349 } else {
4350 match crate::builtins::this_object(self, &this) {
4351 Ok(boxed) => Value::Object(boxed),
4352 Err(_) => this,
4353 }
4354 };
4355 let stack_depth = code.code.stack_size as usize + 1;
4356 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4357 // out of the same recycle pool the locals did.
4358 let stack = self.take_values(stack_depth, Value::Undefined);
4359 self.frames.push(Frame {
4360 code,
4361 env,
4362 this,
4363 args,
4364 passed_count: passed,
4365 passed_overflow: passed_overflow.map(Box::new),
4366 locals,
4367 cells,
4368 local_vars: None,
4369 // Exactly the depth the compiler computed, so the operand stack never
4370 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4371 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4372 // the buffer between calls, so "exactly" costs nothing after the first one.
4373 stack,
4374 pc: 0,
4375 at: 0,
4376 callee,
4377 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4378 cost: frame_cost,
4379 stack_base,
4380 tail: false,
4381 });
4382 Ok(())
4383 }
4384
4385 /// A value buffer of `len` slots, from the recycle pool when there is one.
4386 ///
4387 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4388 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4389 // A frame with no locals asks for nothing, and that is most frames: taking a
4390 // buffer out of the pool, clearing it and resizing it to zero is four operations
4391 // and a pool pop for an empty `Vec`, which is free to construct.
4392 if len == 0 {
4393 return Vec::new();
4394 }
4395 let mut buffer = self.free_values.pop().unwrap_or_default();
4396 buffer.clear();
4397 buffer.resize(len, fill);
4398 buffer
4399 }
4400
4401 /// Return a finished frame's value buffers for the next call to reuse.
4402 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4403 for mut buffer in [
4404 std::mem::take(&mut frame.locals),
4405 frame
4406 .passed_overflow
4407 .take()
4408 .map(|buffer| *buffer)
4409 .unwrap_or_default(),
4410 std::mem::take(&mut frame.stack),
4411 ] {
4412 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4413 // GC root: it kept every value the frame held reachable, which is invisible
4414 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4415 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4416 // exactly that within one run — the target `{}` of a finished IIFE was still
4417 // in its operand stack, in the pool.
4418 buffer.clear();
4419 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4420 // fill the pool with nothing to offer.
4421 if free_values.len() < RECYCLE_SLOTS
4422 && buffer.capacity() > 0
4423 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4424 {
4425 free_values.push(buffer);
4426 }
4427 }
4428 }
4429
4430 /// Pop a finished frame and keep its buffers.
4431 ///
4432 /// Every place that drops a frame goes through here: a recycled buffer is also where
4433 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4434 /// nothing but the reuse.
4435 fn pop_frame(&mut self) -> Option<()> {
4436 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4437 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4438 let last = self.frames.len().checked_sub(1)?;
4439 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4440 self.frames.truncate(last);
4441 Some(())
4442 }
4443
4444 /// Poll the host's interrupt handler, if one is installed.
4445 ///
4446 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4447 /// one `Option` test, and with no handler installed the whole function is that test —
4448 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4449 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4450 #[inline]
4451 fn check_interrupt(&mut self) -> JsResult<()> {
4452 if self.interrupt.is_none() {
4453 return Ok(());
4454 }
4455 if self.interrupt_counter > 0 {
4456 self.interrupt_counter -= 1;
4457 return Ok(());
4458 }
4459 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4460 // The closure is taken out for the duration so that a handler which re-enters the
4461 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4462 let mut handler = self.interrupt.take().expect("checked above");
4463 let abort = handler();
4464 self.interrupt = Some(handler);
4465 if abort {
4466 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4467 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4468 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4469 // documentation says.
4470 self.uncatchable = true;
4471 return Err(Signal::Throw(
4472 self.make_error("InternalError", "interrupted"),
4473 ));
4474 }
4475 Ok(())
4476 }
4477
4478 /// A memory checkpoint: does the heap still fit under its limit?
4479 ///
4480 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4481 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4482 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4483 /// only at calls would let it run until the machine died, which is the exact failure
4484 /// `--memory-limit` exists to prevent.
4485 ///
4486 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4487 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4488 /// script that catches it, drops the reference and carries on is legitimate: measured
4489 /// on `qjs --memory-limit 1M`, the engine recovers.
4490 fn check_memory(&mut self) -> JsResult<()> {
4491 // One `Cell` read and a predictable branch when no limit is set, and an integer
4492 // compare when one is. Containers report their own growth as it happens
4493 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4494 // walking it here was the first version and it was O(live) per 256 instructions,
4495 // which turned a 100k-element push loop into a five-minute one.
4496 let Some(limit) = self.heap.memory_limit() else {
4497 return Ok(());
4498 };
4499 let used = self.heap.used_bytes();
4500 if used <= limit {
4501 // Back under the limit — a collection or a dropped reference did it. The next
4502 // time it goes over is a new failure, not a repeat of this one.
4503 self.oom_reported_at = 0;
4504 return Ok(());
4505 }
4506 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4507 // block runs normally after `out of memory` — it allocates nothing, so nothing
4508 // fails. A check that re-fired on every instruction made the handler itself throw,
4509 // which is a dead end: the error became unobservable from script.
4510 //
4511 // Comparing against the total at the last report gives the same behaviour: the
4512 // handler runs while the total is unchanged, and the very next allocation over the
4513 // limit fails.
4514 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4515 {
4516 return Ok(());
4517 }
4518 self.oom_reported_at = used;
4519 Err(Signal::Throw(
4520 self.make_error("InternalError", "out of memory"),
4521 ))
4522 }
4523
4524 /// Fail before allocating `payload` bytes, if they would not fit.
4525 ///
4526 /// For the allocations whose size comes from script data — `new Array(n)`,
4527 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4528 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4529 /// answering NULL for the one big request.
4530 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4531 if self.heap.fits(payload) {
4532 return Ok(());
4533 }
4534 Err(Signal::Throw(
4535 self.make_error("InternalError", "out of memory"),
4536 ))
4537 }
4538
4539 /// Bytes of frame state the live call chain accounts for.
4540 pub fn stack_used(&self) -> usize {
4541 match self.frames.last() {
4542 Some(frame) => frame.stack_base + frame.cost,
4543 None => 0,
4544 }
4545 }
4546
4547 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4548 ///
4549 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4550 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4551 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4552 /// instead. That is the whole difference between the two models: it rations C stack, we
4553 /// ration frame state, and both quantities are dominated by the value slots — which is
4554 /// why the two depths come out comparable rather than merely proportional.
4555 fn frame_cost(code: &CompiledCode) -> usize {
4556 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4557 std::mem::size_of::<Frame>()
4558 + std::mem::size_of::<Value>() * slots
4559 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4560 }
4561
4562 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4563 ///
4564 /// Only names the eval created are here: a name the frame already declared statically
4565 /// is written through to its own slot instead, so this cannot shadow a real local.
4566 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4567 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4568 let (local_vars, phase) = self.visible_local_vars()?;
4569 if !local_vars.contains(name) {
4570 return None;
4571 }
4572 local_vars.get(name, phase)
4573 }
4574
4575 /// The variables a direct `eval` declared, as the code currently running sees them.
4576 ///
4577 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4578 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4579 /// else it is the current frame's, falling back to the frame the closure was created
4580 /// in.
4581 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4582 ///
4583 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4584 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4585 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4586 /// just to be asked `is_none`.
4587 fn has_visible_local_vars(&self) -> bool {
4588 let index = match self.eval_caller.flatten() {
4589 Some(caller) => caller,
4590 None => match self.frames.len().checked_sub(1) {
4591 Some(top) => top,
4592 None => return false,
4593 },
4594 };
4595 match self.frames.get(index) {
4596 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4597 None => false,
4598 }
4599 }
4600
4601 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4602 // While an `eval` runs, its own frame is on top but its variable environment is
4603 // the *caller's* — so the caller is what the lookup has to start from.
4604 let (index, phase) = match self.eval_caller.flatten() {
4605 Some(caller) => (
4606 caller,
4607 if self.in_parameter_list_at(caller) {
4608 0
4609 } else {
4610 1
4611 },
4612 ),
4613 None => (
4614 self.frames.len().checked_sub(1)?,
4615 if self.in_parameter_list() { 0 } else { 1 },
4616 ),
4617 };
4618 let frame = self.frames.get(index)?;
4619 // The frame's own variables, or — for an arrow, which has no variable environment
4620 // of its own — the one it was created in, which `ClosureEnv` carries.
4621 if let Some(local_vars) = frame.local_vars.clone() {
4622 return Some((local_vars, phase));
4623 }
4624 frame
4625 .env
4626 .local_vars
4627 .clone()
4628 .map(|local_vars| (local_vars, frame.env.local_phase))
4629 }
4630
4631 /// Whether the innermost frame is still evaluating its parameter list.
4632 ///
4633 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4634 /// and a closure created there may only see that much of [`LocalVars`].
4635 fn in_parameter_list(&self) -> bool {
4636 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4637 }
4638
4639 /// [`Interp::in_parameter_list`] for a specific frame.
4640 fn in_parameter_list_at(&self, frame: usize) -> bool {
4641 let Some(frame) = self.frames.get(frame) else {
4642 return false;
4643 };
4644 let code = &frame.code.code;
4645 if !code.has_parameter_expressions {
4646 return false;
4647 }
4648 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4649 // function as its body and let a direct `eval` act accordingly.
4650 if code.body_start == (0, 0) {
4651 return false;
4652 }
4653 match code.position_at(frame.at as u32) {
4654 Some(position) => position < code.body_start,
4655 None => false,
4656 }
4657 }
4658
4659 fn frame(&self) -> &Frame {
4660 self.frames.last().expect("a frame is live")
4661 }
4662
4663 fn frame_mut(&mut self) -> &mut Frame {
4664 self.frames.last_mut().expect("a frame is live")
4665 }
4666
4667 // -- slot access --------------------------------------------------------
4668
4669 /// Move a local's value out, leaving `undefined` in the slot.
4670 ///
4671 /// `None` for a captured slot: its value lives in a cell shared with every closure
4672 /// that closed over it, so it can never be exclusively ours and must not be taken.
4673 ///
4674 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4675 /// for every read and fatal for this one — a clone is exactly the second handle that
4676 /// rules out growing the string in place.
4677 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4678 let frame = self.frames.last_mut()?;
4679 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4680 return None;
4681 }
4682 frame
4683 .locals
4684 .get_mut(slot)
4685 .map(|value| std::mem::replace(value, Value::Undefined))
4686 }
4687
4688 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4689 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4690 ///
4691 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4692 /// it** — the value is put back before the general path runs — so a `valueOf` that
4693 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4694 /// error as it would have without the fusion. This is why the in-place attempt is a
4695 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4696 /// a wrong answer with a good excuse.
4697 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4698 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4699 // is put back on every path that does not append. An earlier version wrote the two
4700 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4701 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4702 // through with its value already taken and dropped: the general path below then
4703 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4704 // A wrong answer, from an optimisation, with every test green.
4705 if matches!(right, Value::String(_))
4706 && let Some(taken) = self.take_loc(slot)
4707 {
4708 if let Value::String(mut left) = taken {
4709 let appended = match left.get_mut() {
4710 Some(string) => string.append_in_place(
4711 // The pattern is the one `matches!` just checked.
4712 match &right {
4713 Value::String(text) => text,
4714 _ => unreachable!("guarded above"),
4715 },
4716 ),
4717 None => None,
4718 };
4719 self.put_loc(slot, Value::String(left));
4720 if let Some(added) = appended {
4721 // The buffer grew where it stood, so the heap's running total has to
4722 // be told: `measure_used` would report the new length, and the two must
4723 // agree or the subtraction at free time leaves the counter wrong.
4724 self.heap.adjust_payload(added as isize);
4725 return Ok(());
4726 }
4727 } else {
4728 self.put_loc(slot, taken);
4729 }
4730 }
4731 // The two-number case, without an operand stack round trip. Everything below
4732 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4733 // store it — five operations and two `Value` clones for what is one integer add.
4734 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4735 // for string append and never got the numeric half, so `t += i` — a counting loop
4736 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4737 let left = self.get_loc(slot);
4738 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4739 self.put_loc(
4740 slot,
4741 match a.checked_add(*b) {
4742 Some(sum) => Value::Int(sum),
4743 None => Value::Float(*a as f64 + *b as f64),
4744 },
4745 );
4746 return Ok(());
4747 }
4748 self.push(left);
4749 self.push(right);
4750 self.binary_add()?;
4751 let value = self.pop();
4752 self.put_loc(slot, value);
4753 Ok(())
4754 }
4755
4756 fn get_arg(&self, slot: usize) -> Value {
4757 self.frame().read_arg(slot)
4758 }
4759
4760 fn put_arg(&mut self, slot: usize, value: Value) {
4761 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4762 if cell == -1 {
4763 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4764 *slot = value;
4765 }
4766 } else {
4767 self.frame().cells[cell as usize].set(value);
4768 }
4769 }
4770
4771 fn get_loc(&self, slot: usize) -> Value {
4772 // The cell mapping is `-1` for every slot that was not captured — which is all of
4773 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4774 // so the common case is one array read and a clone: 20% of every loop iteration
4775 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4776 // sample of `dispatch:arith`).
4777 self.frame().read_loc(slot)
4778 }
4779
4780 fn put_loc(&mut self, slot: usize, value: Value) {
4781 // One borrow instead of three, and the cell check on the frame we already hold.
4782 let frame = self.frames.last_mut().expect("a frame is live");
4783 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4784 if cell < 0 {
4785 if let Some(slot) = frame.locals.get_mut(slot) {
4786 *slot = value;
4787 }
4788 } else if let Some(cell) = frame.cells.get(cell as usize) {
4789 cell.set(value);
4790 }
4791 }
4792
4793 // -- globals ------------------------------------------------------------
4794
4795 /// The name a global-slot operand refers to.
4796 fn global_name(&self, slot: usize) -> String {
4797 self.frame()
4798 .code
4799 .code
4800 .closure_vars
4801 .get(slot)
4802 .map(|c| c.name.clone())
4803 .unwrap_or_default()
4804 }
4805
4806 /// The facts about a global binding that decide where it lives.
4807 ///
4808 /// A script's globals split in two, and the split is observable: `var` and
4809 /// function declarations become properties of the global object (`globalThis.v`
4810 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4811 /// declarations live in the global *lexical* environment and are invisible there
4812 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4813 /// `is_lexical` flag means the answer is already in the bytecode.
4814 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4815 let name = self.global_name(slot);
4816 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4817 // while forwarding a reference through a nested function is built with the
4818 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4819 // closure. Presence in the realm's lexical table is the same fact, recorded
4820 // once, and every slot sees it.
4821 let lexical = self.realm.globals.contains_key(&name);
4822 let is_const = self.realm.lexical_consts.contains(&name);
4823 (name, lexical, is_const)
4824 }
4825
4826 /// The value of `name` in the innermost active `with` object, if any.
4827 ///
4828 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4829 /// innermost frame first and innermost block first within one. Walking frames rather
4830 /// than keeping a separate stack is what makes a closure called from inside a `with`
4831 /// see it, and what keeps the object alive only as long as the block is.
4832 /// The innermost active `with` object that has `name`, if any.
4833 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4834 let objects = self.eval_with.clone().unwrap_or_default();
4835 for object in objects {
4836 let key = self.string(name.to_string());
4837 if self
4838 .has_property(&key, &Value::Object(object.clone()))
4839 .ok()?
4840 {
4841 return Some(object);
4842 }
4843 }
4844 None
4845 }
4846
4847 /// Every active `with` object, innermost first.
4848 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4849 let mut objects = Vec::new();
4850 for frame in self.frames.iter().rev() {
4851 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4852 if var.kind != js_compile::VarKind::With {
4853 continue;
4854 }
4855 // A captured binding lives in its cell and not in the slot list, so the
4856 // cell is consulted first — a closure created inside the block is exactly
4857 // what makes the object captured. Before the store runs the slot still
4858 // holds `undefined`, and a `with` object is always boxed, so a non-object
4859 // entry is simply not in scope yet.
4860 let value = frame
4861 .code
4862 .loc_cell
4863 .get(index)
4864 .copied()
4865 .filter(|cell| *cell >= 0)
4866 .and_then(|cell| frame.cells.get(cell as usize))
4867 .map(|cell| cell.get())
4868 .or_else(|| frame.locals.get(index).cloned());
4869 if let Some(Value::Object(object)) = value {
4870 objects.push(object);
4871 }
4872 }
4873 }
4874 objects
4875 }
4876
4877 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4878 for object in self.eval_with.clone().unwrap_or_default() {
4879 let key = self.string(name.to_string());
4880 if self.has_property(&key, &Value::Object(object.clone()))? {
4881 return Ok(Some(self.read_field(&Value::Object(object), name)?));
4882 }
4883 }
4884 Ok(None)
4885 }
4886
4887 /// Whether every scope between here and the global object is an ordinary one.
4888 ///
4889 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4890 /// bytecode resolved; when any is live the general path has to run in full order. When
4891 /// none is — every ordinary program — a global read is a property read and nothing
4892 /// else, and that is worth caching.
4893 fn scopes_are_plain(&self) -> bool {
4894 self.eval_caller.is_none()
4895 && self.eval_with.is_none()
4896 && self.eval_arguments.is_none()
4897 && self.eval_bindings.is_empty()
4898 && self.eval_scope.is_none()
4899 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4900 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4901 // its `ClosureEnv`, so the test has to be the same one the general path makes.
4902 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4903 // upstream corpus caught and no unit test did.
4904 && !self.has_visible_local_vars()
4905 && self.frame().env.eval_scope.is_none()
4906 }
4907
4908 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4909 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4910 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4911 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4912 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4913 // borrow outlive the `&mut self` the lookup needs.
4914 //
4915 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4916 // forwarded through a nested function has its flags cleared, so the flag cannot
4917 // be believed.
4918 let code = self.frame().code.clone();
4919 let name = code
4920 .code
4921 .closure_vars
4922 .get(slot)
4923 .map(|c| c.name.as_str())
4924 .unwrap_or_default();
4925 let lexical = self.realm.globals.contains_key(name);
4926 // The common case, first: an ordinary global `var`, with a cache in front of the
4927 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4928 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4929 // cache hit and return without touching any of it.
4930 if !lexical && self.scopes_are_plain() {
4931 return self.get_plain_global(name, slot);
4932 }
4933 if name == "arguments"
4934 && let Some(arguments) = &self.eval_arguments
4935 {
4936 return Ok(arguments.clone());
4937 }
4938 // A `with` block around the *call site* is part of the scope an `eval` sees, so
4939 // the objects live when the eval started are consulted before anything else. The
4940 // snapshot is taken at entry rather than scanning the frames on every read: a
4941 // block that has already finished still leaves its object in the slot, and a
4942 // bytecode read outside the block must not see it.
4943 if let Some(value) = self.with_lookup(name)? {
4944 return Ok(value);
4945 }
4946 // A variable a direct `eval` declared shadows everything the compiler resolved,
4947 // including an enclosing function's binding: the eval put it in the caller's own
4948 // variable environment, which is nearer than any captured scope.
4949 if let Some((local_vars, phase)) = self.visible_local_vars()
4950 && let Some(cell) = local_vars.get(name, phase)
4951 {
4952 return Ok(cell.get());
4953 }
4954 // The frame that called `eval` is the innermost scope the eval'd code sees, so
4955 // its local `a` wins over a global `a`.
4956 if let Some(value) = self.eval_binding_value(name) {
4957 return Ok(value);
4958 }
4959 // A closure created by an `eval` resolves its free names against the bindings
4960 // that eval saw, even after the eval (and its frames) are gone.
4961 if let Some(cell) = self
4962 .frame()
4963 .env
4964 .eval_scope
4965 .as_ref()
4966 .and_then(|scope| scope.get(name))
4967 {
4968 let value = cell.get();
4969 if matches!(value, Value::Uninitialized) {
4970 return Err(self.throw_reference(name));
4971 }
4972 return Ok(value);
4973 }
4974 // A binding declared by the strict `eval` currently running shadows anything
4975 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4976 if let Some(scope) = &self.eval_scope
4977 && let Some(value) = scope.get(name)
4978 {
4979 return Ok(value.clone());
4980 }
4981 if lexical {
4982 // A lexical global is a binding in a side table, so the dead zone is
4983 // visible and it is nowhere on the global object.
4984 if let Some(cell) = self.realm.globals.get(name) {
4985 let value = cell.get();
4986 if matches!(value, Value::Uninitialized) {
4987 return Err(self.throw_reference(name));
4988 }
4989 return Ok(value);
4990 }
4991 return Err(self.throw_reference(name));
4992 }
4993 // A `var` global is an ordinary property, so the prototype chain and the
4994 // global object's own builtins are all reachable through it.
4995 match self.get_property(&self.realm.global.clone(), name)? {
4996 Some(value) => Ok(value),
4997 None => Err(self.throw_reference(name)),
4998 }
4999 }
5000
5001 /// Read a plain global `var`: a cached own data property, or the full lookup.
5002 ///
5003 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5004 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5005 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5006 let object = self.realm.global.clone();
5007 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5008 if let Some(cached) = &self.global_cache[site]
5009 && object.upgrades_to(&cached.object)
5010 && let Some(value) = object.data_property_at(cached.index, name)
5011 {
5012 return Ok(value);
5013 }
5014 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5015 // chain exactly as before, then remember the answer if it is worth remembering.
5016 let Some(value) = self.get_property(&object, name)? else {
5017 return Err(self.throw_reference(name));
5018 };
5019 if let Some(index) = object.own_data_index(name) {
5020 self.global_cache[site] = Some(GlobalCache {
5021 object: object.downgrade(),
5022 index,
5023 });
5024 }
5025 Ok(value)
5026 }
5027
5028 /// Store to a global binding.
5029 ///
5030 /// Returns a signal when the store is refused: a `const` global may only be
5031 /// written by its initialiser, and a non-configurable `var` global may not be
5032 /// deleted but is always writable.
5033 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5034 let (name, lexical, is_const) = self.global_binding(slot);
5035
5036 // An assignment inside a `with` writes through to the object that supplies the
5037 // name, which for an `eval` means consulting the same chain `get_global` does.
5038 if let Some(owner) = self.with_owner(&name) {
5039 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5040 return Ok(());
5041 }
5042 // A variable the running eval *declared* takes the write before any caller
5043 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5044 // environment even when an enclosing function has a `var c` of its own.
5045 if self.eval_caller.flatten().is_some()
5046 && let Some((local_vars, phase)) = self.visible_local_vars()
5047 && local_vars.contains(&name)
5048 && let Some(cell) = local_vars.get(&name, phase)
5049 {
5050 cell.set(value);
5051 return Ok(());
5052 }
5053 // A binding of the frame that called `eval` takes the write, which is what
5054 // makes `f("a = 3")` change the caller's `a`.
5055 if self.set_eval_binding(&name, &value)? {
5056 return Ok(());
5057 }
5058 // A closure that outlived its `eval` writes through to the same cell it reads.
5059 if let Some(cell) = self
5060 .frame()
5061 .env
5062 .eval_scope
5063 .as_ref()
5064 .and_then(|scope| scope.get(&name))
5065 .cloned()
5066 {
5067 cell.set(value);
5068 return Ok(());
5069 }
5070 // Inside a strict `eval`, a name it declared itself is stored there. An
5071 // *assignment* to a name nobody declared is not a declaration, so it falls
5072 // through: strict mode raises `ReferenceError` for it, which is what
5073 // `eval("1 + (@not_def = 1)")` has to do.
5074 if let Some(scope) = self.eval_scope.as_mut()
5075 && scope.contains_key(&name)
5076 {
5077 scope.insert(name, value);
5078 return Ok(());
5079 }
5080 if lexical {
5081 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5082 if is_const && !matches!(cell.get(), Value::Uninitialized) {
5083 return Err(self.read_only_global(&name));
5084 }
5085 cell.set(value);
5086 return Ok(());
5087 }
5088 // Writing an undeclared lexical global is a `ReferenceError` in strict
5089 // mode and a silent global creation otherwise; creating the cell here
5090 // keeps both paths from losing the value.
5091 let cell = self.new_cell(value);
5092 self.realm.globals.insert(name, cell);
5093 return Ok(());
5094 }
5095 // A variable a direct `eval` declared in this call shadows the global object, even
5096 // when the global already has a property of that name — `var c = "global"` at the
5097 // top level must not capture `eval("var c = 1")` inside a function.
5098 if let Some((local_vars, phase)) = self.visible_local_vars()
5099 && local_vars.contains(&name)
5100 && let Some(cell) = local_vars.get(&name, phase)
5101 {
5102 cell.set(value);
5103 return Ok(());
5104 }
5105 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5106 // remembered a global's slot index since M12b, but the *store* side never did: it
5107 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5108 // global object's whole table — which holds every builtin — on every assignment to
5109 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5110 // full global lookup per iteration; measured with a counter, `s` as a global made
5111 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5112 //
5113 // Re-validated exactly like the read: same object, same index, still the name, and
5114 // — the one extra check a store needs — still writable. A global that is an
5115 // accessor, non-writable, or inherited fails here and falls through to the full
5116 // path below, which reports the failure the way it always did.
5117 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5118 let global = self.realm.global.clone();
5119 if let Some(cached) = &self.global_cache[site]
5120 && global.upgrades_to(&cached.object)
5121 && global.write_data_at(cached.index, &name, value.clone())
5122 {
5123 return Ok(());
5124 }
5125 match global.own_property(&name) {
5126 // A `var` global is writable, so the store goes straight through — but
5127 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5128 // store (a non-writable or accessor-without-setter global) is a silent
5129 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5130 // split every other assignment has.
5131 Some(_) => {
5132 let on_failure = if self.current_strict() {
5133 DeleteFailure::Throw
5134 } else {
5135 DeleteFailure::Ignore
5136 };
5137 let result = self.set_property_with(&global, &name, value, on_failure);
5138 // Teach the cache the slot for a plain writable own data property, which is
5139 // what a declared `var` is. Without this the fast path above could never
5140 // fire for a global that is only ever *written* — its entry would have to
5141 // be put there by a read of the same slot, and a write-only loop has none.
5142 if result.is_ok()
5143 && let Some(index) = global.own_data_index(&name)
5144 {
5145 self.global_cache[site] = Some(GlobalCache {
5146 object: global.downgrade(),
5147 index,
5148 });
5149 }
5150 result
5151 }
5152 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5153 // declaration creates a *configurable* property, which is what makes it
5154 // deletable and is the one way a global differs from a declared `var`.
5155 // In strict mode the same store is a `ReferenceError` instead: that is the
5156 // whole point of strict mode, and creating the global silently meant
5157 // `"use strict"; x = 1` looked like it worked.
5158 None => {
5159 if self.current_strict() {
5160 return Err(self.throw_reference(&name));
5161 }
5162 // A direct eval declares here rather than on the global object: its
5163 // `var`s belong to the caller's variable environment. `declare_eval_local`
5164 // also covers a plain assignment to a variable an earlier eval made.
5165 if let Some(cell) = self.declare_eval_local(&name) {
5166 cell.set(value);
5167 return Ok(());
5168 }
5169 global.define_data(&name, value);
5170 Ok(())
5171 }
5172 }
5173 }
5174
5175 /// The value of a binding of the frame that called `eval`, if there is one.
5176 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5177 let binding = self
5178 .eval_bindings
5179 .iter()
5180 .find(|binding| binding.name == name)?;
5181 let owner = self.frames.get(binding.frame)?;
5182 let (slot, index) = (binding.slot, binding.index);
5183 Some(match slot {
5184 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5185 cell if cell >= 0 => owner
5186 .cells
5187 .get(cell as usize)
5188 .map(|cell| cell.get())
5189 .unwrap_or(Value::Undefined),
5190 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5191 },
5192 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5193 cell if cell >= 0 => owner
5194 .cells
5195 .get(cell as usize)
5196 .map(|cell| cell.get())
5197 .unwrap_or(Value::Undefined),
5198 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5199 },
5200 })
5201 }
5202
5203 /// Write to a binding of the frame that called `eval`.
5204 ///
5205 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5206 /// matched binding can still refuse the store, which is why this is fallible: a
5207 /// `const` is read-only everywhere, and a named function expression's own name is
5208 /// read-only in strict mode.
5209 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5210 let Some(binding) = self
5211 .eval_bindings
5212 .iter()
5213 .find(|binding| binding.name == name)
5214 else {
5215 return Ok(false);
5216 };
5217 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5218 let strict = self.current_strict();
5219 let Some(owner) = self.frames.get_mut(frame) else {
5220 return Ok(false);
5221 };
5222 match slot {
5223 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5224 cell if cell >= 0 => {
5225 if let Some(cell) = owner.cells.get(cell as usize) {
5226 cell.set(value.clone());
5227 }
5228 }
5229 _ => {
5230 if let Some(slot) = owner.args.get_mut(index) {
5231 *slot = value.clone();
5232 }
5233 }
5234 },
5235 EvalSlot::Local => {
5236 let declared = owner.code.code.vars.get(index);
5237 // A `const` is read-only even through `eval`. The realm records this for
5238 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5239 // the bytecode, so this is where it has to be enforced.
5240 if declared.is_some_and(|var| var.is_const) {
5241 return Err(self.read_only_local(name));
5242 }
5243 // The name of a named function expression is read-only too, but only
5244 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5245 // such a name is ignored, the same as a direct store would be.
5246 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5247 return if strict {
5248 Err(self.read_only_local(name))
5249 } else {
5250 Ok(true)
5251 };
5252 }
5253 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5254 cell if cell >= 0 => {
5255 if let Some(cell) = owner.cells.get(cell as usize) {
5256 cell.set(value.clone());
5257 }
5258 }
5259 _ => {
5260 if let Some(slot) = owner.locals.get_mut(index) {
5261 *slot = value.clone();
5262 }
5263 }
5264 }
5265 }
5266 }
5267 Ok(true)
5268 }
5269
5270 /// The `TypeError` an assignment to a read-only binding raises.
5271 fn read_only_local(&self, name: &str) -> Signal {
5272 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5273 }
5274
5275 /// Declare `name` as a variable of the frame that called the running `eval`.
5276 ///
5277 /// `None` when there is no direct eval in progress, or it was called from the top
5278 /// level — then the caller's variable environment *is* the global one and the
5279 /// existing path is right.
5280 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5281 let caller = self.eval_caller.flatten()?;
5282 // The bottom frame is the top-level script, whose variable environment *is* the
5283 // global one — so `eval("var x = 1")` at the top level still creates a global.
5284 if caller == 0 {
5285 return None;
5286 }
5287 // A name the eval's *own* variable environment already binds is not a new
5288 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5289 // `arguments`, and creating a second binding would leave the first — the one
5290 // closures read — untouched. A binding of an *outer* frame does not count: a
5291 // declaration shadows it rather than writing through.
5292 if self
5293 .eval_bindings
5294 .iter()
5295 .any(|binding| binding.name == name && binding.frame == caller)
5296 {
5297 return None;
5298 }
5299 let phase = if self.in_parameter_list_at(caller) {
5300 0
5301 } else {
5302 1
5303 };
5304 self.frame_local_vars(caller)?;
5305 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5306 if let Some(cell) = local_vars.get(name, 1) {
5307 return Some(cell);
5308 }
5309 let cell = self.new_cell(Value::Undefined);
5310 Some(local_vars.declare(name, phase, cell))
5311 }
5312
5313 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5314 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5315 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5316 return Some(local_vars.clone());
5317 }
5318 let local_vars = Gc::new(self.heap, LocalVars::new());
5319 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5320 Some(local_vars)
5321 }
5322
5323 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5324 /// property of the global object. Used to decide whether a store inside an
5325 /// `eval` writes through to the realm or declares a binding of its own.
5326 ///
5327 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5328 /// write to `Object.prototype.toString`, and must not shadow it either.
5329 fn global_knows(&mut self, name: &str) -> bool {
5330 if self.realm.globals.contains_key(name) {
5331 return true;
5332 }
5333 self.realm.global.own_property(name).is_some()
5334 }
5335
5336 /// Whether the code currently running is strict.
5337 ///
5338 /// Read off the frame's function, which is where the parser's answer ended up; a
5339 /// native function never runs strict-only checks, and there is no frame at all
5340 /// before the first script.
5341 pub fn current_strict(&self) -> bool {
5342 self.frames
5343 .last()
5344 .is_some_and(|frame| frame.code.code.strict)
5345 }
5346
5347 /// Initialise a declared global, which is what ends its dead zone.
5348 ///
5349 /// A `var` global becomes a property of the global object: writable, so a later
5350 /// assignment goes through, and non-configurable, so `delete` refuses.
5351 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5352 let (name, lexical, _) = self.global_binding(slot);
5353 // A `var` declared by the strict `eval` currently running belongs to the
5354 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5355 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5356 // initialised in place, which is what a re-declaration inside eval does.
5357 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5358 self.eval_scope
5359 .as_mut()
5360 .expect("checked above")
5361 .insert(name, value);
5362 return Ok(());
5363 }
5364 if let Some(scope) = self.eval_scope.as_mut()
5365 && scope.contains_key(&name)
5366 {
5367 scope.insert(name, value);
5368 return Ok(());
5369 }
5370 if lexical {
5371 // The cell exists (created at declaration time) holding the dead-zone
5372 // marker; storing the value is what makes the binding readable.
5373 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5374 cell.set(value);
5375 return Ok(());
5376 }
5377 let cell = self.new_cell(value);
5378 self.realm.globals.insert(name, cell);
5379 return Ok(());
5380 }
5381 let global = self.realm.global.clone();
5382 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5383 // to answer `false` and leave the binding in place. `with_attributes` ties
5384 // `configurable` to `writable`, so the property is built field by field.
5385 global.define(
5386 &name,
5387 Property {
5388 value: Some(value),
5389 writable: true,
5390 enumerable: true,
5391 configurable: false,
5392 ..Property::default()
5393 },
5394 );
5395 Ok(())
5396 }
5397
5398 /// The `TypeError` a store to a `const` global raises.
5399 fn read_only_global(&self, name: &str) -> Signal {
5400 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5401 }
5402
5403 // -- properties ---------------------------------------------------------
5404
5405 /// Read `object[key]`, following the prototype chain.
5406 ///
5407 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5408 /// lookup returns the owner rather than just the value.
5409 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5410 self.get_property_key(object, &PropertyKey::from(key))
5411 }
5412
5413 /// [`Interp::get_property`] with a key that may be a symbol.
5414 pub fn get_property_key(
5415 &mut self,
5416 object: &Gc<JsObject>,
5417 key: &PropertyKey,
5418 ) -> JsResult<Option<Value>> {
5419 self.get_property_key_for(object, None, key)
5420 }
5421
5422 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5423 ///
5424 /// The receiver matters when the property is found on a *prototype*: a getter has to
5425 /// see the object the read started from. For a primitive that is the primitive
5426 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5427 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5428 /// the owner.
5429 pub fn get_property_key_for(
5430 &mut self,
5431 object: &Gc<JsObject>,
5432 receiver: Option<&Value>,
5433 key: &PropertyKey,
5434 ) -> JsResult<Option<Value>> {
5435 // A proxy answers for itself, before any of the shortcuts below: `new
5436 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5437 // have.
5438 if object.proxy_state().is_some() {
5439 let receiver = receiver
5440 .cloned()
5441 .unwrap_or_else(|| Value::Object(object.clone()));
5442 return self.proxy_get(object, &receiver, key);
5443 }
5444 // A host class's `get_property` trap replaces the whole read, prototype walk
5445 // included — that is what makes a native accessor free rather than a JavaScript
5446 // getter call.
5447 if let Some(exotic) = object.exotic() {
5448 let receiver_value = receiver
5449 .cloned()
5450 .unwrap_or_else(|| Value::Object(object.clone()));
5451 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5452 return Ok(Some(value));
5453 }
5454 // With no `get_property` trap, a `get_own_property` trap still answers for the
5455 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5456 // and the hook lives exactly there. A key the trap reports as absent is still
5457 // looked for on the prototype, which is why the search resumes *above*.
5458 if let Some(property) = exotic.get_own_property(self, object, key)? {
5459 return match property {
5460 Some(property) => self.read_property(property, object, receiver),
5461 None => match lookup_key_above(object, key) {
5462 Some((_, property)) => self.read_property(property, object, receiver),
5463 None => Ok(None),
5464 },
5465 };
5466 }
5467 }
5468 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5469 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5470 // The `[[Get]]` short-circuit therefore belongs to this one arm.
5471 //
5472 // Constructibility is exactly the split the reference makes: `function f(){}` and
5473 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5474 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5475 // function" — it *is* the predicate, which is why no extra marker is needed.
5476 if let Some(text) = key.as_str()
5477 && (text == "caller" || text == "arguments")
5478 && object.is_constructor()
5479 && object.is_callable()
5480 && !object.is_bound_function()
5481 && object.own_property(text).is_none()
5482 {
5483 return Ok(Some(Value::Undefined));
5484 }
5485 // The element-vector and `length` shortcuts are string-only: an array index
5486 // has no symbol spelling.
5487 if let Some(text) = key.as_str() {
5488 if let Some(value) = self.own_element(object, text) {
5489 return Ok(Some(value));
5490 }
5491 // `length` is not stored as a property: an array's length is its element
5492 // count, and keeping one copy of it is what makes `push`/`pop` and
5493 // `a.length = n` agree.
5494 if let Some(length) = object.array_length()
5495 && text == "length"
5496 {
5497 // Not `Value::Int(length as i32)`: see [`length_value`].
5498 return Ok(Some(crate::object::length_value(length)));
5499 }
5500 }
5501 // A proxy or a hooked exotic object anywhere above `object` makes the static
5502 // table walk below wrong: a proxy's own table is *empty by design* (the properties
5503 // live on its target), so the walk skipped that link entirely and everything behind
5504 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5505 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5506 // -target-is-proxy.js` are the four.
5507 if Self::chain_needs_dispatch(object) {
5508 return self.walk_get(object, receiver, key);
5509 }
5510 match lookup_key(object, key) {
5511 Some((_, property)) => self.read_property(property, object, receiver),
5512 None => Ok(None),
5513 }
5514 }
5515
5516 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5517 /// answer for itself.
5518 ///
5519 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5520 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5521 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5522 /// an inherited getter the object the read started from.
5523 fn walk_get(
5524 &mut self,
5525 start: &Gc<JsObject>,
5526 receiver: Option<&Value>,
5527 key: &PropertyKey,
5528 ) -> JsResult<Option<Value>> {
5529 let receiver = receiver
5530 .cloned()
5531 .unwrap_or_else(|| Value::Object(start.clone()));
5532 let mut current = Some(start.clone());
5533 while let Some(holder) = current {
5534 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5535 // has to ask it, not read its (empty) own-property table. `Object.create(new
5536 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5537 // instead found nothing.
5538 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5539 return Ok(Some(value));
5540 }
5541 // A host class's `get_property` trap replaces the whole read for that holder,
5542 // prototype walk included — the same rule `get_property_key_for` applies to the
5543 // first object.
5544 if let Some(exotic) = holder.exotic()
5545 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5546 {
5547 return Ok(Some(value));
5548 }
5549 if let Some(property) = self.object_get_own_property(&holder, key)? {
5550 return self.read_property(property, &holder, Some(&receiver));
5551 }
5552 current = self.object_prototype_of(&holder)?;
5553 }
5554 Ok(None)
5555 }
5556
5557 /// Whether `object` or anything above it has properties that cannot be read out of a
5558 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
5559 ///
5560 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
5561 /// is the hot path for every property read; this is the check that decides whether it
5562 /// is safe to take it.
5563 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
5564 object
5565 .chain()
5566 .iter()
5567 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
5568 }
5569
5570 /// The value a property read answers.
5571 ///
5572 /// One place rather than three, because an accessor has to run with the *receiver* as
5573 /// `this` whether the descriptor came from the property table, an exotic
5574 /// `get_own_property` trap, or a prototype above one.
5575 fn read_property(
5576 &mut self,
5577 property: Property,
5578 object: &Gc<JsObject>,
5579 receiver: Option<&Value>,
5580 ) -> JsResult<Option<Value>> {
5581 if property.is_accessor() {
5582 match &property.getter {
5583 Some(getter) if !matches!(getter, Value::Undefined) => {
5584 let receiver = receiver
5585 .cloned()
5586 .unwrap_or_else(|| Value::Object(object.clone()));
5587 self.call_value(getter.clone(), receiver, Vec::new())
5588 .map(Some)
5589 }
5590 // An accessor with no getter reads as `undefined`.
5591 _ => Ok(Some(Value::Undefined)),
5592 }
5593 } else {
5594 Ok(property.value)
5595 }
5596 }
5597
5598 /// `super.key` — start the search at `proto`, but report to `receiver`.
5599 ///
5600 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5601 /// found on the prototype of a class has to see the *instance* as `this`, and a
5602 /// plain property read off `proto` would lose that.
5603 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5604 let start = self.require_object(proto)?;
5605 let key = self.propkey(key)?;
5606 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5607 if matches!(proto, Value::Null) {
5608 return Ok(Value::Undefined);
5609 }
5610 match lookup_key(&start, &key) {
5611 Some((_, property)) if property.is_accessor() => match &property.getter {
5612 Some(getter) if !matches!(getter, Value::Undefined) => {
5613 self.call_value(getter.clone(), receiver.clone(), Vec::new())
5614 }
5615 _ => Ok(Value::Undefined),
5616 },
5617 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5618 None => Ok(Value::Undefined),
5619 }
5620 }
5621
5622 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5623 ///
5624 /// A setter found on the prototype runs with `receiver` as `this`; a data property
5625 /// is shadowed by a new own property on the receiver, the same rule an ordinary
5626 /// assignment follows.
5627 fn super_write(
5628 &mut self,
5629 receiver: &Value,
5630 proto: &Value,
5631 key: &Value,
5632 value: Value,
5633 ) -> JsResult<()> {
5634 let target = self.require_object(receiver)?;
5635 let key = self.propkey(key)?;
5636 if !matches!(proto, Value::Null)
5637 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5638 {
5639 if property.is_accessor() {
5640 if let Some(setter) = &property.setter
5641 && !matches!(setter, Value::Undefined)
5642 {
5643 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5644 }
5645 return Ok(());
5646 }
5647 // A data property on the prototype is writable or not; reading `owner` at
5648 // all is only for the attribute check.
5649 if !property.writable {
5650 return Err(self.type_error(format!("'{key}' is read-only")));
5651 }
5652 let _ = owner;
5653 }
5654 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5655 }
5656
5657 /// The object a `super` operation needs, or the `TypeError` the spec raises.
5658 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5659 match value.as_object() {
5660 Some(object) => Ok(object.clone()),
5661 None => Err(Signal::Throw(
5662 self.make_error("TypeError", "value is not an object"),
5663 )),
5664 }
5665 }
5666
5667 /// Build the class object `define_class` produces.
5668 ///
5669 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5670 /// whose prototype property is a fresh object inheriting from the parent's
5671 /// prototype, and whose own prototype is the parent constructor — which is what makes
5672 /// a static method inherited too.
5673 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5674 let ctor = self.pop();
5675 let parent = self.pop();
5676 let Value::Object(function) = &ctor else {
5677 return Err(Signal::Throw(
5678 self.make_error("TypeError", "class constructor must be a function"),
5679 ));
5680 };
5681 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5682 // but gives the instances no prototype at all.
5683 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5684 match &parent {
5685 Value::Null => (Some(self.realm.function_proto.clone()), None),
5686 Value::Object(parent_class) => {
5687 if !parent_class.is_callable() {
5688 return Err(Signal::Throw(
5689 self.make_error("TypeError", "parent class must be constructor"),
5690 ));
5691 }
5692 let proto = self.get_property(parent_class, "prototype")?;
5693 match proto {
5694 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5695 Some(Value::Null) => (Some(parent_class.clone()), None),
5696 _ => {
5697 return Err(Signal::Throw(self.make_error(
5698 "TypeError",
5699 "parent prototype must be an object or null",
5700 )));
5701 }
5702 }
5703 }
5704 _ => {
5705 return Err(Signal::Throw(
5706 self.make_error("TypeError", "parent class must be constructor"),
5707 ));
5708 }
5709 }
5710 } else {
5711 (
5712 Some(self.realm.function_proto.clone()),
5713 Some(self.realm.object_proto.clone()),
5714 )
5715 };
5716 let proto = self.new_object(parent_proto);
5717 function.set_proto(parent_ctor);
5718 // A class is not callable without `new`, and its `prototype` is not writable —
5719 // both follow from being a class and are what `class A {}; A()` throws on.
5720 function.set_class_constructor(true);
5721 function.set_home_object(None);
5722 self.set_function_name(&ctor, name);
5723 self.define_class_properties(function, &ctor, &proto)?;
5724 Ok((ctor, proto))
5725 }
5726
5727 /// Give the constructor its `prototype` and `length`, and the prototype its
5728 /// `constructor` back-pointer.
5729 fn define_class_properties(
5730 &mut self,
5731 function: &Gc<JsObject>,
5732 ctor: &Value,
5733 proto: &Gc<JsObject>,
5734 ) -> JsResult<()> {
5735 proto.define(
5736 "constructor",
5737 Property::with_attributes(ctor.clone(), true, false),
5738 );
5739 function.define(
5740 "prototype",
5741 Property::prototype_of(Value::Object(proto.clone()), false),
5742 );
5743 if let Some((code, _)) = bytecode_of(function) {
5744 let length = code.code.defined_args;
5745 function.define(
5746 "length",
5747 Property::name_or_length(Value::Int(length as i32)),
5748 );
5749 }
5750 Ok(())
5751 }
5752
5753 /// The own array element `key` names, if this object has one.
5754 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5755 // A typed array's elements live in its buffer, not in a property list: reading one
5756 // goes through the view's element type so a bounds check and a detached buffer are
5757 // both handled there.
5758 //
5759 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5760 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5761 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5762 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5763 // consulted. Testing with `array_index` rejected all three, which let a throwing
5764 // getter installed on `TypedArray.prototype["-1"]` run.
5765 if object.typed_array_parts().is_some() {
5766 let property_key = PropertyKey::from(key);
5767 let numeric = canonical_numeric_index(&property_key)?;
5768 if typed_array_index_is_valid(object, numeric) {
5769 return object.typed_array_element(numeric as usize);
5770 }
5771 // Canonical, but not a valid index: `undefined`, and *final*.
5772 return Some(Value::Undefined);
5773 }
5774 let index = array_index(key)?;
5775 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5776 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5777 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5778 // `[1,,3][1]`.
5779 match object.array_get(index as usize) {
5780 Some(Value::Hole) | None => None,
5781 other => other,
5782 }
5783 }
5784
5785 /// Store `object[key] = value`, honouring setters and inherited properties.
5786 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5787 self.set_property_with(object, key, value, DeleteFailure::Throw)
5788 }
5789
5790 /// Store a property, choosing what to do when the object refuses.
5791 ///
5792 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5793 /// mode, which is the one place assignment differs by mode. Native code (the array
5794 /// methods, `JSON`) always asks for the throw.
5795 pub fn set_property_with(
5796 &mut self,
5797 object: &Gc<JsObject>,
5798 key: &str,
5799 value: Value,
5800 on_failure: DeleteFailure,
5801 ) -> JsResult<()> {
5802 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5803 }
5804
5805 /// [`Interp::set_property_with`] with a key that may be a symbol.
5806 pub fn set_property_with_key(
5807 &mut self,
5808 object: &Gc<JsObject>,
5809 key: &PropertyKey,
5810 value: Value,
5811 on_failure: DeleteFailure,
5812 ) -> JsResult<()> {
5813 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5814 }
5815
5816 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5817 ///
5818 /// The receiver split lives one level up, in
5819 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5820 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5821 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5822 /// stores into `object` itself, which is why the element branch below converts `V`
5823 /// before asking whether the index is valid: `V` may put it back in bounds
5824 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5825 fn set_property_with_key_receiver_aware(
5826 &mut self,
5827 object: &Gc<JsObject>,
5828 key: &PropertyKey,
5829 value: Value,
5830 on_failure: DeleteFailure,
5831 ) -> JsResult<()> {
5832 // A proxy's `set` trap decides, and its `false` means the same thing an
5833 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5834 if object.proxy_state().is_some() {
5835 let receiver = Value::Object(object.clone());
5836 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5837 return match (accepted, on_failure) {
5838 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5839 (false, DeleteFailure::Throw) => {
5840 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5841 }
5842 };
5843 }
5844 }
5845 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5846 // refusal and means exactly what a proxy's `false` means.
5847 if let Some(exotic) = object.exotic() {
5848 let receiver = Value::Object(object.clone());
5849 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5850 return match (accepted, on_failure) {
5851 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5852 (false, DeleteFailure::Throw) => {
5853 Err(self.type_error(format!("property '{key}' is read-only")))
5854 }
5855 };
5856 }
5857 }
5858 // The element and `length` shortcuts only exist for string keys: an array
5859 // index has no symbol spelling, and a symbol named `length` is an ordinary
5860 // property.
5861 let text = key.as_str();
5862 // A typed array's elements are a window onto its buffer: the store has to go
5863 // through the view's element type so the value is wrapped (or clamped) and so an
5864 // out-of-range or detached write is a silent no-op, as the spec says.
5865 //
5866 // The key test is `CanonicalNumericIndexString`, like every other index operation
5867 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
5868 // does not exist, so they do nothing and leave no own property behind
5869 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
5870 // path, which created a property named `"-0"`.
5871 //
5872 // The conversion comes **first**, before the index is checked at all, and that
5873 // order is observable twice over:
5874 //
5875 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
5876 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
5877 // then store the converted value;
5878 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
5879 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
5880 // run and its exception to escape.
5881 //
5882 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
5883 // validity check, not a validity check that skips the conversion. The store itself
5884 // is a no-op when the index is invalid by then, which is why no extra guard is
5885 // needed around `typed_array_set`.
5886 if let Some(element) = object.typed_array_element_type()
5887 && let Some(numeric) = canonical_numeric_index(key)
5888 {
5889 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5890 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5891 // in `Interp`, because it is script-observable and the storage borrow inside
5892 // `typed_array_set` must not be held across it.
5893 let stored = self.element_value(element, value)?;
5894 if typed_array_index_is_valid(object, numeric)
5895 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
5896 {
5897 return Err(self.type_error(reason));
5898 }
5899 return Ok(());
5900 }
5901 if let Some(text) = text
5902 && let Some(index) = array_index(text)
5903 && object.is_array()
5904 {
5905 // An accessor defined on an index lives in the property table while the
5906 // element slot is a hole, so the store has to go through the property first.
5907 // Writing the vector directly skipped the setter entirely.
5908 if let Some(existing) = object.own_property_key(key) {
5909 if existing.is_accessor() {
5910 return match existing.setter.clone() {
5911 Some(setter) if !matches!(setter, Value::Undefined) => {
5912 let receiver = Value::Object(object.clone());
5913 self.call_value(setter, receiver, vec![value]).map(|_| ())
5914 }
5915 _ => match on_failure {
5916 DeleteFailure::Throw => Err(self.type_error(format!(
5917 "cannot set property '{text}', it has only a getter"
5918 ))),
5919 DeleteFailure::Ignore => Ok(()),
5920 },
5921 };
5922 }
5923 if !existing.writable {
5924 return match on_failure {
5925 DeleteFailure::Throw => {
5926 Err(self.type_error(format!("'{text}' is read-only")))
5927 }
5928 DeleteFailure::Ignore => Ok(()),
5929 };
5930 }
5931 }
5932 {
5933 // Growing the array needs a writable `length`.
5934 if (index as usize) >= object.array_length().unwrap_or(0)
5935 && !object.length_writable()
5936 {
5937 return match on_failure {
5938 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5939 DeleteFailure::Ignore => Ok(()),
5940 };
5941 }
5942 // Adding an index past the end makes the array longer, which a
5943 // non-extensible array refuses.
5944 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5945 return match on_failure {
5946 DeleteFailure::Throw => Err(self.type_error(format!(
5947 "cannot add property '{key}', object is not extensible"
5948 ))),
5949 DeleteFailure::Ignore => Ok(()),
5950 };
5951 }
5952 if object.element_is_locked(index) {
5953 return match on_failure {
5954 DeleteFailure::Throw => {
5955 Err(self.type_error(format!("'{key}' is read-only")))
5956 }
5957 DeleteFailure::Ignore => Ok(()),
5958 };
5959 }
5960 // The element vector is only half of `[[Set]]` for an index: the
5961 // prototype chain is consulted first, and a setter there answers instead
5962 // of the element store. This branch used to write the element directly, so
5963 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5964 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5965 // the reference calls the setter and the array keeps no own index.
5966 //
5967 // An *exotic* prototype has no entry to find, because its indices live
5968 // outside the property table — `Object.setPrototypeOf([], typedArray)`
5969 // then looked like "nothing on the chain" and the store created the
5970 // element, where the view's `[[Set]]` answers `true` and does nothing for
5971 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
5972 // checks the array's `length` stays 0). So the dispatch comes first.
5973 if !object.has_own_key(key)
5974 && let Some(proto) = object.proto()
5975 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
5976 {
5977 let receiver = Value::Object(object.clone());
5978 let accepted =
5979 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
5980 return if accepted {
5981 Ok(())
5982 } else {
5983 match on_failure {
5984 DeleteFailure::Throw => {
5985 Err(self.type_error(format!("'{key}' is read-only")))
5986 }
5987 DeleteFailure::Ignore => Ok(()),
5988 }
5989 };
5990 }
5991 if let Some((owner, property)) = lookup_key(object, key)
5992 && !owner.ptr_eq(object)
5993 {
5994 match &property {
5995 property if property.is_accessor() => {
5996 match &property.setter {
5997 Some(setter) if !matches!(setter, Value::Undefined) => {
5998 let receiver = Value::Object(object.clone());
5999 self.call_value(setter.clone(), receiver, vec![value])?;
6000 }
6001 _ => {
6002 return match on_failure {
6003 DeleteFailure::Throw => Err(self.type_error(format!(
6004 "cannot set property '{text}', it has only a getter"
6005 ))),
6006 DeleteFailure::Ignore => Ok(()),
6007 };
6008 }
6009 }
6010 return Ok(());
6011 }
6012 property if !property.writable => {
6013 return match on_failure {
6014 DeleteFailure::Throw => {
6015 Err(self.type_error(format!("'{text}' is read-only")))
6016 }
6017 DeleteFailure::Ignore => Ok(()),
6018 };
6019 }
6020 _ => {}
6021 }
6022 }
6023 if object.array_set(self.heap, index as usize, value.clone()) {
6024 return Ok(());
6025 }
6026 // Past the dense limit the slot is too far out to be worth one `Value`
6027 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6028 // constant time by keeping the index as an ordinary property. The store
6029 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6030 // to a legal program.
6031 object.define_key(key, Property::with_attributes(value, true, true));
6032 // Extend, never shorten: the index may be *inside* the current length (a
6033 // huge `length` with a sparse store), and shortening would delete the
6034 // sparse properties above it — including the one just stored.
6035 if index as usize + 1 > object.array_length().unwrap_or(0) {
6036 object.array_set_length(self.heap, index as usize + 1);
6037 }
6038 return Ok(());
6039 }
6040 }
6041 if text == Some("length") && object.is_array() {
6042 if !object.length_writable() {
6043 return match on_failure {
6044 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6045 DeleteFailure::Ignore => Ok(()),
6046 };
6047 }
6048 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6049 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6050 // answered `NaN`, which left the assignment silently ignored
6051 // (`S15.4.5.2_A3_T2`).
6052 let length = self.to_js_number(&value)?;
6053 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6054 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6055 // `RangeError`s; the old code only tested "finite and non-negative" and then
6056 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6057 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6058 let valid = length.is_finite()
6059 && length >= 0.0
6060 && length.fract() == 0.0
6061 && length <= u32::MAX as f64;
6062 if !valid {
6063 return Err(self.range_error("invalid array length"));
6064 }
6065 {
6066 let length = length as usize;
6067 // `a.length = n` with `n` below a non-configurable element cannot
6068 // drop that element, so the whole assignment fails. The spec makes
6069 // this a `TypeError` rather than a silent no-op, in any mode.
6070 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6071 // Sloppy mode stops the truncation at the blocking element
6072 // instead of failing; strict mode raises.
6073 // Both modes stop at the blocking element; they differ in
6074 // whether that is reported. The reference truncates *then*
6075 // throws, so the array is left in the shortened state.
6076 object.array_truncate(self.heap, blocked + 1);
6077 return match on_failure {
6078 DeleteFailure::Throw => {
6079 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6080 }
6081 DeleteFailure::Ignore => Ok(()),
6082 };
6083 }
6084 object.array_set_length(self.heap, length);
6085 return Ok(());
6086 }
6087 }
6088 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6089 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6090 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6091 //
6092 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6093 // applying whatever came back is the same thing for an ordinary prototype and
6094 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6095 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6096 // answers "not mine, the receiver is not me" without touching the buffer. This
6097 // code used to find nothing owned by `o`, find no property on the view either,
6098 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6099 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6100 // `key-is-canonical-invalid-index-prototype-chain-set`).
6101 //
6102 // The read-only and accessor rules of step 1 are what make
6103 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6104 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6105 let own = match self.lookup_for_write(object, key)? {
6106 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6107 _ => None,
6108 };
6109 if let Some(property) = own {
6110 if property.is_accessor() {
6111 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6112 Some(setter) => {
6113 let receiver = Value::Object(object.clone());
6114 self.call_value(setter, receiver, vec![value])?;
6115 Ok(())
6116 }
6117 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6118 // Sloppy code swallows that refusal, strict code raises — the same
6119 // rule the read-only *data* property below follows, and skipping it
6120 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6121 // return silently. The reference answers `TypeError: 'x' is
6122 // read-only`.
6123 None => match on_failure {
6124 DeleteFailure::Throw => {
6125 Err(self.type_error(format!("'{key}' is read-only")))
6126 }
6127 DeleteFailure::Ignore => Ok(()),
6128 },
6129 };
6130 }
6131 // An own non-writable data property stops here: nothing may change it.
6132 if !property.writable {
6133 return match on_failure {
6134 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6135 DeleteFailure::Ignore => Ok(()),
6136 };
6137 }
6138 // An existing writable own property keeps its attributes: only the value
6139 // moves. Redefining instead would reset them, which is how a
6140 // non-configurable global `var` used to become deletable.
6141 if object.write_value_key(key, value.clone()) {
6142 return Ok(());
6143 }
6144 }
6145 // Step 2: hand the store to the prototype, with `object` as the receiver.
6146 if let Some(proto) = object.proto() {
6147 let receiver = Value::Object(object.clone());
6148 let accepted =
6149 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6150 return if accepted {
6151 Ok(())
6152 } else {
6153 match on_failure {
6154 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6155 DeleteFailure::Ignore => Ok(()),
6156 }
6157 };
6158 }
6159 // Step 3: create one, and a non-extensible object cannot.
6160 if !object.is_extensible() {
6161 return match on_failure {
6162 DeleteFailure::Throw => Err(self.type_error(format!(
6163 "cannot add property {key}, object is not extensible"
6164 ))),
6165 DeleteFailure::Ignore => Ok(()),
6166 };
6167 }
6168 object.define_data_key(key, value);
6169 Ok(())
6170 }
6171
6172 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6173 ///
6174 /// The distinction the fast path above does not need: it is called with the store's
6175 /// receiver already being the object it writes to. Here `object` is the one whose
6176 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6177 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6178 /// and not a write to `object`.
6179 ///
6180 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6181 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6182 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6183 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6184 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6185 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6186 ///
6187 /// Answers `false` where the spec says `false`; the caller turns that into the
6188 /// strict-mode `TypeError` or the sloppy-mode silence.
6189 fn ordinary_set_with_receiver(
6190 &mut self,
6191 object: &Gc<JsObject>,
6192 receiver: &Value,
6193 key: &PropertyKey,
6194 value: Value,
6195 on_failure: DeleteFailure,
6196 ) -> JsResult<bool> {
6197 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6198 if object.proxy_state().is_some() {
6199 return Ok(self
6200 .proxy_set(object, key, value, receiver)?
6201 .unwrap_or(true));
6202 }
6203 // A host class decides for itself, with the receiver the caller named.
6204 if let Some(exotic) = object.exotic()
6205 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6206 {
6207 return Ok(accepted);
6208 }
6209 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6210 // rather than the receiver, but the receiver may still *be* the view:
6211 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6212 // itself as receiver, and then the first half applies — convert `V` once, store
6213 // if the index is valid, answer `true` either way. The conversion is the observable
6214 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6215 //
6216 // Only the second half, a view that is *not* the receiver, skips the conversion
6217 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6218 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6219 // below with the value still unconverted.
6220 if object.typed_array_element_type().is_some()
6221 && let Some(numeric) = canonical_numeric_index(key)
6222 {
6223 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6224 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6225 return Ok(true);
6226 }
6227 if !typed_array_index_is_valid(object, numeric) {
6228 return Ok(true);
6229 }
6230 }
6231 let own = self.object_get_own_property(object, key)?;
6232 if let Some(own) = own {
6233 if own.is_accessor() {
6234 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6235 Some(setter) => {
6236 self.call_value(setter, receiver.clone(), vec![value])?;
6237 Ok(true)
6238 }
6239 None => Ok(false),
6240 };
6241 }
6242 // A non-writable data descriptor refuses, own or inherited. Either way the
6243 // receiver must not gain a shadowing property.
6244 if !own.writable {
6245 return Ok(false);
6246 }
6247 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6248 // created or written, and it is created as an ordinary data property.
6249 let Some(receiver_object) = receiver.as_object().cloned() else {
6250 return Ok(false);
6251 };
6252 return match self.object_get_own_property(&receiver_object, key)? {
6253 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6254 Some(existing) => self.object_define_own_property(
6255 &receiver_object,
6256 key,
6257 Property {
6258 value: Some(value),
6259 ..existing
6260 },
6261 ),
6262 None => {
6263 self.object_define_own_property(&receiver_object, key, Property::data(value))
6264 }
6265 };
6266 }
6267 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6268 if let Some(proto) = object.proto() {
6269 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6270 }
6271 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6272 // *default* data descriptor here, so control falls into step 2 exactly as if the
6273 // target had owned a writable property — which means the **receiver's** own
6274 // descriptor is asked for before the write. Skipping that question went straight to
6275 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6276 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6277 // exactly those calls).
6278 let Some(receiver_object) = receiver.as_object().cloned() else {
6279 return Ok(false);
6280 };
6281 match self.object_get_own_property(&receiver_object, key)? {
6282 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6283 Some(existing) => self.object_define_own_property(
6284 &receiver_object,
6285 key,
6286 Property {
6287 value: Some(value),
6288 ..existing
6289 },
6290 ),
6291 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6292 }
6293 }
6294
6295 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6296 ///
6297 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6298 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6299 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6300 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6301 /// the prototype, so the walk resumes above the object.
6302 fn lookup_for_write(
6303 &mut self,
6304 object: &Gc<JsObject>,
6305 key: &PropertyKey,
6306 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6307 let Some(exotic) = object.exotic() else {
6308 return Ok(lookup_key(object, key));
6309 };
6310 Ok(match exotic.get_own_property(self, object, key)? {
6311 Some(Some(property)) => Some((object.clone(), property)),
6312 Some(None) => lookup_key_above(object, key),
6313 None => lookup_key(object, key),
6314 })
6315 }
6316
6317 /// Delete `object[key]`.
6318 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6319 self.delete_property_key(object, &PropertyKey::from(key))
6320 }
6321
6322 /// [`Interp::delete_property`] with a key that may be a symbol.
6323 pub fn delete_property_key(
6324 &mut self,
6325 object: &Gc<JsObject>,
6326 key: &PropertyKey,
6327 ) -> JsResult<bool> {
6328 // A proxy decides for itself, and may even throw; the invariant checks live in
6329 // `proxy_delete`.
6330 if let Some(answer) = self.proxy_delete(object, key)? {
6331 return Ok(answer);
6332 }
6333 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6334 // caller reports as a failed delete.
6335 if let Some(exotic) = object.exotic()
6336 && let Some(answer) = exotic.delete_property(self, object, key)?
6337 {
6338 return Ok(answer);
6339 }
6340 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6341 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6342 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6343 // one answers `false` because the elements are non-configurable. The prototype
6344 // chain is not consulted either, which is what makes a throwing getter on
6345 // `TypedArray.prototype["-1"]` stay unrun.
6346 if object.typed_array_parts().is_some()
6347 && object.proxy_state().is_none()
6348 && let Some(numeric) = canonical_numeric_index(key)
6349 {
6350 return Ok(!typed_array_index_is_valid(object, numeric));
6351 }
6352 let mapped_index = key.as_str().and_then(array_index);
6353 if let Some(index) = mapped_index
6354 && let Some(length) = object.array_length()
6355 && (index as usize) < length
6356 {
6357 // An accessor defined on an index lives in the property table rather than the
6358 // element vector, so both have to be cleared: `delete` after
6359 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6360 object.delete_key(key);
6361 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6362 // index stops answering `in`.
6363 if object.element_is_undeletable(index) {
6364 return Ok(false);
6365 }
6366 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6367 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6368 // and no longer through to the parameter. A refused delete leaves the
6369 // mapping alone.
6370 object.drop_mapped_argument(index as usize);
6371 object.array_set(self.heap, index as usize, Value::Hole);
6372 return Ok(true);
6373 }
6374 // An array's `length` is a non-configurable own property that lives outside the
6375 // property table, so `delete_key` finds nothing and reports success — `Reflect
6376 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6377 // §10.4.4.1 step 3 refuses it.
6378 if key.as_str() == Some("length") && object.array_length().is_some() {
6379 return Ok(false);
6380 }
6381 // The same for an object that is not an array: only a delete that actually
6382 // removed the property ends the alias.
6383 let deleted = object.delete_key(key);
6384 if deleted && let Some(index) = mapped_index {
6385 object.drop_mapped_argument(index as usize);
6386 }
6387 Ok(deleted)
6388 }
6389
6390 // -- proxy traps --------------------------------------------------------
6391 //
6392 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6393 // with the target and the operation's own arguments, then check the answer against
6394 // the target. The checks are not decoration — they are what stops a proxy from
6395 // reporting a `non-configurable` property as missing, which would let a frozen object
6396 // be rewritten by standing in front of it.
6397
6398 /// The target and handler of `object`, or `None` when it is not a proxy.
6399 ///
6400 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6401 /// one has to fail: the slots the traps would have been read from are gone.
6402 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6403 let Some(state) = object.proxy_state() else {
6404 return Ok(None);
6405 };
6406 let state = state.borrow();
6407 match (&state.target, &state.handler) {
6408 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6409 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6410 }
6411 }
6412
6413 /// Call `handler[name]`, or answer `None` when the trap is absent.
6414 ///
6415 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6416 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6417 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6418 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6419 /// one per trap plus the `target-is-proxy` variants.
6420 ///
6421 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6422 /// this cannot simply be "any non-callable means no trap".
6423 fn proxy_trap(
6424 &mut self,
6425 handler: &Value,
6426 name: &str,
6427 args: Vec<Value>,
6428 ) -> JsResult<Option<Value>> {
6429 let Value::Object(table) = handler else {
6430 return Err(self.type_error("proxy handler is not an object"));
6431 };
6432 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6433 match trap {
6434 Value::Undefined | Value::Null => Ok(None),
6435 Value::Object(function) if function.is_callable() => {
6436 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6437 Ok(Some(answer))
6438 }
6439 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6440 }
6441 }
6442
6443 /// Whether the target's own property `key` is one it refuses to lose.
6444 ///
6445 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6446 /// its value behind the target's back.
6447 ///
6448 /// A **method**, not a free function, because §10.5.1's invariants say
6449 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6450 /// property table directly finds nothing (a proxy's table is empty by design), so every
6451 /// invariant check silently passed for a proxy target. That is what
6452 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6453 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6454 /// where an array's elements and its `length` — both fixed, both outside the table —
6455 /// are covered.
6456 fn fixed_property(
6457 &mut self,
6458 target: &Gc<JsObject>,
6459 key: &PropertyKey,
6460 ) -> JsResult<Option<Property>> {
6461 Ok(self
6462 .object_get_own_property(target, key)?
6463 .filter(|property| !property.configurable))
6464 }
6465
6466 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6467 fn proxy_get(
6468 &mut self,
6469 object: &Gc<JsObject>,
6470 receiver: &Value,
6471 key: &PropertyKey,
6472 ) -> JsResult<Option<Value>> {
6473 let Some((target, handler)) = self.proxy_parts(object)? else {
6474 return Ok(None);
6475 };
6476 let key_value = self.key_value(key);
6477 let Some(result) = self.proxy_trap(
6478 &handler,
6479 "get",
6480 vec![Value::Object(target.clone()), key_value, receiver.clone()],
6481 )?
6482 else {
6483 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6484 // inherited getter still sees the proxy.
6485 return Ok(Some(
6486 self.get_property_key_for(&target, Some(receiver), key)?
6487 .unwrap_or(Value::Undefined),
6488 ));
6489 };
6490 if let Some(fixed) = self.fixed_property(&target, key)? {
6491 if fixed.is_accessor() {
6492 // A fixed accessor with no getter must read as `undefined`.
6493 let has_getter = fixed
6494 .getter
6495 .as_ref()
6496 .is_some_and(|getter| !matches!(getter, Value::Undefined));
6497 if !has_getter && !matches!(result, Value::Undefined) {
6498 return Err(self.type_error(format!(
6499 "proxy 'get' must report undefined for the non-configurable property '{key}'"
6500 )));
6501 }
6502 } else if !fixed.writable {
6503 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6504 if !fixed_value.same_value(&result) {
6505 return Err(self.type_error(format!(
6506 "proxy 'get' disagrees with the non-configurable property '{key}'"
6507 )));
6508 }
6509 }
6510 }
6511 Ok(Some(result))
6512 }
6513
6514 /// `[[Set]]` on a proxy.
6515 ///
6516 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6517 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6518 /// read-only store has.
6519 fn proxy_set(
6520 &mut self,
6521 object: &Gc<JsObject>,
6522 key: &PropertyKey,
6523 value: Value,
6524 receiver: &Value,
6525 ) -> JsResult<Option<bool>> {
6526 let Some((target, handler)) = self.proxy_parts(object)? else {
6527 return Ok(None);
6528 };
6529 let key_value = self.key_value(key);
6530 let Some(result) = self.proxy_trap(
6531 &handler,
6532 "set",
6533 vec![
6534 Value::Object(target.clone()),
6535 key_value,
6536 value.clone(),
6537 receiver.clone(),
6538 ],
6539 )?
6540 else {
6541 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6542 // given — not the target. `OrdinarySet` step 3 is
6543 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6544 // object whose prototype is a typed array has to reach the proxy's own
6545 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6546 // calls and expects exactly one. Storing on the target instead put the value
6547 // in the target and never consulted the trap.
6548 let accepted = self.ordinary_set_with_receiver(
6549 &target,
6550 receiver,
6551 key,
6552 value,
6553 DeleteFailure::Ignore,
6554 )?;
6555 return Ok(Some(accepted));
6556 };
6557 if !result.to_boolean() {
6558 return Ok(Some(false));
6559 }
6560 if let Some(fixed) = self.fixed_property(&target, key)? {
6561 if fixed.is_accessor() {
6562 let has_setter = fixed
6563 .setter
6564 .as_ref()
6565 .is_some_and(|setter| !matches!(setter, Value::Undefined));
6566 if !has_setter {
6567 return Err(self.type_error(format!(
6568 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6569 )));
6570 }
6571 } else if !fixed.writable {
6572 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6573 if !fixed_value.same_value(&value) {
6574 return Err(self.type_error(format!(
6575 "proxy 'set' changed the non-configurable property '{key}'"
6576 )));
6577 }
6578 }
6579 }
6580 // A new property cannot appear on a target that refuses new properties.
6581 if self.object_get_own_property(&target, key)?.is_none()
6582 && !self.object_is_extensible(&target)?
6583 {
6584 return Err(self.type_error(format!(
6585 "proxy 'set' added '{key}' to a non-extensible target"
6586 )));
6587 }
6588 Ok(Some(true))
6589 }
6590
6591 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6592 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6593 let Some((target, handler)) = self.proxy_parts(object)? else {
6594 return Ok(None);
6595 };
6596 let key_value = self.key_value(key);
6597 let Some(result) = self.proxy_trap(
6598 &handler,
6599 "has",
6600 vec![Value::Object(target.clone()), key_value],
6601 )?
6602 else {
6603 return Ok(Some(self.has_own_or_inherited(&target, key)?));
6604 };
6605 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6606 return Err(self.type_error(format!(
6607 "proxy 'has' denied the non-configurable property '{key}'"
6608 )));
6609 }
6610 // A non-extensible target cannot grow, so every own property it *has* is fixed.
6611 if !result.to_boolean()
6612 && !self.object_is_extensible(&target)?
6613 && self.object_get_own_property(&target, key)?.is_some()
6614 {
6615 return Err(self.type_error(format!(
6616 "proxy 'has' denied the own property '{key}' of a non-extensible target"
6617 )));
6618 }
6619 Ok(Some(result.to_boolean()))
6620 }
6621
6622 /// `[[Delete]]` on a proxy.
6623 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6624 let Some((target, handler)) = self.proxy_parts(object)? else {
6625 return Ok(None);
6626 };
6627 let key_value = self.key_value(key);
6628 let Some(result) = self.proxy_trap(
6629 &handler,
6630 "deleteProperty",
6631 vec![Value::Object(target.clone()), key_value],
6632 )?
6633 else {
6634 return Ok(Some(self.delete_property_key(&target, key)?));
6635 };
6636 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6637 return Err(self.type_error(format!(
6638 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6639 )));
6640 }
6641 if result.to_boolean()
6642 && !self.object_is_extensible(&target)?
6643 && self.object_get_own_property(&target, key)?.is_some()
6644 {
6645 return Err(self.type_error(format!(
6646 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6647 )));
6648 }
6649 Ok(Some(result.to_boolean()))
6650 }
6651
6652 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6653 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6654 let Some((target, handler)) = self.proxy_parts(object)? else {
6655 return Ok(None);
6656 };
6657 let Some(result) =
6658 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6659 else {
6660 // No trap: the target's own keys, already in the order an object reports.
6661 return Ok(Some(self.object_own_property_keys(&target)?));
6662 };
6663 // `CreateListFromArrayLike` with the string-or-symbol restriction.
6664 let list = self.list_from_array_like(&result, true)?;
6665 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6666 for value in list {
6667 let key = self.propkey(&value)?;
6668 if keys.contains(&key) {
6669 return Err(self.type_error(format!(
6670 "proxy 'ownKeys' returned the duplicate key '{key}'"
6671 )));
6672 }
6673 keys.push(key);
6674 }
6675 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
6676 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
6677 // table is empty, which made every check below vacuous.
6678 let target_keys = self.object_own_property_keys(&target)?;
6679 let extensible = self.object_is_extensible(&target)?;
6680 for key in &target_keys {
6681 if keys.contains(key) {
6682 continue;
6683 }
6684 if self.fixed_property(&target, key)?.is_some() {
6685 return Err(self.type_error(format!(
6686 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6687 )));
6688 }
6689 if !extensible {
6690 return Err(self.type_error(format!(
6691 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6692 )));
6693 }
6694 }
6695 if !extensible {
6696 // §10.5.11 step 12: the lists must match one for one, in any order.
6697 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
6698 {
6699 return Err(
6700 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6701 );
6702 }
6703 }
6704 Ok(Some(keys))
6705 }
6706
6707 /// `[[GetOwnProperty]]` on a proxy.
6708 fn proxy_get_own_property(
6709 &mut self,
6710 object: &Gc<JsObject>,
6711 key: &PropertyKey,
6712 ) -> JsResult<Option<Option<Property>>> {
6713 let Some((target, handler)) = self.proxy_parts(object)? else {
6714 return Ok(None);
6715 };
6716 let key_value = self.key_value(key);
6717 let Some(result) = self.proxy_trap(
6718 &handler,
6719 "getOwnPropertyDescriptor",
6720 vec![Value::Object(target.clone()), key_value],
6721 )?
6722 else {
6723 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
6724 // property table. Two things ride on that choice: a target that is itself a
6725 // proxy has to re-dispatch (its own table is empty, so reading it reported
6726 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
6727 // indices and `length` live outside the table and need the ordinary synthesis.
6728 // `object_get_own_property` does both.
6729 return Ok(Some(self.object_get_own_property(&target, key)?));
6730 };
6731 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
6732 // `ToPropertyDescriptor` runs, because that operation would box the primitive
6733 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
6734 // empty descriptor instead of refusing.
6735 if !matches!(result, Value::Undefined | Value::Object(_)) {
6736 return Err(self.type_error(
6737 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
6738 ));
6739 }
6740 let target_desc = self.object_get_own_property(&target, key)?;
6741 let extensible = self.object_is_extensible(&target)?;
6742 let Some(descriptor) = (match result {
6743 Value::Undefined => None,
6744 _ => Some(self.property_from_descriptor(&result)?),
6745 }) else {
6746 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
6747 // descriptor is configurable *and* the target can still grow back.
6748 if let Some(target_desc) = &target_desc {
6749 if !target_desc.configurable {
6750 return Err(self.type_error(format!(
6751 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6752 )));
6753 }
6754 if !extensible {
6755 return Err(self.type_error(format!(
6756 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
6757 )));
6758 }
6759 }
6760 return Ok(Some(None));
6761 };
6762 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
6763 // which is a stronger requirement than "the target is not contradicting it" — the
6764 // four branches below are each one test262 case.
6765 if !descriptor.configurable {
6766 let Some(target_desc) = &target_desc else {
6767 return Err(self.type_error(format!(
6768 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
6769 )));
6770 };
6771 if target_desc.configurable {
6772 return Err(self.type_error(format!(
6773 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
6774 )));
6775 }
6776 let target_is_data = !target_desc.is_accessor();
6777 let result_is_data = !descriptor.is_accessor();
6778 if result_is_data && !target_is_data {
6779 return Err(self.type_error(format!(
6780 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6781 )));
6782 }
6783 if target_is_data && !target_desc.writable {
6784 if !result_is_data {
6785 return Err(self.type_error(format!(
6786 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6787 )));
6788 }
6789 if descriptor.writable {
6790 return Err(self.type_error(format!(
6791 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6792 )));
6793 }
6794 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
6795 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6796 if !fixed_value.same_value(&reported) {
6797 return Err(self.type_error(format!(
6798 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6799 )));
6800 }
6801 }
6802 // Step 16.d: a reported *read-only* data property needs a real read-only data
6803 // property behind it. Missing this let a trap bolt a frozen property onto a
6804 // writable target intent (`resultdesc-is-not-configurable-not-writable-
6805 // targetdesc-is-writable`).
6806 if result_is_data && !descriptor.writable {
6807 if !target_is_data {
6808 return Err(self.type_error(format!(
6809 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6810 )));
6811 }
6812 if target_desc.writable {
6813 return Err(self.type_error(format!(
6814 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
6815 )));
6816 }
6817 }
6818 if descriptor.is_accessor() {
6819 // Step 16.e: a getter the target does not have may not be invented, and
6820 // vice versa.
6821 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6822 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6823 (Some(a), Some(b)) => a.same_value(b),
6824 _ => false,
6825 };
6826 if !same(&target_desc.getter, &descriptor.getter)
6827 || !same(&target_desc.setter, &descriptor.setter)
6828 {
6829 return Err(self.type_error(format!(
6830 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6831 )));
6832 }
6833 }
6834 }
6835 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
6836 // where the target's own is locked. Without it a handler could advertise
6837 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
6838 // that believed it would try to redefine something it cannot.
6839 if descriptor.configurable
6840 && let Some(target_desc) = &target_desc
6841 && !target_desc.configurable
6842 {
6843 return Err(self.type_error(format!(
6844 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6845 )));
6846 }
6847 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
6848 // through the trap either, however well-formed the descriptor is. This is the
6849 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
6850 // the frozen target does not own.
6851 if !extensible {
6852 let Some(target_desc) = &target_desc else {
6853 return Err(self.type_error(format!(
6854 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
6855 )));
6856 };
6857 if target_desc.is_accessor() == descriptor.is_accessor() {
6858 let target_is_data = !target_desc.is_accessor();
6859 let result_is_data = !descriptor.is_accessor();
6860 if target_is_data && !target_desc.writable && descriptor.writable {
6861 return Err(self.type_error(format!(
6862 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6863 )));
6864 }
6865 if !result_is_data && !target_is_data {
6866 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6867 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6868 (Some(a), Some(b)) => a.same_value(b),
6869 _ => false,
6870 };
6871 if !same(&target_desc.getter, &descriptor.getter)
6872 || !same(&target_desc.setter, &descriptor.setter)
6873 {
6874 return Err(self.type_error(format!(
6875 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6876 )));
6877 }
6878 }
6879 }
6880 }
6881 Ok(Some(Some(descriptor)))
6882 }
6883
6884 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
6885 ///
6886 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
6887 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
6888 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
6889 /// for a data property. `Property` cannot express "this field is absent", so the whole
6890 /// property path is skipped and the descriptor is assembled here field by field.
6891 ///
6892 /// `current` is the property the trap reported, used only to tell a data property from
6893 /// an accessor.
6894 pub fn proxy_seal_property(
6895 &mut self,
6896 object: &Gc<JsObject>,
6897 key: &PropertyKey,
6898 frozen: bool,
6899 current: &Property,
6900 ) -> JsResult<bool> {
6901 let Some((_target, handler)) = self.proxy_parts(object)? else {
6902 return Err(self.type_error("not a proxy"));
6903 };
6904 let descriptor = self.new_object(None);
6905 descriptor.define_data("configurable", Value::Bool(false));
6906 if frozen && !current.is_accessor() {
6907 descriptor.define_data("writable", Value::Bool(false));
6908 }
6909 let key_value = self.key_value(key);
6910 let target = object
6911 .proxy_state()
6912 .and_then(|state| state.borrow().target.clone());
6913 let Some(target) = target else {
6914 return Err(self.type_error("cannot use a proxy that has been revoked"));
6915 };
6916 let Some(result) = self.proxy_trap(
6917 &handler,
6918 "defineProperty",
6919 vec![Value::Object(target), key_value, Value::Object(descriptor)],
6920 )?
6921 else {
6922 // No trap means the definition belongs to the target; `false` is its answer.
6923 return Ok(false);
6924 };
6925 Ok(result.to_boolean())
6926 }
6927
6928 /// `[[DefineOwnProperty]]` on a proxy.
6929 fn proxy_define_property(
6930 &mut self,
6931 object: &Gc<JsObject>,
6932 key: &PropertyKey,
6933 property: Property,
6934 ) -> JsResult<Option<bool>> {
6935 let Some((target, handler)) = self.proxy_parts(object)? else {
6936 return Ok(None);
6937 };
6938 let key_value = self.key_value(key);
6939 let descriptor = self.descriptor_from_property(&property);
6940 let Some(result) = self.proxy_trap(
6941 &handler,
6942 "defineProperty",
6943 vec![Value::Object(target.clone()), key_value, descriptor],
6944 )?
6945 else {
6946 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
6947 // going" answer and `object_define_own_property` turns it into exactly that
6948 // forwarding — see the note there. (Reading it as "not a proxy" would define
6949 // the property on the proxy object itself, whose table is empty and which no
6950 // read ever consults.)
6951 return Ok(None);
6952 };
6953 if !result.to_boolean() {
6954 return Ok(Some(false));
6955 }
6956 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
6957 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
6958 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
6959 // and treating them alike made four cases pass a descriptor the target contradicts.
6960 let target_desc = self.object_get_own_property(&target, key)?;
6961 let extensible = self.object_is_extensible(&target)?;
6962 let named = property
6963 .descriptor_fields
6964 .unwrap_or(crate::object::DescriptorFields {
6965 value: false,
6966 writable: false,
6967 enumerable: false,
6968 configurable: false,
6969 get: false,
6970 set: false,
6971 });
6972 if named.configurable && !property.configurable {
6973 let Some(target_desc) = &target_desc else {
6974 return Err(self.type_error(format!(
6975 "proxy 'defineProperty' invented the non-configurable '{key}'"
6976 )));
6977 };
6978 if target_desc.configurable {
6979 return Err(self.type_error(format!(
6980 "proxy 'defineProperty' made '{key}' non-configurable"
6981 )));
6982 }
6983 }
6984 // Step 11's other half: reporting that a property was made *configurable* needs a
6985 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
6986 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
6987 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
6988 // target`).
6989 if named.configurable
6990 && property.configurable
6991 && let Some(target_desc) = &target_desc
6992 && !target_desc.configurable
6993 {
6994 return Err(
6995 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
6996 );
6997 }
6998 // Step 12: a property cannot be reported *made writable* when the target's copy is
6999 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7000 // the trap is allowed to claim a definition it did not perform, as long as the
7001 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7002 // legal, and refusing it broke the commonest way to seed a proxy).
7003 if named.writable
7004 && property.writable
7005 && let Some(target_desc) = &target_desc
7006 && !target_desc.writable
7007 {
7008 return Err(self.type_error(format!(
7009 "proxy 'defineProperty' made the read-only '{key}' writable"
7010 )));
7011 }
7012 // Step 13: making a property read-only needs an existing read-only property.
7013 if named.writable
7014 && !property.writable
7015 && let Some(target_desc) = &target_desc
7016 && !target_desc.is_accessor()
7017 && target_desc.writable
7018 {
7019 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7020 }
7021 // Step 14: a non-writable, non-configurable property's value is fixed.
7022 if named.value
7023 && let Some(target_desc) = &target_desc
7024 && !target_desc.is_accessor()
7025 && !target_desc.writable
7026 && !target_desc.configurable
7027 {
7028 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7029 let reported = property.value.clone().unwrap_or(Value::Undefined);
7030 if !fixed_value.same_value(&reported) {
7031 return Err(self.type_error(format!(
7032 "proxy 'defineProperty' changed the value of '{key}'"
7033 )));
7034 }
7035 }
7036 // Step 15: a non-extensible target cannot grow.
7037 if target_desc.is_none() && !extensible {
7038 return Err(self.type_error(format!(
7039 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7040 )));
7041 }
7042 Ok(Some(true))
7043 }
7044
7045 /// `[[GetPrototypeOf]]` on a proxy.
7046 fn proxy_get_prototype_of(
7047 &mut self,
7048 object: &Gc<JsObject>,
7049 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7050 let Some((target, handler)) = self.proxy_parts(object)? else {
7051 return Ok(None);
7052 };
7053 let Some(result) = self.proxy_trap(
7054 &handler,
7055 "getPrototypeOf",
7056 vec![Value::Object(target.clone())],
7057 )?
7058 else {
7059 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7060 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7061 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7062 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7063 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7064 return Ok(Some(self.object_prototype_of(&target)?));
7065 };
7066 let proto = match &result {
7067 Value::Null => None,
7068 Value::Object(proto) => Some(proto.clone()),
7069 _ => {
7070 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7071 }
7072 };
7073 if !self.object_is_extensible(&target)? {
7074 let actual = self.object_prototype_of(&target)?;
7075 if !same_proto(proto.as_ref(), actual.as_ref()) {
7076 return Err(self.type_error(
7077 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7078 ));
7079 }
7080 }
7081 Ok(Some(proto))
7082 }
7083
7084 /// `[[SetPrototypeOf]]` on a proxy.
7085 fn proxy_set_prototype_of(
7086 &mut self,
7087 object: &Gc<JsObject>,
7088 proto: Option<Gc<JsObject>>,
7089 ) -> JsResult<Option<bool>> {
7090 let Some((target, handler)) = self.proxy_parts(object)? else {
7091 return Ok(None);
7092 };
7093 let proto_value = match &proto {
7094 Some(proto) => Value::Object(proto.clone()),
7095 None => Value::Null,
7096 };
7097 let Some(result) = self.proxy_trap(
7098 &handler,
7099 "setPrototypeOf",
7100 vec![Value::Object(target.clone()), proto_value],
7101 )?
7102 else {
7103 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7104 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7105 // its stored prototype overwritten behind its back.
7106 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7107 };
7108 if result.to_boolean()
7109 && !self.object_is_extensible(&target)?
7110 && !same_proto(
7111 Some(&proto).and_then(|p| p.clone()).as_ref(),
7112 self.object_prototype_of(&target)?.as_ref(),
7113 )
7114 {
7115 return Err(self.type_error(
7116 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7117 ));
7118 }
7119 Ok(Some(result.to_boolean()))
7120 }
7121
7122 /// `[[IsExtensible]]` on a proxy.
7123 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7124 let Some((target, handler)) = self.proxy_parts(object)? else {
7125 return Ok(None);
7126 };
7127 let Some(result) = self.proxy_trap(
7128 &handler,
7129 "isExtensible",
7130 vec![Value::Object(target.clone())],
7131 )?
7132 else {
7133 return Ok(Some(self.object_is_extensible(&target)?));
7134 };
7135 // The answer is not the proxy's to invent: it must agree with the target, or a
7136 // script could learn `false` while the target keeps accepting new properties.
7137 if result.to_boolean() != self.object_is_extensible(&target)? {
7138 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7139 }
7140 Ok(Some(result.to_boolean()))
7141 }
7142
7143 /// `[[PreventExtensions]]` on a proxy.
7144 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7145 let Some((target, handler)) = self.proxy_parts(object)? else {
7146 return Ok(None);
7147 };
7148 let Some(result) = self.proxy_trap(
7149 &handler,
7150 "preventExtensions",
7151 vec![Value::Object(target.clone())],
7152 )?
7153 else {
7154 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7155 // its answer can be `false`.
7156 return Ok(Some(self.object_prevent_extensions(&target)?));
7157 };
7158 if result.to_boolean() && self.object_is_extensible(&target)? {
7159 return Err(self.type_error(
7160 "proxy 'preventExtensions' reported success but the target is still extensible",
7161 ));
7162 }
7163 Ok(Some(result.to_boolean()))
7164 }
7165
7166 /// `[[Call]]` on a proxy, through the `apply` trap.
7167 fn proxy_apply(
7168 &mut self,
7169 object: &Gc<JsObject>,
7170 this: Value,
7171 args: Vec<Value>,
7172 ) -> JsResult<Option<Value>> {
7173 let Some((target, handler)) = self.proxy_parts(object)? else {
7174 return Ok(None);
7175 };
7176 // The trap gets the arguments as one array, which is the shape the spec passes
7177 // and the shape `apply` traps are written against (`args[0]` is the first one).
7178 let arguments = self.new_array(args.clone());
7179 let this_for_trap = this.clone();
7180 let Some(result) = self.proxy_trap(
7181 &handler,
7182 "apply",
7183 vec![
7184 Value::Object(target.clone()),
7185 this_for_trap,
7186 Value::Object(arguments),
7187 ],
7188 )?
7189 else {
7190 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7191 };
7192 Ok(Some(result))
7193 }
7194
7195 /// `[[Construct]]` on a proxy, through the `construct` trap.
7196 fn proxy_construct(
7197 &mut self,
7198 object: &Gc<JsObject>,
7199 args: Vec<Value>,
7200 new_target: &Value,
7201 ) -> JsResult<Option<Value>> {
7202 let Some((target, handler)) = self.proxy_parts(object)? else {
7203 return Ok(None);
7204 };
7205 if !target.is_callable() {
7206 return Err(self.type_error("proxy target is not a constructor"));
7207 }
7208 let arguments = self.new_array(args.clone());
7209 let Some(result) = self.proxy_trap(
7210 &handler,
7211 "construct",
7212 vec![
7213 Value::Object(target.clone()),
7214 Value::Object(arguments),
7215 new_target.clone(),
7216 ],
7217 )?
7218 else {
7219 return Ok(Some(self.construct(
7220 Value::Object(target),
7221 new_target.clone(),
7222 args,
7223 )?));
7224 };
7225 if !matches!(result, Value::Object(_)) {
7226 return Err(self.type_error("proxy 'construct' must return an object"));
7227 }
7228 Ok(Some(result))
7229 }
7230
7231 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7232 pub(crate) fn has_own_or_inherited(
7233 &mut self,
7234 object: &Gc<JsObject>,
7235 key: &PropertyKey,
7236 ) -> JsResult<bool> {
7237 // The object itself first: it may be a proxy, and then the answer is its trap's.
7238 if let Some(answer) = self.proxy_has(object, key)? {
7239 return Ok(answer);
7240 }
7241 // An integer-indexed exotic object answers a canonical numeric index from
7242 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7243 // prototype chain. That is observable twice: a view the buffer has been resized
7244 // away from has no indices, so `2 in view` is `false` even when
7245 // `Object.getPrototypeOf(view)[2]` exists (what
7246 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7247 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7248 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7249 // goes through here, which is why the same rule is repeated in `has_property_key`
7250 // rather than living only there.
7251 if object.typed_array_parts().is_some()
7252 && let Some(numeric) = canonical_numeric_index(key)
7253 {
7254 return Ok(typed_array_index_is_valid(object, numeric));
7255 }
7256 // A host class answers `in` for its own keys, which may live nowhere in a property
7257 // table — `"x" in point` is true because the class says so, not because a property
7258 // exists.
7259 if let Some(exotic) = object.exotic()
7260 && let Some(answer) = exotic.has_property(self, object, key)?
7261 {
7262 return Ok(answer);
7263 }
7264 // `has_own` rather than `own_property_key`: an array's elements and its derived
7265 // `length` are invisible to the property table, and `Array.prototype` is an array.
7266 // A host class's `get_own_property` counts too, because the reference's
7267 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7268 // lives — a class with only `get_own_property` answers `in` through it.
7269 if self.exotic_has_own(object, key)? {
7270 return Ok(true);
7271 }
7272 // A hole is *not* the end of the search: the chain may still have the key, which
7273 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7274 for ancestor in object.chain() {
7275 // A proxy further up the chain answers for itself.
7276 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7277 return Ok(answer);
7278 }
7279 // Same for a host class: a prototype may be one, and `in` reaches it.
7280 if let Some(exotic) = ancestor.exotic()
7281 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7282 {
7283 return Ok(answer);
7284 }
7285 if self.exotic_has_own(&ancestor, key)? {
7286 return Ok(true);
7287 }
7288 }
7289 Ok(false)
7290 }
7291
7292 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7293 /// trap included.
7294 ///
7295 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7296 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7297 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7298 if let Some(exotic) = object.exotic()
7299 && let Some(answer) = exotic.get_own_property(self, object, key)?
7300 {
7301 return Ok(answer.is_some());
7302 }
7303 Ok(has_own(object, key))
7304 }
7305
7306 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7307 ///
7308 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7309 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7310 /// `TypeError` instead of a property named `"1.5"`.
7311 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7312 let object = self.object_from(value)?;
7313 let length = self
7314 .get_property(&object, "length")?
7315 .map(|value| value.to_number())
7316 .unwrap_or(0.0);
7317 if !length.is_finite() || length < 0.0 {
7318 return Err(self.type_error("invalid array-like length"));
7319 }
7320 let length = length as usize;
7321 let mut items = Vec::with_capacity(length.min(1024));
7322 for index in 0..length {
7323 let item = self
7324 .get_property(&object, &index.to_string())?
7325 .unwrap_or(Value::Undefined);
7326 if keys_only && matches!(&item, Value::Symbol(_)) {
7327 items.push(item);
7328 continue;
7329 }
7330 if keys_only && !matches!(&item, Value::String(_)) {
7331 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7332 }
7333 items.push(item);
7334 }
7335 Ok(items)
7336 }
7337
7338 /// A `Property` from the descriptor object a trap returned.
7339 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7340 let object = self.object_from(value)?;
7341 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7342 interp.get_property(&object, name)
7343 };
7344 let getter = field(self, "get")?;
7345 let setter = field(self, "set")?;
7346 let accessor = getter.is_some() || setter.is_some();
7347 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7348 Ok(interp
7349 .get_property(&object, name)?
7350 .is_some_and(|value| value.to_boolean()))
7351 };
7352 let enumerable = boolean(self, "enumerable")?;
7353 let configurable = boolean(self, "configurable")?;
7354 if accessor {
7355 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7356 return Err(
7357 self.type_error("a descriptor cannot be both a data property and an accessor")
7358 );
7359 }
7360 Ok(Property {
7361 getter: getter.or(Some(Value::Undefined)),
7362 setter: setter.or(Some(Value::Undefined)),
7363 enumerable,
7364 configurable,
7365 writable: false,
7366 value: None,
7367 descriptor_fields: None,
7368 })
7369 } else {
7370 Ok(Property {
7371 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7372 writable: boolean(self, "writable")?,
7373 enumerable,
7374 configurable,
7375 getter: None,
7376 setter: None,
7377 descriptor_fields: None,
7378 })
7379 }
7380 }
7381
7382 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7383 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7384 let object = self.new_object(None);
7385 // A partial descriptor names only some fields, and the trap must see exactly those:
7386 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7387 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7388 // case, where every field is present.
7389 let fields = property.descriptor_fields;
7390 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7391 fields.is_none_or(|fields| field(&fields))
7392 };
7393 if property.is_accessor() {
7394 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7395 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7396 object.define_data("get", getter);
7397 object.define_data("set", setter);
7398 } else {
7399 if names(|fields| fields.value) {
7400 let value = property.value.clone().unwrap_or(Value::Undefined);
7401 object.define_data("value", value);
7402 }
7403 if names(|fields| fields.writable) {
7404 object.define_data("writable", Value::Bool(property.writable));
7405 }
7406 }
7407 if names(|fields| fields.enumerable) {
7408 object.define_data("enumerable", Value::Bool(property.enumerable));
7409 }
7410 if names(|fields| fields.configurable) {
7411 object.define_data("configurable", Value::Bool(property.configurable));
7412 }
7413 Value::Object(object)
7414 }
7415
7416 // -- calling ------------------------------------------------------------
7417
7418 /// Call `callee` with `this` and `args`.
7419 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7420 let Value::Object(function) = &callee else {
7421 // `typeof x === "function"` is not enough to make `x()` legal: only a
7422 // callable object is. `null` and `undefined` need no special wording
7423 // here — their `ToString` already reads the way the reference's does.
7424 let what = format!("{} is not a function", callee.to_js_string());
7425 return Err(Signal::Throw(self.make_error("TypeError", &what)));
7426 };
7427 // A proxy of a function is called through its `apply` trap. It has no
7428 // `ObjectKind::Function` of its own, so this has to come before the dispatch
7429 // below, and a proxy of a non-function has nothing to forward to.
7430 if function.proxy_state().is_some() {
7431 return match self.proxy_apply(function, this, args)? {
7432 Some(result) => Ok(result),
7433 None => Err(Signal::Throw(
7434 self.make_error("TypeError", "proxy target is not callable"),
7435 )),
7436 };
7437 }
7438 let callable = function.with(|data| match &data.kind {
7439 ObjectKind::Function(callable) => match callable {
7440 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7441 // The `Rc` is cloned out so the borrow of this object's data is released
7442 // before the closure runs: the closure may touch the same object.
7443 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7444 Callable::Bound {
7445 target,
7446 this,
7447 args: leading,
7448 } => Some(NativeCall::Bound {
7449 target: target.clone(),
7450 this: this.clone(),
7451 leading: leading.clone(),
7452 }),
7453 Callable::Bytecode { code, env } => {
7454 Some(NativeCall::Bytecode(code.clone(), env.clone()))
7455 }
7456 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7457 Callable::PromiseResolve(promise) => {
7458 Some(NativeCall::PromiseResolve(promise.clone()))
7459 }
7460 Callable::PromiseReject(promise) => {
7461 Some(NativeCall::PromiseReject(promise.clone()))
7462 }
7463 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7464 state: state.clone(),
7465 }),
7466 Callable::ThenShim {
7467 handler,
7468 resolve,
7469 reject,
7470 fulfilled,
7471 } => Some(NativeCall::ThenShim {
7472 handler: handler.clone(),
7473 resolve: resolve.clone(),
7474 reject: reject.clone(),
7475 fulfilled: *fulfilled,
7476 }),
7477 Callable::AwaitResume {
7478 coroutine,
7479 promise,
7480 kind,
7481 } => Some(NativeCall::AwaitResume {
7482 coroutine: coroutine.clone(),
7483 promise: promise.clone(),
7484 kind: *kind,
7485 }),
7486 Callable::CombinatorSettle {
7487 state,
7488 index,
7489 fulfilled,
7490 } => Some(NativeCall::CombinatorSettle {
7491 state: state.clone(),
7492 index: *index,
7493 fulfilled: *fulfilled,
7494 }),
7495 Callable::FinallyShim {
7496 callback,
7497 fulfilled,
7498 constructor,
7499 } => Some(NativeCall::FinallyShim {
7500 callback: callback.clone(),
7501 fulfilled: *fulfilled,
7502 constructor: constructor.clone(),
7503 }),
7504 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7505 Callable::CompletedReturn {
7506 generator,
7507 promise,
7508 rejected,
7509 } => Some(NativeCall::CompletedReturn {
7510 generator: generator.clone(),
7511 promise: promise.clone(),
7512 rejected: *rejected,
7513 }),
7514 Callable::YieldResult {
7515 generator,
7516 promise,
7517 done,
7518 } => Some(NativeCall::YieldResult {
7519 generator: generator.clone(),
7520 promise: promise.clone(),
7521 done: *done,
7522 }),
7523 Callable::DisposeStep {
7524 remaining,
7525 promise,
7526 error,
7527 rejected,
7528 } => Some(NativeCall::DisposeStep {
7529 remaining: remaining.clone(),
7530 promise: promise.clone(),
7531 error: error.clone(),
7532 rejected: *rejected,
7533 }),
7534 Callable::GeneratorResume {
7535 generator,
7536 promise,
7537 kind,
7538 } => Some(NativeCall::GeneratorResume {
7539 generator: generator.clone(),
7540 promise: promise.clone(),
7541 kind: *kind,
7542 }),
7543 Callable::SettlePromise {
7544 promise,
7545 value,
7546 rejected,
7547 } => Some(NativeCall::SettlePromise {
7548 promise: promise.clone(),
7549 value: value.clone(),
7550 rejected: *rejected,
7551 }),
7552 },
7553 _ => None,
7554 });
7555 match callable {
7556 Some(NativeCall::Host(func)) => {
7557 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7558 // function by name rather than stopping at the caller.
7559 let frame_less = function
7560 .own_property("_frame_less")
7561 .and_then(|property| property.value)
7562 .is_some_and(|value| value.to_boolean());
7563 let outer = if frame_less {
7564 None
7565 } else {
7566 self.native_frames
7567 .push((function.clone(), self.frames.len()));
7568 Some(self.current_native.replace(function.clone()))
7569 };
7570 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
7571 // constructor reads it through `current_new_target` because it is handed
7572 // `undefined` for `this`. Taking the parked value here is what stops a
7573 // *plain* call made from inside a constructor body from seeing the
7574 // enclosing `new.target`.
7575 let parked = self.pending_new_target.take();
7576 let result = {
7577 let outer_new_target = std::mem::replace(
7578 &mut self.active_new_target,
7579 parked.unwrap_or(Value::Undefined),
7580 );
7581 let result = {
7582 let mut body = func.borrow_mut();
7583 body(self, this, &args)
7584 };
7585 self.active_new_target = outer_new_target;
7586 result
7587 };
7588 if !frame_less {
7589 self.native_frames.pop();
7590 self.current_native = outer.flatten();
7591 }
7592 result
7593 }
7594 Some(NativeCall::Native(func)) => {
7595 // A function marked `_frame_less` is one the reference implements
7596 // without a call frame — `eval` is the only one so far.
7597 let frame_less = function
7598 .own_property("_frame_less")
7599 .and_then(|property| property.value)
7600 .is_some_and(|value| value.to_boolean());
7601 let outer = if frame_less {
7602 None
7603 } else {
7604 self.native_frames
7605 .push((function.clone(), self.frames.len()));
7606 Some(self.current_native.replace(function.clone()))
7607 };
7608 let parked = self.pending_new_target.take();
7609 let outer_new_target = std::mem::replace(
7610 &mut self.active_new_target,
7611 parked.unwrap_or(Value::Undefined),
7612 );
7613 let result = func(self, this, &args);
7614 self.active_new_target = outer_new_target;
7615 if !frame_less {
7616 self.native_frames.pop();
7617 self.current_native = outer.flatten();
7618 }
7619 result
7620 }
7621 Some(NativeCall::Revoker(slots)) => {
7622 // Idempotent: revoking twice answers `undefined` again rather than
7623 // complaining, which is what the spec says and what a `finally` block
7624 // relies on.
7625 let mut state = slots.borrow_mut();
7626 state.target = None;
7627 state.handler = None;
7628 Ok(Value::Undefined)
7629 }
7630 Some(NativeCall::PromiseResolve(promise)) => {
7631 // One-shot: a second call is silently ignored, which
7632 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
7633 let value = args.first().cloned().unwrap_or(Value::Undefined);
7634 self.resolve_promise_with(&promise, value)?;
7635 Ok(Value::Undefined)
7636 }
7637 Some(NativeCall::PromiseReject(promise)) => {
7638 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7639 self.reject_promise(&promise, reason);
7640 Ok(Value::Undefined)
7641 }
7642 Some(NativeCall::ThenShim {
7643 handler,
7644 resolve,
7645 reject,
7646 fulfilled,
7647 }) => {
7648 // `PerformPromiseThen` with a capability: run the handler, then settle
7649 // through the capability's own pair. A throw from the handler is the
7650 // rejection, and a throw from the capability's `resolve` is not caught —
7651 // exactly the spec's `?`.
7652 let value = args.first().cloned().unwrap_or(Value::Undefined);
7653 match handler {
7654 Some(handler) => {
7655 match self.call_value(handler, Value::Undefined, vec![value]) {
7656 Ok(result) => {
7657 self.call_value(resolve, Value::Undefined, vec![result])?;
7658 }
7659 Err(Signal::Throw(reason)) => {
7660 self.call_value(reject, Value::Undefined, vec![reason])?;
7661 }
7662 Err(signal) => return Err(signal),
7663 }
7664 }
7665 None => {
7666 let handler = if fulfilled { resolve } else { reject };
7667 self.call_value(handler, Value::Undefined, vec![value])?;
7668 }
7669 }
7670 Ok(Value::Undefined)
7671 }
7672 Some(NativeCall::CapabilityExecutor { state }) => {
7673 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7674 // slot holds a value yet. The test is on the *values*, not on a call count —
7675 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7676 // called-twice`'s first case does exactly that), while a second call after a
7677 // real pair is the `TypeError`.
7678 let defined = |name: &str| {
7679 state
7680 .own_property(name)
7681 .and_then(|property| property.value)
7682 .is_some_and(|value| !matches!(value, Value::Undefined))
7683 };
7684 if defined("resolve") || defined("reject") {
7685 return Err(self.type_error("promise capability executor called twice"));
7686 }
7687 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7688 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7689 state.define_data("resolve", resolve);
7690 state.define_data("reject", reject);
7691 Ok(Value::Undefined)
7692 }
7693 Some(NativeCall::CombinatorSettle {
7694 state,
7695 index,
7696 fulfilled,
7697 }) => {
7698 let value = args.first().cloned().unwrap_or(Value::Undefined);
7699 self.settle_combinator(&state, index, fulfilled, value)?;
7700 Ok(Value::Undefined)
7701 }
7702 Some(NativeCall::AwaitResume {
7703 coroutine,
7704 promise,
7705 kind,
7706 }) => {
7707 // Resume *inline*, in the reaction that delivered the value. Deferring it
7708 // by another job inserts a tick between every `await` and its
7709 // continuation, which reorders `await` against unrelated `then` chains —
7710 // `f().then(g)` then runs before `f`'s own next statement.
7711 self.drive_async(
7712 &coroutine,
7713 &promise,
7714 kind,
7715 args.first().cloned().unwrap_or(Value::Undefined),
7716 )
7717 .map(|()| Value::Undefined)
7718 }
7719 Some(NativeCall::FinallyShim {
7720 callback,
7721 fulfilled,
7722 constructor,
7723 }) => {
7724 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
7725 // that settles with the *original* outcome once the callback's result has
7726 // settled. The callback's own value is discarded — that is the whole
7727 // difference between `finally` and `then`.
7728 let original = args.first().cloned().unwrap_or(Value::Undefined);
7729 let result = match &callback {
7730 Some(callback) => {
7731 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7732 }
7733 None => Value::Undefined,
7734 };
7735 // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
7736 // already a promise of this constructor is reused rather than rewrapped.
7737 let resolved = self.promise_resolve_for(&constructor, result)?;
7738 let Value::Object(resolved) = resolved else {
7739 return Ok(original);
7740 };
7741 // The wait is a chained promise rather than a bare return, so a callback
7742 // that returns a slow promise really does delay the continuation.
7743 let waiting = self.new_promise();
7744 let pass = JsObject::function(
7745 self.heap,
7746 Some(self.realm.function_proto.clone()),
7747 Callable::SettlePromise {
7748 promise: waiting.clone(),
7749 value: original,
7750 rejected: !fulfilled,
7751 },
7752 );
7753 let pass = Value::Object(pass);
7754 // Whichever way the callback's promise settles, the original outcome wins.
7755 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
7756 Ok(Value::Object(waiting))
7757 }
7758 Some(NativeCall::DisposeStep {
7759 remaining,
7760 promise,
7761 error,
7762 rejected,
7763 }) => {
7764 let error = if rejected {
7765 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7766 self.merge_dispose_error(reason, error)
7767 } else {
7768 error
7769 };
7770 self.dispose_step(&remaining, &promise, error)?;
7771 Ok(Value::Undefined)
7772 }
7773 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7774 Some(NativeCall::CompletedReturn {
7775 generator,
7776 promise,
7777 rejected,
7778 }) => {
7779 let value = args.first().cloned().unwrap_or(Value::Undefined);
7780 let outcome = if rejected {
7781 AsyncOutcome::Error(value)
7782 } else {
7783 AsyncOutcome::Value(self.iterator_result(value, true)?)
7784 };
7785 self.settle_async_request(&generator, &promise, outcome)?;
7786 Ok(Value::Undefined)
7787 }
7788 Some(NativeCall::YieldResult {
7789 generator,
7790 promise,
7791 done,
7792 }) => {
7793 let value = args.first().cloned().unwrap_or(Value::Undefined);
7794 let result = self.iterator_result(value, done)?;
7795 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7796 Ok(Value::Undefined)
7797 }
7798 Some(NativeCall::GeneratorResume {
7799 generator,
7800 promise,
7801 kind,
7802 }) => {
7803 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7804 // tick and reorders the generator against other chains.
7805 self.step_async_generator(
7806 &generator,
7807 &promise,
7808 kind,
7809 args.first().cloned().unwrap_or(Value::Undefined),
7810 )
7811 .map(|()| Value::Undefined)
7812 }
7813 Some(NativeCall::SettlePromise {
7814 promise,
7815 value,
7816 rejected,
7817 }) => {
7818 if rejected {
7819 self.reject_promise(&promise, value);
7820 } else {
7821 self.fulfill_promise(&promise, value);
7822 }
7823 Ok(Value::Undefined)
7824 }
7825 Some(NativeCall::Bound {
7826 target,
7827 this: bound_this,
7828 leading,
7829 }) => {
7830 let mut all = leading;
7831 all.extend(args);
7832 self.call_value(target, bound_this, all)
7833 }
7834 Some(NativeCall::Bytecode(code, env)) => {
7835 if code.code.kind.is_generator() {
7836 return self.new_generator(callee, this, args);
7837 }
7838 if code.code.kind.is_async() {
7839 // Same coroutine machinery as a generator; the difference is only in
7840 // what the completion does — see `new_async_function`.
7841 return self.new_async_function(callee, this, args);
7842 }
7843 self.execute(code, env, this, args, callee)
7844 }
7845 None => Err(Signal::Throw(
7846 self.make_error("TypeError", "not a function"),
7847 )),
7848 }
7849 }
7850
7851 /// Give a freshly built function its own `prototype` object.
7852 ///
7853 /// Every function that can be used with `new` carries one, and its
7854 /// `constructor` points back at the function — a reference cycle, which is
7855 /// exactly what the collector's cycle pass exists to reclaim.
7856 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
7857 self.install_function_prototype_with(function, None);
7858 }
7859
7860 /// [`Interp::install_function_prototype`] with an explicit parent for the new
7861 /// `prototype` object.
7862 ///
7863 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
7864 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
7865 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
7866 /// `None` means `%Object.prototype%`.
7867 fn install_function_prototype_with(
7868 &mut self,
7869 function: &Gc<JsObject>,
7870 parent: Option<Gc<JsObject>>,
7871 ) {
7872 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
7873 let prototype = self.new_object(Some(parent));
7874 let constructor = Value::Object(function.clone());
7875 prototype.define(
7876 "constructor",
7877 Property::with_attributes(constructor, true, false),
7878 );
7879 let value = Value::Object(prototype);
7880 function.define("prototype", Property::prototype_of(value, true));
7881 }
7882
7883 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
7884 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
7885 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
7886 ///
7887 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
7888 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
7889 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
7890 /// is `[]` there.
7891 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
7892 let prototype = self.new_object(Some(parent));
7893 let value = Value::Object(prototype);
7894 function.define("prototype", Property::prototype_of(value, true));
7895 }
7896
7897 /// The `[[Prototype]]` a newly created generator object gets:
7898 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
7899 ///
7900 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
7901 /// function's `prototype` is writable, so a script can replace it with anything, and
7902 /// only an *object* is consulted.
7903 fn generator_instance_proto(
7904 &mut self,
7905 function: &Gc<JsObject>,
7906 default: Gc<JsObject>,
7907 ) -> JsResult<Gc<JsObject>> {
7908 match self.get_property(function, "prototype")? {
7909 Some(Value::Object(prototype)) => Ok(prototype),
7910 _ => Ok(default),
7911 }
7912 }
7913
7914 /// A getter or setter that reads or writes the reference cell behind a mapped
7915 /// `arguments` index.
7916 ///
7917 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
7918 /// count — which is what the collector treats as "a reference from outside the
7919 /// heap". The closure therefore keeps the cell alive for exactly as long as the
7920 /// accessor is reachable, which is the same lifetime the arguments object has.
7921 ///
7922 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
7923 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
7924 /// parameter value and the arguments object reaches the closure, never the other
7925 /// way round. Nothing the collector has to see is hidden.
7926 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
7927 let name = if is_setter { "set" } else { "get" };
7928 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
7929 if is_setter {
7930 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
7931 Ok(Value::Undefined)
7932 } else {
7933 Ok(cell.get())
7934 }
7935 };
7936 self.new_host_function(name, 1, Box::new(func))
7937 }
7938
7939 /// The object `special_object` builds.
7940 ///
7941 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
7942 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
7943 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
7944 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
7945 /// write through `arguments` does not reach the parameter.
7946 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
7947 match magic {
7948 0 | 1 => {
7949 let args = self.frame().passed().to_vec();
7950 let proto = self.realm.object_proto.clone();
7951 let object = self.new_object(Some(proto));
7952 // The marker `Object.prototype.toString` needs: an arguments object is an
7953 // ordinary object apart from reporting `[object Arguments]`, and that has
7954 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
7955 // show up ahead of them in a key listing anyway — it is non-enumerable.
7956 self.internal_set(&object, "_class", self.string("Arguments"));
7957 // `length` is writable and configurable but neither enumerable nor a
7958 // plain data property: `Object.keys(arguments)` lists the indices only,
7959 // which is how `{...arguments}` copies them without the length.
7960 object.define(
7961 "length",
7962 Property::with_attributes(Value::Int(args.len() as i32), true, false),
7963 );
7964 // `magic == 1` is sloppy mode, where each index is *mapped* to the
7965 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
7966 // change `a`, and assigning `a` has to change `arguments[0]`.
7967 //
7968 // The shared storage is the parameter's reference cell. The compiler
7969 // gives every parameter of such a function one (see
7970 // `provide_body_arguments`), and the cell outlives the frame, so this
7971 // keeps working after the arguments object escapes.
7972 //
7973 // The index becomes an accessor rather than a data property. A mapped
7974 // index reports as a plain writable/enumerable data property through
7975 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
7976 // the getter/setter pair is only the plumbing underneath.
7977 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
7978 let frame = self.frame();
7979 frame
7980 .code
7981 .arg_cell
7982 .iter()
7983 .map(|cell| {
7984 (*cell >= 0)
7985 .then(|| frame.cells.get(*cell as usize).cloned())
7986 .flatten()
7987 })
7988 .collect()
7989 } else {
7990 Vec::new()
7991 };
7992 // Tell the object which indices are mapped, so
7993 // `Object.getOwnPropertyDescriptor` can report them as the data
7994 // properties the spec describes instead of the accessors that
7995 // implement the aliasing.
7996 if magic == 1 {
7997 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
7998 for cell in &mapped_cells {
7999 table.push(cell.clone());
8000 }
8001 object.set_mapped_arguments(table);
8002 }
8003 for (index, value) in args.into_iter().enumerate() {
8004 match mapped_cells.get(index).cloned().flatten() {
8005 Some(cell) => {
8006 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8007 let setter = self.new_mapped_arguments_accessor(cell, true);
8008 object.define(
8009 &index.to_string(),
8010 Property::accessor_with(
8011 Some(Value::Object(getter)),
8012 Some(Value::Object(setter)),
8013 true,
8014 ),
8015 );
8016 }
8017 None => object.define_data(&index.to_string(), value),
8018 }
8019 }
8020 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8021 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8022 // non-enumerable and non-configurable. It is not a nicety — it is the only
8023 // documented way to reach `%ThrowTypeError%`:
8024 //
8025 // Object.getOwnPropertyDescriptor(function(){"use strict";
8026 // return arguments;}(), "callee").get
8027 //
8028 // and the whole `ThrowTypeError/` directory is written against that
8029 // expression. Without it 13 cases failed with `cannot read property 'get'
8030 // of undefined`, which reads like a test harness bug rather than a missing
8031 // accessor.
8032 //
8033 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8034 // writable data property holding the function being called, and
8035 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8036 // `hasOwnProperty("callee")` hold there.
8037 if magic == 1 {
8038 let callee = self.frame().callee.clone();
8039 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8040 object.define("callee", Property::with_attributes(callee, true, false));
8041 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8042 && object.own_property("callee").is_none()
8043 {
8044 object.define(
8045 "callee",
8046 Property {
8047 getter: Some(Value::Object(thrower.clone())),
8048 setter: Some(Value::Object(thrower)),
8049 enumerable: false,
8050 configurable: false,
8051 ..Property::default()
8052 },
8053 );
8054 }
8055 // An arguments object is iterable: `[...arguments]` and
8056 // `for (const a of arguments)` both work, through the *array* iterator
8057 // because the object is array-like. Without this the whole spread form
8058 // reported "not iterable".
8059 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8060 let values = self
8061 .realm
8062 .array_proto
8063 .own_property("values")
8064 .and_then(|property| property.value);
8065 if let Some(values) = values {
8066 object.define_key(
8067 &iterator_key,
8068 Property::with_attributes(values, true, false),
8069 );
8070 }
8071 Ok(Value::Object(object))
8072 }
8073 // `this.active_func`: the constructor `super()` resolves against.
8074 //
8075 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8076 // own, so it inherits this from the function it was written in along with `this`
8077 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8078 // the constructor and is called back later (`iter.return = () => super()`) has
8079 // the constructor nowhere on the stack. The compiler therefore reads it out of
8080 // a closure variable of the enclosing function, exactly as the reference does
8081 // with its `this_active_func` local.
8082 2 => Ok(self
8083 .current_callee()
8084 .map_or(Value::Undefined, Value::Object)),
8085 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8086 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8087 // its own either, so the lookup walks out to the nearest non-arrow frame for
8088 // the same reason as `this.active_func` above — without that, `super()` inside
8089 // an arrow passed `undefined` as the new target and the parent constructor was
8090 // then rejected for being invoked without `new`.
8091 3 => Ok(self
8092 .eval_new_target
8093 .clone()
8094 .unwrap_or_else(|| self.frame().new_target.clone())),
8095 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8096 // An arrow has none of its own, so the lookup walks out to the enclosing
8097 // method — which is why `super` works inside an arrow inside a method.
8098 4 => Ok(self
8099 .frames
8100 .iter()
8101 .rev()
8102 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8103 .map_or(Value::Undefined, Value::Object)),
8104 // `import.meta`: the innermost module body's meta object. Outside a module
8105 // the compiler never emits this, so an empty fallback is unreachable rather
8106 // than permissive.
8107 6 => {
8108 let name = self.module_stack.last().cloned();
8109 let meta = name
8110 .and_then(|name| self.modules.get(&name).cloned())
8111 .and_then(|module| module.with(|r| r.import_meta.clone()));
8112 Ok(meta.map_or(Value::Undefined, Value::Object))
8113 }
8114 other => Err(Signal::Throw(self.make_error(
8115 "InternalError",
8116 &format!("special_object {other} is not implemented yet"),
8117 ))),
8118 }
8119 }
8120
8121 /// `[[HomeObject]]` of the innermost function that has one, if any.
8122 ///
8123 /// An arrow has none, so the search walks out to the enclosing method — the same
8124 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8125 /// inside a method.
8126 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8127 self.frames
8128 .iter()
8129 .rev()
8130 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8131 }
8132
8133 /// The dispose method a `using` declaration should snapshot, or an error.
8134 ///
8135 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8136 /// is what makes a resource that only knows the synchronous protocol usable in both
8137 /// forms.
8138 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8139 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8140 if value.is_nullish() {
8141 return Ok(Value::Undefined);
8142 }
8143 let Some(object) = value.as_object() else {
8144 return Err(self.type_error("not an object"));
8145 };
8146 let mut method = if await_form {
8147 let found = self.get_property_key(
8148 object,
8149 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8150 )?;
8151 match found {
8152 Some(found) if !found.is_nullish() => Some(found),
8153 _ => self
8154 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8155 }
8156 } else {
8157 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8158 };
8159 let Some(found) = method.take() else {
8160 return Err(self.type_error("value is not disposable"));
8161 };
8162 if found.is_nullish() {
8163 return Err(self.type_error("value is not disposable"));
8164 }
8165 let callable = found.as_object().is_some_and(|object| object.is_callable());
8166 if !callable {
8167 return Err(self.type_error("dispose method is not a function"));
8168 }
8169 Ok(found)
8170 }
8171
8172 /// Call one resource's disposer, folding a failure into `error_state`.
8173 ///
8174 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8175 /// because a captured `using` binding lives in its reference cell and the local slot is
8176 /// stale — a closure over the resource is legal and must not change what is disposed.
8177 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8178 let value = self.get_loc(slot);
8179 let method = self.get_loc(slot + 1);
8180 // A resource that was never initialised — its declaration threw — or that is
8181 // `null`/`undefined` has nothing to dispose.
8182 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8183 return Ok(error_state);
8184 }
8185 if matches!(method, Value::Undefined | Value::Uninitialized) {
8186 return Ok(error_state);
8187 }
8188 match self.call_value(method, value, Vec::new()) {
8189 Ok(_) => Ok(error_state),
8190 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8191 Err(other) => Err(other),
8192 }
8193 }
8194
8195 /// Combine a disposal failure with whatever was already going wrong.
8196 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8197 if matches!(error_state, Value::Uninitialized) {
8198 return new_error;
8199 }
8200 self.new_suppressed_error(new_error, error_state)
8201 }
8202
8203 /// A `SuppressedError` instance built straight from its prototype.
8204 ///
8205 /// Not through the constructor: a script that rewrites
8206 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8207 /// error wrapping.
8208 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8209 let proto = self
8210 .realm
8211 .suppressed_error_proto
8212 .clone()
8213 .unwrap_or_else(|| self.realm.error_proto.clone());
8214 let object = self.new_object(Some(proto));
8215 object.define("error", Property::with_attributes(error, true, true));
8216 object.define(
8217 "suppressed",
8218 Property::with_attributes(suppressed, true, true),
8219 );
8220 object.define(
8221 "message",
8222 Property::with_attributes(self.string("SuppressedError"), true, true),
8223 );
8224 self.internal_set(&object, "_class", self.string("Error"));
8225 self.add_stack(&object);
8226 Value::Object(object)
8227 }
8228
8229 /// Call `callee`, or push its frame and let the main loop run it.
8230 ///
8231 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8232 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8233 /// continues, so `function f(){ return f() }` costs heap and stops at
8234 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8235 /// is entered directly, and natives do not re-enter JavaScript in this
8236 /// milestone.
8237 ///
8238 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8239 /// because the returning frame will.
8240 /// The elements of an array-like value, as a call argument list.
8241 ///
8242 /// `apply` accepts any array-like, not only a real array: the reference reads
8243 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8244 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8245 let Some(object) = value.as_object().cloned() else {
8246 if value.is_nullish() {
8247 // `f.apply(this, null)` passes no arguments at all.
8248 return Ok(Vec::new());
8249 }
8250 return Err(self.type_error("createListFromArrayLike called on non-object"));
8251 };
8252 let length = match self.get_property(&object, "length")? {
8253 Some(length) => length.to_number(),
8254 None => 0.0,
8255 };
8256 if !length.is_finite() || length <= 0.0 {
8257 return Ok(Vec::new());
8258 }
8259 let length = (length as usize).min(1_000_000);
8260 let mut args = Vec::with_capacity(length);
8261 for index in 0..length {
8262 let element = self.get_property(&object, &index.to_string())?;
8263 args.push(element.unwrap_or(Value::Undefined));
8264 }
8265 Ok(args)
8266 }
8267
8268 /// Turn a call to a generator function into a generator object.
8269 ///
8270 /// The frame is built exactly as an ordinary call would build it, then detached and
8271 /// stored in the generator before any body instruction runs — which is what makes
8272 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8273 /// is `initial_yield`, the first instruction of every suspending body.
8274 pub fn new_generator(
8275 &mut self,
8276 function: Value,
8277 this: Value,
8278 args: Vec<Value>,
8279 ) -> JsResult<Value> {
8280 let Some(object) = function.as_object().cloned() else {
8281 return Err(self.type_error("not a generator function"));
8282 };
8283 let Some((code, env)) = bytecode_of(&object) else {
8284 return Err(self.type_error("not a generator function"));
8285 };
8286 let is_async = code.code.kind.is_async();
8287 self.push_frame(code, env, this, args, function)?;
8288 let frame = self.frames.pop().expect("push_frame just pushed it");
8289 // A fresh generator is *suspended at start*: the body has not run, so a
8290 // `return`/`throw` on it finishes without executing anything.
8291 let mut state = GeneratorState {
8292 frame: Some(frame),
8293 phase: GeneratorPhase::SuspendedStart,
8294 parked_on_await: false,
8295 parked_on_yield_star: false,
8296 requests: std::collections::VecDeque::new(),
8297 async_busy: false,
8298 is_async,
8299 };
8300 // Run to the first suspension. For a generator that is `initial_yield`, so no
8301 // body code runs; for a malformed body it would be the first `yield`.
8302 // An `async function*` answers an async generator: same coroutine, but its
8303 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8304 let default_proto = if is_async {
8305 self.realm
8306 .async_generator_proto
8307 .clone()
8308 .unwrap_or_else(|| self.realm.generator_proto.clone())
8309 } else {
8310 self.realm.generator_proto.clone()
8311 };
8312 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8313 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8314 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8315 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8316 let proto = self.generator_instance_proto(&object, default_proto)?;
8317 let generator = self.new_object(Some(proto));
8318 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8319 Ok(_) => {}
8320 Err(error) => return Err(error),
8321 }
8322 generator.with_mut(|data| {
8323 data.kind = ObjectKind::Generator(Box::new(state));
8324 });
8325 Ok(Value::Object(generator))
8326 }
8327
8328 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8329 ///
8330 /// Returns the `{value, done}` object itself rather than the pair, because a
8331 /// `yield*` suspension already has one — the inner iterator's own result — and the
8332 /// protocol says to hand that straight through rather than nest it.
8333 /// Advance a generator and report *why* it parked.
8334 ///
8335 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8336 /// "hand this value to the caller" — but an async generator does: an `await` has to
8337 /// settle before it can answer, while a `yield` is the answer.
8338 fn resume_generator_detailed(
8339 &mut self,
8340 generator: &Gc<JsObject>,
8341 kind: ResumeKind,
8342 value: Value,
8343 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8344 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8345 ObjectKind::Generator(state) => {
8346 let is_async = state.is_async;
8347 Some(std::mem::replace(
8348 state.as_mut(),
8349 GeneratorState {
8350 frame: None,
8351 phase: GeneratorPhase::Executing,
8352 parked_on_await: false,
8353 parked_on_yield_star: false,
8354 requests: std::collections::VecDeque::new(),
8355 // **Busy while the body runs**, so a `next()` called *from inside*
8356 // the body queues instead of being served. §27.6.3.7
8357 // `AsyncGeneratorResumeNext` returns immediately for the state
8358 // "executing", and the request is served once the body suspends;
8359 // with `false` here the re-entrant call found an empty frame and
8360 // rejected (`request-queue-order-state-executing`).
8361 async_busy: is_async,
8362 is_async,
8363 },
8364 ))
8365 }
8366 _ => None,
8367 }) else {
8368 return Err(self.type_error("not a generator"));
8369 };
8370 let result = self.step_generator(&mut state, kind, value);
8371 // Requests queued *while* the body ran live on the placeholder, because the real
8372 // state is out of the object for the duration. They have to be folded back in
8373 // before the placeholder is overwritten, or the promise they carry never settles.
8374 let queued = generator.with_mut(|data| match &mut data.kind {
8375 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8376 _ => std::collections::VecDeque::new(),
8377 });
8378 state.requests.extend(queued);
8379 generator.with_mut(|data| {
8380 data.kind = ObjectKind::Generator(Box::new(state));
8381 });
8382 result
8383 }
8384
8385 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8386 ///
8387 /// Returns the `{value, done}` object itself rather than the pair, because a
8388 /// `yield*` suspension already has one — the inner iterator's own result — and the
8389 /// protocol says to hand that straight through rather than nest it.
8390 pub fn resume_generator(
8391 &mut self,
8392 generator: &Gc<JsObject>,
8393 kind: ResumeKind,
8394 value: Value,
8395 ) -> JsResult<Value> {
8396 let (value, done, ready, _reason) =
8397 self.resume_generator_detailed(generator, kind, value)?;
8398 if ready {
8399 return Ok(value);
8400 }
8401 self.iterator_result(value, done)
8402 }
8403
8404 /// `next`/`return`/`throw` on an async generator, which answer a promise.
8405 ///
8406 /// The body is the same coroutine a sync generator runs; what changes is that an
8407 /// `await` inside it has to settle before the method can answer, so the step is
8408 /// driven off the job queue rather than returning inline.
8409 pub fn resume_async_generator(
8410 &mut self,
8411 generator: &Gc<JsObject>,
8412 kind: ResumeKind,
8413 value: Value,
8414 ) -> JsResult<Value> {
8415 let promise = self.new_promise();
8416 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8417 // that order, and the second value must reach the *second* `yield`.
8418 let idle = generator.with_mut(|data| match &mut data.kind {
8419 ObjectKind::Generator(state) => {
8420 state.requests.push_back(AsyncRequest {
8421 kind,
8422 value,
8423 promise: promise.clone(),
8424 });
8425 !state.async_busy
8426 }
8427 _ => false,
8428 });
8429 if idle {
8430 self.next_async_request(generator)?;
8431 }
8432 Ok(Value::Object(promise))
8433 }
8434
8435 /// Serve the front queued request, if the generator is free to run one.
8436 ///
8437 /// A finished generator answers from the queue without running anything:
8438 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8439 /// first, and `throw(e)` rejects.
8440 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8441 enum Front {
8442 Idle,
8443 Run(ResumeKind, Value, Gc<JsObject>),
8444 Finished(ResumeKind, Value, Gc<JsObject>),
8445 }
8446 let front = generator.with_mut(|data| match &mut data.kind {
8447 ObjectKind::Generator(state) => {
8448 let Some(request) = state.requests.front() else {
8449 return Front::Idle;
8450 };
8451 // Busy means a request is still in flight — awaiting inside the body, not
8452 // finished. Serving another now would interleave two requests.
8453 if state.async_busy && state.phase != GeneratorPhase::Completed {
8454 return Front::Idle;
8455 }
8456 let kind = request.kind;
8457 let value = request.value.clone();
8458 let promise = request.promise.clone();
8459 state.async_busy = true;
8460 if state.phase == GeneratorPhase::Completed {
8461 Front::Finished(kind, value, promise)
8462 } else {
8463 Front::Run(kind, value, promise)
8464 }
8465 }
8466 _ => Front::Idle,
8467 });
8468 match front {
8469 Front::Idle => Ok(()),
8470 Front::Run(kind, value, promise) => {
8471 self.step_async_generator(generator, &promise, kind, value)
8472 }
8473 Front::Finished(kind, value, promise) => match kind {
8474 ResumeKind::Throw => {
8475 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
8476 }
8477 ResumeKind::Next | ResumeKind::Start => {
8478 let result = self.iterator_result(Value::Undefined, true)?;
8479 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
8480 }
8481 ResumeKind::Return => {
8482 // `js_async_generator_completed_return`: the value is awaited before it
8483 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
8484 // finished generator answers `1`, not a promise.
8485 let resolved = match self.promise_resolve_intrinsic(value) {
8486 Ok(resolved) => resolved,
8487 Err(Signal::Throw(reason)) => {
8488 return self.settle_async_request(
8489 generator,
8490 &promise,
8491 AsyncOutcome::Error(reason),
8492 );
8493 }
8494 Err(other) => return Err(other),
8495 };
8496 let done = JsObject::function(
8497 self.heap,
8498 Some(self.realm.function_proto.clone()),
8499 Callable::CompletedReturn {
8500 generator: generator.clone(),
8501 promise: promise.clone(),
8502 rejected: false,
8503 },
8504 );
8505 let failed = JsObject::function(
8506 self.heap,
8507 Some(self.realm.function_proto.clone()),
8508 Callable::CompletedReturn {
8509 generator: generator.clone(),
8510 promise: promise.clone(),
8511 rejected: true,
8512 },
8513 );
8514 let Value::Object(resolved) = resolved else {
8515 return self.settle_async_request(
8516 generator,
8517 &promise,
8518 AsyncOutcome::Error(Value::Undefined),
8519 );
8520 };
8521 self.perform_then(
8522 &resolved,
8523 Some(Value::Object(done)),
8524 Some(Value::Object(failed)),
8525 )?;
8526 Ok(())
8527 }
8528 },
8529 }
8530 }
8531
8532 /// Settle the front request and start the next one.
8533 ///
8534 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
8535 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
8536 /// generator would strand every later request.
8537 fn settle_async_request(
8538 &mut self,
8539 generator: &Gc<JsObject>,
8540 promise: &Gc<JsObject>,
8541 outcome: AsyncOutcome,
8542 ) -> JsResult<()> {
8543 let settled = generator.with_mut(|data| match &mut data.kind {
8544 ObjectKind::Generator(state) => {
8545 let front = state.requests.front();
8546 debug_assert!(
8547 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
8548 "a request settled outside its turn"
8549 );
8550 state.requests.pop_front();
8551 state.async_busy = false;
8552 true
8553 }
8554 _ => false,
8555 });
8556 if settled {
8557 match outcome {
8558 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
8559 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
8560 }
8561 }
8562 self.next_async_request(generator)
8563 }
8564
8565 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
8566 ///
8567 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
8568 /// disposer runs **synchronously** — the reference starts it before returning, which
8569 /// a test can observe by logging after the call — and the rest follow once their
8570 /// predecessor settles.
8571 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
8572 let promise = self.new_promise();
8573 let mut pairs = Vec::with_capacity(resources.len());
8574 for (value, method) in resources {
8575 let pair = self.new_array(vec![value, method]);
8576 pairs.push(Value::Object(pair));
8577 }
8578 let remaining = self.new_array(pairs);
8579 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
8580 Ok(Value::Object(promise))
8581 }
8582
8583 /// One link of the `disposeAsync` chain.
8584 ///
8585 /// Loops while the disposers finish synchronously, and parks on the first thenable it
8586 /// meets — pushing itself back in as the continuation, with the accumulated error
8587 /// carried along so a later failure can still be folded into the `SuppressedError`.
8588 fn dispose_step(
8589 &mut self,
8590 remaining: &Gc<JsObject>,
8591 promise: &Gc<JsObject>,
8592 mut error: Value,
8593 ) -> JsResult<()> {
8594 loop {
8595 let length = remaining.array_length().unwrap_or(0);
8596 if length == 0 {
8597 if matches!(error, Value::Uninitialized) {
8598 self.fulfill_promise(promise, Value::Undefined);
8599 } else {
8600 self.reject_promise(promise, error);
8601 }
8602 return Ok(());
8603 }
8604 let Some(Value::Object(pair)) = remaining
8605 .array_get(length - 1)
8606 .filter(|v| !matches!(v, Value::Hole))
8607 else {
8608 remaining.array_truncate(self.heap, length - 1);
8609 continue;
8610 };
8611 remaining.array_truncate(self.heap, length - 1);
8612 let value = pair.array_get(0).unwrap_or(Value::Undefined);
8613 let Some(Value::Object(method)) = pair.array_get(1) else {
8614 continue;
8615 };
8616 if !method.is_callable() {
8617 continue;
8618 }
8619 match self.call_value(Value::Object(method), value, Vec::new()) {
8620 Ok(result) => {
8621 if !self.is_thenable(&result)? {
8622 // Finished synchronously; the next disposer is the next iteration.
8623 continue;
8624 }
8625 let awaited = match self.promise_resolve_value(result) {
8626 Ok(awaited) => awaited,
8627 Err(Signal::Throw(reason)) => {
8628 self.reject_promise(promise, reason);
8629 return Ok(());
8630 }
8631 Err(other) => return Err(other),
8632 };
8633 let Value::Object(awaited) = awaited else {
8634 continue;
8635 };
8636 let ok = JsObject::function(
8637 self.heap,
8638 Some(self.realm.function_proto.clone()),
8639 Callable::DisposeStep {
8640 remaining: remaining.clone(),
8641 promise: promise.clone(),
8642 error: error.clone(),
8643 rejected: false,
8644 },
8645 );
8646 let failed = JsObject::function(
8647 self.heap,
8648 Some(self.realm.function_proto.clone()),
8649 Callable::DisposeStep {
8650 remaining: remaining.clone(),
8651 promise: promise.clone(),
8652 error,
8653 rejected: true,
8654 },
8655 );
8656 self.perform_then(
8657 &awaited,
8658 Some(Value::Object(ok)),
8659 Some(Value::Object(failed)),
8660 )?;
8661 return Ok(());
8662 }
8663 Err(Signal::Throw(thrown)) => {
8664 error = self.merge_dispose_error(thrown, error);
8665 }
8666 Err(other) => return Err(other),
8667 }
8668 }
8669 }
8670
8671 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8672 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8673 let Value::Object(object) = value else {
8674 return Ok(false);
8675 };
8676 Ok(matches!(
8677 self.get_property(object, "then")?,
8678 Some(Value::Object(then)) if then.is_callable()
8679 ))
8680 }
8681
8682 /// One step of an async generator, settling `promise` with an `{value, done}` result.
8683 fn step_async_generator(
8684 &mut self,
8685 generator: &Gc<JsObject>,
8686 promise: &Gc<JsObject>,
8687 kind: ResumeKind,
8688 value: Value,
8689 ) -> JsResult<()> {
8690 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
8691 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
8692 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
8693 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
8694 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
8695 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
8696 // out of the same read, one as a rejection and one as a rethrow.
8697 //
8698 // Narrow on purpose: only a value that is *already a promise* is inspected, so
8699 // nothing changes for `return 1` and the extra read is a plain data-property
8700 // lookup on the intrinsic case.
8701 if kind == ResumeKind::Return
8702 && let Value::Object(object) = &value
8703 && self.promise_state(object).is_some()
8704 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
8705 {
8706 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
8707 }
8708 let stepped = self.resume_generator_detailed(generator, kind, value);
8709 let (value, done, ready, reason) = match stepped {
8710 Ok(stepped) => stepped,
8711 Err(Signal::Throw(reason)) => {
8712 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8713 }
8714 Err(other) => return Err(other),
8715 };
8716 // Only an `await` has to wait before the method can answer.
8717 if !done && reason == Some(SuspendKind::Await) {
8718 let awaited = match self.promise_resolve_value(value) {
8719 Ok(awaited) => awaited,
8720 Err(Signal::Throw(reason)) => {
8721 return self.settle_async_request(
8722 generator,
8723 promise,
8724 AsyncOutcome::Error(reason),
8725 );
8726 }
8727 Err(other) => return Err(other),
8728 };
8729 let Value::Object(awaited) = awaited else {
8730 return Ok(());
8731 };
8732 let resumed = JsObject::function(
8733 self.heap,
8734 Some(self.realm.function_proto.clone()),
8735 Callable::GeneratorResume {
8736 generator: generator.clone(),
8737 promise: promise.clone(),
8738 kind: ResumeKind::Next,
8739 },
8740 );
8741 let raised = JsObject::function(
8742 self.heap,
8743 Some(self.realm.function_proto.clone()),
8744 Callable::GeneratorResume {
8745 generator: generator.clone(),
8746 promise: promise.clone(),
8747 kind: ResumeKind::Throw,
8748 },
8749 );
8750 self.perform_then(
8751 &awaited,
8752 Some(Value::Object(resumed)),
8753 Some(Value::Object(raised)),
8754 )?;
8755 return Ok(());
8756 }
8757 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
8758 // completes it — both arrive as the settled value rather than as the promise
8759 // object. A plain value skips the round trip, which is also what keeps `yield 1`
8760 // from costing an extra tick.
8761 let awaits_value = self.is_thenable(&value)?;
8762 if awaits_value {
8763 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
8764 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
8765 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
8766 // no `PromiseResolve` appears, so that path keeps the shortcut.
8767 let awaited = match if done {
8768 self.promise_resolve_intrinsic(value)
8769 } else {
8770 self.promise_resolve_value(value)
8771 } {
8772 Ok(awaited) => awaited,
8773 Err(Signal::Throw(reason)) => {
8774 return self.settle_async_request(
8775 generator,
8776 promise,
8777 AsyncOutcome::Error(reason),
8778 );
8779 }
8780 Err(other) => return Err(other),
8781 };
8782 let Value::Object(awaited) = awaited else {
8783 return Ok(());
8784 };
8785 // A rejected yield throws *at the yield* inside the body, so the rejection
8786 // resumes the generator rather than the method's promise.
8787 let answer = JsObject::function(
8788 self.heap,
8789 Some(self.realm.function_proto.clone()),
8790 Callable::YieldResult {
8791 generator: generator.clone(),
8792 promise: promise.clone(),
8793 done,
8794 },
8795 );
8796 let raise = JsObject::function(
8797 self.heap,
8798 Some(self.realm.function_proto.clone()),
8799 Callable::GeneratorResume {
8800 generator: generator.clone(),
8801 promise: promise.clone(),
8802 kind: ResumeKind::Throw,
8803 },
8804 );
8805 self.perform_then(
8806 &awaited,
8807 Some(Value::Object(answer)),
8808 Some(Value::Object(raise)),
8809 )?;
8810 return Ok(());
8811 }
8812 let result = if ready {
8813 // `yield*` handed back the inner iterator's own result object.
8814 value
8815 } else {
8816 self.iterator_result(value, done)?
8817 };
8818 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
8819 }
8820
8821 /// The `{value, done}` object an iterator method answers with.
8822 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
8823 let result = self.new_object(Some(self.realm.object_proto.clone()));
8824 result.define_data("value", value);
8825 result.define_data("done", Value::Bool(done));
8826 Ok(Value::Object(result))
8827 }
8828
8829 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
8830 fn step_generator(
8831 &mut self,
8832 state: &mut GeneratorState,
8833 kind: ResumeKind,
8834 value: Value,
8835 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8836 match state.phase {
8837 GeneratorPhase::Executing => {
8838 return Err(self.type_error("cannot invoke a running generator"));
8839 }
8840 GeneratorPhase::Completed => {
8841 // A finished generator answers every resumption without running.
8842 return Ok(match kind {
8843 ResumeKind::Throw => return Err(Signal::Throw(value)),
8844 ResumeKind::Return => (value, true, false, None),
8845 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
8846 });
8847 }
8848 GeneratorPhase::SuspendedStart => {
8849 if kind != ResumeKind::Next && kind != ResumeKind::Start {
8850 // The body never started, so there is nothing to unwind or return
8851 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
8852 state.frame = None;
8853 state.phase = GeneratorPhase::Completed;
8854 return Ok(match kind {
8855 ResumeKind::Throw => return Err(Signal::Throw(value)),
8856 _ => (value, true, false, None),
8857 });
8858 }
8859 }
8860 GeneratorPhase::SuspendedYield => {}
8861 }
8862
8863 let Some(mut frame) = state.frame.take() else {
8864 return Ok((Value::Undefined, true, false, None));
8865 };
8866 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
8867 // number that says which method resumed it; the emitted `if_false` branches on
8868 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
8869 let mut raised = None;
8870 match kind {
8871 ResumeKind::Next | ResumeKind::Start => {
8872 if state.phase == GeneratorPhase::SuspendedYield {
8873 frame.stack.push(value);
8874 // An `await` resumes with its value alone; only a `yield` gets the
8875 // magic number that says which of `next`/`return` resumed it.
8876 if !state.parked_on_await {
8877 frame.stack.push(Value::Int(RESUME_NEXT));
8878 }
8879 }
8880 }
8881 ResumeKind::Return => {
8882 // A `return` on a not-yet-started generator is handled above, so this is
8883 // always a real resumption.
8884 frame.stack.push(value);
8885 frame.stack.push(Value::Int(RESUME_RETURN));
8886 }
8887 ResumeKind::Throw => {
8888 // At a `yield*` the exception is *data* for the delegation: the compiled
8889 // code resumes with the value and magic `2` and calls the inner iterator's
8890 // `throw`. Everywhere else it is raised at the suspension point, so the
8891 // body's own handler sees it.
8892 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
8893 frame.stack.push(value);
8894 frame.stack.push(Value::Int(RESUME_THROW));
8895 } else {
8896 raised = Some(value);
8897 }
8898 }
8899 }
8900 state.phase = GeneratorPhase::Executing;
8901
8902 let depth = self.frames.len();
8903 self.frames.push(frame);
8904 // A `throw` unwinds from where the frame parked, exactly as if the exception had
8905 // happened at the `yield`.
8906 if let Some(exception) = raised {
8907 if self.catch_here(exception.clone()).is_none() {
8908 self.pop_frame();
8909 state.phase = GeneratorPhase::Completed;
8910 return Err(Signal::Throw(exception));
8911 }
8912 }
8913
8914 // Only the generator's *own* frame ends the generator. The body may call ordinary
8915 // functions, and those push frames of their own: a `Step::Return` from one of them
8916 // is a nested call finishing, not the generator completing. Miscounting that is
8917 // silent — the generator reports the callee's value as its own result and marks
8918 // itself done — so the depth comparison is load-bearing, not defensive.
8919 let own_frame = depth + 1;
8920 loop {
8921 match self.step() {
8922 Ok(Step::Continue) => {}
8923 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
8924 let mut frame = self.frames.pop().expect("a frame is live");
8925 // `yield` left the value on the stack; `initial_yield` left nothing.
8926 let yielded = if reason == SuspendKind::Initial {
8927 Value::Undefined
8928 } else {
8929 frame.stack.pop().unwrap_or(Value::Undefined)
8930 };
8931 state.frame = Some(frame);
8932 state.parked_on_await = reason == SuspendKind::Await;
8933 state.parked_on_yield_star =
8934 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
8935 state.phase = if reason == SuspendKind::Initial {
8936 GeneratorPhase::SuspendedStart
8937 } else {
8938 GeneratorPhase::SuspendedYield
8939 };
8940 // `yield*` hands the inner iterator's own result object straight
8941 // back, so the caller sees one `{value, done}` rather than a nested
8942 // one — which is why the third field says "already a result".
8943 return Ok((
8944 yielded,
8945 false,
8946 reason == SuspendKind::YieldStar,
8947 Some(reason),
8948 ));
8949 }
8950 Ok(Step::Suspend(_)) => {
8951 // A `yield` in a frame other than the generator's would mean a
8952 // generator body entered as an ordinary call, which
8953 // `call_or_push` prevents.
8954 self.unwind_to(depth);
8955 state.phase = GeneratorPhase::Completed;
8956 return Err(Signal::Throw(self.make_error(
8957 "InternalError",
8958 "a generator body ran as an ordinary call",
8959 )));
8960 }
8961 Ok(Step::Return(value)) => {
8962 self.pop_frame();
8963 if self.frames.len() > depth {
8964 // A nested call finished: hand the value back to its caller and
8965 // keep running the generator body.
8966 self.frames
8967 .last_mut()
8968 .expect("a caller is live")
8969 .stack
8970 .push(value);
8971 continue;
8972 }
8973 state.phase = GeneratorPhase::Completed;
8974 // The reference closes the generator's closure variables here; ours
8975 // live in cells the frame owned, which the drop below releases.
8976 return Ok((value, true, false, None));
8977 }
8978 Err(Signal::Throw(exception)) => {
8979 // The frame that threw gets the first chance to catch, exactly as in
8980 // the ordinary call loop; a frame above the generator's is popped and
8981 // the exception carries on down.
8982 let exception = exception;
8983 loop {
8984 if self.frames.len() <= depth {
8985 // The generator's own frame is gone, so nothing here caught it.
8986 state.phase = GeneratorPhase::Completed;
8987 return Err(Signal::Throw(exception));
8988 }
8989 if self.catch_here(exception.clone()).is_some() {
8990 break;
8991 }
8992 self.pop_frame();
8993 }
8994 }
8995 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
8996 }
8997 }
8998 }
8999
9000 /// Pop frames until `depth` are left, keeping their buffers.
9001 fn unwind_to(&mut self, depth: usize) {
9002 while self.frames.len() > depth {
9003 self.pop_frame();
9004 }
9005 }
9006 fn call_or_push(
9007 &mut self,
9008 callee: Value,
9009 this: Value,
9010 args: Vec<Value>,
9011 ) -> JsResult<Option<Value>> {
9012 if let Value::Object(function) = &callee
9013 && let Some((code, env)) = bytecode_of(function)
9014 {
9015 // Calling a generator function does not run anything: it captures the
9016 // arguments in a frame and hands back the generator object.
9017 if code.code.kind.is_generator() {
9018 return self.new_generator(callee, this, args).map(Some);
9019 }
9020 // An async function answers a promise and runs its body as a coroutine, so it
9021 // takes the same path as a plain call into it.
9022 if code.code.kind.is_async() {
9023 return self.new_async_function(callee, this, args).map(Some);
9024 }
9025 self.push_frame(code, env, this, args, callee)?;
9026 return Ok(None);
9027 }
9028 self.call_value(callee, this, args).map(Some)
9029 }
9030
9031 /// `new callee(args)`.
9032 ///
9033 /// A constructor differs from a plain call in three ways: it gets a fresh object
9034 /// as `this` whose prototype is the constructor's `prototype` property, its
9035 /// return value is *replaced* by that object unless it returns an object itself,
9036 /// and a native constructor is expected to initialise the object it is given
9037 /// rather than build one.
9038 pub fn construct(
9039 &mut self,
9040 callee: Value,
9041 new_target: Value,
9042 args: Vec<Value>,
9043 ) -> JsResult<Value> {
9044 // `new` on a bound function constructs its *target*, prepending the arguments
9045 // the bind fixed and ignoring the bound `this` — a bound function is a
9046 // constructor only when its target is one, and `new` always makes a fresh
9047 // object of the target's prototype rather than reusing the bound receiver.
9048 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9049 // ran the body with `this === null` and threw on `this.x = a`.
9050 let mut callee = callee;
9051 let mut new_target = new_target;
9052 let mut args = args;
9053 loop {
9054 let Some(object) = callee.as_object().cloned() else {
9055 return Err(Signal::Throw(
9056 self.make_error("TypeError", "not a constructor"),
9057 ));
9058 };
9059 // A proxy of a function constructs through its `construct` trap, and the
9060 // trap's answer is the result directly — no fresh object is made here.
9061 if object.proxy_state().is_some() {
9062 return match self.proxy_construct(&object, args, &new_target)? {
9063 Some(result) => Ok(result),
9064 None => Err(Signal::Throw(
9065 self.make_error("TypeError", "proxy target is not a constructor"),
9066 )),
9067 };
9068 }
9069 // A generator function has no `[[Construct]]`, and the reference names it in
9070 // the message: `new (function* G(){})()` reports "G is not a constructor".
9071 if object.with(|data| match &data.kind {
9072 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9073 code.code.kind.is_generator()
9074 }
9075 _ => false,
9076 }) {
9077 let name = object
9078 .own_property("name")
9079 .and_then(|property| property.value)
9080 .map(|value| value.to_js_string())
9081 .unwrap_or_default();
9082 return Err(Signal::Throw(
9083 self.make_error("TypeError", &format!("{name} is not a constructor")),
9084 ));
9085 }
9086 let bound = object.with(|data| match &data.kind {
9087 ObjectKind::Function(Callable::Bound {
9088 target,
9089 args: leading,
9090 ..
9091 }) => Some((target.clone(), leading.clone())),
9092 _ => None,
9093 });
9094 let Some((target, leading)) = bound else {
9095 // Not a bound function, so this object is the callee. §7.2.4
9096 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9097 // refusals above cover only the built-ins the reference also refuses by
9098 // name. Everything else — a method, an arrow, an async function — has no
9099 // `[[Construct]]` either, and answering "yes" here made
9100 // `new (Array.prototype.map)` build an object instead of throwing.
9101 if !object.is_constructor() {
9102 let name = object
9103 .own_property("name")
9104 .and_then(|property| property.value)
9105 .map(|value| value.to_js_string())
9106 .unwrap_or_default();
9107 return Err(Signal::Throw(
9108 self.make_error("TypeError", &format!("{name} is not a constructor")),
9109 ));
9110 }
9111 break;
9112 };
9113 let mut all = leading;
9114 all.extend(args);
9115 args = all;
9116 // A bound function that is its own `new.target` stands in for its target:
9117 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9118 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9119 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9120 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9121 _ => false,
9122 };
9123 if same_wrapper {
9124 new_target = target.clone();
9125 }
9126 callee = target;
9127 }
9128 let Value::Object(function) = &callee else {
9129 unreachable!("the loop above only breaks on an object");
9130 };
9131 // The fresh object's prototype comes from `new.target`, not from the callee: a
9132 // derived constructor reaches here through `super()`, and the instance must be a
9133 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9134 // an object inheriting `D.prototype` rather than `C.prototype`.
9135 let prototype_source = match new_target.as_object() {
9136 Some(target) => target.clone(),
9137 None => function.clone(),
9138 };
9139 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9140 // has validated its arguments. Pre-building one here would read
9141 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9142 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9143 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9144 let is_native = function.native_creates_own_instance();
9145 let this = if is_native {
9146 Value::Undefined
9147 } else {
9148 let prototype = self.get_property(&prototype_source, "prototype")?;
9149 let prototype = match prototype {
9150 Some(Value::Object(proto)) => Some(proto),
9151 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9152 // object, the answer is the realm's *intrinsic* prototype for this
9153 // constructor, not `%Object.prototype%`.
9154 _ => {
9155 let fallback = self.get_property(function, "prototype")?;
9156 match fallback {
9157 Some(Value::Object(proto)) => Some(proto),
9158 _ => Some(self.realm.object_proto.clone()),
9159 }
9160 }
9161 };
9162 Value::Object(self.new_object(prototype))
9163 };
9164 // `new.target` inside the body is the constructor that was written, so a bound
9165 // function's target sees itself rather than the bound wrapper.
9166 //
9167 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9168 // `?`, so assigning `None` after the call would be skipped and the failed
9169 // `new.target` would stay visible to every later native call. The symptom was a
9170 // native constructor refusing a plain call — `var s = Symbol(); new
9171 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9172 // "FinalizationRegistry is not a constructor".
9173 let outer_new_target = self.pending_new_target.replace(new_target);
9174 let result = self.call_value(callee, this.clone(), args);
9175 self.pending_new_target = outer_new_target;
9176 let result = result?;
9177 // A constructor that returns an object overrides `this`; any other return
9178 // value (including `undefined`) is ignored.
9179 Ok(match result {
9180 Value::Object(_) => result,
9181 _ => this,
9182 })
9183 }
9184
9185 /// `new.target` for the call currently being made.
9186 ///
9187 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9188 /// it as `this`), but a *host* constructor that builds its own instance is handed
9189 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9190 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9191 /// it here.
9192 ///
9193 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9194 /// receives for a plain call.
9195 pub fn current_new_target(&self) -> Value {
9196 self.active_new_target.clone()
9197 }
9198
9199 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9200 ///
9201 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9202 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9203 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9204 let constructor = self.realm.errors.get("AggregateError").cloned();
9205 let Some(constructor) = constructor else {
9206 return self.make_error("AggregateError", message);
9207 };
9208 let list = self.new_array(errors);
9209 match self.construct(
9210 Value::Object(constructor.clone()),
9211 Value::Object(constructor),
9212 vec![Value::Object(list), self.string(message)],
9213 ) {
9214 Ok(value) => value,
9215 // A user could have replaced `AggregateError` with something that throws; the
9216 // engine still owes the caller a rejection, so it falls back rather than
9217 // turning `Promise.any`'s rejection into a throw.
9218 Err(_) => self.make_error("AggregateError", message),
9219 }
9220 }
9221
9222 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9223 ///
9224 /// The error classes themselves arrive with the builtins milestone; what
9225 /// matters here is that the thrown value stringifies the way a script printing
9226 /// the caught value expects.
9227 ///
9228 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9229 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9230 /// rely on when they print a caught value.
9231 pub fn make_error(&self, name: &str, message: &str) -> Value {
9232 let proto = self
9233 .realm
9234 .errors
9235 .get(name)
9236 .map(|constructor| self.prototype_of(constructor))
9237 .unwrap_or_else(|| self.realm.error_proto.clone());
9238 let error = self.new_object(Some(proto));
9239 // `name` and `message` are own properties of the instance, which is what
9240 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9241 // `Error`.
9242 error.define(
9243 "name",
9244 Property::with_attributes(self.string(name), true, false),
9245 );
9246 error.define(
9247 "message",
9248 Property::with_attributes(self.string(message), true, false),
9249 );
9250 // The internal class, which is what tells a printer this is an error rather than a
9251 // plain object with `name` and `message` properties. The constructor path sets it
9252 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9253 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9254 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9255 // a `RangeError` still prints as `RangeError`.
9256 self.internal_set(&error, "_class", self.string("Error"));
9257 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9258 // answered `false` from `Error.isError` while a constructed one answered `true`,
9259 // because only the constructor set the slot. The reference answers `true` for both
9260 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9261 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9262 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9263 // engine-thrown error lost its blank line.
9264 self.internal_set(&error, "_error_data", Value::Bool(true));
9265 // The trace is captured where the error is *made*, which is where the reference
9266 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9267 // way out, so a caught engine error already has its stack even if the handler
9268 // never rethrows it.
9269 self.add_stack(&error);
9270 Value::Object(error)
9271 }
9272
9273 /// Give an error object its `stack` property, from the current frame stack.
9274 ///
9275 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9276 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9277 /// `stack` a script set, is not rewritten.
9278 pub fn add_stack(&self, object: &Gc<JsObject>) {
9279 self.add_stack_skipping(object, 0);
9280 }
9281
9282 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9283 ///
9284 /// An `Error` constructor passes 1: the reference builds those traces with
9285 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9286 /// constructor itself, while a `RangeError` raised inside `toISOString` does
9287 /// report `at toISOString (native)`.
9288 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9289 if object.has_own("stack") {
9290 return;
9291 }
9292 // The trace is *captured* here but not installed as a property: `stack` is an
9293 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9294 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9295 // is kept in a hidden slot and the getter materialises it on first read.
9296 //
9297 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9298 // shows it — this is the same discipline `_error_data` and `_class` follow.
9299 let trace = self.stack_trace_skipping(skip);
9300 let text = self.string(trace);
9301 self.internal_set(object, "_stack_trace", text);
9302 }
9303
9304 /// The function object currently being called, if any.
9305 ///
9306 /// A native function is a bare `fn` pointer, so it cannot capture which class
9307 /// it belongs to; it reads that from the callee instead. This is also what a
9308 /// stack trace would use.
9309 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9310 match &self.frames.last()?.callee {
9311 Value::Object(object) => Some(object.clone()),
9312 _ => None,
9313 }
9314 }
9315
9316 /// The `prototype` property of a constructor, falling back to
9317 /// `Object.prototype` for anything that is not shaped like one.
9318 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9319 constructor
9320 .own_property("prototype")
9321 .and_then(|property| property.value)
9322 .and_then(|value| value.as_object().cloned())
9323 .unwrap_or_else(|| self.realm.object_proto.clone())
9324 }
9325
9326 /// Throw a `TypeError` carrying `message`.
9327 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9328 Signal::Throw(self.make_error("TypeError", message.as_ref()))
9329 }
9330
9331 /// Throw a `RangeError` carrying `message`.
9332 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9333 Signal::Throw(self.make_error("RangeError", message.as_ref()))
9334 }
9335
9336 /// The `ReferenceError` a read of an uninitialised binding raises.
9337 /// The name of the binding `slot` refers to, for an error message.
9338 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9339 match kind {
9340 VarSlot::Loc => self
9341 .frame()
9342 .code
9343 .code
9344 .vars
9345 .get(slot)
9346 .map(|v| v.name.clone()),
9347 VarSlot::Closure => self
9348 .frame()
9349 .code
9350 .code
9351 .closure_vars
9352 .get(slot)
9353 .map(|c| c.name.clone()),
9354 }
9355 .unwrap_or_default()
9356 }
9357
9358 /// Whether `slot` names a `const` binding, which rejects every store after its
9359 /// initialiser.
9360 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9361 match kind {
9362 VarSlot::Loc => self
9363 .frame()
9364 .code
9365 .code
9366 .vars
9367 .get(slot)
9368 .is_some_and(|v| v.is_const),
9369 VarSlot::Closure => self
9370 .frame()
9371 .code
9372 .code
9373 .closure_vars
9374 .get(slot)
9375 .is_some_and(|c| c.is_const),
9376 }
9377 }
9378
9379 /// The `TypeError` a store to a `const` binding raises.
9380 ///
9381 /// `const` is enforced here rather than at compile time because the binding can be
9382 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9383 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9384 /// both halves of what "checked store" means: the dead zone is over, and the
9385 /// binding is writable.
9386 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9387 let name = self.binding_name(slot, kind);
9388 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
9389 }
9390
9391 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
9392 let name = match kind {
9393 VarSlot::Loc => self
9394 .frame()
9395 .code
9396 .code
9397 .vars
9398 .get(slot)
9399 .map(|v| v.name.clone()),
9400 VarSlot::Closure => self
9401 .frame()
9402 .code
9403 .code
9404 .closure_vars
9405 .get(slot)
9406 .map(|c| c.name.clone()),
9407 }
9408 .unwrap_or_default();
9409 Signal::Throw(self.make_error(
9410 "ReferenceError",
9411 &format!("cannot access '{name}' before initialization"),
9412 ))
9413 }
9414
9415 fn throw_reference(&self, name: &str) -> Signal {
9416 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
9417 }
9418
9419 // -- the instruction loop -----------------------------------------------
9420
9421 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
9422 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
9423 // measured at 16% of a tight arithmetic loop's total time.
9424 #[inline(always)]
9425 fn step(&mut self) -> JsResult<Step> {
9426 // The instruction is already decoded (see [`crate::insn`]), so this is an index
9427 // and a `Copy` read rather than a table lookup plus a width switch. Only the
9428 // borrow lives across the boundary; nothing is cloned.
9429 // **One** borrow of the frame: fetch the record, then advance in the same scope.
9430 // The obvious version borrowed it three times (`last` to read, `last_mut` to
9431 // write, and once more inside the handler), and each is a bounds check plus an
9432 // `Option` unwrap — on the one path every instruction takes.
9433 let Some((insn, next)) = ({
9434 let frame = self
9435 .frames
9436 .last_mut()
9437 .expect("step() is only called with a live frame");
9438 // Past the last instruction is a normal return: the compiler ends a function
9439 // with `return`, and a jump to the end of a block lands here.
9440 let insn = frame.insns().get(frame.pc).copied();
9441 match insn {
9442 None => None,
9443 Some(insn) => {
9444 // A fused record stands for the next few instructions, so the next
9445 // `pc` is its width ahead — the instructions it replaces are never
9446 // dispatched. `at` is the byte offset a stack trace reports; it stays
9447 // an offset because the line table is keyed by bytes.
9448 frame.at = insn.offset as usize;
9449 frame.pc += insn.width();
9450 Some((insn, frame.pc))
9451 }
9452 }
9453 }) else {
9454 return Ok(Step::Return(Value::Undefined));
9455 };
9456 self.check_memory()?;
9457 self.check_interrupt()?;
9458 if insn.fused == crate::insn::Fused::None {
9459 self.execute_instruction(insn.op, insn.a, insn.b, next)
9460 } else {
9461 self.execute_fused(insn)
9462 }
9463 }
9464
9465 /// Run a fused instruction: several bytecode instructions in one dispatch.
9466 ///
9467 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
9468 /// it cannot throw and cannot allocate — and anything else falls back to the real
9469 /// instructions, in their real order, so an exception leaves the operand stack
9470 /// exactly as it would have been.
9471 #[inline]
9472 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
9473 use crate::insn::Fused;
9474 let slot = insn.a as usize;
9475 match insn.fused {
9476 // `x = k`: `push k; put_loc x`.
9477 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
9478 // `x += k`: `get_loc x; push k; add; put_loc x`.
9479 Fused::AddImmLoc => {
9480 let delta = insn.b as i32;
9481 match self.get_loc(slot) {
9482 Value::Int(left) => {
9483 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
9484 // that built two `Value`s, called a function, and matched on them
9485 // again to reach this same `checked_add`. It is the innermost
9486 // operation of every accumulator in every program.
9487 let answer = match left.checked_add(delta) {
9488 Some(sum) => Value::Int(sum),
9489 None => Value::Float(left as f64 + delta as f64),
9490 };
9491 self.put_loc(slot, answer);
9492 }
9493 other => {
9494 self.push(other);
9495 self.push(Value::Int(delta));
9496 self.binary_add()?;
9497 let value = self.pop();
9498 self.put_loc(slot, value);
9499 }
9500 }
9501 }
9502 // `x += "literal"` and `x += y`: the two shapes that can append in place.
9503 Fused::AddAtomLoc => {
9504 let text = self.atom_wtf8(insn.b as usize);
9505 let right = self.string_wtf8(text);
9506 self.add_into_loc(slot, right)?;
9507 }
9508 Fused::AddLocLoc => {
9509 let source = (insn.a & 0xFFFF) as usize;
9510 let target = (insn.a >> 16) as usize;
9511 let right = self.get_loc(source);
9512 self.add_into_loc(target, right)?;
9513 }
9514 Fused::AddArgLoc => {
9515 let source = (insn.a & 0xFFFF) as usize;
9516 let target = (insn.a >> 16) as usize;
9517 let right = self.get_arg(source);
9518 self.add_into_loc(target, right)?;
9519 }
9520 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
9521 Fused::PostIncLoc => match self.get_loc(slot) {
9522 Value::Int(left) => {
9523 let answer = match left.checked_add(1) {
9524 Some(sum) => Value::Int(sum),
9525 None => Value::Float(left as f64 + 1.0),
9526 };
9527 self.put_loc(slot, answer);
9528 }
9529 other => {
9530 self.push(other);
9531 let raw = self.pop();
9532 let (old, updated) = self.advance_numeric(raw, true)?;
9533 self.push(old);
9534 self.push(updated);
9535 let value = self.pop();
9536 self.put_loc(slot, value);
9537 self.pop();
9538 }
9539 },
9540 // `if (!(x < arg)) goto target`: a loop header.
9541 //
9542 // The comparison is computed rather than replayed on the operand stack. That
9543 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
9544 // that throws: the effects happen in the same order, and a handler truncates
9545 // the stack down to its marker, so the intermediate values are unobservable.
9546 Fused::LtLocArgJump => {
9547 let loc = (insn.a >> 16) as usize;
9548 let arg = (insn.a & 0xFFFF) as usize;
9549 let left = self.get_loc(loc);
9550 let right = self.get_arg(arg);
9551 let taken = match (&left, &right) {
9552 (Value::Int(left), Value::Int(right)) => !(left < right),
9553 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9554 };
9555 if taken {
9556 self.frame_mut().pc = insn.b as usize;
9557 }
9558 }
9559 // `i < k` in a loop header, where `k` is an integer literal.
9560 Fused::LtLocImmJump => {
9561 let left = self.get_loc(insn.a as usize);
9562 let right = Value::Int(insn.imm as i32);
9563 let taken = match &left {
9564 Value::Int(left) => !(*left < insn.imm as i32),
9565 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9566 };
9567 if taken {
9568 self.frame_mut().pc = insn.b as usize;
9569 }
9570 }
9571 Fused::None => unreachable!("only called for a fused record"),
9572 }
9573 Ok(Step::Continue)
9574 }
9575
9576 /// Run records that cannot call script, cannot throw and cannot change frames.
9577 ///
9578 /// Returns `Some(value)` when the function ran off the end of its instructions (a
9579 /// normal return), and `None` when it stopped in front of an instruction the slow path
9580 /// has to handle — `pc` is written back either way, so `step` resumes at the right
9581 /// place.
9582 ///
9583 /// **The invariant is the whole point.** Every arm here is restricted to work that
9584 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
9585 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
9586 /// that the memory limit has to see. An opcode whose operands turn out to need any of
9587 /// that **stops the loop** instead of trying, so the slow path gets the instruction
9588 /// untouched and with its operands still on the stack. That is why the fallback is a
9589 /// `break` and not a duplicated slow arm: a second implementation of the same
9590 /// semantics is how a wrong answer gets in with no test noticing.
9591 ///
9592 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
9593 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
9594 fn run_fast(&mut self) -> JsResult<Option<Value>> {
9595 use crate::insn::Fused;
9596 // The outer loop exists only so a `Call` can come back through here: once a
9597 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
9598 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
9599 // frame. Re-entering re-reads both from whichever frame is now on top. Every
9600 // other exit from the inner loop returns, so this costs one loop per call.
9601 'outer: loop {
9602 // One reference-count bump per *slow* instruction (a call, an allocation, a
9603 // property access), never one per instruction — that distinction is worth
9604 // two orders of magnitude and was measured as such.
9605 let (code, mut pc) = {
9606 let frame = self.frame();
9607 (frame.code.clone(), frame.pc)
9608 };
9609 let insns = &code.insns;
9610 loop {
9611 let Some(insn) = insns.get(pc).copied() else {
9612 self.frame_mut().pc = pc;
9613 return Ok(Some(Value::Undefined));
9614 };
9615 match insn.fused {
9616 // `x = k`
9617 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
9618 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
9619 // object — stops the loop so `binary_add` can decide.
9620 Fused::AddImmLoc => {
9621 let slot = insn.a as usize;
9622 let delta = insn.b as i32;
9623 let Value::Int(left) = self.get_loc(slot) else {
9624 return Ok(self.stop(pc));
9625 };
9626 let sum = match left.checked_add(delta) {
9627 Some(sum) => Value::Int(sum),
9628 None => Value::Float(left as f64 + delta as f64),
9629 };
9630 self.put_loc(slot, sum);
9631 }
9632 // `x += "literal"` / `x += y`: the operand is a string, so the append
9633 // either allocates one or grows one. Both are the slow path's business;
9634 // the fusion's job is only to make the *slot* the sole owner, which is what
9635 // `execute_fused` needs and what `get_loc` alone destroys.
9636 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
9637 return Ok(self.stop(pc));
9638 }
9639 // `x++` on an integer, old value dropped.
9640 Fused::PostIncLoc => {
9641 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
9642 // value is read in place and overwritten in place, so the reference
9643 // count it held is released by the same assignment that stores the
9644 // new one. `get_loc` plus `put_loc` did two borrows, two table
9645 // lookups and a clone, and this arm is the whole body of a counting
9646 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
9647 let slot = insn.a as usize;
9648 let frame = self.frames.last_mut().expect("a frame is live");
9649 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
9650 let target = if cell < 0 {
9651 frame.locals.get_mut(slot)
9652 } else {
9653 None
9654 };
9655 let Some(target) = target else {
9656 return Ok(self.stop(pc));
9657 };
9658 let Value::Int(left) = *target else {
9659 return Ok(self.stop(pc));
9660 };
9661 *target = match left.checked_add(1) {
9662 Some(sum) => Value::Int(sum),
9663 None => Value::Float(left as f64 + 1.0),
9664 };
9665 }
9666 // A loop header, `if (!(x < arg)) goto target`, with both sides already
9667 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
9668 // bound stayed small integers.
9669 Fused::LtLocArgJump => {
9670 let loc = (insn.a >> 16) as usize;
9671 let arg = (insn.a & 0xFFFF) as usize;
9672 // One borrow for both slots: this arm *is* the whole loop of a
9673 // `for (i = 0; i < n; i++)` with an argument bound, so a second
9674 // `frames.last()` here is paid on every iteration. Measured 7.5% on
9675 // `dispatch:empty-loop`.
9676 let (left, right) = {
9677 let frame = self.frame();
9678 (frame.read_loc(loc), frame.read_arg(arg))
9679 };
9680 // Heavily measured: the bound is very often a `Float` even when the
9681 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
9682 // `JSON.parse` or a division is one — so requiring both sides to be
9683 // `Int` sent every iteration of those loops down the slow path. The
9684 // comparison below is the same one `relational` makes for two numbers.
9685 if !is_number(&left) || !is_number(&right) {
9686 return Ok(self.stop(pc));
9687 }
9688 // `if_false` branches on the comparison being false, which is **not**
9689 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
9690 // `>=` is also false and would keep it running forever. Clippy wants the
9691 // negation folded; that would be a wrong answer.
9692 let ordered = left.to_number() < right.to_number();
9693 let take_branch = !ordered;
9694 if take_branch {
9695 pc = insn.b as usize;
9696 continue;
9697 }
9698 }
9699 // The same header with a literal bound: `if (!(x < k)) goto target`.
9700 // The bound is an immediate, so only the counter needs a type test.
9701 #[allow(clippy::neg_cmp_op_on_partial_ord)]
9702 Fused::LtLocImmJump => {
9703 let left = self.get_loc(insn.a as usize);
9704 if !is_number(&left) {
9705 return Ok(self.stop(pc));
9706 }
9707 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9708 if take_branch {
9709 pc = insn.b as usize;
9710 continue;
9711 }
9712 }
9713 Fused::None => match insn.op {
9714 // -- branches ---------------------------------------------------
9715 // A jump is an assignment now, because the target is an instruction
9716 // index. No arithmetic, no resolution table.
9717 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9718 let target = insn.a as usize;
9719 // A **back-edge** is a loop, and it is the only place an
9720 // instruction-level checkpoint can stop one: `for(;;){}` compiles
9721 // to a jump to itself and never leaves this loop, so the
9722 // per-instruction checks in `step` never run. That is exactly the
9723 // hole this arm closes — a host's `JS_SetInterruptHandler` did
9724 // nothing to a `for(;;){}` until it did, which is what
9725 // `tests/c/embed.c` is for.
9726 //
9727 // Polling here rather than on every instruction in this loop is
9728 // also the reference's choice (`OP_goto` calls
9729 // `js_poll_interrupts`), and it costs one compare per branch
9730 // instead of one decrement per instruction.
9731 if target <= pc {
9732 self.frame_mut().pc = target;
9733 self.check_memory()?;
9734 self.check_interrupt()?;
9735 }
9736 pc = target;
9737 continue;
9738 }
9739 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
9740 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
9741 let taken = self.pop().to_boolean();
9742 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
9743 if taken == want {
9744 pc = insn.a as usize;
9745 continue;
9746 }
9747 }
9748 // -- slot access -------------------------------------------------
9749 // A load's slot is already an operand (see `insn::implicit_operand`);
9750 // a captured one goes through its cell, which runs no script.
9751 Opcode::GetLoc
9752 | Opcode::GetLoc8
9753 | Opcode::GetLoc0
9754 | Opcode::GetLoc1
9755 | Opcode::GetLoc2
9756 | Opcode::GetLoc3 => {
9757 let value = self.get_loc(insn.a as usize);
9758 self.push(value);
9759 }
9760 Opcode::PutLoc
9761 | Opcode::PutLoc8
9762 | Opcode::PutLoc0
9763 | Opcode::PutLoc1
9764 | Opcode::PutLoc2
9765 | Opcode::PutLoc3 => {
9766 let value = self.pop();
9767 self.put_loc(insn.a as usize, value);
9768 }
9769 Opcode::GetArg
9770 | Opcode::GetArg0
9771 | Opcode::GetArg1
9772 | Opcode::GetArg2
9773 | Opcode::GetArg3 => {
9774 let value = self.get_arg(insn.a as usize);
9775 self.push(value);
9776 }
9777 Opcode::PutArg
9778 | Opcode::PutArg0
9779 | Opcode::PutArg1
9780 | Opcode::PutArg2
9781 | Opcode::PutArg3 => {
9782 let value = self.pop();
9783 self.put_arg(insn.a as usize, value);
9784 }
9785 // `a[i]` with an integer index on a dense array: see `fast_array_get`
9786 // for why a non-hole own element is exactly the slow path's answer.
9787 // The two operands are *peeked*, so a miss leaves the stack as the
9788 // slow path expects to find it.
9789 Opcode::GetArrayEl => {
9790 // One lookup, not two. The guard used `if …is_some()` and the arm
9791 // then called it again to get the value — two `peek`s, two
9792 // `array_get`s and two `Value` clones for one element.
9793 // `fast_array_get` was 13.1% of `array:indexed`, and the same
9794 // double call was the first version of the `get_field` fast path.
9795 let Some(value) = self.fast_array_get() else {
9796 return Ok(self.stop(pc));
9797 };
9798 // `a[i]` consumes both operands and leaves the element in their
9799 // place: one `truncate` and one write, no `pop`/`push` pair.
9800 let frame = self.frame_mut();
9801 frame.stack.truncate(frame.stack.len() - 2);
9802 frame.stack.push(value);
9803 }
9804 // `a[i] = v` on a dense array with an integer index: see
9805 // `fast_array_set` for why the whole store is one step.
9806 Opcode::PutArrayEl if self.fast_array_set() => {}
9807 // `o.x` resolved from the inline cache without leaving the loop.
9808 //
9809 // The cache is keyed by `(receiver identity, atom, site)` and a
9810 // monomorphic read re-validates the same chain every iteration, so
9811 // each one used to cost a `stop(pc)` — a write of `pc` into the
9812 // frame, a return out of this loop, a re-dispatch through `step` and
9813 // a re-entry. `property:monomorphic` spent 18% in
9814 // `read_field_cached` and 21% in `push`, both across that boundary.
9815 //
9816 // The site is `pc + width`, which is exactly the `next` the slow arm
9817 // passes — the two must agree or every fast lookup misses and
9818 // re-records the same entry forever.
9819 //
9820 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
9821 // slow arm finds the receiver where it expects it.
9822 // `name` resolved from the global-variable cache inside the loop.
9823 //
9824 // Same shape as `get_field` above and for the same reason: `get_var`
9825 // was not in the fast loop, so reading a global — which `fib` does
9826 // once per recursive call, for its own name — cost a `stop(pc)`, a
9827 // return out of the loop, a `step` re-dispatch and a re-entry, before
9828 // `get_global` even started its `scopes_are_plain` checks.
9829 //
9830 // Everything here is exactly `get_global`'s first branch: not lexical,
9831 // no `eval` scope, cache hit. Anything else leaves the stack untouched
9832 // and lets the slow arm decide.
9833 Opcode::GetVar => {
9834 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
9835 return Ok(self.stop(pc));
9836 };
9837 self.push(value);
9838 }
9839 Opcode::GetField | Opcode::GetField2 => {
9840 let Some(value) =
9841 self.fast_field_get(insn.a as usize, pc + insn.width())
9842 else {
9843 return Ok(self.stop(pc));
9844 };
9845 if insn.op == Opcode::GetField2 {
9846 // `get_field2` keeps the receiver for the `call_method` that
9847 // follows.
9848 self.push(value);
9849 } else {
9850 // `get_field` replaces the receiver, so this is one store over
9851 // the top slot rather than a `pop` and a `push`: the length
9852 // never changes, so neither `Vec` arm has a capacity check or a
9853 // drop to run beyond the one the overwrite itself does.
9854 let frame = self.frame_mut();
9855 match frame.stack.last_mut() {
9856 Some(slot) => *slot = value,
9857 None => return Ok(self.stop(pc)),
9858 }
9859 }
9860 }
9861 // -- constants ---------------------------------------------------
9862 Opcode::PushMinus1
9863 | Opcode::Push0
9864 | Opcode::Push1
9865 | Opcode::Push2
9866 | Opcode::Push3
9867 | Opcode::Push4
9868 | Opcode::Push5
9869 | Opcode::Push6
9870 | Opcode::Push7
9871 | Opcode::PushI8
9872 | Opcode::PushI16
9873 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
9874 // -- stack shuffling ---------------------------------------------
9875 Opcode::Drop => {
9876 self.pop();
9877 }
9878 // -- arithmetic on two integers ----------------------------------
9879 //
9880 // The operands are *looked at* before they are popped, so a non-integer
9881 // pair leaves the stack exactly as the slow path expects to find it.
9882 Opcode::Add if self.numeric_pair() => {
9883 let right = self.pop();
9884 let left = self.pop();
9885 // Exactly [`add_numbers`], which is what the slow arm reaches.
9886 let answer = match (&left, &right) {
9887 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9888 Some(sum) => Value::Int(sum),
9889 None => Value::Float(*a as f64 + *b as f64),
9890 },
9891 _ => Value::Float(left.to_number() + right.to_number()),
9892 };
9893 self.push(answer);
9894 }
9895 Opcode::Sub
9896 | Opcode::And
9897 | Opcode::Or
9898 | Opcode::Xor
9899 | Opcode::Shl
9900 | Opcode::Sar
9901 | Opcode::Shr
9902 if self.numeric_pair() =>
9903 {
9904 let right = self.pop();
9905 let left = self.pop();
9906 let answer =
9907 arithmetic(insn.op, left, right).expect("numbers cannot throw");
9908 self.push(answer);
9909 }
9910 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
9911 if self.numeric_pair() =>
9912 {
9913 let right = self.pop();
9914 let left = self.pop();
9915 let answer = self
9916 .relational(insn.op, left, right)
9917 .expect("numbers cannot throw");
9918 self.push(answer);
9919 }
9920 // -- calls -------------------------------------------------------
9921 //
9922 // A plain call: `callee(arg0, …, argN) -> result`.
9923 //
9924 // This arm exists because of one measurement. `call:recursion` had
9925 // **20.4% of its profile in `execute_instruction`** — the *slow*
9926 // executor — and `fib`'s recursive call is the only thing in that
9927 // function which is not a fast arm. Every call therefore left this
9928 // loop via `stop()`, went through `step()`'s dispatch and
9929 // `execute_instruction`'s match over every opcode, and came back here
9930 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
9931 //
9932 // Two things make it safe to do here rather than only in the slow path:
9933 //
9934 // * the caller's `pc` is stored *before* the call, which is what
9935 // `step` does too — so when the callee returns, the caller resumes
9936 // after the call and not at it;
9937 // * `check_memory` runs, because `step` calls it once per instruction
9938 // and a call allocates a frame, its locals and its cells. Skipping
9939 // the checkpoint here would let a `--memory-limit` script overshoot
9940 // by one call per instruction.
9941 Opcode::Call
9942 | Opcode::Call0
9943 | Opcode::Call1
9944 | Opcode::Call2
9945 | Opcode::Call3 => {
9946 let argc = self.argc_operand(insn.op, insn.a);
9947 let next = pc + insn.width();
9948 {
9949 let frame = self
9950 .frames
9951 .last_mut()
9952 .expect("run_fast() is only called with a live frame");
9953 // `at` is what a stack trace reports for this frame, so a throw
9954 // inside the callee has to see the call site and not whatever
9955 // the last `stop()` left there.
9956 frame.at = insn.offset as usize;
9957 frame.pc = next;
9958 }
9959 self.check_memory()?;
9960 self.check_interrupt()?;
9961 let args = self.pop_n(argc);
9962 let callee = self.pop();
9963 // A plain call has no receiver; the callee decides what to do with
9964 // `undefined` (a sloppy function substitutes the global object).
9965 if let Some(result) =
9966 self.call_or_push(callee, Value::Undefined, args)?
9967 {
9968 // Native, host, generator, async, bound — no frame was pushed,
9969 // so this loop is still describing the right function. `pc`
9970 // is advanced by the loop tail like every other arm; only the
9971 // frame's copy had to be written here, and it already was.
9972 self.push(result);
9973 } else {
9974 // A bytecode callee: its frame is on top now, and `insns` and
9975 // `pc` both belong to the caller. Start over on the new frame.
9976 continue 'outer;
9977 }
9978 }
9979 // -- return ------------------------------------------------------
9980 Opcode::Return => {
9981 let value = self.pop();
9982 self.frame_mut().pc = pc + insn.width();
9983 return Ok(Some(value));
9984 }
9985 Opcode::ReturnUndef => {
9986 self.frame_mut().pc = pc + insn.width();
9987 return Ok(Some(Value::Undefined));
9988 }
9989 // Everything else needs the slow path.
9990 _ => return Ok(self.stop(pc)),
9991 },
9992 }
9993 pc += insn.width();
9994 }
9995 }
9996 }
9997
9998 /// Whether the top two operand-stack values are both numbers.
9999 ///
10000 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10001 /// cannot run script, so the arm may not throw and may not change frames.
10002 fn numeric_pair(&self) -> bool {
10003 is_number(&self.peek(0)) && is_number(&self.peek(1))
10004 }
10005
10006 /// `a[i]` for a dense array and an integer index, without the string round trip.
10007 ///
10008 /// The slow path answers this by turning `i` into a string (`propkey` →
10009 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10010 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10011 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10012 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10013 /// without even the cheap `Int` formatting.
10014 ///
10015 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10016 /// unambiguously the one the slow path would give:
10017 ///
10018 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10019 /// `2^32-1` is the length, not an index),
10020 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10021 /// typed array or an ordinary object, all of which have their own rules),
10022 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10023 /// starts walking the prototype chain, and `a[i]` on a hole must find
10024 /// `Array.prototype[i]` if it exists rather than `undefined`.
10025 ///
10026 /// The last condition is the one that makes this safe rather than merely fast: an own
10027 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10028 /// `get_var` answered from the global-variable cache, or `None`.
10029 ///
10030 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10031 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10032 /// records nothing — the slow arm is about to walk the chain and record it.
10033 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10034 let frame = self.frame();
10035 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10036 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10037 // `GlobalRef` forwarded through a nested function has its flags cleared.
10038 if self.realm.globals.contains_key(name) {
10039 return None;
10040 }
10041 if !self.scopes_are_plain() {
10042 return None;
10043 }
10044 let object = &self.realm.global;
10045 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10046 let cached = self.global_cache[site].as_ref()?;
10047 if !object.upgrades_to(&cached.object) {
10048 return None;
10049 }
10050 object.data_property_at(cached.index, name)
10051 }
10052
10053 /// `o.x` answered entirely from the inline cache, or `None`.
10054 ///
10055 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10056 /// about to do exactly that and recording it twice would rebuild the chain for every
10057 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10058 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10059 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10060 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10061 // an object receiver is a reference-count bump that the answer never needs.
10062 let frame = self.frame();
10063 let object = frame.stack.last()?;
10064 let Value::Object(target) = object else {
10065 return None;
10066 };
10067 // A proxy traps the lookup, so no cache entry ever describes it.
10068 if target.proxy_state().is_some() {
10069 return None;
10070 }
10071 let key = frame.code.atom_keys.get(atom)?;
10072 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10073 if cached.key != *key {
10074 return None;
10075 }
10076 Self::cached_hit(target, cached)
10077 }
10078
10079 fn fast_array_get(&self) -> Option<Value> {
10080 let Value::Int(index) = self.peek(0) else {
10081 return None;
10082 };
10083 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10084 // set for an `i32`.
10085 if index < 0 {
10086 return None;
10087 }
10088 let Value::Object(object) = self.peek(1) else {
10089 return None;
10090 };
10091 match object.array_get(index as usize) {
10092 Some(value) if !matches!(value, Value::Hole) => Some(value),
10093 _ => None,
10094 }
10095 }
10096
10097 /// `a[i] = v` on a dense array with an integer index, as one store.
10098 ///
10099 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10100 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10101 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10102 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10103 /// reference at the time it was measured (14.7x).
10104 ///
10105 /// Every condition here is one the slow path would also have to satisfy before
10106 /// storing into the element vector:
10107 ///
10108 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10109 /// accepts as an index;
10110 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10111 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10112 /// one inside a recorded descriptor, reports `false` and the caller stops.
10113 ///
10114 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10115 /// writes the own element too once `array_set` says it did.
10116 fn fast_array_set(&mut self) -> bool {
10117 // Every test runs *before* anything is popped: a refusal has to leave the stack
10118 // exactly as the slow path expects to find it. Popping first and reporting the
10119 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10120 // then ran the slow path with nothing to write.
10121 let Value::Int(index) = self.peek(1) else {
10122 return false;
10123 };
10124 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10125 if index < 0 {
10126 return false;
10127 }
10128 // Only a real array: a typed array's elements live in its buffer, a string-like
10129 // object has no element vector, and `array_set` on either does nothing.
10130 let Value::Object(object) = self.peek(2) else {
10131 return false;
10132 };
10133 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10134 return false;
10135 }
10136 // A non-extensible array reports `false` here, but the *slow* path has to decide
10137 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10138 // that with the key and the stack still intact.
10139 if !object.is_extensible() {
10140 return false;
10141 }
10142 // Inside the logical length, so the store cannot change `length`. Combined with
10143 // extensibility above, the only growth left for `array_set` is filling a hole in
10144 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10145 // shape this fast path exists for. A store past the length would grow the array,
10146 // and whether that is allowed is the slow path's question.
10147 if index as usize >= object.array_length().unwrap_or(0) {
10148 return false;
10149 }
10150 // Only an *own element* can take the inline store. A hole is not an own property,
10151 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10152 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10153 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10154 // the one case this path used to swallow.
10155 //
10156 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10157 // `array:push` appends past the length, which this path already refused.
10158 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10159 {
10160 return false;
10161 }
10162 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10163 // to report a failure after the operands are gone.
10164 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10165 return false;
10166 }
10167 let value = self.pop();
10168 self.pop();
10169 self.pop();
10170 object.array_store(self.heap, index as usize, value)
10171 }
10172
10173 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10174 fn stop(&mut self, pc: usize) -> Option<Value> {
10175 self.frame_mut().pc = pc;
10176 None
10177 }
10178
10179 fn push(&mut self, value: Value) {
10180 self.frame_mut().stack.push(value);
10181 }
10182
10183 fn pop(&mut self) -> Value {
10184 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10185 }
10186
10187 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10188 let frame = self.frame_mut();
10189 let start = frame.stack.len().saturating_sub(count);
10190 frame.stack.split_off(start)
10191 }
10192
10193 fn peek(&self, back: usize) -> Value {
10194 let frame = self.frame();
10195 frame
10196 .stack
10197 .get(frame.stack.len().wrapping_sub(1 + back))
10198 .cloned()
10199 .unwrap_or(Value::Undefined)
10200 }
10201
10202 #[allow(clippy::too_many_lines)]
10203 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10204 use Opcode::*;
10205 match op {
10206 // -- constants and stack shuffling -----------------------------
10207 Nop => {}
10208 PushMinus1 => self.push(Value::Int(-1)),
10209 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10210 let value = match op {
10211 Push0 => 0,
10212 Push1 => 1,
10213 Push2 => 2,
10214 Push3 => 3,
10215 Push4 => 4,
10216 Push5 => 5,
10217 Push6 => 6,
10218 _ => 7,
10219 };
10220 self.push(Value::Int(value));
10221 }
10222 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10223 PushBigintI32 => {
10224 // The immediate form of a `BigInt` literal; the reference has the same
10225 // split between this and a constant-pool entry.
10226 let value = crate::bigint::BigInt::from_i64(a as i64);
10227 self.push(self.bigint(value));
10228 }
10229 PushTrue => self.push(Value::Bool(true)),
10230 PushFalse => self.push(Value::Bool(false)),
10231 PushEmptyString => self.push(self.string("")),
10232 Undefined => self.push(Value::Undefined),
10233 Null => self.push(Value::Null),
10234 Object => {
10235 let proto = self.realm.object_proto.clone();
10236 self.push(Value::Object(self.new_object(Some(proto))));
10237 }
10238 PushThis => {
10239 let this = self.frame().this.clone();
10240 self.push(this);
10241 }
10242 PushConst | PushConst8 => {
10243 let value = self.constant(a as usize)?;
10244 self.push(value);
10245 }
10246 PushAtomValue => {
10247 let text = self.atom_wtf8(a as usize);
10248 self.push(self.string_wtf8(text));
10249 }
10250 Dup => {
10251 let value = self.peek(0);
10252 self.push(value);
10253 }
10254 Dup2 => {
10255 // `a b -> a b a b`
10256 let b = self.peek(0);
10257 let a = self.peek(1);
10258 self.push(a);
10259 self.push(b);
10260 }
10261 Dup3 => {
10262 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10263 // prototype and key while reading the current value through them.
10264 let c = self.peek(0);
10265 let b = self.peek(1);
10266 let a = self.peek(2);
10267 self.push(a);
10268 self.push(b);
10269 self.push(c);
10270 }
10271 Swap => {
10272 // `a b -> b a`
10273 let bottom = self.pop();
10274 let top = self.pop();
10275 self.push(bottom);
10276 self.push(top);
10277 }
10278 Perm3 => {
10279 // `a b c -> b a c`, the reference's reordering for a spread method
10280 // call: `obj func array` becomes the `func this array` that `apply`
10281 // takes.
10282 let c = self.pop();
10283 let b = self.pop();
10284 let a = self.pop();
10285 self.push(b);
10286 self.push(a);
10287 self.push(c);
10288 }
10289 Dup1 => {
10290 let value = self.peek(1);
10291 self.push(value);
10292 }
10293 Drop => {
10294 self.pop();
10295 }
10296 Nip => {
10297 // `a b -> b`
10298 let top = self.pop();
10299 self.pop();
10300 self.push(top);
10301 }
10302 Perm4 => {
10303 // `obj prop a b -> a obj prop b`, the reference's reordering for a
10304 // postfix update of a computed element: it puts the *old* value
10305 // underneath the receiver and key so `put_array_el` can consume them
10306 // and leave the old value as the expression's result.
10307 let d = self.pop();
10308 let c = self.pop();
10309 let b = self.pop();
10310 let a = self.pop();
10311 self.push(c);
10312 self.push(a);
10313 self.push(b);
10314 self.push(d);
10315 }
10316 Insert2 => {
10317 // `obj a -> a obj a`
10318 let value = self.pop();
10319 let object = self.pop();
10320 self.push(value.clone());
10321 self.push(object);
10322 self.push(value);
10323 }
10324 Insert3 => {
10325 // `obj prop a -> a obj prop a`
10326 let value = self.pop();
10327 let key = self.pop();
10328 let object = self.pop();
10329 self.push(value.clone());
10330 self.push(object);
10331 self.push(key);
10332 self.push(value);
10333 }
10334 Insert4 => {
10335 // `this obj prop a -> a this obj prop a`
10336 //
10337 // `put_super_value` consumes all four and yields nothing, so the copy
10338 // underneath is what leaves the assignment an expression value.
10339 let value = self.pop();
10340 let key = self.pop();
10341 let object = self.pop();
10342 let receiver = self.pop();
10343 self.push(value.clone());
10344 self.push(receiver);
10345 self.push(object);
10346 self.push(key);
10347 self.push(value);
10348 }
10349 Swap2 => {
10350 // `a b c d -> c d a b`
10351 let d = self.pop();
10352 let c = self.pop();
10353 let b = self.pop();
10354 let a = self.pop();
10355 self.push(c);
10356 self.push(d);
10357 self.push(a);
10358 self.push(b);
10359 }
10360 Rot3l => {
10361 // `x a b -> a b x`
10362 let b = self.pop();
10363 let a = self.pop();
10364 let x = self.pop();
10365 self.push(a);
10366 self.push(b);
10367 self.push(x);
10368 }
10369 Rot3r => {
10370 // `a b c -> c a b`
10371 let c = self.pop();
10372 let b = self.pop();
10373 let a_value = self.pop();
10374 self.push(c);
10375 self.push(a_value);
10376 self.push(b);
10377 }
10378
10379 Rest => {
10380 // `...rest` in a parameter list: the arguments from index `a` on, as a
10381 // real array. It takes nothing off the stack — the arguments are in the
10382 // frame, not on it.
10383 let frame = self.frame();
10384 let from = a as usize;
10385 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10386 let array = self.new_array(collected);
10387 self.push(Value::Object(array));
10388 }
10389
10390 // -- slots ------------------------------------------------------
10391 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
10392 let slot = self.slot_operand(op, a);
10393 let value = self.get_loc(slot);
10394 self.push(value);
10395 }
10396 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
10397 let slot = self.slot_operand(op, a);
10398 let value = self.pop();
10399 self.put_loc(slot, value);
10400 }
10401 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
10402 let slot = self.slot_operand(op, a);
10403 let value = self.pop();
10404 self.put_loc(slot, value.clone());
10405 self.push(value);
10406 }
10407 // The `_check` forms are the temporal dead zone: they throw when the
10408 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
10409 // *reads*, so only the two writes may pop — mishandling that quietly
10410 // consumes the value the caller pushed just before.
10411 GetLocCheck => {
10412 let slot = self.slot_operand(op, a);
10413 let value = self.get_loc(slot);
10414 if matches!(value, Value::Uninitialized) {
10415 return Err(self.dead_zone(slot, VarSlot::Loc));
10416 }
10417 self.push(value);
10418 }
10419 PutLocCheck | SetLocCheck => {
10420 let slot = self.slot_operand(op, a);
10421 let value = self.pop();
10422 if matches!(value, Value::Uninitialized) {
10423 return Err(self.dead_zone(slot, VarSlot::Loc));
10424 }
10425 // The initialiser goes through `put_loc`, not this, so any store that
10426 // reaches here is a later assignment — which a `const` refuses.
10427 if self.is_read_only(slot, VarSlot::Loc) {
10428 return Err(self.read_only(slot, VarSlot::Loc));
10429 }
10430 if op == SetLocCheck {
10431 self.put_loc(slot, value.clone());
10432 self.push(value);
10433 } else {
10434 self.put_loc(slot, value);
10435 }
10436 }
10437 PutLocCheckInit => {
10438 // The one store that *initialises* a lexical slot: `this` in a derived
10439 // constructor, which only exists after `super()` has run. A second
10440 // initialisation is the error the reference reports as
10441 // "'this' can be initialized only once".
10442 let slot = self.slot_operand(op, a);
10443 let value = self.pop();
10444 if !matches!(self.get_loc(slot), Value::Uninitialized) {
10445 return Err(Signal::Throw(self.make_error(
10446 "ReferenceError",
10447 "'this' can be initialized only once",
10448 )));
10449 }
10450 self.put_loc(slot, value);
10451 }
10452 CheckCtor => {
10453 // A class constructor may only run under `new`, which is what makes
10454 // `class A {}; A()` a TypeError.
10455 if matches!(self.frame().new_target, Value::Undefined) {
10456 return Err(Signal::Throw(self.make_error(
10457 "TypeError",
10458 "class constructors must be invoked with 'new'",
10459 )));
10460 }
10461 }
10462 InitCtor => {
10463 // The body a derived class gets when it declares no constructor:
10464 // forward every argument to the parent constructor, keeping `new.target`.
10465 if matches!(self.frame().new_target, Value::Undefined) {
10466 return Err(Signal::Throw(self.make_error(
10467 "TypeError",
10468 "class constructors must be invoked with 'new'",
10469 )));
10470 }
10471 let Some(callee) = self.current_callee() else {
10472 return Err(Signal::Throw(
10473 self.make_error("TypeError", "no constructor to inherit from"),
10474 ));
10475 };
10476 let parent = callee.proto().map_or(Value::Null, Value::Object);
10477 let new_target = self.frame().new_target.clone();
10478 let args = self.frame().passed().to_vec();
10479 let result = self.construct(parent, new_target, args)?;
10480 self.push(result);
10481 }
10482 SetLocUninitialized => {
10483 let slot = self.slot_operand(op, a);
10484 self.put_loc(slot, Value::Uninitialized);
10485 }
10486 CloseLoc => {
10487 // "Close" a binding: give it a *fresh* cell holding the current
10488 // value. Closures created before this point keep the old cell and the
10489 // ones created after see the new one, which is what makes every
10490 // iteration of `for (let i ...)` capture its own `i`, and what freezes
10491 // a block-scoped binding when the block ends.
10492 //
10493 // Clearing the slot instead (which this used to do) broke both: a
10494 // closure over a captured block variable read `undefined`, and a loop
10495 // terminated after one iteration.
10496 let slot = self.slot_operand(op, a);
10497 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
10498 if index >= 0 {
10499 let current = self.frame().cells[index as usize].get();
10500 let fresh = self.new_cell(current);
10501 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
10502 *cell = fresh;
10503 }
10504 }
10505 }
10506 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
10507 let slot = self.slot_operand(op, a);
10508 let value = self.get_arg(slot);
10509 self.push(value);
10510 }
10511 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
10512 let slot = self.slot_operand(op, a);
10513 let value = self.pop();
10514 self.put_arg(slot, value);
10515 }
10516 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
10517 let slot = self.slot_operand(op, a);
10518 let value = self.pop();
10519 self.put_arg(slot, value.clone());
10520 self.push(value);
10521 }
10522
10523 // -- closure variables ------------------------------------------
10524 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
10525 let slot = self.slot_operand(op, a);
10526 // A name a direct `eval` created shadows the binding the compiler chose.
10527 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
10528 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
10529 // and only a runtime lookup can know that.
10530 if let Some(cell) = self.eval_created_local(slot) {
10531 self.push(cell.get());
10532 return self.step();
10533 }
10534 let value = self.cell_value(slot)?;
10535 self.push(value);
10536 }
10537 GetVarRefCheck => {
10538 let slot = self.slot_operand(op, a);
10539 let value = self.cell_value(slot)?;
10540 if matches!(value, Value::Uninitialized) {
10541 return Err(self.dead_zone(slot, VarSlot::Closure));
10542 }
10543 self.push(value);
10544 }
10545 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
10546 let slot = self.slot_operand(op, a);
10547 let value = self.pop();
10548 if let Some(cell) = self.eval_created_local(slot) {
10549 cell.set(value);
10550 return self.step();
10551 }
10552 // Same rule as `PutLocCheck`: a checked store to a captured binding
10553 // refuses a `const` once its initialiser has run.
10554 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
10555 return Err(self.read_only(slot, VarSlot::Closure));
10556 }
10557 self.set_cell(slot, value)?;
10558 }
10559 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
10560 let slot = self.slot_operand(op, a);
10561 let value = self.pop();
10562 if let Some(cell) = self.eval_created_local(slot) {
10563 cell.set(value.clone());
10564 self.push(value);
10565 return self.step();
10566 }
10567 self.set_cell(slot, value.clone())?;
10568 self.push(value);
10569 }
10570
10571 // -- globals ----------------------------------------------------
10572 GetVar => {
10573 let value = self.get_global(a as usize)?;
10574 self.push(value);
10575 }
10576 GetVarUndef => {
10577 let value = self
10578 .get_global(a as usize)
10579 .or_else(|_| Ok(Value::Undefined))?;
10580 self.push(value);
10581 }
10582 DeleteVar => {
10583 // `delete name` for a name that is not a declared binding. A lexical
10584 // global lives in the reference table and cannot be deleted; anything
10585 // reachable only as a property of the global object is *implicit* —
10586 // `x = 1` with no declaration — and goes away if it is configurable,
10587 // which is what `delete` on an implicit global answers.
10588 let name = self.atom_text(a as usize);
10589 let global = self.realm.global.clone();
10590 let deleted = if self.realm.globals.contains_key(&name) {
10591 false
10592 } else if global.own_property(&name).is_some() {
10593 self.delete_property(&global, &name)?
10594 } else {
10595 true
10596 };
10597 self.push(Value::Bool(deleted));
10598 }
10599 PutVar => {
10600 let value = self.pop();
10601 self.put_global(a as usize, value)?;
10602 }
10603 PutVarInit => {
10604 let slot = a as usize;
10605 let value = self.pop();
10606 self.init_global(slot, value)?;
10607 }
10608
10609 // -- arithmetic -------------------------------------------------
10610 Add => self.binary_add()?,
10611 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
10612 let raw_right = self.pop();
10613 let raw_left = self.pop();
10614 // BigInt arithmetic is a separate path, and not only for the type of the
10615 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
10616 // rather than a silent conversion.
10617 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
10618 let left = self.primitive_of(raw_left)?;
10619 let right = self.primitive_of(raw_right)?;
10620 let value = self.bigint_arithmetic(op, left, right)?;
10621 self.push(value);
10622 } else {
10623 let right = self.numeric(raw_right)?;
10624 let left = self.numeric(raw_left)?;
10625 self.push(arithmetic(op, left, right)?);
10626 }
10627 }
10628 Neg => {
10629 let raw = self.pop();
10630 match raw {
10631 // A bigint negates exactly, however wide it is.
10632 Value::BigInt(big) => {
10633 let negated = big.negate();
10634 self.push(self.bigint(negated));
10635 }
10636 other => {
10637 let value = self.numeric(other)?;
10638 self.push(negate(value));
10639 }
10640 }
10641 }
10642 Plus => {
10643 let value = self.pop();
10644 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
10645 // unary plus is defined to produce a *number*, which a bigint cannot
10646 // become without loss. It used to fall through to `NaN`.
10647 if matches!(value, Value::BigInt(_)) {
10648 return Err(self.type_error("cannot convert bigint to number"));
10649 }
10650 let numeric = self.numeric_of(value)?;
10651 self.push(numeric);
10652 }
10653 Inc => {
10654 let raw = self.pop();
10655 let (_, updated) = self.advance_numeric(raw, true)?;
10656 self.push(updated);
10657 }
10658 Dec => {
10659 let raw = self.pop();
10660 let (_, updated) = self.advance_numeric(raw, false)?;
10661 self.push(updated);
10662 }
10663 PostInc | PostDec => {
10664 // `x -> x x+1`: the *new* value ends up on top, so the store the
10665 // compiler emits right after (`put_var`) writes the incremented
10666 // one, while the old value stays underneath for the expression's
10667 // own result. Getting this backwards makes `i++` a no-op, which
10668 // turns `while (i < 3)` into an infinite loop.
10669 let raw = self.pop();
10670 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
10671 self.push(old);
10672 self.push(updated);
10673 }
10674 Not => {
10675 let raw = self.pop();
10676 match raw {
10677 // `~x` on a bigint is `-x - 1`, exact at any width.
10678 Value::BigInt(big) => {
10679 let inverted = big.bitnot();
10680 self.push(self.bigint(inverted));
10681 }
10682 other => {
10683 let value = self.numeric(other)?;
10684 self.push(Value::Int(!value.to_int32()));
10685 }
10686 }
10687 }
10688 Lnot => {
10689 let value = self.pop();
10690 self.push(Value::Bool(!value.to_boolean()));
10691 }
10692
10693 // -- comparison -------------------------------------------------
10694 Lt | Lte | Gt | Gte => {
10695 let right = self.pop();
10696 let left = self.pop();
10697 let answer = self.relational(op, left, right)?;
10698 self.push(answer);
10699 }
10700 Eq | Neq => {
10701 let right = self.pop();
10702 let left = self.pop();
10703 let equal = self.abstract_equals(left, right)?;
10704 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
10705 }
10706 StrictEq => {
10707 let right = self.pop();
10708 let left = self.pop();
10709 self.push(Value::Bool(left.strict_equals(&right)));
10710 }
10711 StrictNeq => {
10712 let right = self.pop();
10713 let left = self.pop();
10714 self.push(Value::Bool(!left.strict_equals(&right)));
10715 }
10716 IsUndefined => {
10717 // `=== undefined`, which is what a destructuring default tests. It is
10718 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10719 let value = self.pop();
10720 self.push(Value::Bool(matches!(value, Value::Undefined)));
10721 }
10722 IsUndefinedOrNull => {
10723 let value = self.pop();
10724 self.push(Value::Bool(value.is_nullish()));
10725 }
10726 Typeof => {
10727 let value = self.pop();
10728 self.push(self.string(value.type_of()));
10729 }
10730 ToObject => {
10731 // A destructuring *object* pattern starts here, which is why
10732 // `var {} = null` throws. Only `undefined` and `null` are refused; a
10733 // primitive is boxed.
10734 let value = self.pop();
10735 let object = self.object_from(&value)?;
10736 self.push(Value::Object(object));
10737 }
10738 Instanceof => {
10739 let constructor = self.pop();
10740 let object = self.pop();
10741 let answer = self.instance_of(&object, &constructor)?;
10742 self.push(Value::Bool(answer));
10743 }
10744 In => {
10745 let object = self.pop();
10746 let key = self.pop();
10747 let answer = self.has_property(&key, &object)?;
10748 self.push(Value::Bool(answer));
10749 }
10750
10751 // -- control flow -----------------------------------------------
10752 Goto | Goto8 | Goto16 => {
10753 self.frame_mut().pc = a as usize;
10754 }
10755 IfTrue | IfTrue8 => {
10756 let value = self.pop();
10757 if value.to_boolean() {
10758 self.frame_mut().pc = a as usize;
10759 }
10760 }
10761 IfFalse | IfFalse8 => {
10762 let value = self.pop();
10763 if !value.to_boolean() {
10764 self.frame_mut().pc = a as usize;
10765 }
10766 }
10767 Catch => {
10768 // Pushes the handler target onto the value stack; `unwind` finds it.
10769 self.push(Value::CatchOffset(a));
10770 }
10771 Gosub => {
10772 self.push(Value::ReturnAddress(next as u32));
10773 self.frame_mut().pc = a as usize;
10774 }
10775 Ret => {
10776 let value = self.pop();
10777 match value {
10778 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
10779 _ => {
10780 return Err(Signal::Throw(
10781 self.make_error("InternalError", "invalid return address"),
10782 ));
10783 }
10784 }
10785 }
10786 NipCatch => {
10787 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
10788 // including the marker, keeping the top value.
10789 let top = self.pop();
10790 loop {
10791 match self.pop() {
10792 Value::CatchOffset(_) | Value::Undefined => break,
10793 _ => {}
10794 }
10795 if self.frame().stack.is_empty() {
10796 break;
10797 }
10798 }
10799 self.push(top);
10800 }
10801 Throw => {
10802 let value = self.pop();
10803 return Err(Signal::Throw(value));
10804 }
10805 ThrowError => {
10806 let name = self.atom_text(a as usize);
10807 let (class, message) = match b {
10808 0 => ("TypeError", format!("'{name}' is read-only")),
10809 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
10810 2 => ("ReferenceError", format!("'{name}' is not initialized")),
10811 // `delete super.x` is a syntax-level mistake the reference reports
10812 // with this wording, not a property-access failure.
10813 3 => (
10814 "ReferenceError",
10815 "unsupported reference to 'super'".to_string(),
10816 ),
10817 4 => (
10818 "TypeError",
10819 "iterator does not have a throw method".to_string(),
10820 ),
10821 5 => (
10822 "ReferenceError",
10823 "invalid assignment left-hand side".to_string(),
10824 ),
10825 _ => ("TypeError", format!("invalid operation on '{name}'")),
10826 };
10827 return Err(Signal::Throw(self.make_error(class, &message)));
10828 }
10829 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
10830 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
10831 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
10832 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
10833 Await => return Ok(Step::Suspend(SuspendKind::Await)),
10834 ReturnAsync => {
10835 // The reference's `return_async` returns `undefined` and lets the resume
10836 // machinery pick the real value off `sp[-1]`, which is how it tells a
10837 // completion from a suspension. Carrying the value explicitly says the
10838 // same thing without the implicit stack slot.
10839 let value = self.pop();
10840 return Ok(Step::Return(value));
10841 }
10842 Return => {
10843 let value = self.pop();
10844 return Ok(Step::Return(value));
10845 }
10846 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
10847
10848 // -- calls ------------------------------------------------------
10849 Call | Call0 | Call1 | Call2 | Call3 => {
10850 let argc = self.argc_operand(op, a);
10851 let args = self.pop_n(argc);
10852 let callee = self.pop();
10853 // A plain call has no receiver; the callee decides what to do with
10854 // `undefined` (a sloppy function substitutes the global object).
10855 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
10856 self.push(result);
10857 }
10858 }
10859 CallConstructor => {
10860 // `constructor this_obj args… -> object`. The duplicated
10861 // constructor is `new.target`; this milestone does not expose it,
10862 // so the extra copy is simply consumed here.
10863 let argc = a as usize;
10864 let args = self.pop_n(argc);
10865 let new_target = self.pop();
10866 let callee = self.pop();
10867 let result = self.construct(callee, new_target, args)?;
10868 self.push(result);
10869 }
10870 CallMethod => {
10871 let argc = a as usize;
10872 let args = self.pop_n(argc);
10873 let callee = self.pop();
10874 let this = self.pop();
10875 if let Some(result) = self.call_or_push(callee, this, args)? {
10876 self.push(result);
10877 }
10878 }
10879 Apply => {
10880 // `func this array -> result`, the spread-call form: the compiler
10881 // builds one array of arguments, and all that is left here is to
10882 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
10883 let array = self.pop();
10884 let this = self.pop();
10885 let callee = self.pop();
10886 let args = self.array_like_to_args(&array)?;
10887 if a & 1 != 0 {
10888 let result = self.construct(callee, this, args)?;
10889 self.push(result);
10890 } else if let Some(result) = self.call_or_push(callee, this, args)? {
10891 self.push(result);
10892 }
10893 }
10894 TailCall | TailCallMethod => {
10895 // `tail_call` is `call` whose result is returned immediately — the
10896 // reference jumps straight to `done` instead of storing the value and
10897 // running on. The callee still gets its own frame, so deep tail
10898 // recursion hits the stack limit exactly like plain recursion does;
10899 // marking this frame lets the return path unwind without needing
10900 // instructions after the call.
10901 let argc = if op == TailCallMethod {
10902 a as usize
10903 } else {
10904 self.argc_operand(op, a)
10905 };
10906 let args = self.pop_n(argc);
10907 let callee = self.pop();
10908 let this = if op == TailCallMethod {
10909 self.pop()
10910 } else {
10911 Value::Undefined
10912 };
10913 if let Value::Object(function) = &callee
10914 && let Some((code, env)) = bytecode_of(function)
10915 {
10916 // A generator or async body is not run here at all: calling it only
10917 // *creates* the generator/coroutine, so it must not inherit this
10918 // frame. Doing so made `function f(){ return g() }` push `g`'s body
10919 // onto `f`'s frame, and the first `yield`/`await` then reported
10920 // "a generator body ran as an ordinary call".
10921 if code.code.kind.is_generator() || code.code.kind.is_async() {
10922 let value = self.call_value(callee, this, args)?;
10923 return Ok(Step::Return(value));
10924 }
10925 self.frame_mut().tail = true;
10926 self.push_frame(code, env, this, args, callee)?;
10927 return Ok(Step::Continue);
10928 }
10929 // A native callee has no frame to reuse, so its value is simply
10930 // returned.
10931 let value = self.call_value(callee, this, args)?;
10932 return Ok(Step::Return(value));
10933 }
10934
10935 // -- objects ----------------------------------------------------
10936 SpecialObject => {
10937 let value = self.special_object(a)?;
10938 self.push(value);
10939 }
10940 PrivateSymbol => {
10941 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
10942 // symbol each time it is evaluated, which is why the compiler evaluates it
10943 // once (at class definition) and stores it in a class-scope binding.
10944 let name = self.atom_text(a as usize);
10945 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
10946 self.push(Value::Symbol(symbol));
10947 }
10948 GetPrivateField => {
10949 // `obj symbol -> value`. A missing private field is a TypeError, which is what
10950 // makes `#x` inaccessible on any object not built by this class.
10951 let symbol = self.pop();
10952 let object = self.pop();
10953 let value = self.read_private_field(&object, &symbol)?;
10954 self.push(value);
10955 }
10956 PutPrivateField => {
10957 // `obj value symbol ->`, and the store is a plain assignment to a property the
10958 // class already created, so there is no setter to consult.
10959 let symbol = self.pop();
10960 let value = self.pop();
10961 let object = self.pop();
10962 self.write_private_field(&object, &symbol, value)?;
10963 }
10964 DefinePrivateField => {
10965 // `obj symbol value -> obj`: a field initialiser creates the property, and
10966 // redefining one is a TypeError ("already exists").
10967 let value = self.pop();
10968 let symbol = self.pop();
10969 let object = self.pop();
10970 self.define_private_field(&object, &symbol, value)?;
10971 self.push(object);
10972 }
10973 PrivateIn => {
10974 // `obj key -> bool`: `#x in o`. The second operand decides which question is
10975 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
10976 // is a field, so this is an own-property test; a *function* is a method or
10977 // accessor, so this is a brand check.
10978 let key = self.pop();
10979 let object = self.pop();
10980 let Some(target) = object.as_object() else {
10981 return Err(Signal::Throw(
10982 self.make_error("TypeError", "invalid 'in' operand"),
10983 ));
10984 };
10985 let present = match &key {
10986 Value::Object(_) => self.check_brand(target, &key)?,
10987 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
10988 };
10989 self.push(Value::Bool(present));
10990 }
10991 AddBrand => {
10992 // `obj home ->`: create the class brand on `home` if it has none, then give
10993 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
10994 // class definition: only the prototype's copy of the symbol is wanted.
10995 let home = self.pop();
10996 let object = self.pop();
10997 self.add_brand(&object, &home)?;
10998 }
10999 CheckBrand => {
11000 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11001 // Both stay, because the caller needs them — `nip` halves a read into its
11002 // value and `call_method` uses the pair as receiver and callee.
11003 let function = self.peek(0);
11004 let object = self.peek(1);
11005 let Some(target) = object.as_object() else {
11006 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11007 };
11008 if !self.check_brand(target, &function)? {
11009 return Err(Signal::Throw(
11010 self.make_error("TypeError", "invalid brand on object"),
11011 ));
11012 }
11013 }
11014 GetLength => {
11015 // `get_length` is the `.length` read; an array and a string answer
11016 // from their own length, anything else from the property.
11017 let target = self.pop();
11018 let value = match &target {
11019 Value::Object(object) => match object.array_length() {
11020 Some(length) => crate::object::length_value(length),
11021 None => self.read_field(&target, "length")?,
11022 },
11023 Value::String(text) => Value::Int(text.utf16_len() as i32),
11024 _ => self.read_field(&target, "length")?,
11025 };
11026 self.push(value);
11027 }
11028 GetField | GetField2 => {
11029 let object = self.pop();
11030 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11031 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11032 // just below is what lets the borrow outlive the `&mut self` the lookup
11033 // needs — one refcount bump instead of a key clone plus its drop, on the
11034 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11035 let code = self.frame().code.clone();
11036 let key = &code.atom_keys[a as usize];
11037 let value = self.read_field_cached(&object, key, next)?;
11038 if op == GetField2 {
11039 self.push(object);
11040 }
11041 self.push(value);
11042 }
11043 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11044 let key = self.pop();
11045 let object = self.pop();
11046 let key = self.propkey(&key)?;
11047 let value = self.read_field_key(&object, &key)?;
11048 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11049 self.push(object);
11050 }
11051 if op == GetArrayEl3 {
11052 // The key goes back in its *value* form, which the compiler stores
11053 // into the target of a destructuring assignment.
11054 self.push(match &key {
11055 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11056 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11057 });
11058 }
11059 self.push(value);
11060 }
11061 PutField => {
11062 let value = self.pop();
11063 let object = self.pop();
11064 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11065 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11066 // only reads. `this.value = …` is the write half of the hottest loop in
11067 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11068 let code = self.frame().code.clone();
11069 let key = &code.atom_keys[a as usize];
11070 self.write_field_key(&object, key, value)?;
11071 }
11072 PutArrayEl => {
11073 let value = self.pop();
11074 let key = self.pop();
11075 let object = self.pop();
11076 let key = self.propkey(&key)?;
11077 self.write_field_key(&object, &key, value)?;
11078 }
11079 DefineField => {
11080 let value = self.pop();
11081 let object = self.pop();
11082 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11083 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11084 // three U+FFFD — a property under a different name from the one
11085 // `o["\uD800"]` reads.
11086 let code = self.frame().code.clone();
11087 let key = code.atom_keys[a as usize].clone();
11088 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11089 // emits `set_name` — and only where `NamedEvaluation` applies, so
11090 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11091 // reaches a property definition got that case wrong, and the compiler is
11092 // the only place that can tell the two apart.
11093 if let Some(target) = object.as_object() {
11094 // Only an *array* stores into the element vector. A numeric key
11095 // on an ordinary object is an ordinary property, which is what
11096 // makes `{1: 'a'}` iterate as a key rather than disappear.
11097 let stored = target.is_array()
11098 && key.as_str().and_then(array_index).is_some_and(|index| {
11099 target.array_set(self.heap, index as usize, value.clone())
11100 });
11101 if !stored {
11102 target.define_data_key(&key, value);
11103 }
11104 }
11105 self.push(object);
11106 }
11107 DefineArrayEl => {
11108 // `obj key value -> obj key`. The *value* form of the key is what goes
11109 // back on the stack — the compiler stores it into the pattern's binding —
11110 // so the symbol is not stringified on the way through.
11111 let value = self.pop();
11112 let key_value = self.pop();
11113 let object = self.peek(0);
11114 let key = self.propkey(&key_value)?;
11115 self.write_field_key(&object, &key, value)?;
11116 self.push(key_value);
11117 }
11118 SetHomeObject => {
11119 // `obj func -> obj func`: records the object a method was defined on so
11120 // `super` inside it resolves against that object's prototype.
11121 let function = self.peek(0);
11122 let home = self.peek(1);
11123 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11124 function.set_home_object(Some(home.clone()));
11125 }
11126 }
11127 Regexp => {
11128 // `pattern flags -> regexp`. A literal compiles here rather than through the
11129 // constructor, which is both what the reference's dedicated opcode is for
11130 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11131 let flags = self.pop();
11132 let pattern = self.pop();
11133 let pattern = self.to_js_string(&pattern)?;
11134 let flags = self.to_js_string(&flags)?;
11135 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11136 self.push(Value::Object(object));
11137 }
11138 UsingDisposeInit => {
11139 // The error state a disposal accumulates into. Uninitialised means "no
11140 // failure yet"; anything else is the exception being propagated.
11141 self.push(Value::Uninitialized);
11142 }
11143 UsingCheck => {
11144 // `value -> value, method`: validate and snapshot the disposer now, so a
11145 // later change to `Symbol.dispose` cannot change what gets called, and so a
11146 // value that is not disposable fails before the body runs.
11147 let value = self.pop();
11148 let method = self.using_method_for(&value, a as u8 == 1)?;
11149 self.push(value);
11150 self.push(method);
11151 }
11152 UsingDispose => {
11153 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11154 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11155 // the pending error.
11156 let slot = self.slot_operand(op, a);
11157 let error_state = self.pop();
11158 let merged = self.using_dispose_once(slot, error_state)?;
11159 self.push(merged);
11160 }
11161 UsingDisposeMerge => {
11162 let new_error = self.pop();
11163 let error_state = self.pop();
11164 let merged = self.merge_dispose_error(new_error, error_state);
11165 self.push(merged);
11166 }
11167 UsingDisposeEnd => {
11168 // A disposal that failed replaces the block's normal completion, so the
11169 // error state becomes a real throw here rather than at the call site.
11170 let error_state = self.pop();
11171 if !matches!(error_state, Value::Uninitialized) {
11172 return Err(Signal::Throw(error_state));
11173 }
11174 }
11175 UsingDisposeAsync => {
11176 // `await using` needs a promise to await and this runtime has no
11177 // `Promise` builtin, so the disposer is called synchronously and its result
11178 // discarded. That is correct for a disposer that returns nothing and is
11179 // reported as a gap rather than silently skipped.
11180 let slot = self.slot_operand(op, a);
11181 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11182 self.push(error_state);
11183 }
11184 GetSuper => {
11185 // `obj -> obj's prototype`: the starting point of a `super` lookup.
11186 let object = self.pop();
11187 let proto = match &object {
11188 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11189 _ => Value::Null,
11190 };
11191 self.push(proto);
11192 }
11193 GetSuperValue => {
11194 // `receiver proto key -> value`, searching from `proto` but reporting to
11195 // `receiver`, which is what `super.g` must do for a getter to see `this`.
11196 //
11197 // Three values in, one out: the receiver is *consumed*, not left under the
11198 // result. Leaving it there was invisible for `super.x` in `return` or
11199 // statement position (the result is what gets popped) and corrupted the
11200 // frame everywhere else — `print(super.x)` left the class where the call
11201 // opcode looks for the receiver and called the class itself.
11202 let key = self.pop();
11203 let proto = self.pop();
11204 let receiver = self.pop();
11205 let value = self.super_read(&receiver, &proto, &key)?;
11206 self.push(value);
11207 }
11208 PutSuperValue => {
11209 // `receiver proto key value ->`: a store that starts at `proto` but
11210 // assigns to `receiver`.
11211 let value = self.pop();
11212 let key = self.pop();
11213 let proto = self.pop();
11214 let receiver = self.pop();
11215 self.super_write(&receiver, &proto, &key, value)?;
11216 }
11217 DefineClass => {
11218 // `parent ctor -> ctor proto`: the constructor becomes the class and a
11219 // fresh prototype object lands on top for the methods to go on.
11220 let name = self.atom_text(a as usize);
11221 let (ctor, proto) = self.define_class(&name, b)?;
11222 self.push(ctor);
11223 self.push(Value::Object(proto));
11224 }
11225 DefineClassComputed => {
11226 // `parent ctor key -> ctor proto key`: the computed name stays put so
11227 // `define_field`-style consumers can still read it.
11228 let key = self.pop();
11229 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11230 let (ctor, proto) = self.define_class(&name, b)?;
11231 self.push(ctor);
11232 self.push(Value::Object(proto));
11233 self.push(key);
11234 }
11235 DefineMethod => {
11236 let function = self.pop();
11237 let object = self.pop();
11238 // The exact key, like `define_field`: a quoted method key may hold an
11239 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11240 // that `o["\uD800"]` finds.
11241 let code = self.frame().code.clone();
11242 let key = code.atom_keys[a as usize].clone();
11243 // A method's `[[HomeObject]]` is the object it was defined on, which is
11244 // what `super` inside it resolves against.
11245 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11246 function.set_home_object(Some(object.clone()));
11247 }
11248 if let Some(text) = key.as_wtf8() {
11249 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11250 } else {
11251 self.set_function_name(
11252 &function,
11253 &key_with_accessor_prefix(&key.to_string(), b),
11254 );
11255 }
11256 if let Some(array) = object.as_object() {
11257 define_function_property(array, &key, function, b);
11258 }
11259 self.push(object);
11260 }
11261 DefineMethodComputed => {
11262 let function = self.pop();
11263 let key = self.pop();
11264 let object = self.pop();
11265 let key = self.propkey(&key)?;
11266 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11267 // the name: `super` inside a computed method resolves through it. Without
11268 // this, `class B extends A { [k]() { return super.m() } }` read the
11269 // home object as null and threw.
11270 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11271 function.set_home_object(Some(object.clone()));
11272 }
11273 match key.as_wtf8() {
11274 Some(text) => {
11275 let name = accessor_prefixed(text, a);
11276 self.set_function_name_wtf8(&function, &name);
11277 }
11278 None => self.set_function_name(
11279 &function,
11280 &key_with_accessor_prefix(&key.to_string(), a),
11281 ),
11282 }
11283 if let Some(array) = object.as_object() {
11284 define_function_property(array, &key, function, a);
11285 }
11286 self.push(object);
11287 }
11288 SetProto => {
11289 let proto = self.pop();
11290 let object = self.pop();
11291 if let Some(target) = object.as_object() {
11292 target.set_proto(proto.as_object().cloned());
11293 }
11294 self.push(object);
11295 }
11296 CopyDataProperties => {
11297 let exclusion = self.pop();
11298 let source = self.pop();
11299 let target = self.peek(0);
11300 self.copy_properties(&target, &source, &exclusion)?;
11301 self.push(source);
11302 self.push(exclusion);
11303 }
11304 ToPropkey => {
11305 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11306 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11307 // ordinary `"Symbol(b)"` property.
11308 let value = self.pop();
11309 let key = match self.propkey(&value)? {
11310 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11311 PropertyKey::String(text) => self.string_wtf8(text),
11312 };
11313 self.push(key);
11314 }
11315 SetName => {
11316 let function = self.peek(0);
11317 let name = self.atom_wtf8(a as usize);
11318 self.set_function_name_wtf8(&function, &name);
11319 }
11320 SetNameComputed => {
11321 let key = self.peek(1);
11322 let function = self.peek(0);
11323 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11324 self.set_function_name(&function, &name);
11325 }
11326
11327 // -- arrays -----------------------------------------------------
11328 ArrayFrom => {
11329 let count = a as usize;
11330 let elements = self.pop_n(count);
11331 let array = self.new_array(elements);
11332 self.push(Value::Object(array));
11333 }
11334 Append => {
11335 // `array index iterable -> array new_index`
11336 let iterable = self.pop();
11337 self.pop();
11338 let array = self.peek(0);
11339 let added = self.append_enumerate(&array, &iterable)?;
11340 self.push(Value::Int(added));
11341 }
11342
11343 // -- iteration --------------------------------------------------
11344 ForInStart => {
11345 let value = self.pop();
11346 let record = self.for_in_record(&value)?;
11347 self.push(Value::Object(record));
11348 }
11349 ForInNext => {
11350 // `record -> record key done`. The flag is *done*, not "found":
11351 // the compiler tests it with `if_false` to jump back into the body,
11352 // so reporting `true` while keys remain would end the loop at once.
11353 let record = self.peek(0);
11354 match self.for_in_advance(&record)? {
11355 Some(key) => {
11356 let text = self.string(key);
11357 self.push(text);
11358 self.push(Value::Bool(false));
11359 }
11360 None => {
11361 self.push(Value::Undefined);
11362 self.push(Value::Bool(true));
11363 }
11364 }
11365 }
11366 ForOfStart => {
11367 let value = self.pop();
11368 let iterator = self.get_iterator(&value)?;
11369 self.push(iterator.object);
11370 self.push(iterator.next);
11371 self.push(Value::CatchOffset(0));
11372 }
11373 ForOfNext => {
11374 // `iter next catch_offset -> iter next catch_offset value done`.
11375 //
11376 // The operand is how many values sit *above* the iterator triple: a
11377 // destructuring rest element keeps its target array and running index
11378 // there while draining the iterator, so the triple is not at the top.
11379 let extra = a as usize;
11380 let iterator_slot = 2 + extra;
11381 // An exhausted iterator is replaced by `undefined` (see below), so a
11382 // second step must not call `next` again — `Array.from` and a
11383 // destructuring pattern both keep stepping past the end.
11384 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
11385 (Value::Undefined, true)
11386 } else {
11387 let iterator = Iterator {
11388 object: self.peek(iterator_slot),
11389 next: self.peek(1 + extra),
11390 };
11391 self.iterator_step(&iterator)?
11392 };
11393 if done {
11394 // The result's `value` is meaningless once the iterator is done:
11395 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
11396 // rather than binding the generator's return value.
11397 let top = self.frame().stack.len() - 1 - iterator_slot;
11398 self.frame_mut().stack[top] = Value::Undefined;
11399 self.push(Value::Undefined);
11400 self.push(Value::Bool(true));
11401 } else {
11402 self.push(value);
11403 self.push(Value::Bool(false));
11404 }
11405 }
11406 IteratorNext => {
11407 // `iter next catch val -> iter next catch val'`: replace the argument with
11408 // the result of `next(val)`. The triple below stays put, which is why the
11409 // three instructions of the `yield*` loop all address the stack the same way.
11410 let value = self.pop();
11411 let object = self.peek(2);
11412 let next = self.peek(1);
11413 let result = self.call_value(next, object, vec![value])?;
11414 self.push(result);
11415 }
11416 IteratorCall => {
11417 // `iter next catch val -> iter next catch val' flag`.
11418 //
11419 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
11420 // The flag is `true` when the method was missing, which is how the
11421 // caller learns that the inner iterator cannot take part in the
11422 // unwinding.
11423 let value = self.pop();
11424 let object = self.peek(2);
11425 let key = if a & 1 != 0 { "throw" } else { "return" };
11426 let method = self.read_field(&object, key)?;
11427 if matches!(method, Value::Undefined | Value::Null) {
11428 self.push(value);
11429 self.push(Value::Bool(true));
11430 } else {
11431 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
11432 let result = self.call_value(method, object, argument)?;
11433 self.push(result);
11434 self.push(Value::Bool(false));
11435 }
11436 }
11437 IteratorCheckObject => {
11438 if !matches!(self.peek(0), Value::Object(_)) {
11439 return Err(Signal::Throw(
11440 self.make_error("TypeError", "iterator must return an object"),
11441 ));
11442 }
11443 }
11444 IteratorClose => {
11445 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
11446 // calling the iterator's `return` so it can release whatever it holds.
11447 //
11448 // The catch offset goes first, so an exception from `return` is not caught
11449 // by the loop being abandoned. This used to pop the three operands and call
11450 // nothing at all, which made `break` out of a `for of` invisible to an
11451 // iterator with a `return` method.
11452 self.pop();
11453 self.pop();
11454 let iterator = self.pop();
11455 if !matches!(iterator, Value::Undefined) {
11456 let method = self.read_field(&iterator, "return")?;
11457 if !matches!(method, Value::Undefined | Value::Null) {
11458 let result = self.call_value(method, iterator.clone(), Vec::new())?;
11459 // §7.4.6: a `return` that answers a non-object is a TypeError.
11460 if !matches!(result, Value::Object(_)) {
11461 return Err(Signal::Throw(
11462 self.make_error("TypeError", "iterator must return an object"),
11463 ));
11464 }
11465 }
11466 }
11467 }
11468 Import => {
11469 // `import(specifier)`: the options slot is on top and is not read yet.
11470 let _options = self.pop();
11471 let specifier = self.pop();
11472 let promise = self.dynamic_import(specifier)?;
11473 self.push(promise);
11474 }
11475 ForAwaitOfStart => {
11476 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
11477 // `Symbol.iterator` fallback.
11478 let value = self.pop();
11479 let iterator = self.get_async_iterator(&value)?;
11480 self.push(iterator.object);
11481 self.push(iterator.next);
11482 self.push(Value::CatchOffset(0));
11483 }
11484 ForAwaitOfNext => {
11485 // `for await` steps the iterator and leaves the *result* wrapped in a
11486 // promise, so the `await` the compiler emits right after this can suspend
11487 // on it. Unwrapping happens in `iterator_get_value_done`.
11488 let extra = a as usize;
11489 let iterator_slot = 2 + extra;
11490 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
11491 Value::Undefined
11492 } else {
11493 let iterator = Iterator {
11494 object: self.peek(iterator_slot),
11495 next: self.peek(1 + extra),
11496 };
11497 let next = iterator.next.clone();
11498 self.call_value(next, iterator.object, Vec::new())?
11499 };
11500 let promise = self.promise_resolve_value(result)?;
11501 self.push(promise);
11502 }
11503 IteratorGetValueDone => {
11504 // `result -> value done`. A missing result object means the iterator was
11505 // already exhausted, which the loop treats as `done`.
11506 let result = self.pop();
11507 let done = match &result {
11508 Value::Object(object) => self
11509 .get_property(object, "done")?
11510 .is_some_and(|value| value.to_boolean()),
11511 _ => true,
11512 };
11513 if done {
11514 // Clear the iterator object so the `iterator_close` the loop emits on
11515 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
11516 // on normal completion, and this is where a normal completion is
11517 // recognised — the same trick `for_of_next` uses, which also replaces
11518 // the slot with `undefined`.
11519 //
11520 // The layout is fixed because only `for await` emits this opcode:
11521 // `iter next catch [result]`, so the iterator is three below the top.
11522 let depth = self.frame().stack.len();
11523 if depth >= 3 {
11524 self.frame_mut().stack[depth - 3] = Value::Undefined;
11525 }
11526 self.push(Value::Undefined);
11527 self.push(Value::Bool(true));
11528 } else {
11529 let Value::Object(object) = &result else {
11530 self.push(Value::Undefined);
11531 self.push(Value::Bool(true));
11532 return Ok(Step::Continue);
11533 };
11534 let value = self
11535 .get_property(object, "value")?
11536 .unwrap_or(Value::Undefined);
11537 self.push(value);
11538 self.push(Value::Bool(false));
11539 }
11540 }
11541
11542 Delete => {
11543 // `delete obj[key]`, where the key was just pushed. Deleting an array
11544 // index leaves a *hole* rather than closing the gap, and a
11545 // non-configurable property answers `false` and stays.
11546 let key = self.pop();
11547 let target = self.pop();
11548 let key = self.propkey(&key)?;
11549 let text_label = key.as_str().unwrap_or("").to_string();
11550 let deleted = match &target {
11551 Value::Object(object) => {
11552 let object = object.clone();
11553 self.delete_property_key(&object, &key)?
11554 }
11555 // A string's `length` and its index properties are
11556 // non-configurable, so deleting one answers `false`.
11557 Value::String(text) => {
11558 !(text_label == "length"
11559 || array_index(&text_label)
11560 .is_some_and(|index| (index as usize) < text.utf16_len()))
11561 }
11562 // "delete null.a" is a TypeError, not a no-op: the operator needs an
11563 // object to delete from, and only a *boxable* primitive has one.
11564 Value::Undefined | Value::Null => {
11565 return Err(Signal::Throw(
11566 self.make_error("TypeError", "cannot convert to object"),
11567 ));
11568 }
11569 // Any other primitive has no own properties; deleting nothing
11570 // succeeds.
11571 _ => true,
11572 };
11573 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
11574 // `TypeError` rather than a `false` result. Sloppy mode silently reports
11575 // the refusal, which is why the same statement throws here but not there.
11576 if !deleted && self.current_strict() {
11577 return Err(Signal::Throw(
11578 self.make_error("TypeError", "cannot delete property"),
11579 ));
11580 }
11581 self.push(Value::Bool(deleted));
11582 }
11583
11584 // -- exceptions and bookkeeping ---------------------------------
11585 Fclosure | Fclosure8 => {
11586 let value = self.closure(a as usize)?;
11587 self.push(value);
11588 }
11589
11590 other => {
11591 let name = other.info().name;
11592 return Err(Signal::Throw(self.make_error(
11593 "InternalError",
11594 &format!("{name} is not implemented yet"),
11595 )));
11596 }
11597 }
11598 Ok(Step::Continue)
11599 }
11600
11601 // -- operand helpers ----------------------------------------------------
11602
11603 /// The slot index an operand names, taking short forms into account.
11604 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
11605 use Opcode::*;
11606 match op {
11607 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
11608 | SetVarRef0 => 0,
11609 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
11610 | SetVarRef1 => 1,
11611 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
11612 | SetVarRef2 => 2,
11613 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
11614 | SetVarRef3 => 3,
11615 _ => a as usize,
11616 }
11617 }
11618
11619 /// The argument count of a call, taking `call0`…`call3` into account.
11620 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
11621 use Opcode::*;
11622 match op {
11623 Call0 => 0,
11624 Call1 => 1,
11625 Call2 => 2,
11626 Call3 => 3,
11627 _ => a as usize,
11628 }
11629 }
11630
11631 /// The atom's name as a property key.
11632 ///
11633 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
11634 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
11635 /// `String::clone` was a heap allocation and a copy — per property access.
11636 /// The atom at `index`, as a property key.
11637 ///
11638 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
11639 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
11640 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
11641 /// 5.3% of `property:monomorphic`.
11642 /// The atom's text, exactly — including an unpaired surrogate.
11643 ///
11644 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
11645 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
11646 /// `atom_text` below is for the other kind of use, where the atom is a key in the
11647 /// engine's own tables.
11648 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
11649 self.frame()
11650 .code
11651 .code
11652 .atoms
11653 .get(index)
11654 .map(|atom| match atom {
11655 Atom::Str(text) => text.clone(),
11656 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
11657 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
11658 Atom::Null => crate::value::Wtf8::new(String::new()),
11659 })
11660 .unwrap_or_default()
11661 }
11662
11663 fn atom_text(&self, index: usize) -> String {
11664 self.frame()
11665 .code
11666 .code
11667 .atoms
11668 .get(index)
11669 .map(|atom| match atom {
11670 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
11671 // compare it to an identifier, and a surrogate-bearing name is reachable
11672 // through `atom_wtf8` where it matters.
11673 Atom::Str(text) => text.to_string_lossy().into_owned(),
11674 Atom::Index(value) => value.to_string(),
11675 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
11676 // `throw_error`, `delete super.x`) never read it.
11677 Atom::Null => String::new(),
11678 })
11679 .unwrap_or_default()
11680 }
11681
11682 fn constant(&mut self, index: usize) -> JsResult<Value> {
11683 let constant = self.frame().code.code.cpool.get(index).cloned();
11684 Ok(match &constant {
11685 Some(Constant::Number(number)) => Value::Float(*number),
11686 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
11687 Some(Constant::BigInt { digits, radix }) => {
11688 match crate::bigint::BigInt::from_radix(digits, *radix) {
11689 Some(big) => self.bigint(big),
11690 // A literal the parser accepted is always parseable; a failure here
11691 // would be a compiler bug, so it reads as an `InternalError`.
11692 None => {
11693 return Err(Signal::Throw(
11694 self.make_error("InternalError", "unparseable bigint literal"),
11695 ));
11696 }
11697 }
11698 }
11699 Some(Constant::Function(_)) => {
11700 return Err(Signal::Throw(
11701 self.make_error("InternalError", "a bare function constant"),
11702 ));
11703 }
11704 // A tagged template's call site: a frozen array of the cooked chunks with a
11705 // frozen `raw` array beside it, which is what `String.raw` reads back.
11706 Some(Constant::Template { cooked, raw }) => {
11707 let cooked_values: Vec<Value> = cooked
11708 .iter()
11709 .map(|chunk| match chunk {
11710 Some(text) => self.string_wtf8(text.clone()),
11711 None => Value::Undefined,
11712 })
11713 .collect();
11714 let raw_values: Vec<Value> =
11715 raw.iter().map(|text| self.string(text.clone())).collect();
11716 let raw_array = self.new_array(raw_values);
11717 raw_array.set_extensible(false);
11718 let template = self.new_array(cooked_values);
11719 template.define(
11720 "raw",
11721 Property::with_attributes(Value::Object(raw_array), false, false),
11722 );
11723 template.set_extensible(false);
11724 Value::Object(template)
11725 }
11726 _ => Value::Undefined,
11727 })
11728 }
11729
11730 /// The reference cell a closure-variable slot names.
11731 ///
11732 /// Two kinds of binding share this addressing: a genuine closure variable
11733 /// (captured from an enclosing function) lives in this frame's environment,
11734 /// while a *declared global* lives in the realm so that a script, a function
11735 /// declaration and their uses all see one binding. A plain `Global` — an
11736 /// undeclared name that may be satisfied by the global object — has no cell at
11737 /// all, which is how `typeof x` still works for a name that does not exist.
11738 /// The reference cell a closure-variable slot names.
11739 ///
11740 /// The environment is resolved once, when the closure is built, and this is
11741 /// just the lookup afterwards. A *declared global* is in there too, pointing at
11742 /// the realm's cell, so a script, a hoisted function declaration and their uses
11743 /// all share one binding. A plain `Global` — a name the script never declared —
11744 /// is read and written through `get_var`/`put_var` by name instead, which is
11745 /// what lets the global object satisfy it.
11746 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
11747 self.frame().env.cells.get(slot).cloned()
11748 }
11749
11750 /// Whether `slot` refers to a global binding through the reference table.
11751 ///
11752 /// A global's cell in the closure environment only exists so the slot has
11753 /// something to point at; the binding itself lives on the global object (a `var`)
11754 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
11755 /// be routed, not performed on the placeholder.
11756 fn is_global_slot(&self, slot: usize) -> bool {
11757 self.frame()
11758 .code
11759 .code
11760 .closure_vars
11761 .get(slot)
11762 .is_some_and(|c| {
11763 // A module's declarations and imports are *not* globals: their cells are
11764 // the module environment's, filled by the host, so the placeholder routing
11765 // must not apply to them.
11766 matches!(
11767 c.closure_type,
11768 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
11769 )
11770 })
11771 }
11772
11773 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
11774 if self.is_global_slot(slot) {
11775 return self.get_global(slot);
11776 }
11777 Ok(self
11778 .var_ref_cell(slot)
11779 .map(|cell| cell.get())
11780 .unwrap_or(Value::Undefined))
11781 }
11782
11783 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
11784 // A function declaration is hoisted by storing into a global reference before
11785 // the body runs, so this path is also what puts it on the global object.
11786 if self.is_global_slot(slot) {
11787 return self.put_global(slot, value);
11788 }
11789 if let Some(cell) = self.var_ref_cell(slot) {
11790 cell.set(value);
11791 }
11792 Ok(())
11793 }
11794
11795 // -- closures -----------------------------------------------------------
11796
11797 /// Build the closure for the function constant `index`.
11798 ///
11799 /// Every entry in the child's closure table names where its binding lives in
11800 /// *this* frame: a local or argument slot that was marked captured, or a cell
11801 /// this frame is itself holding. That is how a variable three functions deep
11802 /// stays one binding.
11803 fn closure(&mut self, index: usize) -> JsResult<Value> {
11804 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
11805 else {
11806 return Err(Signal::Throw(
11807 self.make_error("InternalError", "fclosure of a non-function"),
11808 ));
11809 };
11810 let mut cells = Vec::with_capacity(function.closure_vars.len());
11811 for closure_var in &function.closure_vars {
11812 let cell = match closure_var.closure_type {
11813 ClosureType::Arg => {
11814 let slot = closure_var.var_idx as usize;
11815 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
11816 }
11817 ClosureType::Local => {
11818 let slot = closure_var.var_idx as usize;
11819 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
11820 }
11821 ClosureType::Ref | ClosureType::GlobalRef => {
11822 // A `Ref` names a cell in this frame's own closure table; a
11823 // `GlobalRef` also starts there, then resolves by name below.
11824 let slot = closure_var.var_idx as usize;
11825 if let Some(cell) = self.frame().env.cells.get(slot) {
11826 cells.push(cell.clone());
11827 continue;
11828 }
11829 -1
11830 }
11831 _ => -1,
11832 };
11833 if cell >= 0 {
11834 let cell = self.frame().cells[cell as usize].clone();
11835 cells.push(cell);
11836 continue;
11837 }
11838 // A global: the cell is created on demand and shared through the realm,
11839 // so every function sees one binding.
11840 let name = closure_var.name.clone();
11841 let cell = match self.realm.globals.get(&name) {
11842 Some(cell) => cell.clone(),
11843 None => {
11844 let cell = self.new_cell(Value::Undefined);
11845 self.realm.globals.insert(name.clone(), cell.clone());
11846 cell
11847 }
11848 };
11849 cells.push(cell);
11850 }
11851 let name = function.name.clone();
11852 // `.length` is the arity before any default or rest parameter, not the number
11853 // of slots a pattern parameter needs.
11854 let length = function.defined_args;
11855 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
11856 // function and an arrow function do not. A *method* also does not, but that is not
11857 // known here — the method is marked when the `[[HomeObject]]` is attached (see
11858 // `set_home_object`), which is the moment it becomes a method.
11859 let function_kind = function.kind;
11860 let constructible =
11861 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
11862 let code = Gc::new(self.heap, CompiledCode::new(*function));
11863 // A closure built inside an `eval` inherits the eval's view of the enclosing
11864 // bindings, so it can still read them once the eval has returned.
11865 let eval_scope = self
11866 .active_eval_scope
11867 .clone()
11868 .or_else(|| self.frame().env.eval_scope.clone());
11869 // A closure sees the variables a direct `eval` declared in the frame it was
11870 // created in — the ones declared before *and after* it, so the same object is
11871 // shared; only the phase bounds which of them are visible.
11872 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
11873 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
11874 let env = Gc::new(
11875 self.heap,
11876 ClosureEnv {
11877 cells,
11878 eval_scope,
11879 local_vars,
11880 local_phase,
11881 },
11882 );
11883 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
11884 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
11885 // the only thing that carries `Symbol.toStringTag`, so without it
11886 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
11887 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
11888 let proto = match function_kind {
11889 js_compile::bytecode::FunctionKind::AsyncGenerator => self
11890 .realm
11891 .async_generator_function_proto
11892 .clone()
11893 .or_else(|| self.realm.function_proto.clone().into()),
11894 js_compile::bytecode::FunctionKind::Generator => self
11895 .realm
11896 .generator_function_proto
11897 .clone()
11898 .or_else(|| self.realm.function_proto.clone().into()),
11899 js_compile::bytecode::FunctionKind::Async => self
11900 .realm
11901 .async_function_proto
11902 .clone()
11903 .or_else(|| self.realm.function_proto.clone().into()),
11904 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
11905 };
11906 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
11907 object.set_constructible(constructible);
11908 object.define(
11909 "length",
11910 Property::name_or_length(Value::Int(length as i32)),
11911 );
11912 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
11913 // that checks the own-property descriptor fails if the property is missing.
11914 object.define("name", Property::name_or_length(self.string(name)));
11915 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
11916 // when `[[Construct]]` is created, so an async function and an arrow function have
11917 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
11918 // function) an own `prototype` property, which `builtin.js` checks for absence.
11919 //
11920 // A **generator** function is the exception that is not constructible: it still
11921 // gets a `prototype` field, because that object is what a generator *instance*
11922 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
11923 // made `function* g(){}; g.prototype` `undefined` and every generator share
11924 // `%GeneratorPrototype%` as its direct prototype.
11925 if constructible {
11926 self.install_function_prototype(&object);
11927 } else if matches!(
11928 function_kind,
11929 js_compile::bytecode::FunctionKind::Generator
11930 | js_compile::bytecode::FunctionKind::AsyncGenerator
11931 ) {
11932 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
11933 self.realm.generator_proto.clone()
11934 } else {
11935 self.realm
11936 .async_generator_proto
11937 .clone()
11938 .unwrap_or_else(|| self.realm.generator_proto.clone())
11939 };
11940 self.install_generator_prototype(&object, parent);
11941 }
11942 Ok(Value::Object(object))
11943 }
11944
11945 // -- conversions used by the operators ----------------------------------
11946
11947 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
11948 // `+x` is `ToNumber`, which for a string parses it and for an object runs
11949 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
11950 // string, which then behaves differently in every later comparison.
11951 match value {
11952 Value::Int(_) | Value::Float(_) => Ok(value),
11953 other => Ok(Value::Float(self.to_js_number(&other)?)),
11954 }
11955 }
11956
11957 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
11958 ///
11959 /// Returns the *converted* old value and the new one, because the two callers need
11960 /// different halves: `++x` yields the new value, while `x++` yields the old one and
11961 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
11962 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
11963 /// boolean.
11964 ///
11965 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
11966 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
11967 /// a bigint algorithm then ran exactly once.
11968 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
11969 if let Value::BigInt(big) = &value {
11970 let one = crate::bigint::BigInt::from_i64(1);
11971 let next = if up { big.add(&one) } else { big.sub(&one) };
11972 return Ok((value, self.bigint(next)));
11973 }
11974 let old = self.numeric(value)?;
11975 let new = if up {
11976 increment(old.clone())
11977 } else {
11978 decrement(old.clone())
11979 };
11980 Ok((old, new))
11981 }
11982
11983 fn numeric(&mut self, value: Value) -> JsResult<Value> {
11984 // `ToNumber` on an object runs `ToPrimitive` first, which is how
11985 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
11986 // heard at all. Reading the object's own tag instead (`other.to_number()`)
11987 // turned the whole operand into `NaN` and swallowed the exception.
11988 match value {
11989 Value::Int(_) | Value::Float(_) => Ok(value),
11990 other => Ok(Value::Float(self.to_js_number(&other)?)),
11991 }
11992 }
11993
11994 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
11995 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
11996 match value {
11997 Value::BigInt(big) => Ok((**big).clone()),
11998 // The reference words this the same way for every operator, so a failing
11999 // script reads identically; the operator itself adds nothing a caller can use.
12000 _ => Err(Signal::Throw(
12001 self.make_error("TypeError", "cannot convert bigint to number"),
12002 )),
12003 }
12004 }
12005
12006 /// Arithmetic where at least one operand is a `BigInt`.
12007 ///
12008 /// The two numeric types never mix, so a bigint paired with anything else is an error
12009 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12010 /// that the relational operators handle it separately.
12011 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12012 use Opcode::*;
12013 let a = self.bigint_operand(&left)?;
12014 let b = self.bigint_operand(&right)?;
12015 let result = match op {
12016 Add => a.add(&b),
12017 Sub => a.sub(&b),
12018 Mul => a.mul(&b),
12019 Div | Mod => {
12020 let Some((quotient, remainder)) = a.div_rem(&b) else {
12021 return Err(Signal::Throw(
12022 self.make_error("RangeError", "division by zero"),
12023 ));
12024 };
12025 if op == Div { quotient } else { remainder }
12026 }
12027 Pow => {
12028 let Some(value) = a.pow(&b) else {
12029 return Err(Signal::Throw(self.make_error(
12030 "RangeError",
12031 "BigInt exponent must be non-negative and not absurdly large",
12032 )));
12033 };
12034 value
12035 }
12036 And => a.bitand(&b),
12037 Or => a.bitor(&b),
12038 Xor => a.bitxor(&b),
12039 Shl | Sar => {
12040 // A shift count is a `BigInt` here, and both directions are exact; a
12041 // negative count would be the other direction, which the spec forbids.
12042 let Some(count) = b.to_i64() else {
12043 return Err(Signal::Throw(
12044 self.make_error("RangeError", "BigInt shift count is too large"),
12045 ));
12046 };
12047 if count < 0 {
12048 return Err(Signal::Throw(self.make_error(
12049 "RangeError",
12050 "BigInt shift count must be non-negative",
12051 )));
12052 }
12053 if op == Shl {
12054 a.shl(count as u64)
12055 } else {
12056 a.shr(count as u64)
12057 }
12058 }
12059 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12060 _ => {
12061 return Err(Signal::Throw(self.make_error(
12062 "TypeError",
12063 "BigInts have no unsigned right shift, use >> instead",
12064 )));
12065 }
12066 };
12067 Ok(self.bigint(result))
12068 }
12069
12070 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12071 ///
12072 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12073 /// is on the mathematical values, and nothing is rounded first.
12074 /// `<`, `<=`, `>`, `>=`.
12075 ///
12076 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12077 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12078 /// It is a `?`-returning function for exactly that reason: an object operand can run
12079 /// script, and script can throw. The old version compared `to_number` of the raw
12080 /// values, which answered `false` for every object instead of calling `valueOf` —
12081 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12082 /// never ran.
12083 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12084 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12085 // call, nothing that can throw.
12086 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12087 let ordering = Some(left.cmp(right));
12088 return Ok(ordering_answer(op, ordering));
12089 }
12090 // Anything that can run script has to be converted first, in this order.
12091 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12092 {
12093 (
12094 self.to_primitive(left, Hint::Number)?,
12095 self.to_primitive(right, Hint::Number)?,
12096 )
12097 } else {
12098 (left, right)
12099 };
12100 let ordering = match (&left, &right) {
12101 // The loop condition `i < n` is integer against integer, and it runs once
12102 // per iteration of every loop in every program. Without this arm it took the
12103 // `to_number` path twice, which is a `match` plus a conversion each.
12104 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12105 (Value::String(a), Value::String(b)) => {
12106 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12107 }
12108 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12109 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12110 // is true even though `2.5` has no bigint form.
12111 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12112 let b = other.to_number();
12113 if b.is_nan() {
12114 None
12115 } else {
12116 compare_bigint_and_f64(a, b)
12117 }
12118 }
12119 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12120 let a = other.to_number();
12121 if a.is_nan() {
12122 None
12123 } else {
12124 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12125 }
12126 }
12127 _ => left.to_number().partial_cmp(&right.to_number()),
12128 };
12129 Ok(ordering_answer(op, ordering))
12130 }
12131
12132 fn binary_add(&mut self) -> JsResult<()> {
12133 let right = self.pop();
12134 let left = self.pop();
12135 // Two integers add without any of the machinery below: no `ToPrimitive` (an
12136 // `Int` is already primitive), no string check, no bigint check, no allocation.
12137 // `x += 1` in a loop is the single most common instruction sequence in real
12138 // script, and it used to walk every one of those checks before reaching the
12139 // same `checked_add`.
12140 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12141 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12142 return Ok(());
12143 }
12144 let left = self.primitive_of(left)?;
12145 let right = self.primitive_of(right)?;
12146 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12147 // that check comes before the bigint one: `"" + 1n` is a string, not a
12148 // mixed-type error.
12149 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12150 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12151 // `TypeError`, the one place a symbol and a string do not mix.
12152 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12153 // between a copy and a rope from their lengths, and a rope is what turns
12154 // `text += "abc"` in a loop from quadratic into linear.
12155 if let (Value::String(left), Value::String(right)) = (&left, &right) {
12156 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12157 // reports as `InternalError: string too long`.
12158 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12159 return Err(Signal::Throw(
12160 self.make_error("InternalError", "string too long"),
12161 ));
12162 };
12163 self.push(Value::String(Gc::new(self.heap, joined)));
12164 return Ok(());
12165 }
12166 // At least one operand was not a string, so `ToString` it. This rejects a
12167 // symbol, which is the one place a symbol and a string do not mix.
12168 let left = self.checked_to_wtf8(&left)?;
12169 let right = self.checked_to_wtf8(&right)?;
12170 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12171 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12172 let text = left.concat(&right);
12173 self.push(self.string_wtf8(text));
12174 return Ok(());
12175 }
12176 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12177 // not a conversion.
12178 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12179 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12180 self.push(value);
12181 return Ok(());
12182 }
12183 let left = self.numeric(left)?;
12184 let right = self.numeric(right)?;
12185 self.push(add_numbers(left, right));
12186 Ok(())
12187 }
12188
12189 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12190 self.to_primitive(value, Hint::Default)
12191 }
12192
12193 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12194 ///
12195 /// The order depends on the hint: the "number" order tries `valueOf` first and
12196 /// `toString` second, the "string" order the other way round, and the default
12197 /// hint uses the number order. A result that is still an object is a `TypeError`,
12198 /// because no built-in `valueOf`/`toString` returns one.
12199 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12200 let Value::Object(object) = &value else {
12201 return Ok(value);
12202 };
12203 // A Date overrides the default hint to mean "string", which is what
12204 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12205 // this, `"" + new Date()` would print the milliseconds, not the date.
12206 let hint = if hint == Hint::Default && is_date_object(self, object) {
12207 Hint::String
12208 } else {
12209 hint
12210 };
12211 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12212 // handed the hint as a string. This is the hook a Date uses for its default hint
12213 // and a script uses to take over conversion entirely.
12214 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12215 // `GetMethod`, not "is it a callable object": the property has to be read and then
12216 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12217 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12218 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12219 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12220 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12221 // callable.
12222 match self.get_property_key(object, &key)? {
12223 None | Some(Value::Undefined) | Some(Value::Null) => {}
12224 Some(Value::Object(function)) if function.is_callable() => {
12225 let hint = match hint {
12226 Hint::String => "string",
12227 Hint::Number => "number",
12228 Hint::Default => "default",
12229 };
12230 let hint = self.string(hint);
12231 let result = self.call_value(
12232 Value::Object(function),
12233 Value::Object(object.clone()),
12234 vec![hint],
12235 )?;
12236 if !matches!(result, Value::Object(_)) {
12237 return Ok(result);
12238 }
12239 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12240 }
12241 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12242 }
12243 let order: [&str; 2] = match hint {
12244 Hint::String => ["toString", "valueOf"],
12245 Hint::Number | Hint::Default => ["valueOf", "toString"],
12246 };
12247 let receiver = object.clone();
12248 for method in order {
12249 if let Some(function) = self.get_property(&receiver, method)?
12250 && matches!(&function, Value::Object(object) if object.is_callable())
12251 {
12252 let result =
12253 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12254 if !matches!(result, Value::Object(_)) {
12255 return Ok(result);
12256 }
12257 }
12258 }
12259 Err(self.type_error("cannot convert object to primitive value"))
12260 }
12261
12262 /// `ToString` with the object case going through `ToPrimitive`.
12263 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12264 if matches!(value, Value::Object(_)) {
12265 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12266 return Ok(primitive.to_js_string());
12267 }
12268 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12269 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12270 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12271 // check here broke `String(Symbol())` and 45 cases that print a symbol.
12272 Ok(value.to_js_string())
12273 }
12274
12275 /// `ToString(value)`, with §7.1.19's symbol refusal.
12276 ///
12277 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12278 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12279 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12280 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12281 if matches!(value, Value::Symbol(_)) {
12282 return Err(self.type_error("cannot convert a Symbol to a string"));
12283 }
12284 if matches!(value, Value::Object(_)) {
12285 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12286 if matches!(primitive, Value::Symbol(_)) {
12287 return Err(self.type_error("cannot convert a Symbol to a string"));
12288 }
12289 return Ok(primitive.to_js_string());
12290 }
12291 Ok(value.to_js_string())
12292 }
12293
12294 /// `ToString` that keeps the string's code units instead of flattening them.
12295 ///
12296 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12297 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12298 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12299 if matches!(value, Value::Symbol(_)) {
12300 return Err(Signal::Throw(
12301 self.make_error("TypeError", "cannot convert symbol to string"),
12302 ));
12303 }
12304 // An object runs `ToPrimitive` first, which may itself produce a symbol.
12305 let value = self.to_primitive(value.clone(), Hint::String)?;
12306 match value {
12307 Value::Symbol(_) => Err(Signal::Throw(
12308 self.make_error("TypeError", "cannot convert symbol to string"),
12309 )),
12310 Value::String(text) => Ok(text.wtf8().clone()),
12311 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12312 }
12313 }
12314
12315 /// `ToNumber` with the object case going through `ToPrimitive`.
12316 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12317 let value = if matches!(value, Value::Object(_)) {
12318 self.to_primitive(value.clone(), Hint::Number)?
12319 } else {
12320 value.clone()
12321 };
12322 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12323 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12324 // `NaN` to stay total, and the operators check for the bigint themselves — but
12325 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12326 // refuse, and answering `NaN` made them silently wrong instead.
12327 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12328 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12329 match value {
12330 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12331 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12332 other => Ok(other.to_number()),
12333 }
12334 }
12335
12336 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12337 /// [`ElementType::write`].
12338 ///
12339 /// This is separated from the write because both conversions are observable script —
12340 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12341 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12342 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12343 /// setters, and a plain `a[i] = v`.
12344 pub(crate) fn element_value(
12345 &mut self,
12346 element: crate::builtins::typedarray::ElementType,
12347 value: Value,
12348 ) -> JsResult<Value> {
12349 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12350 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12351 let primitive = match &value {
12352 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12353 _ => value,
12354 };
12355 if element.is_bigint() {
12356 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12357 Ok(Value::BigInt(Gc::new(self.heap, big)))
12358 } else {
12359 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12360 Ok(Value::Float(self.to_js_number(&primitive)?))
12361 }
12362 }
12363
12364 /// `ToPropertyKey`: what a computed member access uses as its key.
12365 ///
12366 /// A symbol is returned as itself, never stringified — that is what keeps
12367 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
12368 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
12369 match value {
12370 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
12371 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
12372 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
12373 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
12374 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12375 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
12376 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
12377 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
12378 other.to_js_string(),
12379 ))),
12380 },
12381 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
12382 }
12383 }
12384
12385 /// `ToPropertyKey` for the callers that can only use a string key.
12386 ///
12387 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
12388 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
12389 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
12390 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
12391 /// program continues with a value nobody asked for.
12392 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12393 use crate::value::Wtf8;
12394 Ok(match value {
12395 // A string key keeps its code units. Going through a lossy `String` would make
12396 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
12397 Value::String(text) => text.wtf8().clone(),
12398 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
12399 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
12400 // falling back to its `ToString` would print `[object Object]`.
12401 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12402 Value::String(text) => text.wtf8().clone(),
12403 other => Wtf8::new(other.to_js_string()),
12404 },
12405 other => Wtf8::new(other.to_js_string()),
12406 })
12407 }
12408
12409 // -- object operations used by instructions -----------------------------
12410
12411 /// Read `object[key]`, returning `undefined` when the property is missing.
12412 ///
12413 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
12414 /// primitive (looking through its prototype) as well as an object — which is what
12415 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
12416 /// argument needs too.
12417 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
12418 self.read_field_key(object, &PropertyKey::from(key))
12419 }
12420
12421 /// [`Interp::read_field`] with a key that may be a symbol.
12422 ///
12423 /// A symbol key never reaches the string shortcuts: a string's `length` and its
12424 /// indices are string properties, and a symbol named `length` is a different
12425 /// property that a string primitive cannot have.
12426 /// [`Interp::read_field_key`], with an inline cache in front of it.
12427 ///
12428 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
12429 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
12430 /// without this the engine walked the chain and compared ~40 property names on each
12431 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
12432 ///
12433 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
12434 /// missing property. Those answers depend on running code or on state the guard below
12435 /// does not cover, and a wrong answer here is far more expensive than a lookup.
12436 ///
12437 /// A hit is re-validated against the *whole* walked chain, not just the level that
12438 /// answered: the receiver and every prototype down to that level must still be the same
12439 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
12440 /// property-table *lengths* — which is what catches a property appearing on an
12441 /// intermediate prototype and shadowing the cached one.
12442 pub fn read_field_cached(
12443 &mut self,
12444 object: &Value,
12445 key: &PropertyKey,
12446 slot: usize,
12447 ) -> JsResult<Value> {
12448 let index = Self::field_cache_slot(object, key, slot);
12449 let Value::Object(target) = object else {
12450 return self.read_field_key(object, key);
12451 };
12452 if target.proxy_state().is_some() {
12453 return self.read_field_key(object, key);
12454 }
12455 if let Some(cached) = &self.field_cache[index]
12456 && cached.key == *key
12457 && let Some(value) = Self::cached_hit(target, cached)
12458 {
12459 return Ok(value);
12460 }
12461 let value = self.read_field_key(object, key)?;
12462 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
12463 Ok(value)
12464 }
12465
12466 /// Whether a cache entry still describes this lookup, and if so the value.
12467 ///
12468 /// The guard is the whole point of the entry: identity plus property-table length for
12469 /// every level walked. Re-checked per level rather than once at the receiving end,
12470 /// because a shadowing property can appear anywhere along the chain.
12471 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
12472 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
12473 // starts with: a clone is a reference-count bump and a drop, and for
12474 // `property:monomorphic` every single hit takes only this arm.
12475 let (weak, len) = cached.chain[0].as_ref()?;
12476 if !target.upgrades_to(weak) {
12477 return None;
12478 }
12479 if cached.level == 0 {
12480 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
12481 return target.cached_property_at(cached.index, &cached.key, *len);
12482 }
12483 if target.props_len() != *len {
12484 return None;
12485 }
12486 let mut level = 1;
12487 let mut current = target.proto()?;
12488 loop {
12489 let (weak, len) = cached.chain[level].as_ref()?;
12490 if !current.upgrades_to(weak) || current.props_len() != *len {
12491 return None;
12492 }
12493 if level == cached.level as usize {
12494 // The level that answered: the value is only reusable while the key is
12495 // still there and still a plain data property.
12496 return current.cached_data_property(cached.index, &cached.key);
12497 }
12498 current = current.proto()?;
12499 level += 1;
12500 }
12501 }
12502
12503 /// Build a cache entry for a lookup that just went through the slow path.
12504 ///
12505 /// Records the chain only when the answer came from a plain data property at a level
12506 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
12507 /// costs the next lookup the walk it would have cost anyway.
12508 fn record_field_lookup(
12509 target: &Gc<JsObject>,
12510 key: &PropertyKey,
12511 _value: Value,
12512 ) -> Option<FieldCache> {
12513 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
12514 [None, None, None];
12515 let mut current = target.clone();
12516 for level in 0..MAX_CACHED_CHAIN {
12517 chain[level] = Some((current.downgrade(), current.props_len()));
12518 if let Some((found, _)) = current.own_property_index(key) {
12519 // `own_property_index` declines an accessor and a hole, which is exactly
12520 // the set that must not be cached.
12521 return Some(FieldCache {
12522 key: key.clone(),
12523 index: found,
12524 level: level as u8,
12525 chain,
12526 });
12527 }
12528 current = current.proto()?;
12529 }
12530 None
12531 }
12532
12533 /// Which cache slot a lookup uses.
12534 ///
12535 /// Mixes the object's address, the name and the site, so that two properties of one
12536 /// object, and one property of two objects, land in different slots — which is what lets
12537 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
12538 /// other iteration.
12539 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
12540 let mut hash = match object {
12541 Value::Object(object) => object.address(),
12542 _ => 0,
12543 };
12544 hash = hash
12545 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
12546 .rotate_left(17)
12547 .wrapping_add(key.hash_code());
12548 hash = hash.wrapping_add(site.wrapping_mul(31));
12549 // The table is a power of two, so the low bits are the slot.
12550 hash & (FIELD_CACHE_SLOTS - 1)
12551 }
12552
12553 /// Read `key` from `object`, without the inline cache.
12554 ///
12555 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
12556 /// prototype chain, while the cached form answers an own data property from memory.
12557 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
12558 let text = key.as_str().unwrap_or("");
12559 let Value::Object(object) = object else {
12560 // Reading a property of `undefined`/`null` is the classic TypeError.
12561 if object.is_nullish() {
12562 return Err(Signal::Throw(self.make_error(
12563 "TypeError",
12564 &format!("cannot read property '{key}' of {}", object.to_js_string()),
12565 )));
12566 }
12567 // A string has `length` and index access without being boxed.
12568 if let Value::String(value) = object {
12569 if text == "length" {
12570 return Ok(Value::Int(value.utf16_len() as i32));
12571 }
12572 if let Some(index) = array_index(text) {
12573 return Ok(match value.wtf8().unit_at(index as usize) {
12574 Some(unit) => self.string_wtf8(unit),
12575 None => Value::Undefined,
12576 });
12577 }
12578 }
12579 // A property of a primitive is looked up on its prototype: this is what
12580 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
12581 let prototype = match object {
12582 Value::String(_) => self.realm.string_proto.clone(),
12583 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12584 Value::Bool(_) => self.realm.boolean_proto.clone(),
12585 // A symbol's methods live on `Symbol.prototype`, reached the same way —
12586 // `sym.description` reads through the prototype, not off the symbol.
12587 Value::Symbol(_) => self.realm.symbol_proto.clone(),
12588 // …and a bigint's on `BigInt.prototype`, which is how
12589 // `(255n).toString(16)` reaches its method.
12590 Value::BigInt(_) => self.realm.bigint_proto.clone(),
12591 _ => None,
12592 };
12593 if let Some(prototype) = prototype
12594 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
12595 {
12596 return Ok(value);
12597 }
12598 return Ok(Value::Undefined);
12599 };
12600 Ok(self
12601 .get_property_key(object, key)?
12602 .unwrap_or(Value::Undefined))
12603 }
12604
12605 /// The `#name` a private symbol stands for, for error messages.
12606 ///
12607 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
12608 /// was made from.
12609 fn private_name(symbol: &Value) -> Option<String> {
12610 match symbol {
12611 Value::Symbol(symbol) if symbol.is_private() => Some(
12612 symbol
12613 .description()
12614 .map(|text| text.to_string())
12615 .unwrap_or_default(),
12616 ),
12617 _ => None,
12618 }
12619 }
12620
12621 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
12622 ///
12623 /// Every private-field opcode takes the symbol the class stored in its own scope; a
12624 /// non-symbol here would be a compiler bug, and the reference guards it with
12625 /// `JS_ThrowTypeErrorNotASymbol`.
12626 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
12627 match symbol {
12628 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
12629 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
12630 }
12631 }
12632
12633 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
12634 ///
12635 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
12636 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
12637 /// would hit if the parser did not reject it first.
12638 fn define_private_field(
12639 &mut self,
12640 object: &Value,
12641 symbol: &Value,
12642 value: Value,
12643 ) -> JsResult<()> {
12644 let key = self.private_key(symbol)?;
12645 let Some(target) = object.as_object() else {
12646 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12647 };
12648 if !target.is_extensible() {
12649 return Err(Signal::Throw(
12650 self.make_error("TypeError", "object is not extensible"),
12651 ));
12652 }
12653 if target.own_property_key(&key).is_some() {
12654 let name = Self::private_name(symbol).unwrap_or_default();
12655 return Err(Signal::Throw(self.make_error(
12656 "TypeError",
12657 &format!("private class field '{name}' already exists"),
12658 )));
12659 }
12660 target.define_data_key(&key, value);
12661 Ok(())
12662 }
12663
12664 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
12665 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
12666 let key = self.private_key(symbol)?;
12667 let Some(target) = object.as_object() else {
12668 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12669 };
12670 match target.own_property_key(&key) {
12671 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
12672 None => {
12673 let name = Self::private_name(symbol).unwrap_or_default();
12674 Err(Signal::Throw(self.make_error(
12675 "TypeError",
12676 &format!("private class field '{name}' does not exist"),
12677 )))
12678 }
12679 }
12680 }
12681
12682 /// `JS_SetPrivateField`: the store half of the same rule.
12683 fn write_private_field(
12684 &mut self,
12685 object: &Value,
12686 symbol: &Value,
12687 value: Value,
12688 ) -> JsResult<()> {
12689 let key = self.private_key(symbol)?;
12690 let Some(target) = object.as_object() else {
12691 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12692 };
12693 if target.write_value_key(&key, value) {
12694 return Ok(());
12695 }
12696 let name = Self::private_name(symbol).unwrap_or_default();
12697 Err(Signal::Throw(self.make_error(
12698 "TypeError",
12699 &format!("private class field '{name}' does not exist"),
12700 )))
12701 }
12702
12703 /// The `in` half: does `object` have this private field?
12704 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
12705 ///
12706 /// The symbol is created once per class — the first `add_brand` on a given home object
12707 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
12708 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
12709 /// emit for the *instance* brand passes null because all it wants is the symbol.
12710 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
12711 let Some(home_object) = home.as_object() else {
12712 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12713 };
12714 let symbol = match home_object.private_brand() {
12715 Some(symbol) => symbol,
12716 None => {
12717 let symbol = Gc::new(
12718 self.heap,
12719 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
12720 );
12721 home_object.set_private_brand(symbol.clone());
12722 symbol
12723 }
12724 };
12725 let Some(target) = object.as_object() else {
12726 // Not an object: nothing to brand. The reference does the same, and `undefined`
12727 // here would otherwise turn a field initialiser into a TypeError.
12728 return Ok(());
12729 };
12730 if !target.is_extensible() {
12731 return Err(Signal::Throw(
12732 self.make_error("TypeError", "object is not extensible"),
12733 ));
12734 }
12735 if target.carries_brand(&symbol) {
12736 return Err(Signal::Throw(
12737 self.make_error("TypeError", "private method is already present"),
12738 ));
12739 }
12740 target.add_brand(symbol);
12741 Ok(())
12742 }
12743
12744 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
12745 ///
12746 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
12747 /// decides whether to throw.
12748 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
12749 let Some(function) = function.as_object() else {
12750 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12751 };
12752 let Some(home) = function.home_object() else {
12753 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12754 };
12755 let Some(brand) = home.private_brand() else {
12756 return Err(Signal::Throw(
12757 self.make_error("TypeError", "expecting <brand> private field"),
12758 ));
12759 };
12760 Ok(object.carries_brand(&brand))
12761 }
12762
12763 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
12764 let Value::Object(object) = object else {
12765 return Err(Signal::Throw(self.make_error(
12766 "TypeError",
12767 &format!("cannot set property '{key}' of {}", object.to_js_string()),
12768 )));
12769 };
12770 // The write half of the property inline cache, in effect: an own, writable,
12771 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
12772 // decide — no prototype walk (an own property shadows the chain before a setter
12773 // there could matter), no extensibility check (the object already has the key),
12774 // and no `[[DefineOwnProperty]]`.
12775 //
12776 // `this.value = …` inside a method is the whole write side of
12777 // `property:method-call`, and it was reaching `set_property_with_key` with its
12778 // proxy test, its typed-array test, its array-index test and finally a linear
12779 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
12780 //
12781 // Every disqualifier is checked here: a proxy traps the set, an array index and
12782 // `length` live outside the property table, and a typed array's element is stored
12783 // through its view's element type.
12784 if object.proxy_state().is_none()
12785 && !object.is_array()
12786 && object.typed_array_element_type().is_none()
12787 && object.write_value_key(key, value.clone())
12788 {
12789 return Ok(());
12790 }
12791 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
12792 let on_failure = if self.frame().code.code.strict {
12793 DeleteFailure::Throw
12794 } else {
12795 DeleteFailure::Ignore
12796 };
12797 self.set_property_with_key(object, key, value, on_failure)
12798 }
12799
12800 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
12801 ///
12802 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
12803 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
12804 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
12805 /// `Number.parseInt(sym)` — so those callers use this instead.
12806 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
12807 if matches!(value, Value::Symbol(_)) {
12808 return Err(Signal::Throw(
12809 self.make_error("TypeError", "cannot convert symbol to string"),
12810 ));
12811 }
12812 // An object runs `ToPrimitive` first, which may itself produce a symbol —
12813 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
12814 let value = self.to_primitive(value.clone(), Hint::String)?;
12815 if matches!(value, Value::Symbol(_)) {
12816 return Err(Signal::Throw(
12817 self.make_error("TypeError", "cannot convert symbol to string"),
12818 ));
12819 }
12820 Ok(value.to_js_string())
12821 }
12822
12823 /// `ToPropertyKey` for a builtin that takes a key argument.
12824 ///
12825 /// Fallible: a key whose `toString` throws has to propagate that error, both for
12826 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
12827 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
12828 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
12829 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
12830 self.propkey(value)
12831 }
12832
12833 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
12834 ///
12835 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
12836 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
12837 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
12838 /// `RangeError` — and why this cannot be a plain `ToNumber`.
12839 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
12840 let number = match value {
12841 Value::Int(number) => *number as f64,
12842 Value::Float(number) => *number,
12843 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
12844 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
12845 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
12846 // reference answers 0.
12847 Value::Null | Value::Bool(_) => value.to_number(),
12848 _ => {
12849 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
12850 match primitive {
12851 Value::Int(number) => number as f64,
12852 Value::Float(number) => number,
12853 other => {
12854 // `ToString` then `ToNumber`, so a string length goes through the
12855 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
12856 // `Value::to_number` on the string already implements exactly that.
12857 let text = self.to_js_string(&other)?;
12858 crate::value::string_to_number(&text)
12859 }
12860 }
12861 }
12862 };
12863 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
12864 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
12865 // is a `RangeError`, not `0`.
12866 if !number.is_finite()
12867 || number.fract() != 0.0
12868 || !(0.0..=u32::MAX as f64).contains(&number)
12869 {
12870 return Err(self.range_error("invalid array length"));
12871 }
12872 Ok(number as u32)
12873 }
12874
12875 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
12876 /// `Object.getOwnPropertySymbols` put in their result array.
12877 pub fn key_value(&self, key: &PropertyKey) -> Value {
12878 match key {
12879 PropertyKey::String(text) => self.string_wtf8(text.clone()),
12880 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12881 }
12882 }
12883
12884 /// Fill in a String exotic object: `_value`, `length` and the index properties.
12885 ///
12886 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
12887 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
12888 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
12889 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
12890 /// the two paths had drifted; this is the one both now use.
12891 ///
12892 /// The indices are *code units*, so an astral character occupies two of them — the
12893 /// same rule `s.length` and `s[i]` follow.
12894 /// Give an already-created object the internal slot that makes it a wrapper of
12895 /// `value`, so the primitive's prototype methods work on it.
12896 ///
12897 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
12898 /// which are wrappers of their own type holding the empty value.
12899 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
12900 self.internal_set(object, "_value", value);
12901 }
12902
12903 pub(crate) fn init_string_wrapper(
12904 &mut self,
12905 object: &Gc<JsObject>,
12906 text: &Gc<crate::value::JsString>,
12907 ) {
12908 object.define(
12909 "length",
12910 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
12911 );
12912 for index in 0..text.utf16_len() {
12913 if let Some(unit) = text.wtf8().unit_at(index) {
12914 object.define(
12915 &index.to_string(),
12916 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
12917 Property::with_attributes(self.string_wtf8(unit), false, true),
12918 );
12919 }
12920 }
12921 object.define_key(
12922 &self.internal_slot("_value"),
12923 Property::with_attributes(Value::String(text.clone()), false, false),
12924 );
12925 }
12926
12927 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
12928 ///
12929 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
12930 /// throws. The wrapper carries its primitive in `_value` — the same slot
12931 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
12932 /// on a boxed value no constructor ever built.
12933 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12934 let (prototype, primitive) = match value {
12935 Value::Object(object) => return Ok(object.clone()),
12936 Value::String(text) => {
12937 let object = self.new_object(self.realm.string_proto.clone());
12938 self.init_string_wrapper(&object, text);
12939 return Ok(object);
12940 }
12941 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
12942 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
12943 // A symbol and a bigint box into wrappers whose methods live on
12944 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
12945 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
12946 // branch below instead produced an object with *no* prototype, so those
12947 // methods were unreachable on a box.
12948 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
12949 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
12950 Value::Undefined | Value::Null => {
12951 return Err(Signal::Throw(self.make_error(
12952 "TypeError",
12953 &format!("cannot convert {} to object", value.to_js_string()),
12954 )));
12955 }
12956 _ => (None, value.clone()),
12957 };
12958 let object = self.new_object(prototype);
12959 self.internal_set(&object, "_value", primitive);
12960 Ok(object)
12961 }
12962
12963 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
12964 ///
12965 /// Split out for a reader that has to create the object *before* it knows what it wraps:
12966 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
12967 /// written before its primitive, so the placeholder has to exist first and be filled in
12968 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
12969 /// than a second in the deserialiser.
12970 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
12971 let prototype = match value {
12972 Value::String(_) => self.realm.string_proto.clone(),
12973 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12974 Value::Bool(_) => self.realm.boolean_proto.clone(),
12975 Value::Symbol(_) => self.realm.symbol_proto.clone(),
12976 Value::BigInt(_) => self.realm.bigint_proto.clone(),
12977 _ => {
12978 return Err(Signal::Throw(self.make_error(
12979 "TypeError",
12980 &format!("cannot box {}", value.to_js_string()),
12981 )));
12982 }
12983 };
12984 object.set_proto(prototype);
12985 if let Value::String(text) = value {
12986 self.init_string_wrapper(object, text);
12987 return Ok(());
12988 }
12989 self.internal_set(object, "_value", value.clone());
12990 Ok(())
12991 }
12992
12993 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
12994 ///
12995 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
12996 /// through the `Symbol` function object, so the registry is reachable as a method rather
12997 /// than only from `builtins::symbol`.
12998 pub fn symbol_for(&mut self, key: &str) -> Value {
12999 if let Some(existing) = self.realm.symbol_registry.get(key) {
13000 return existing.clone();
13001 }
13002 let symbol = crate::builtins::symbol::symbol_value(
13003 self,
13004 crate::value::JsSymbol::registered(key.to_string()),
13005 );
13006 self.realm
13007 .symbol_registry
13008 .insert(key.to_string(), symbol.clone());
13009 symbol
13010 }
13011
13012 /// `a == b`, the coercing comparison.
13013 ///
13014 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13015 /// which is what makes `[] == ""` true: `[]` becomes `""` via
13016 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13017 /// because the conversion is allowed to call script code, so the two primitive
13018 /// operands are handed back to it.
13019 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13020 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13021 return Ok(left.loose_equals(&right));
13022 }
13023 // `null == undefined` holds even though neither is an object.
13024 if matches!(left, Value::Undefined | Value::Null)
13025 && matches!(right, Value::Undefined | Value::Null)
13026 {
13027 return Ok(true);
13028 }
13029 if matches!(left, Value::Undefined | Value::Null)
13030 || matches!(right, Value::Undefined | Value::Null)
13031 {
13032 return Ok(false);
13033 }
13034 // Two objects compare by identity. Only an object *against a primitive* is
13035 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13036 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13037 return Ok(a.ptr_eq(b));
13038 }
13039 let left = self.to_primitive(left, Hint::Default)?;
13040 let right = self.to_primitive(right, Hint::Default)?;
13041 Ok(left.loose_equals(&right))
13042 }
13043
13044 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13045 let Value::Object(object) = object else {
13046 return Err(Signal::Throw(
13047 self.make_error("TypeError", "cannot use 'in' on a non-object"),
13048 ));
13049 };
13050 let key = self.propkey(key)?;
13051 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13052 // trap. One implementation, so an array's derived `length` and its inherited holes
13053 // cannot be right in one caller and wrong in another.
13054 self.has_own_or_inherited(object, &key)
13055 }
13056
13057 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13058 ///
13059 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13060 /// whole reason the operator is a hook rather than a prototype walk.
13061 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13062 if let Value::Object(function) = constructor {
13063 let key = self.realm.well_known_key(WellKnown::HasInstance);
13064 let method = self.get_property_key(function, &key)?;
13065 if let Some(method) = method
13066 && !matches!(method, Value::Undefined)
13067 {
13068 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13069 return Ok(answer.to_boolean());
13070 }
13071 }
13072 self.instance_of(object, constructor)
13073 }
13074
13075 /// `OrdinaryHasInstance`: the prototype walk on its own.
13076 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13077 self.instance_of(object, constructor)
13078 }
13079
13080 /// `IsArray`: an array, or a proxy whose target is one.
13081 ///
13082 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13083 /// makes `Array.isArray(new Proxy([], {}))` true.
13084 pub fn is_array_value(&self, value: &Value) -> bool {
13085 match value {
13086 Value::Object(object) => {
13087 if let Some(state) = object.proxy_state() {
13088 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13089 }
13090 object.is_array()
13091 }
13092 _ => false,
13093 }
13094 }
13095
13096 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13097 ///
13098 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13099 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13100 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13101 /// see [`Interp::enqueue_job_function`].
13102 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13103 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13104 // the handler is reported rather than lost — the same reason a `then` reaction needs a
13105 // promise to settle.
13106 let promise = self.new_promise();
13107 self.fulfill_promise(&promise, Value::Undefined);
13108 self.jobs.push_back(Job::Reaction {
13109 handler: Some(function),
13110 argument: Value::Undefined,
13111 rejected: false,
13112 promise,
13113 });
13114 Ok(())
13115 }
13116
13117 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13118 ///
13119 /// Four of its steps were missing or wrong, and each one is a test262 case in
13120 /// `Function/prototype/Symbol.hasInstance/`:
13121 ///
13122 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13123 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13124 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
13125 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13126 /// `prototype` of its own, so without this step the walk below gives `false`;
13127 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13128 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13129 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13130 let Value::Object(function) = constructor else {
13131 return Ok(false);
13132 };
13133 if !function.is_callable() {
13134 return Ok(false);
13135 }
13136 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13137 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13138 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13139 if let Some((target, this)) = function.bound_target_and_this() {
13140 let object = if this.as_object().is_some() {
13141 this
13142 } else {
13143 object.clone()
13144 };
13145 return self.instance_of(&object, &target);
13146 }
13147 let Value::Object(target) = object else {
13148 return Ok(false);
13149 };
13150 let prototype = self.get_property(function, "prototype")?;
13151 let Some(Value::Object(prototype)) = prototype else {
13152 return Err(Signal::Throw(self.make_error(
13153 "TypeError",
13154 "function has non-object prototype in instanceof check",
13155 )));
13156 };
13157 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13158 // which is also what makes `proxyOfInstance instanceof C` work.
13159 let mut current = Some(target.clone());
13160 while let Some(object) = current {
13161 if object.ptr_eq(&prototype) {
13162 return Ok(true);
13163 }
13164 current = self.object_prototype_of(&object)?;
13165 }
13166 Ok(false)
13167 }
13168
13169 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13170 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13171 if let Some(proto) = self.proxy_get_prototype_of(object)? {
13172 return Ok(proto);
13173 }
13174 if let Some(exotic) = object.exotic()
13175 && let Some(proto) = exotic.get_prototype(self, object)?
13176 {
13177 return Ok(proto);
13178 }
13179 Ok(object.proto())
13180 }
13181
13182 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13183 pub fn object_set_prototype_of(
13184 &mut self,
13185 object: &Gc<JsObject>,
13186 proto: Option<Gc<JsObject>>,
13187 ) -> JsResult<bool> {
13188 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13189 return Ok(answer);
13190 }
13191 if let Some(exotic) = object.exotic()
13192 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13193 {
13194 return Ok(answer);
13195 }
13196 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13197 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13198 // inheriting from itself, which every later prototype walk then had to defend
13199 // against — and `Reflect.setPrototypeOf` reported success for an operation the
13200 // language says is impossible.
13201 if let Some(proto) = &proto {
13202 let mut current = Some(proto.clone());
13203 let mut guard = 0;
13204 while let Some(node) = current {
13205 if node.ptr_eq(object) {
13206 return Err(Signal::Throw(
13207 self.make_error("TypeError", "circular prototype chain"),
13208 ));
13209 }
13210 guard += 1;
13211 if guard > 1000 {
13212 break;
13213 }
13214 current = node.proto();
13215 }
13216 }
13217 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13218 // re-setting it to the *same* one is a no-op `true`. Missing this made
13219 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13220 // actually reparent the object — and it is what
13221 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13222 // forwarding path has nothing else left to refuse it.
13223 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13224 return Ok(false);
13225 }
13226 object.set_proto(proto);
13227 Ok(true)
13228 }
13229
13230 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13231 ///
13232 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13233 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13234 /// already one.
13235 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13236 // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
13237 // (§10.4.5.2 step 1.b) — the prototype chain is *not* consulted for a canonical
13238 // numeric index. That is observable twice over: a view that has been resized out
13239 // of bounds has no indices, so `2 in view` must then be `false` even when
13240 // `Object.getPrototypeOf(view)[2]` exists, and a key like `"-1"` or `"1.5"` is
13241 // canonical-numeric-but-invalid, so `in` answers `false` where an ordinary
13242 // lookup would have found `TypedArray.prototype["1.5"]`. A proxy is excluded
13243 // because it has no `[[ViewedArrayBuffer]]` slot of its own.
13244 if object.typed_array_parts().is_some()
13245 && object.proxy_state().is_none()
13246 && let Some(numeric) = canonical_numeric_index(key)
13247 {
13248 return Ok(typed_array_index_is_valid(object, numeric));
13249 }
13250 let mut current = Some(object.clone());
13251 // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
13252 let mut guard = 0;
13253 while let Some(node) = current {
13254 guard += 1;
13255 if guard > 1000 {
13256 return Ok(false);
13257 }
13258 let own = self.object_get_own_property(&node, key)?;
13259 if own.is_some() {
13260 return Ok(true);
13261 }
13262 current = self.object_prototype_of(&node)?;
13263 }
13264 Ok(false)
13265 }
13266
13267 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13268 ///
13269 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13270 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13271 /// boolean as well, and it needs the receiver to be the one the caller named.
13272 pub fn set_property_with_key_receiver(
13273 &mut self,
13274 object: &Gc<JsObject>,
13275 key: &PropertyKey,
13276 value: Value,
13277 receiver: Option<&Value>,
13278 on_failure: DeleteFailure,
13279 ) -> JsResult<bool> {
13280 let receiver = receiver
13281 .cloned()
13282 .unwrap_or_else(|| Value::Object(object.clone()));
13283 if object.proxy_state().is_some() {
13284 return match self.proxy_set(object, key, value, &receiver)? {
13285 Some(accepted) => Ok(accepted),
13286 None => Ok(true),
13287 };
13288 }
13289 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13290 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13291 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13292 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13293 //
13294 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13295 //
13296 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13297 // * an *invalid* index with a different receiver answers `true` and does nothing,
13298 // not even converting `V` (`valueOfCalls` stays 0);
13299 // * a valid index with a different receiver falls through to
13300 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13301 // value lands on the **receiver**, unconverted, and can be refused by a
13302 // non-extensible receiver, an accessor, or a read-only index there.
13303 //
13304 // The last one used to write into the view itself, which left `target[0]` changed
13305 // and `receiver[0]` untouched — backwards.
13306 if object.typed_array_element_type().is_some()
13307 && let Some(numeric) = canonical_numeric_index(key)
13308 {
13309 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13310 if same {
13311 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13312 return Ok(true);
13313 }
13314 if !typed_array_index_is_valid(object, numeric) {
13315 return Ok(true);
13316 }
13317 let Some(receiver) = receiver.as_object().cloned() else {
13318 return Ok(false);
13319 };
13320 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13321 if existing.is_accessor() || !existing.writable {
13322 return Ok(false);
13323 }
13324 let property = Property {
13325 value: Some(value),
13326 ..existing
13327 };
13328 return self.object_define_own_property(&receiver, key, property);
13329 }
13330 return self.object_define_own_property(&receiver, key, Property::data(value));
13331 }
13332 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13333 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13334 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13335 // `Reflect.set` to *report* the refusal instead of raising.
13336 //
13337 // A receiver that is not the object turns the whole operation into
13338 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13339 // `[[Set]]` rather than a lookup — that is what makes
13340 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13341 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13342 // writes to `object`, so it cannot express that and is only used when the two are
13343 // the same.
13344 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13345 if !same {
13346 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
13347 }
13348 // Same receiver: the plain path below writes into `object`, which is right, but it
13349 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
13350 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
13351 if let Some(existing) = self.object_get_own_property(object, key)? {
13352 if existing.is_accessor() {
13353 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
13354 Some(setter) => {
13355 self.call_value(setter, receiver, vec![value])?;
13356 Ok(true)
13357 }
13358 None => Ok(false),
13359 };
13360 }
13361 if !existing.writable {
13362 return Ok(false);
13363 }
13364 }
13365 // Otherwise it is an ordinary create-or-write into `object` itself.
13366 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13367 Ok(true)
13368 }
13369
13370 /// `[[IsExtensible]]`, with the proxy trap when there is one.
13371 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13372 if let Some(answer) = self.proxy_is_extensible(object)? {
13373 return Ok(answer);
13374 }
13375 if let Some(exotic) = object.exotic()
13376 && let Some(answer) = exotic.is_extensible(self, object)?
13377 {
13378 return Ok(answer);
13379 }
13380 Ok(object.is_extensible())
13381 }
13382
13383 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
13384 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13385 if let Some(answer) = self.proxy_prevent_extensions(object)? {
13386 return Ok(answer);
13387 }
13388 if let Some(exotic) = object.exotic()
13389 && let Some(answer) = exotic.prevent_extensions(self, object)?
13390 {
13391 return Ok(answer);
13392 }
13393 object.set_extensible(false);
13394 Ok(true)
13395 }
13396
13397 fn copy_properties(
13398 &mut self,
13399 target: &Value,
13400 source: &Value,
13401 exclusion: &Value,
13402 ) -> JsResult<()> {
13403 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
13404 // does contribute: its index properties are own, enumerable and writable, which
13405 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
13406 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
13407 // is a no-op.
13408 let Some(target) = target.as_object() else {
13409 return Ok(());
13410 };
13411 let source_object = match source {
13412 Value::Object(object) => object.clone(),
13413 Value::String(text) => {
13414 // Untaken keys are the string's indices, which are code units.
13415 for index in 0..text.utf16_len() {
13416 if let Some(unit) = text.wtf8().unit_at(index) {
13417 target.define_data(&index.to_string(), self.string_wtf8(unit));
13418 }
13419 }
13420 return Ok(());
13421 }
13422 _ => return Ok(()),
13423 };
13424 // An object *rest* element passes the keys already taken by the literal part as
13425 // an array of strings; a spread passes `null`, which excludes nothing. Only the
13426 // string keys of the exclusion array are meaningful, so an array is read by its
13427 // elements rather than by its own property names.
13428 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
13429 if let Value::Object(list) = exclusion
13430 && let Some(length) = list.array_length()
13431 {
13432 for index in 0..length {
13433 if let Some(value) = list.array_get(index) {
13434 excluded.push(self.propkey_of(&value)?);
13435 }
13436 }
13437 }
13438 let source = &source_object;
13439 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
13440 // Reading the property table directly made every spread of a proxy empty.
13441 let keys = self.object_own_property_keys(source)?;
13442 for as_key in keys {
13443 if as_key.is_symbol() {
13444 // A spread copies string-keyed properties only.
13445 continue;
13446 }
13447 if excluded.contains(&crate::value::Wtf8::new(
13448 as_key.as_str().unwrap_or_default(),
13449 )) {
13450 continue;
13451 }
13452 let enumerable = self
13453 .object_get_own_property(source, &as_key)?
13454 .is_some_and(|property| property.enumerable);
13455 if !enumerable {
13456 continue;
13457 }
13458 let value = self
13459 .get_property_key(source, &as_key)?
13460 .unwrap_or(Value::Undefined);
13461 target.define_data_key(&as_key, value);
13462 }
13463 Ok(())
13464 }
13465
13466 // -- iteration ---------------------------------------------------------
13467
13468 /// One object's own keys in enumeration order: array indices ascending, then the
13469 /// rest in insertion order.
13470 ///
13471 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
13472 /// whether the key is enumerable, which the caller resolves per key because an
13473 /// array's elements are not in the same store as its named properties.
13474 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
13475 // An index can arrive twice, once from the array's element store and once from
13476 // its property map, so the numeric keys go through a map that keeps the
13477 // enumerable answer if either source gave one.
13478 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
13479 for (key, enumerable) in &own {
13480 if let Some(index) = key.as_str().and_then(array_index) {
13481 let entry = numeric.entry(index).or_insert(false);
13482 *entry = *entry || *enumerable;
13483 }
13484 }
13485 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
13486 .into_iter()
13487 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
13488 .collect();
13489 ordered.extend(
13490 own.into_iter()
13491 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
13492 );
13493 ordered
13494 }
13495
13496 /// Build the key list a `for-in` loop walks.
13497 ///
13498 /// The order is the specification's: own properties before inherited ones, and
13499 /// within one object the integer-like keys in ascending numeric order ahead of the
13500 /// string keys in insertion order. A shadowed key only appears once, and a key that
13501 /// is a non-enumerable own property anywhere nearer is skipped entirely.
13502 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13503 let record = self.new_object(None);
13504 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
13505 // A proxy supplies its own key list, and — the reason this is not just another
13506 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
13507 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
13508 // descriptor there.
13509 if let Value::Object(object) = value
13510 && object.proxy_state().is_some()
13511 {
13512 let own = self
13513 .proxy_own_keys(object)?
13514 .unwrap_or_else(|| object.own_property_keys());
13515 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
13516 let mut numeric: Vec<u32> = Vec::new();
13517 let mut rest: Vec<PropertyKey> = Vec::new();
13518 for key in own {
13519 match key.as_str().and_then(array_index) {
13520 Some(index) => numeric.push(index),
13521 None => rest.push(key),
13522 }
13523 }
13524 numeric.sort_unstable();
13525 ordered.extend(
13526 numeric
13527 .into_iter()
13528 .map(|index| PropertyKey::from(index.to_string())),
13529 );
13530 ordered.extend(rest);
13531 for (index, key) in ordered.into_iter().enumerate() {
13532 record.define_data(&index.to_string(), self.key_value(&key));
13533 }
13534 record.define_data("__index", Value::Int(0));
13535 // The mark that makes `for_in_advance` re-ask the proxy per key.
13536 record.define_data("__proxy", Value::Object(object.clone()));
13537 return Ok(record);
13538 }
13539 if let Value::Object(object) = value {
13540 let mut chain = vec![object.clone()];
13541 chain.extend(object.chain());
13542 // Every own string key the walk has seen, enumerable or not. A
13543 // non-enumerable own property still hides a same-named enumerable one
13544 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
13545 // keeps `x` out of the loop even when the prototype has one.
13546 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
13547 for object in chain {
13548 let mut own: Vec<(crate::value::Wtf8, bool)> = object
13549 .own_property_keys()
13550 .iter()
13551 .filter_map(|key| key.as_wtf8().cloned())
13552 .map(|key| {
13553 let enumerable = object
13554 .own_property(&key.to_string_lossy())
13555 .map(|property| property.enumerable)
13556 .unwrap_or(false);
13557 (key, enumerable)
13558 })
13559 .collect();
13560 if let Some(length) = object.array_length() {
13561 own.retain(|(key, _)| key.as_str() != Some("length"));
13562 for index in 0..length {
13563 if object.array_get(index).is_some() {
13564 own.push((crate::value::Wtf8::new(index.to_string()), true));
13565 }
13566 }
13567 }
13568 // Integer-like keys come first in ascending order, then the rest in
13569 // insertion order — and the ordering is *per object*, not for the chain
13570 // as a whole: one pass over every collected key lifted a prototype's
13571 // `"4"` above the target's own `x`/`y`, which is not the order
13572 // `for…in` reports.
13573 for (key, enumerable) in Self::order_own_keys(own) {
13574 if visited.contains(&key) {
13575 continue;
13576 }
13577 visited.push(key.clone());
13578 if enumerable {
13579 keys.push(key);
13580 }
13581 }
13582 }
13583 }
13584 for (index, key) in keys.into_iter().enumerate() {
13585 record.define_data(&index.to_string(), self.string_wtf8(key));
13586 }
13587 record.define_data("__index", Value::Int(0));
13588 Ok(record)
13589 }
13590
13591 /// The next key of a `for…in` record, `None` when the loop is done.
13592 ///
13593 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
13594 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
13595 /// the loop reaches it, so a handler that stops reporting a key partway through drops
13596 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
13597 /// key the handler had already withdrawn.
13598 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
13599 let Value::Object(record) = record else {
13600 return Ok(None);
13601 };
13602 let proxy = record
13603 .own_property("__proxy")
13604 .and_then(|property| property.value);
13605 loop {
13606 let index = record
13607 .own_property("__index")
13608 .and_then(|property| property.value)
13609 .map(|value| value.to_int32())
13610 .unwrap_or(0);
13611 let Some(candidate) = record
13612 .own_property(&index.to_string())
13613 .and_then(|property| property.value)
13614 else {
13615 return Ok(None);
13616 };
13617 record.define_data("__index", Value::Int(index + 1));
13618 let text = candidate.to_js_string();
13619 let Some(Value::Object(proxy)) = &proxy else {
13620 return Ok(Some(text));
13621 };
13622 // The candidate is already a key string here, so the lookup does not need a
13623 // second `ToPropertyKey` conversion.
13624 let key = PropertyKey::from(text.as_str());
13625 let live = match self.proxy_get_own_property(proxy, &key)? {
13626 Some(descriptor) => descriptor,
13627 // Not a proxy after all, or it lost its state: fall back to the target.
13628 None => proxy.own_property_key(&key),
13629 };
13630 if live.is_some_and(|property| property.enumerable) {
13631 return Ok(Some(text));
13632 }
13633 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
13634 // next one.
13635 }
13636 }
13637
13638 /// The iterator for `for-of`: the object and its `next` method.
13639 ///
13640 /// An object that already carries a `next` method is used as it is — that is what
13641 /// `arr.values()` returns — and only arrays and strings get the built-in
13642 /// sequence iterator.
13643 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
13644 ///
13645 /// Callers that must choose between the iterable and the array-like protocol — the
13646 /// typed-array constructor is the main one — need to ask *before* committing to one.
13647 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
13648 let key = self.realm.well_known_key(WellKnown::Iterator);
13649 let method = self.read_field_key(value, &key)?;
13650 if matches!(method, Value::Undefined | Value::Null) {
13651 return Ok(false);
13652 }
13653 if !matches!(&method, Value::Object(object) if object.is_callable()) {
13654 return Err(Signal::Throw(
13655 self.make_error("TypeError", "Symbol.iterator is not callable"),
13656 ));
13657 }
13658 Ok(true)
13659 }
13660
13661 /// Collect everything an iterable yields.
13662 ///
13663 /// The cap is a guard against a generator that never ends: an unbounded collect would
13664 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
13665 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
13666 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
13667 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
13668 const MAX_ITEMS: usize = 1 << 24;
13669 let iterator = self.get_iterator(value)?;
13670 let mut out = Vec::new();
13671 loop {
13672 let (element, done) = self.iterator_step(&iterator)?;
13673 if done {
13674 return Ok(out);
13675 }
13676 out.push(element);
13677 if out.len() > MAX_ITEMS {
13678 // Close before refusing: the walk is being abandoned, so the iterator's
13679 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
13680 // unrun and a locked resource unreleased.
13681 self.close_iterator_after_throw(&iterator)?;
13682 return Err(self.range_error("iterable is too long to collect"));
13683 }
13684 }
13685 }
13686
13687 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
13688 ///
13689 /// A native constructor calls this once it has validated its arguments, which is the
13690 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
13691 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
13692 /// never reached. The prototype comes from `new.target` when it is an object, and from
13693 /// `default_proto` otherwise.
13694 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13695 let proto = self.ctor_prototype(default_proto)?;
13696 Ok(self.new_object(Some(proto)))
13697 }
13698
13699 /// An **array** whose prototype comes from `new.target`.
13700 ///
13701 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
13702 /// instance from `new.target.prototype`, and building a plain array instead made every
13703 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
13704 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
13705 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
13706 Ok(JsObject::array(self.heap, Some(proto), 0))
13707 }
13708
13709 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
13710 ///
13711 /// The `Option` form is for the constructors that build their instance in a helper which
13712 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
13713 /// from `await`'s internal promise, and only the first has a `new.target`.
13714 fn ctor_prototype_opt(
13715 &mut self,
13716 default_proto: Option<Gc<JsObject>>,
13717 ) -> JsResult<Option<Gc<JsObject>>> {
13718 // `active_new_target`: by the time a native constructor runs, `call_value` has
13719 // already consumed the parked value.
13720 let Some(target) = self
13721 .active_new_target
13722 .as_object()
13723 .cloned()
13724 .map(Value::Object)
13725 else {
13726 return Ok(default_proto);
13727 };
13728 let Some(target) = target.as_object().cloned() else {
13729 return Ok(default_proto);
13730 };
13731 match self.get_property(&target, "prototype")? {
13732 Some(Value::Object(proto)) => Ok(Some(proto)),
13733 _ => Ok(default_proto),
13734 }
13735 }
13736
13737 /// `new.target.prototype`, or `default_proto` when this is a plain call.
13738 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13739 let Some(target) = self.active_new_target.as_object().cloned() else {
13740 return Ok(default_proto);
13741 };
13742 match self.get_property(&target, "prototype")? {
13743 Some(Value::Object(proto)) => Ok(proto),
13744 _ => Ok(default_proto),
13745 }
13746 }
13747
13748 /// `CreateDataPropertyOrThrow(O, key, value)`.
13749 ///
13750 /// A *definition*, not an assignment. The difference is visible the moment the target
13751 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
13752 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
13753 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
13754 /// refused (`configurable: false`).
13755 ///
13756 /// The fast path exists because this is called once per element by `map`, `filter`,
13757 /// `slice` and friends: a plain array with no custom element descriptors and a writable
13758 /// `length` can store straight into its element vector.
13759 pub fn create_data_property_or_throw(
13760 &mut self,
13761 object: &Gc<JsObject>,
13762 index: usize,
13763 value: Value,
13764 ) -> JsResult<()> {
13765 if object.is_array()
13766 && object.elements_writable()
13767 && !object.has_element_descriptors()
13768 && object.is_extensible()
13769 && object.array_set(self.heap, index, value.clone())
13770 {
13771 return Ok(());
13772 }
13773 let key = PropertyKey::from(index.to_string());
13774 let property = Property {
13775 value: Some(value),
13776 writable: true,
13777 enumerable: true,
13778 configurable: true,
13779 ..Property::default()
13780 };
13781 // `CreateDataProperty` always asks for the default attributes, so it can only ever
13782 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
13783 // the rest. Checking here rather than inside `object_define_own_property` is
13784 // deliberate: that function receives a fully-populated `Property` and cannot tell
13785 // an omitted attribute from an explicit `false`, so the generic check it would need
13786 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
13787 // writable property (that cost eight `Object/defineProperty` tests).
13788 if let Some(existing) = self.object_get_own_property(object, &key)?
13789 && !existing.configurable
13790 {
13791 return Err(self.type_error("cannot create the property"));
13792 }
13793 if self.object_define_own_property(object, &key, property)? {
13794 return Ok(());
13795 }
13796 Err(self.type_error("cannot create the property"))
13797 }
13798
13799 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
13800 ///
13801 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
13802 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
13803 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
13804 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
13805 /// run user code and both can throw.
13806 pub fn species_constructor(
13807 &mut self,
13808 object: &Gc<JsObject>,
13809 default: Value,
13810 ) -> JsResult<Value> {
13811 let Some(constructor) = self.get_property(object, "constructor")? else {
13812 return Ok(default);
13813 };
13814 let constructor = match constructor {
13815 Value::Undefined => return Ok(default),
13816 Value::Object(constructor) => constructor,
13817 _ => return Err(self.type_error("constructor is not an object")),
13818 };
13819 let key = self.realm.well_known_key(WellKnown::Species);
13820 let species = self.get_property_key(&constructor, &key)?;
13821 match species {
13822 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
13823 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
13824 Some(_) => Err(self.type_error("species is not a constructor")),
13825 }
13826 }
13827
13828 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
13829 ///
13830 /// The result is an array of `length` holes whose prototype comes from
13831 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
13832 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
13833 /// is why the `IsArray` check is the first step and not an optimisation.
13834 pub fn array_species_create(
13835 &mut self,
13836 original: &Value,
13837 length: usize,
13838 ) -> JsResult<Gc<JsObject>> {
13839 let Some(object) = original.as_object().cloned() else {
13840 return Ok(self.new_array_of_length(length));
13841 };
13842 if !object.is_array() {
13843 return Ok(self.new_array_of_length(length));
13844 }
13845 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
13846 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
13847 let Some(constructor) = self.get_property(&object, "constructor")? else {
13848 return Ok(self.new_array_of_length(length));
13849 };
13850 let species = match constructor {
13851 Value::Undefined => return Ok(self.new_array_of_length(length)),
13852 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
13853 return Ok(self.new_array_of_length(length));
13854 }
13855 Value::Object(constructor) => {
13856 let key = self.realm.well_known_key(WellKnown::Species);
13857 match self.get_property_key(&constructor, &key)? {
13858 None | Some(Value::Undefined) | Some(Value::Null) => {
13859 return Ok(self.new_array_of_length(length));
13860 }
13861 Some(species) => species,
13862 }
13863 }
13864 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
13865 // is a `TypeError`, not "the default". Treating it as the default made
13866 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
13867 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
13868 // `concat/create-ctor-non-object` are the same rule three times.
13869 _ => return Err(self.type_error("constructor is not an object")),
13870 };
13871 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
13872 // that is merely callable is the `create-species-non-ctor` case.
13873 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
13874 return Err(self.type_error("species is not a constructor"));
13875 }
13876 let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
13877 let Some(created) = created.as_object().cloned() else {
13878 return Err(self.type_error("species constructor did not answer an object"));
13879 };
13880 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
13881 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
13882 // object, and `create-species-with-non-writable-property` asserts exactly that.
13883 // The length is set for the array case; the generic case is the caller's
13884 // `Set(A, "length", …)`.
13885 if created.is_array() {
13886 created.array_set_length(self.heap, length);
13887 }
13888 Ok(created)
13889 }
13890
13891 /// Whether `object` is this realm's `%Array%`.
13892 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
13893 self.realm
13894 .array_constructor
13895 .as_ref()
13896 .is_some_and(|array| array.ptr_eq(object))
13897 }
13898
13899 /// A fresh `length`-hole array with the intrinsic prototype.
13900 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
13901 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
13902 array.array_set_length(self.heap, length);
13903 array
13904 }
13905
13906 /// Whether this call is a construction, i.e. `new.target` is defined.
13907 ///
13908 /// A native constructor receives `this = undefined` (it builds its own instance), so it
13909 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
13910 /// The native function currently executing, if any.
13911 pub fn current_native(&self) -> Option<Gc<JsObject>> {
13912 self.current_native.clone()
13913 }
13914
13915 /// Whether this call is a construction, i.e. `new.target` is defined.
13916 pub fn is_constructing(&self) -> bool {
13917 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
13918 // `call_value` before a native runs, so by the time a constructor body asks, the
13919 // answer is only in the active slot.
13920 matches!(self.active_new_target, Value::Object(_))
13921 }
13922
13923 /// The `TypeError` a constructor too primitive to have a wrapper raises.
13924 ///
13925 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
13926 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
13927 /// happens inside the native function, which is why the trace carries an
13928 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
13929 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
13930 /// constructor`, and an unnamed one reports the leading space of `" is not a
13931 /// constructor"` because the reference formats the empty name as it is.
13932 ///
13933 /// It is also the answer for a `new.target` that cannot be named at all — not a
13934 /// function, or a throwing `name` getter — where the reference falls back to the bare
13935 /// `not a constructor`.
13936 pub fn not_a_constructor_error(&mut self) -> Signal {
13937 let target = self.active_new_target.clone();
13938 self.not_a_constructor_error_for(target)
13939 }
13940
13941 /// The same `TypeError` for an explicit target, for the callers that check
13942 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
13943 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
13944 let target = match target {
13945 Value::Object(target) if target.is_callable() => target,
13946 _ => return self.type_error("not a constructor"),
13947 };
13948 let name = match self.get_property(&target, "name") {
13949 Ok(Some(value)) => value.to_js_string(),
13950 _ => return self.type_error("not a constructor"),
13951 };
13952 self.type_error(format!("{name} is not a constructor"))
13953 }
13954
13955 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
13956 ///
13957 /// True whenever `new.target` is not the callee itself, or when it has no usable
13958 /// `prototype` — the cases where reading the property is observable at all.
13959 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
13960 match &self.active_new_target {
13961 Value::Object(target) => !target.ptr_eq(callee),
13962 Value::Undefined => false,
13963 _ => true,
13964 }
13965 }
13966
13967 /// The symbol key for one of the engine's own hidden slots.
13968 ///
13969 /// Cached on the realm, so every object of a kind shares one key and a slot can be
13970 /// read back by name.
13971 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
13972 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
13973 return PropertyKey::Symbol(symbol.clone());
13974 }
13975 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
13976 self.realm
13977 .internal_slots
13978 .borrow_mut()
13979 .insert(name, Value::Symbol(symbol.clone()));
13980 PropertyKey::Symbol(symbol)
13981 }
13982
13983 /// Read a hidden slot, or `None` when the object has none of that name.
13984 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
13985 let slots = self.realm.internal_slots.borrow();
13986 let Value::Symbol(symbol) = slots.get(name)? else {
13987 return None;
13988 };
13989 object
13990 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
13991 .and_then(|property| property.value)
13992 }
13993
13994 /// Define a hidden slot.
13995 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
13996 let key = self.internal_slot(name);
13997 object.define_key(&key, Property::with_attributes(value, false, false));
13998 }
13999
14000 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
14001 ///
14002 /// The method is looked up on the value (through its prototype), called with no
14003 /// arguments, and its result becomes the iterator. A generator gets here through
14004 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
14005 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
14006 ///
14007 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
14008 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
14009 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
14010 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
14011 /// does, and a user-defined iterable works without a special case.
14012 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
14013 /// `Symbol.iterator`.
14014 ///
14015 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
14016 /// iterable is legal there, and each value it produces is simply already settled by
14017 /// the time the `await` around it runs.
14018 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14019 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
14020 let method = self.read_field_key(value, &async_key)?;
14021 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
14022 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
14023 // is *present but not callable* is a TypeError — it does not mean "try the other
14024 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
14025 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
14026 // guard is there to catch.
14027 let absent = matches!(method, Value::Undefined | Value::Null);
14028 if !absent {
14029 let Value::Object(object) = &method else {
14030 return Err(Signal::Throw(
14031 self.make_error("TypeError", "value is not iterable"),
14032 ));
14033 };
14034 if !object.is_callable() {
14035 return Err(Signal::Throw(
14036 self.make_error("TypeError", "value is not iterable"),
14037 ));
14038 }
14039 }
14040 if absent {
14041 return self.get_iterator(value);
14042 }
14043 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14044 if !matches!(iterator, Value::Object(_)) {
14045 return Err(Signal::Throw(
14046 self.make_error("TypeError", "iterator is not an object"),
14047 ));
14048 }
14049 let next = self.read_field(&iterator, "next")?;
14050 Ok(Iterator {
14051 object: iterator,
14052 next,
14053 })
14054 }
14055
14056 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14057 /// read — `@@iterator` is **not** consulted.
14058 ///
14059 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14060 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14061 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14062 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14063 /// refused it with "[object Object] is not iterable".
14064 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14065 if !matches!(value, Value::Object(_)) {
14066 return Err(self.type_error("iterator is not an object"));
14067 }
14068 let next = self.read_field(&value, "next")?;
14069 Ok(Iterator {
14070 object: value,
14071 next,
14072 })
14073 }
14074
14075 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14076 let key = self.realm.well_known_key(WellKnown::Iterator);
14077 let method = self.read_field_key(value, &key)?;
14078 let Value::Object(function) = &method else {
14079 return Err(Signal::Throw(self.make_error(
14080 "TypeError",
14081 &format!("{} is not iterable", value.to_js_string()),
14082 )));
14083 };
14084 if !function.is_callable() {
14085 return Err(Signal::Throw(self.make_error(
14086 "TypeError",
14087 &format!("{} is not iterable", value.to_js_string()),
14088 )));
14089 }
14090 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14091 // The spec requires an object here; a primitive iterator has no `next` to call
14092 // and would fail one step later with a confusing message.
14093 if !matches!(iterator, Value::Object(_)) {
14094 return Err(Signal::Throw(
14095 self.make_error("TypeError", "iterator is not an object"),
14096 ));
14097 }
14098 let next = self.read_field(&iterator, "next")?;
14099 Ok(Iterator {
14100 object: iterator,
14101 next,
14102 })
14103 }
14104
14105 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
14106 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
14107 /// exception from `return` propagates normally instead of being swallowed. That is the
14108 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
14109 /// because confusing them is exactly the bug both exist to avoid.
14110 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
14111 let method = self.read_field(&iterator.object, "return")?;
14112 if matches!(method, Value::Undefined | Value::Null) {
14113 return Ok(());
14114 }
14115 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14116 return Err(self.type_error("iterator return is not a function"));
14117 }
14118 self.call_value(method, iterator.object.clone(), Vec::new())?;
14119 Ok(())
14120 }
14121
14122 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
14123 /// cannot replace it.
14124 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
14125 let method = self.read_field(&iterator.object, "return")?;
14126 if matches!(method, Value::Undefined | Value::Null) {
14127 return Ok(());
14128 }
14129 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14130 return Err(self.type_error("iterator return is not a function"));
14131 }
14132 self.call_value(method, iterator.object.clone(), Vec::new())?;
14133 Ok(())
14134 }
14135
14136 /// One step of an internal iterator: the value and whether it is exhausted.
14137 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
14138 // A real iterator (`next` is a function) answers with a result object.
14139 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
14140 let result =
14141 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
14142 let Some(result) = result.as_object().cloned() else {
14143 return Err(self.type_error("iterator result is not an object"));
14144 };
14145 let done = self
14146 .get_property(&result, "done")?
14147 .is_some_and(|value| value.to_boolean());
14148 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
14149 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
14150 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
14151 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
14152 // made an unrelated `value` getter observable after the loop was over.
14153 if done {
14154 return Ok((Value::Undefined, true));
14155 }
14156 let value = self
14157 .get_property(&result, "value")?
14158 .unwrap_or(Value::Undefined);
14159 return Ok((value, false));
14160 }
14161 // An iterator whose `next` is not callable is treated as exhausted, which is
14162 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
14163 // that are not iterable at all.
14164 Ok((Value::Undefined, true))
14165 }
14166
14167 /// `[...iterable]`: append everything the iterator yields, and answer the next
14168 /// index.
14169 ///
14170 /// This goes through the same iterator machinery `for-of` uses rather than copying
14171 /// an array's elements, because a spread source is any iterable: a string spreads
14172 /// into its characters and an array iterator spreads into its results. Handling
14173 /// only arrays made `[..."ab"]` come out empty with no error at all.
14174 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
14175 let Some(target) = array.as_object().cloned() else {
14176 return Ok(0);
14177 };
14178 let start = target.array_length().unwrap_or(0);
14179 let mut added = 0;
14180 let iterator = self.get_iterator(iterable)?;
14181 loop {
14182 let (value, done) = self.iterator_step(&iterator)?;
14183 if done {
14184 break;
14185 }
14186 target.array_set(self.heap, start + added, value);
14187 added += 1;
14188 }
14189 Ok((start + added) as i32)
14190 }
14191
14192 /// How an uncaught exception is reported.
14193 ///
14194 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
14195 /// with `ToString` — `js_std_dump_error` is three lines that end in
14196 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
14197 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
14198 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
14199 ///
14200 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
14201 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
14202 /// `toString`"; it does call it, but only for objects of a class it does not know how
14203 /// to walk, and never for errors, arrays or plain objects.
14204 ///
14205 /// A printer that fails must not take the reporter down with it, so that case falls
14206 /// back to the `ToString` rendering.
14207 pub fn describe_exception(&mut self, value: &Value) -> String {
14208 match crate::print::sprint(self, value) {
14209 Ok(text) => text,
14210 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
14211 }
14212 }
14213
14214 /// The file name of whatever is running, innermost frame first.
14215 ///
14216 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
14217 /// innermost frame's file name, without distinguishing a module body from a plain
14218 /// script. `import()` uses it as the base for a relative specifier, which is why
14219 /// `import('./x.js')` inside a script resolves next to the script and not next to the
14220 /// process's working directory.
14221 pub fn script_or_module_name(&self) -> Option<String> {
14222 self.script_or_module_name_at(0)
14223 }
14224
14225 /// [`Interp::script_or_module_name`] `level` frames further out.
14226 ///
14227 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
14228 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
14229 /// frame without a file name is skipped rather than counted, because a native call
14230 /// pushes no frame of its own and so cannot be a level.
14231 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
14232 self.frames
14233 .iter()
14234 .rev()
14235 .filter_map(|frame| frame.code.code.filename.clone())
14236 .nth(level)
14237 }
14238
14239 /// The current call stack, formatted the way `qjs` prints `error.stack`.
14240 ///
14241 /// One ` at name (file:line:col)` line per active frame, innermost first. The
14242 /// position is the one recorded for the instruction each frame is stopped on, which
14243 /// is why the compiler builds a pc-to-position table per function: without it a
14244 /// trace could only name the function, not the line inside it.
14245 ///
14246 /// A frame whose code has no positions prints just `(file)`, matching the
14247 /// reference's output for stripped bytecode.
14248 pub fn stack_trace(&self) -> String {
14249 self.stack_trace_skipping(0)
14250 }
14251
14252 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
14253 fn stack_trace_skipping(&self, skip: usize) -> String {
14254 // One ordered list, innermost first, so `skip` counts the same thing whether the
14255 // frames it leaves out are native or bytecode. Indices rather than references: a
14256 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
14257 let depth = self.frames.len();
14258 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
14259 // A native entered while `at` bytecode frames were live was called *from* the
14260 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
14261 // entered at the current depth are therefore innermost of all.
14262 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
14263 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
14264 if *at == wanted {
14265 order.push((true, index));
14266 }
14267 }
14268 };
14269 push_natives(&mut order, depth);
14270 for index in (0..depth).rev() {
14271 order.push((false, index));
14272 push_natives(&mut order, index);
14273 }
14274 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
14275 // barrier. Natives entered at exactly the barrier depth are the eval entry point
14276 // itself (`evalScript (native)`), and the reference leaves those out too.
14277 if let Some(barrier) = self.trace_barriers.last().copied() {
14278 order.retain(|(is_native, index)| match is_native {
14279 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
14280 false => *index >= barrier,
14281 });
14282 }
14283
14284 let mut out = String::new();
14285 for (is_native, index) in order.into_iter().skip(skip) {
14286 match is_native {
14287 true => {
14288 out.push_str(" at ");
14289 let (native, _) = &self.native_frames[index];
14290 let name = native
14291 .own_property("name")
14292 .and_then(|property| property.value)
14293 .map(|value| value.to_js_string())
14294 .unwrap_or_default();
14295 out.push_str(&name);
14296 out.push_str(" (native)\n");
14297 }
14298 false => {
14299 let frame = &self.frames[index];
14300 let code = &frame.code.code;
14301 let file = code.filename.as_deref().unwrap_or("<input>");
14302 // The name comes from the function *object*, not from the compiled code:
14303 // an anonymous function expression is named by the property it is stored
14304 // in (`{valueOf: function(){}}`), which only the object knows.
14305 let bound_name = match &frame.callee {
14306 Value::Object(object) => {
14307 object
14308 .own_property("name")
14309 .and_then(|property| match property.value {
14310 Some(Value::String(text)) if !text.wtf8().is_empty() => {
14311 Some(text.to_string_lossy().into_owned())
14312 }
14313 _ => None,
14314 })
14315 }
14316 _ => None,
14317 };
14318 // No callee object means the body was entered by the host, so the
14319 // name has to come from the compiled code. Two cases differ:
14320 //
14321 // * an *unnamed* function of any kind — the reference reads the
14322 // `name` property, finds it empty, and prints `<anonymous>`;
14323 // * a *module* body, which has no `name` property at all: the
14324 // reference builds that function object with `js_closure2` and
14325 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
14326 // so a trace reaching it also prints `<anonymous>` — while a
14327 // *script* body prints `<eval>`, its `name`.
14328 let unnamed = code.name.is_empty() || code.module.is_some();
14329 out.push_str(" at ");
14330 match bound_name.as_deref() {
14331 Some(name) => out.push_str(name),
14332 None if unnamed => out.push_str("<anonymous>"),
14333 None => out.push_str(&code.name),
14334 }
14335 match code.position_at(frame.at as u32) {
14336 Some((line, column)) => {
14337 out.push_str(&format!(" ({file}:{line}:{column})\n"));
14338 }
14339 None => out.push_str(&format!(" ({file})\n")),
14340 }
14341 }
14342 }
14343 }
14344 out
14345 }
14346
14347 /// Give an anonymous function the name of the property it is stored in.
14348 ///
14349 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
14350 /// enumerable and not configurable, and a function that already has a real name
14351 /// keeps it.
14352 ///
14353 /// "Already named" means a *non-empty* name: every function object is created with
14354 /// a `name` of `""` so the property exists on all of them, and treating that empty
14355 /// string as a name left every anonymous function nameless — which is how a stack
14356 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
14357 /// `SetFunctionName`, for a name that came from source text.
14358 fn set_function_name(&mut self, function: &Value, name: &str) {
14359 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
14360 }
14361
14362 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
14363 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
14364 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
14365 let Value::Object(object) = function else {
14366 return;
14367 };
14368 // `SetFunctionName` applies to *functions* and classes only, and only when they are
14369 // anonymous. Without the callability guard, `{value: someObject}` renamed
14370 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
14371 // on the right-hand side of a property. That is how a `zipKeyed` result object
14372 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
14373 // has no `NamedEvaluation` at all.
14374 if !object.is_callable() {
14375 return;
14376 }
14377 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
14378 && !existing.wtf8().is_empty()
14379 {
14380 return;
14381 }
14382 let text = self.string_wtf8(name.clone());
14383 object.define("name", Property::name_or_length(text));
14384 }
14385
14386 // -- global declarations -----------------------------------------------
14387
14388 /// Declare a global binding, creating its reference cell.
14389 /// Declare a `var` or function global, whose home is the global object.
14390 ///
14391 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
14392 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
14393 /// such as `print`, or a redeclaration — is left alone.
14394 pub fn declare_var_global(&mut self, name: &str) {
14395 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
14396 // global object is exactly the leak `typeof my_var === "undefined"` after
14397 // `eval("var my_var=2")` rules out.
14398 if let Some(scope) = self.eval_scope.as_mut() {
14399 scope.entry(name.to_string()).or_insert(Value::Undefined);
14400 return;
14401 }
14402 // A sloppy direct eval declares into its *caller's* variable environment. Doing
14403 // this on the global object instead made `eval("var c = 1")` inside a parameter
14404 // list overwrite a global `c`, and made two calls to the same function share one
14405 // binding.
14406 if let Some(cell) = self.declare_eval_local(name) {
14407 cell.set(Value::Undefined);
14408 return;
14409 }
14410 let global = self.realm.global.clone();
14411 if global.own_property(name).is_some() {
14412 return;
14413 }
14414 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
14415 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
14416 // whole point of that trick and what lets `Object.defineProperty` reshape it
14417 // afterwards. `eval_scope` is `Some` while an eval is running.
14418 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
14419 global.define(
14420 name,
14421 Property {
14422 value: Some(Value::Undefined),
14423 writable: true,
14424 enumerable: true,
14425 configurable: from_eval,
14426 ..Property::default()
14427 },
14428 );
14429 }
14430
14431 /// Declare a *lexical* global binding, which starts in its dead zone.
14432 ///
14433 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
14434 /// global object and is created when its initialiser runs.
14435 pub fn declare_global(&mut self, name: &str, is_const: bool) {
14436 if is_const {
14437 self.realm.lexical_consts.insert(name.to_string());
14438 }
14439 if !self.realm.globals.contains_key(name) {
14440 // `Uninitialized` rather than `Undefined`: the binding exists but is not
14441 // readable until its initialiser runs, and that is what `let x` before
14442 // `x = 1` has to observe.
14443 let cell = self.new_cell(Value::Uninitialized);
14444 self.realm.globals.insert(name.to_string(), cell);
14445 self.realm.declared.push(name.to_string());
14446 }
14447 }
14448}
14449
14450/// The bytecode and environment of a function object, if it is a bytecode function.
14451///
14452/// Extracted before a call so no borrow of the object is held across it.
14453fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
14454 function.with(|data| match &data.kind {
14455 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
14456 _ => None,
14457 })
14458}
14459
14460/// A native call target, extracted before the call so no borrow is held.
14461enum NativeCall {
14462 Native(NativeFn),
14463 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
14464 /// not hold that object's `RefCell` borrow.
14465 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
14466 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
14467 Bound {
14468 target: Value,
14469 this: Value,
14470 leading: Vec<Value>,
14471 },
14472 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
14473 Revoker(crate::object::ProxyRef),
14474 /// A promise's `resolve`.
14475 PromiseResolve(Gc<JsObject>),
14476 /// A promise's `reject`.
14477 PromiseReject(Gc<JsObject>),
14478 /// The executor `NewPromiseCapability(C)` hands a user constructor.
14479 CapabilityExecutor {
14480 state: Gc<JsObject>,
14481 },
14482 /// One leg of a `then` that settles through a user capability.
14483 ThenShim {
14484 handler: Option<Value>,
14485 resolve: Value,
14486 reject: Value,
14487 fulfilled: bool,
14488 },
14489 /// One continuation of an `await`.
14490 AwaitResume {
14491 coroutine: Gc<JsObject>,
14492 promise: Gc<JsObject>,
14493 kind: ResumeKind,
14494 },
14495 /// One element of a `Promise` combinator settling.
14496 CombinatorSettle {
14497 state: Gc<JsObject>,
14498 index: usize,
14499 fulfilled: bool,
14500 },
14501 /// One of `Promise.prototype.finally`'s two shims.
14502 FinallyShim {
14503 callback: Option<Value>,
14504 fulfilled: bool,
14505 constructor: Value,
14506 },
14507 /// Settle a promise with a fixed outcome.
14508 SettlePromise {
14509 promise: Gc<JsObject>,
14510 value: Value,
14511 rejected: bool,
14512 },
14513 /// Continue an async generator after its `await` settled.
14514 GeneratorResume {
14515 generator: Gc<JsObject>,
14516 promise: Gc<JsObject>,
14517 kind: ResumeKind,
14518 },
14519 /// Read a module namespace's binding out of its cell.
14520 ModuleBinding(Gc<Cell>),
14521 /// Finish a completed async generator's `return(v)` once `v` has settled.
14522 CompletedReturn {
14523 generator: Gc<JsObject>,
14524 promise: Gc<JsObject>,
14525 rejected: bool,
14526 },
14527 /// Answer a pending async-generator method with `{value, done}`.
14528 YieldResult {
14529 generator: Gc<JsObject>,
14530 promise: Gc<JsObject>,
14531 done: bool,
14532 },
14533 /// One step of `AsyncDisposableStack.disposeAsync`.
14534 DisposeStep {
14535 remaining: Gc<JsObject>,
14536 promise: Gc<JsObject>,
14537 error: Value,
14538 rejected: bool,
14539 },
14540}
14541
14542/// What a store does when the object refuses the write.
14543#[derive(Clone, Copy, PartialEq, Eq)]
14544pub enum DeleteFailure {
14545 /// Raise a `TypeError`, which is what strict mode and every built-in does.
14546 Throw,
14547 /// Ignore the write, which is what a sloppy-mode assignment does.
14548 Ignore,
14549}
14550
14551/// Whether `object` is a `Date` instance, by the class tag it carries.
14552///
14553/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
14554/// builtins module depending on the interpreter's conversion order.
14555fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
14556 interp
14557 .internal_get(object, "_class")
14558 .is_some_and(|value| value.to_js_string() == "Date")
14559}
14560
14561/// Which type `ToPrimitive` prefers when it converts an object.
14562#[derive(Clone, Copy, PartialEq, Eq)]
14563pub enum Hint {
14564 /// The default hint, which behaves like [`Hint::Number`].
14565 Default,
14566 /// `Number(obj)` and the arithmetic operators.
14567 Number,
14568 /// `String(obj)` and `ToPropertyKey`.
14569 String,
14570}
14571
14572/// Which table a binding slot indexes, for the messages that name it.
14573#[derive(Clone, Copy)]
14574enum VarSlot {
14575 Loc,
14576 Closure,
14577}
14578
14579/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
14580fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
14581 Ok(this)
14582}
14583
14584/// An internal iterator: the sequence plus a cursor.
14585pub(crate) struct Iterator {
14586 pub(crate) object: Value,
14587 pub(crate) next: Value,
14588}
14589
14590/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
14591/// and plain `a` for a method.
14592///
14593/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
14594/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
14595/// reads `at get a (file:1:2)`.
14596/// The same prefixing, for a name that may hold an unpaired surrogate.
14597fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
14598 let prefix = match flags & 3 {
14599 1 => "get ",
14600 2 => "set ",
14601 _ => return key.clone(),
14602 };
14603 let mut units: Vec<u16> = prefix.encode_utf16().collect();
14604 units.extend_from_slice(&key.to_units());
14605 crate::value::Wtf8::from_units(&units)
14606}
14607
14608fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
14609 match flags & 3 {
14610 1 => format!("get {key}"),
14611 2 => format!("set {key}"),
14612 _ => key.to_string(),
14613 }
14614}
14615
14616/// Define a method or accessor property, per the `define_method` flag byte.
14617///
14618/// The low two bits pick value/getter/setter and bit 2 marks the property
14619/// enumerable.
14620///
14621/// A getter and a setter arrive as two separate `define_method` instructions, and the
14622/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
14623/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
14624/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
14625/// `JS_DefineProperty`, which leaves the other half alone.
14626fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
14627 let enumerable = flags & 4 != 0;
14628 let kind = flags & 3;
14629 let existing = object.own_property_key(key);
14630 let property = match kind {
14631 1 => Property {
14632 getter: Some(function),
14633 // The setter half, if this literal already defined one.
14634 setter: existing
14635 .filter(Property::is_accessor)
14636 .and_then(|p| p.setter),
14637 enumerable,
14638 configurable: true,
14639 ..Property::default()
14640 },
14641 2 => Property {
14642 getter: existing
14643 .filter(Property::is_accessor)
14644 .and_then(|p| p.getter),
14645 setter: Some(function),
14646 enumerable,
14647 configurable: true,
14648 ..Property::default()
14649 },
14650 _ => Property {
14651 value: Some(function),
14652 writable: true,
14653 enumerable,
14654 configurable: true,
14655 ..Property::default()
14656 },
14657 };
14658 object.define_key(key, property);
14659}
14660
14661// ---------------------------------------------------------------------------
14662// Operand decoding
14663// ---------------------------------------------------------------------------
14664
14665/// How `print` renders a value: the reference's `JS_PrintValue`.
14666///
14667/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
14668/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
14669/// The format is reproduced closely because the test suite compares output text:
14670///
14671/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
14672/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
14673/// * a cycle prints `[circular N]` with `N` the stack index of the object;
14674/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
14675/// end print as `<N empty item(s)>`;
14676/// * a string is quoted inside a container but raw at the top level, which is why
14677/// `print("x")` and `print(["x"])` differ.
14678pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
14679 // A string argument is printed raw: `js_print` converts it with `ToString`
14680 // instead of dumping it, and the quoting only appears inside a container.
14681 if let Value::String(text) = value {
14682 return text.to_string_lossy().into_owned();
14683 }
14684 let mut printer = Printer {
14685 interp,
14686 out: String::new(),
14687 stack: Vec::new(),
14688 };
14689 printer.value(value, 0);
14690 printer.out
14691}
14692
14693/// The internal class name an object carries, when it has one.
14694fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
14695 interp
14696 .internal_get(object, "_class")
14697 .map(|value| value.to_js_string())
14698}
14699
14700/// A string property, looked up the way `GetProperty` does: own first, then the
14701/// prototype chain. Needed because the print formatter holds the interpreter
14702/// immutably and so cannot run getters.
14703fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
14704 let mut current = Some(object.clone());
14705 // Bounded, because a prototype cycle would otherwise loop forever.
14706 for _ in 0..100 {
14707 let node = current?;
14708 if let Some(property) = node.own_property(name)
14709 && let Some(value) = property.value
14710 {
14711 return Some(value.to_js_string());
14712 }
14713 current = node.with(|data| data.proto.clone());
14714 }
14715 None
14716}
14717
14718/// The `JS_PrintValue` state: output, and the objects currently being printed.
14719struct Printer<'a, 'rt> {
14720 /// Kept for the class-name lookups that typed arrays and `Date` will need.
14721 #[allow(dead_code)]
14722 interp: &'a Interp<'rt>,
14723 out: String,
14724 stack: Vec<Gc<JsObject>>,
14725}
14726
14727impl Printer<'_, '_> {
14728 /// Depth past which a container is summarised by its class name.
14729 const MAX_DEPTH: usize = 2;
14730
14731 fn value(&mut self, value: &Value, level: usize) {
14732 match value {
14733 Value::Undefined
14734 | Value::Uninitialized
14735 | Value::Hole
14736 | Value::CatchOffset(_)
14737 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
14738 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
14739 // The printer writes a bigint the way the language spells one, so a dump is
14740 // unambiguous about which kind of number it is showing.
14741 Value::BigInt(big) => {
14742 self.out.push_str(&big.to_decimal_string());
14743 self.out.push('n');
14744 }
14745 Value::Null => self.out.push_str("null"),
14746 Value::Bool(true) => self.out.push_str("true"),
14747 Value::Bool(false) => self.out.push_str("false"),
14748 Value::Int(number) => self.out.push_str(&number.to_string()),
14749 Value::Float(number) => {
14750 self.out
14751 .push_str(&crate::value::number_to_string_for_print(*number));
14752 }
14753 Value::String(text) => self.print_string(&text.to_string_lossy()),
14754 Value::Object(object) => self.object(object, level),
14755 }
14756 }
14757
14758 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
14759 // A cycle is reported rather than followed; the index is where the object
14760 // already sits in the print stack, which is what the reference shows.
14761 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
14762 self.out.push_str(&format!("[circular {index}]"));
14763 return;
14764 }
14765 if object.is_callable() {
14766 let name = object
14767 .own_property("name")
14768 .and_then(|property| property.value)
14769 .map(|value| value.to_js_string())
14770 .unwrap_or_default();
14771 if name.is_empty() {
14772 self.out.push_str("[Function (anonymous)]");
14773 } else {
14774 self.out.push_str(&format!("[Function {name}]"));
14775 }
14776 return;
14777 }
14778 if level >= Self::MAX_DEPTH {
14779 let class = if object.is_array() { "Array" } else { "Object" };
14780 self.out.push_str(&format!("[{class}]"));
14781 return;
14782 }
14783 // `Date` and `Error` print as themselves rather than as bags of properties:
14784 // the ISO string, and `Name: message` followed by the trace.
14785 if let Some(class) = class_of(self.interp, object) {
14786 if class == "Date" {
14787 self.date(object);
14788 return;
14789 }
14790 if class == "Error" {
14791 self.error(object);
14792 return;
14793 }
14794 }
14795 self.stack.push(object.clone());
14796 if object.is_array() {
14797 self.array(object, level);
14798 } else {
14799 self.plain_object(object, level);
14800 }
14801 self.stack.pop();
14802 }
14803
14804 /// A Date prints as its ISO string; an invalid one falls through to the plain
14805 /// object form, the way the reference falls back when `toISOString` throws.
14806 fn date(&mut self, object: &Gc<JsObject>) {
14807 let value = self
14808 .interp
14809 .internal_get(object, "_date_value")
14810 .map(|value| value.to_number());
14811 match value.and_then(crate::builtins::date::iso_string) {
14812 Some(text) => self.out.push_str(&text),
14813 None => self.plain_object(object, 0),
14814 }
14815 }
14816
14817 /// `Name: message`, then the trace with its trailing newline removed.
14818 fn error(&mut self, object: &Gc<JsObject>) {
14819 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
14820 self.out.push_str(&name);
14821 if let Some(message) = inherited(object, "message")
14822 && !message.is_empty()
14823 {
14824 self.out.push_str(": ");
14825 self.out.push_str(&message);
14826 }
14827 if let Some(stack) = inherited(object, "stack") {
14828 self.out.push('\n');
14829 self.out.push_str(stack.trim_end_matches('\n'));
14830 }
14831 }
14832
14833 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
14834 let elements = object.array_elements().unwrap_or_default();
14835 self.out.push_str("[ ");
14836 // An interior hole means the array is "sparse": the reference prints those
14837 // as `index: value` pairs and says nothing about the holes themselves, while
14838 // a hole run at the end becomes a single `<N empty items>` note.
14839 let last_present = elements
14840 .iter()
14841 .rposition(|value| !matches!(value, Value::Hole));
14842 let has_interior_hole = match last_present {
14843 Some(last) => elements[..last]
14844 .iter()
14845 .any(|value| matches!(value, Value::Hole)),
14846 None => false,
14847 };
14848 let mut first = true;
14849 if has_interior_hole {
14850 let mut index = 0;
14851 while index < elements.len() {
14852 let value = &elements[index];
14853 if matches!(value, Value::Hole) {
14854 index += 1;
14855 continue;
14856 }
14857 if !first {
14858 self.out.push_str(", ");
14859 }
14860 first = false;
14861 self.out.push_str(&format!("{index}: "));
14862 self.value(value, level + 1);
14863 index += 1;
14864 }
14865 } else {
14866 for (index, value) in elements.iter().enumerate() {
14867 if matches!(value, Value::Hole) {
14868 continue;
14869 }
14870 if !first {
14871 self.out.push_str(", ");
14872 }
14873 first = false;
14874 let _ = index;
14875 self.value(value, level + 1);
14876 }
14877 if let Some(last) = last_present {
14878 let trailing = elements.len() - last - 1;
14879 if trailing > 0 {
14880 if !first {
14881 self.out.push_str(", ");
14882 }
14883 self.out.push_str(&format!(
14884 "<{trailing} empty item{}>",
14885 if trailing > 1 { "s" } else { "" }
14886 ));
14887 }
14888 } else if !elements.is_empty() {
14889 let count = elements.len();
14890 self.out.push_str(&format!(
14891 "<{count} empty item{}>",
14892 if count > 1 { "s" } else { "" }
14893 ));
14894 }
14895 }
14896 self.out.push_str(" ]");
14897 }
14898
14899 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
14900 self.out.push_str("{ ");
14901 let mut first = true;
14902 for key in object.own_keys() {
14903 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
14904 continue;
14905 };
14906 if !property.enumerable {
14907 continue;
14908 }
14909 if !first {
14910 self.out.push_str(", ");
14911 }
14912 first = false;
14913 self.out
14914 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
14915 &key.to_string_lossy(),
14916 )));
14917 self.out.push_str(": ");
14918 // An accessor has no value to dump; the reference names the half that
14919 // exists instead of calling it.
14920 if property.is_accessor() {
14921 let text = match (property.getter.is_some(), property.setter.is_some()) {
14922 (true, true) => "[Getter/Setter]",
14923 (false, true) => "[Setter]",
14924 _ => "[Getter]",
14925 };
14926 self.out.push_str(text);
14927 } else {
14928 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
14929 }
14930 }
14931 self.out.push_str(" }");
14932 }
14933
14934 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
14935 fn print_string(&mut self, text: &str) {
14936 self.out.push('"');
14937 for character in text.chars() {
14938 match character {
14939 '"' => self.out.push_str("\\\""),
14940 '\\' => self.out.push_str("\\\\"),
14941 '\n' => self.out.push_str("\\n"),
14942 '\r' => self.out.push_str("\\r"),
14943 '\t' => self.out.push_str("\\t"),
14944 c if (c as u32) < 0x20 => {
14945 self.out.push_str(&format!("\\u{:04x}", c as u32));
14946 }
14947 c => self.out.push(c),
14948 }
14949 }
14950 self.out.push('"');
14951 }
14952}
14953
14954/// How `print` renders a value.
14955///
14956/// `ToString`, except that negative zero keeps its sign — the reference's host
14957/// printer does that while `String(-0)` is `"0"`.
14958pub fn display(value: &Value) -> String {
14959 match value {
14960 Value::Float(number) => crate::value::number_to_string_for_print(*number),
14961 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
14962 "undefined".to_string()
14963 }
14964 other => other.to_js_string(),
14965 }
14966}
14967
14968// ---------------------------------------------------------------------------
14969// Numeric operators
14970// ---------------------------------------------------------------------------
14971
14972/// `a + b` keeping the `Int` representation when it fits.
14973fn add_numbers(left: Value, right: Value) -> Value {
14974 match (&left, &right) {
14975 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
14976 Some(sum) => Value::Int(sum),
14977 None => Value::Float(*a as f64 + *b as f64),
14978 },
14979 _ => Value::Float(left.to_number() + right.to_number()),
14980 }
14981}
14982
14983/// The arithmetic operators other than `+`, which needs string concatenation.
14984fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14985 use Opcode::*;
14986 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
14987 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
14988 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
14989 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
14990 return Ok(match op {
14991 And => Value::Int(x & y),
14992 Or => Value::Int(x | y),
14993 Xor => Value::Int(x ^ y),
14994 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
14995 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
14996 Shr => match (*x as u32) >> ((*y as u32) & 31) {
14997 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
14998 shifted => Value::Float(shifted as f64),
14999 },
15000 Sub => match x.checked_sub(*y) {
15001 Some(value) => Value::Int(value),
15002 None => Value::Float(*x as f64 - *y as f64),
15003 },
15004 _ => return arithmetic_slow(op, left, right),
15005 });
15006 }
15007 arithmetic_slow(op, left, right)
15008}
15009
15010/// [`arithmetic`] for everything the integer fast path above does not take.
15011fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15012 use Opcode::*;
15013 let (a, b) = (left.to_number(), right.to_number());
15014 Ok(match op {
15015 Sub => match (&left, &right) {
15016 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
15017 Some(value) => Value::Int(value),
15018 None => Value::Float(a - b),
15019 },
15020 _ => Value::Float(a - b),
15021 },
15022 Mul => Value::Float(a * b),
15023 Div => Value::Float(a / b),
15024 Mod => Value::Float(js_mod(a, b)),
15025 Pow => Value::Float(a.powf(b)),
15026 And => Value::Int(left.to_int32() & right.to_int32()),
15027 Or => Value::Int(left.to_int32() | right.to_int32()),
15028 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
15029 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
15030 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
15031 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
15032 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
15033 // fits the small-integer representation stays an `Int`; the rest become a
15034 // float, which is how the reference keeps `n >>> 0` non-negative.
15035 Shr => {
15036 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15037 match i32::try_from(shifted) {
15038 Ok(value) => Value::Int(value),
15039 Err(_) => Value::Float(shifted as f64),
15040 }
15041 }
15042 _ => Value::Float(a),
15043 })
15044}
15045
15046/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
15047///
15048/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
15049/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
15050/// slow path where the rules live.
15051fn is_number(value: &Value) -> bool {
15052 matches!(value, Value::Int(_) | Value::Float(_))
15053}
15054
15055/// The `Value::Bool` a comparison operator answers for `ordering`.
15056///
15057/// `None` is the unordered case — a `NaN` on either side — and every operator answers
15058/// false for it, including `<=` and `>=`.
15059fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
15060 use Opcode::*;
15061 let answer = match (op, ordering) {
15062 (_, None) => false,
15063 (Lt, Some(ordering)) => ordering.is_lt(),
15064 (Lte, Some(ordering)) => ordering.is_le(),
15065 (Gt, Some(ordering)) => ordering.is_gt(),
15066 (Gte, Some(ordering)) => ordering.is_ge(),
15067 _ => false,
15068 };
15069 Value::Bool(answer)
15070}
15071
15072/// `%`, which follows the sign of the dividend rather than Rust's.
15073fn js_mod(left: f64, right: f64) -> f64 {
15074 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
15075 return f64::NAN;
15076 }
15077 if right.is_infinite() {
15078 return left;
15079 }
15080 let remainder = left % right;
15081 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
15082 // the spec makes the sign match the dividend.
15083 if remainder == 0.0 {
15084 0.0f64.copysign(left)
15085 } else {
15086 remainder
15087 }
15088}
15089
15090fn negate(value: Value) -> Value {
15091 match value {
15092 Value::Int(0) => Value::Float(-0.0),
15093 Value::Int(i) => Value::Int(-i),
15094 other => Value::Float(-other.to_number()),
15095 }
15096}
15097
15098fn increment(value: Value) -> Value {
15099 match value {
15100 Value::Int(i) => match i.checked_add(1) {
15101 Some(next) => Value::Int(next),
15102 None => Value::Float(i as f64 + 1.0),
15103 },
15104 other => Value::Float(other.to_number() + 1.0),
15105 }
15106}
15107
15108fn decrement(value: Value) -> Value {
15109 match value {
15110 Value::Int(i) => match i.checked_sub(1) {
15111 Some(next) => Value::Int(next),
15112 None => Value::Float(i as f64 - 1.0),
15113 },
15114 other => Value::Float(other.to_number() - 1.0),
15115 }
15116}
15117
15118/// Compare a `BigInt` with an `f64` on their mathematical values.
15119///
15120/// Neither side is rounded to the other's precision: the number is split into its integer
15121/// part (compared as an exact bigint) and its fraction, which is what decides the answer
15122/// when the integer parts are equal. An infinite value is larger than every bigint.
15123fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
15124 use std::cmp::Ordering;
15125 if number.is_nan() {
15126 return None;
15127 }
15128 if number.is_infinite() {
15129 return Some(if number > 0.0 {
15130 Ordering::Less
15131 } else {
15132 Ordering::Greater
15133 });
15134 }
15135 let truncated = number.trunc();
15136 // A number wider than `i128` still has an exact integer part, but no bigint form we can
15137 // build cheaply; the sign of the difference is all that is needed, so compare against
15138 // the bigint's own magnitude instead.
15139 if truncated.abs() >= 1.7e38 {
15140 let big_as_f64 = big.to_f64();
15141 return big_as_f64.partial_cmp(&number);
15142 }
15143 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
15144 match big.cmp(&integer) {
15145 Ordering::Equal => {
15146 // Same integer part: the fraction decides, and a negative number's fraction is
15147 // below the integer (`-1.5` truncates to `-1`).
15148 if number > truncated {
15149 Some(Ordering::Less)
15150 } else if number < truncated {
15151 Some(Ordering::Greater)
15152 } else {
15153 Some(Ordering::Equal)
15154 }
15155 }
15156 other => Some(other),
15157 }
15158}
15159
15160/// `CanonicalNumericIndexString(argument)` (§7.1.21).
15161///
15162/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
15163/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
15164/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
15165/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
15166/// rather than treating it as `0`.
15167fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
15168 let PropertyKey::String(text) = key else {
15169 // A symbol is never an index.
15170 return None;
15171 };
15172 let text = text.to_string_lossy();
15173 if text == "-0" {
15174 return Some(-0.0);
15175 }
15176 let number: f64 = text.parse().ok()?;
15177 // The round-trip test *is* the definition: only the canonical spelling qualifies.
15178 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
15179 // `"0.10"` does not.
15180 let rendered = Value::Float(number).to_js_string();
15181 (rendered == text).then_some(number)
15182}
15183
15184/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
15185///
15186/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
15187/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
15188/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
15189/// numeric and invalid, which is why they stop the prototype chain instead of falling
15190/// through it.
15191///
15192/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
15193/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
15194/// `in`, `delete` and `defineProperty` separately to make sure it does not.
15195fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
15196 numeric.is_finite()
15197 && numeric.fract() == 0.0
15198 && !(numeric == 0.0 && numeric.is_sign_negative())
15199 && numeric >= 0.0
15200 && object
15201 .typed_array_length()
15202 .is_some_and(|length| (numeric as usize) < length)
15203}