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 pending_new_target: Option<Value>,
1133 /// Names of the native functions currently executing, outermost first.
1134 ///
1135 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1136 /// trace still names it with `(native)` instead of a position, so the names are
1137 /// tracked separately and stitched into [`Interp::stack_trace`].
1138 ///
1139 /// The third field is how many bytecode frames were live when the native was entered,
1140 /// which is what places it *among* them rather than before all of them. Native
1141 /// functions used to be emitted up front on the grounds that they never re-enter
1142 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1143 /// The natives currently running, innermost last: the function object and the
1144 /// depth it was entered at.
1145 ///
1146 /// The *name* is deliberately not stored. It used to be, read with
1147 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1148 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1149 /// benchmark. A stack trace is built rarely; it can read the name then.
1150 native_frames: Vec<(Gc<JsObject>, usize)>,
1151 /// The native function currently executing, for the ones that have to know *which*
1152 /// function they are — a typed-array constructor reads its element type off itself.
1153 ///
1154 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1155 /// reports whatever the enclosing bytecode frame was called with.
1156 current_native: Option<Gc<JsObject>>,
1157 /// Text written by `print` and friends, in order.
1158 ///
1159 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1160 /// once at the end, which is also when upstream's line buffering becomes
1161 /// visible for the cases compared here.
1162 pub output: String,
1163 /// Where `print` also writes, as it goes. `output` keeps the full log for
1164 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1165 ///
1166 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1167 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1168 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1169 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1170 /// would show a script's output all at once when it finished.
1171 pub output_sink: Option<Box<dyn std::io::Write>>,
1172 /// Where recent property reads found their value.
1173 ///
1174 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1175 /// table remembering *which object* and *which entry of its property table* answered a
1176 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1177 /// can move; the property can become an accessor), which is what makes a stale entry a
1178 /// miss rather than a wrong answer.
1179 ///
1180 /// The object is held weakly: a cache that held it strongly would keep up to
1181 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1182 /// program cannot see and cannot work around.
1183 pub field_cache: Vec<Option<FieldCache>>,
1184 /// Global lookups, by binding slot. See [`GlobalCache`].
1185 global_cache: Vec<Option<GlobalCache>>,
1186 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1187 /// under its limit. See [`Interp::check_memory`].
1188 pub oom_reported_at: usize,
1189 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1190 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1191 ///
1192 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1193 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1194 /// host that wants to stop a runaway script must not have to wait for it to return.
1195 ///
1196 /// Two things this cannot do, both of them differences a host can observe:
1197 ///
1198 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1199 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1200 /// needs a signal that the `catch` machinery does not see, which is a change to
1201 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1202 /// a host that stops the script itself.
1203 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1204 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1205 /// both, so the difference is when the counter hits zero, not whether it will.
1206 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1207 /// Instructions until the next [`Interp::interrupt`] poll.
1208 pub interrupt_counter: u32,
1209 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1210 ///
1211 /// A separate field from [`Interp::uncatchable`] because the two live for different
1212 /// spans. This one is the host's standing request; it survives the start of an
1213 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1214 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1215 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1216 /// cleared it before the script it was set for had a chance to throw.
1217 pub uncatchable_next: bool,
1218 /// Whether the exception now unwinding may be caught by a `catch`.
1219 ///
1220 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1221 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1222 /// a host stopping a runaway loop is not fought by the loop.
1223 ///
1224 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1225 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1226 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1227 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1228 pub uncatchable: bool,
1229 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1230 ///
1231 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1232 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1233 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1234 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1235 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1236 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1237 ///
1238 /// The numbers come out close for the same reason a C frame and a heap frame of this
1239 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1240 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1241 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1242 /// `crates/quickjs-cli/tests/limits.rs`.
1243 pub stack_limit: usize,
1244 /// The most frames that may be live at once, whatever the byte budget says.
1245 ///
1246 /// A second bound for a reason the reference does not have: our frames cost less than
1247 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1248 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1249 /// `--stack-size 1G` from being a memory bomb.
1250 pub max_frames: usize,
1251 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1252 ///
1253 /// Script execution does not return until this has drained, which is what makes
1254 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1255 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1256 /// not a `for`.
1257 pub(crate) jobs: std::collections::VecDeque<Job>,
1258 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1259 ///
1260 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1261 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1262 pub(crate) tasks: Vec<Task>,
1263 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1264 /// barrier'd evaluation started.
1265 ///
1266 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1267 /// lets a REPL report an error from the line it just evaluated without also reporting
1268 /// its own readline loop.
1269 trace_barriers: Vec<usize>,
1270 /// `os.signal` handlers, keyed by signal number.
1271 ///
1272 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1273 /// a handler cannot be freed while it is still registered.
1274 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1275 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1276 ///
1277 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1278 /// that is only reachable from a host closure could be freed while still registered.
1279 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1280 /// The next timer id.
1281 ///
1282 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1283 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1284 next_timer_id: i32,
1285 /// Errors thrown by timer callbacks, already rendered.
1286 ///
1287 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1288 /// that throws has no promise behind it. Both are reported by the host at the end of
1289 /// the loop, but only one is fixed up by a later `.catch`.
1290 timer_errors: Vec<String>,
1291 /// The module registry, keyed by canonical name.
1292 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1293 /// How the host turns a specifier into bytes.
1294 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1295 /// The module the host was asked to run, for `import.meta.main`.
1296 pub main_module_name: Option<String>,
1297 /// Module bodies currently running, innermost last.
1298 ///
1299 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1300 /// this is the only place that knows which module that is.
1301 pub module_stack: Vec<String>,
1302 /// Rejections that no handler has claimed, with the promise they belong to.
1303 ///
1304 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1305 /// reason alone cannot say whether somebody eventually listened.
1306 unhandled: Vec<(Gc<JsObject>, Value)>,
1307}
1308
1309impl<'a> Interp<'a> {
1310 /// Build an interpreter over `heap`, with a fresh realm.
1311 pub fn new(heap: &'a Heap) -> Interp<'a> {
1312 let object_proto = JsObject::ordinary(heap, None);
1313 let function_proto = JsObject::function(
1314 heap,
1315 Some(object_proto.clone()),
1316 Callable::Native {
1317 func: |_, _, _| Ok(Value::Undefined),
1318 own_instance: false,
1319 },
1320 );
1321 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1322 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1323 let mut interp = Interp {
1324 heap,
1325 realm: Realm {
1326 global,
1327 object_proto,
1328 function_proto,
1329 array_proto,
1330 array_constructor: None,
1331 promise_constructor: None,
1332 globals: BTreeMap::new(),
1333 declared: Vec::new(),
1334 lexical_consts: BTreeSet::new(),
1335 errors: BTreeMap::new(),
1336 string_proto: None,
1337 number_proto: None,
1338 boolean_proto: None,
1339 bigint_proto: None,
1340 error_proto: JsObject::ordinary(heap, None),
1341 date_proto: JsObject::ordinary(heap, None),
1342 throw_type_error: None,
1343 generator_proto: JsObject::ordinary(heap, None),
1344 promise_proto: None,
1345 async_generator_proto: None,
1346 async_iterator_proto: None,
1347 symbol_proto: None,
1348 symbol_registry: BTreeMap::new(),
1349 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1350 regexp_proto: None,
1351 regexp_ctor: None,
1352 suppressed_error_proto: None,
1353 disposable_stack_proto: None,
1354 map_proto: None,
1355 set_proto: None,
1356 finalization_registries: Vec::new(),
1357 array_buffer_proto: None,
1358 typed_array_proto: None,
1359 typed_array_protos: Vec::new(),
1360 data_view_proto: None,
1361 async_disposable_stack_proto: None,
1362 iterator_proto: None,
1363 iterator_ctor: None,
1364 iterator_helper_proto: None,
1365 iterator_wrap_proto: None,
1366 generator_function_proto: None,
1367 async_function_proto: None,
1368 async_generator_function_proto: None,
1369 iterator_protos: std::collections::BTreeMap::new(),
1370 well_known_symbols: WellKnownSymbols::default(),
1371 host_classes: HostClasses::new(),
1372 },
1373 frames: Vec::new(),
1374 free_values: Vec::new(),
1375 global_cache: {
1376 let mut cache = Vec::new();
1377 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1378 cache
1379 },
1380 eval_scope: None,
1381 eval_depth: 0,
1382 eval_bindings: Vec::new(),
1383 eval_arguments: None,
1384 eval_with: None,
1385 active_eval_scope: None,
1386 eval_caller: None,
1387 pending_new_target: None,
1388 eval_new_target: None,
1389 native_frames: Vec::new(),
1390 current_native: None,
1391 output: String::new(),
1392 output_sink: None,
1393 field_cache: {
1394 let mut cache = Vec::new();
1395 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1396 cache
1397 },
1398 oom_reported_at: 0,
1399 interrupt: None,
1400 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1401 uncatchable_next: false,
1402 uncatchable: false,
1403 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1404 // absent.
1405 stack_limit: DEFAULT_STACK_SIZE,
1406 max_frames: MAX_FRAMES,
1407 jobs: std::collections::VecDeque::new(),
1408 tasks: Vec::new(),
1409 trace_barriers: Vec::new(),
1410 signal_handlers: std::collections::BTreeMap::new(),
1411 fd_handlers: std::collections::BTreeMap::new(),
1412 next_timer_id: 1,
1413 timer_errors: Vec::new(),
1414 modules: std::collections::BTreeMap::new(),
1415 module_loader: None,
1416 main_module_name: None,
1417 module_stack: Vec::new(),
1418 unhandled: Vec::new(),
1419 };
1420 crate::builtins::install(&mut interp);
1421 interp
1422 }
1423
1424 // -- allocation helpers -------------------------------------------------
1425
1426 /// A new string value.
1427 /// A `BigInt` value from a computed big integer.
1428 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1429 Value::BigInt(Gc::new(self.heap, value))
1430 }
1431
1432 /// A string value from bytes that are already WTF-8, which is how a string with an
1433 /// unpaired surrogate reaches a `Value`.
1434 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1435 Value::string_wtf8(self.heap, text)
1436 }
1437
1438 /// A new string value, from text that is valid UTF-8.
1439 pub fn string(&self, text: impl Into<String>) -> Value {
1440 Value::string(self.heap, text)
1441 }
1442
1443 /// A new ordinary object with the given prototype.
1444 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1445 JsObject::ordinary(self.heap, proto)
1446 }
1447
1448 // -- host classes -------------------------------------------------------
1449
1450 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1451 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1452 self.realm.host_classes.register(def)
1453 }
1454
1455 /// Register `def` under an id the host already holds (`JS_NewClass`).
1456 ///
1457 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1458 /// `JS_NewClass`.
1459 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1460 self.realm.host_classes.define(id, def)
1461 }
1462
1463 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1464 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1465 self.realm.host_classes.set_proto(id, proto);
1466 }
1467
1468 /// The prototype installed for `id`, if any.
1469 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1470 self.realm.host_classes.proto(id)
1471 }
1472
1473 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1474 ///
1475 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1476 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1477 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1478 /// host installed none.
1479 ///
1480 /// Answers `None` for an id that was never registered: the C API would return an
1481 /// exception, and silently making an ordinary object instead would move the failure to
1482 /// the first `JS_GetOpaque` that no longer matches.
1483 pub fn new_host_object(
1484 &mut self,
1485 proto: Option<Gc<JsObject>>,
1486 class_id: ClassId,
1487 ) -> Option<Gc<JsObject>> {
1488 let class = self.realm.host_classes.def(class_id)?;
1489 let proto = proto
1490 .or_else(|| self.realm.host_classes.proto(class_id))
1491 .or_else(|| Some(self.realm.object_proto.clone()));
1492 Some(JsObject::host_object(self.heap, proto, class_id, class))
1493 }
1494
1495 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1496 ///
1497 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1498 /// object, it is an object of another class, or the class never got a payload. A host
1499 /// that has to tell them apart uses [`JsObject::host_class_id`].
1500 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1501 let object = value.as_object()?;
1502 if object.host_class_id()? != class_id {
1503 return None;
1504 }
1505 object.host_opaque()
1506 }
1507
1508 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1509 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1510 match value.as_object() {
1511 Some(object) => object.set_host_opaque(opaque),
1512 None => false,
1513 }
1514 }
1515
1516 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1517 ///
1518 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1519 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1520 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1521 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1522 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1523 /// said `[object Object]` instead of `[object Array Iterator]`.
1524 ///
1525 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1526 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1527 /// its own.
1528 pub fn new_iterator_prototype(
1529 &mut self,
1530 tag: &str,
1531 next: crate::object::NativeFn,
1532 ) -> Gc<JsObject> {
1533 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1534 return existing.clone();
1535 }
1536 let parent = self.realm.iterator_proto.clone();
1537 let proto = self.new_object(parent);
1538 let next = self.new_native("next", 0, next);
1539 proto.define(
1540 "next",
1541 Property::with_attributes(Value::Object(next), true, false),
1542 );
1543 let key = self.realm.well_known_key(WellKnown::Iterator);
1544 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1545 proto.define_key(
1546 &key,
1547 Property::with_attributes(Value::Object(identity), true, false),
1548 );
1549 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1550 let tag_value = self.string(tag);
1551 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1552 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1553 // checks it.
1554 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1555 self.realm
1556 .iterator_protos
1557 .insert(tag.to_string(), proto.clone());
1558 proto
1559 }
1560
1561 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1562 ///
1563 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1564 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1565 /// produced. That is why the two branches are not merged.
1566 pub fn object_own_property_keys(
1567 &mut self,
1568 object: &Gc<JsObject>,
1569 ) -> JsResult<Vec<PropertyKey>> {
1570 if let Some(keys) = self.proxy_own_keys(object)? {
1571 return Ok(keys);
1572 }
1573 // Integer-like keys ascending, then the string keys in insertion order, then the
1574 // symbols — the order every schema that walks an object expects.
1575 let entries = object.property_entries();
1576 let mut numeric: Vec<u32> = Vec::new();
1577 // An integer-indexed exotic object reports its indices as own keys even though they
1578 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1579 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1580 // order). The length is asked per call, so a resizable buffer's view reports the
1581 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1582 if object.typed_array_parts().is_some() {
1583 for index in 0..object.typed_array_length().unwrap_or(0) {
1584 // `u32::try_from` cannot fail for a real length, but the length is a
1585 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1586 // as an array index and one element beyond is not.
1587 match u32::try_from(index) {
1588 Ok(index) => numeric.push(index),
1589 Err(_) => break,
1590 }
1591 }
1592 }
1593 let mut strings: Vec<PropertyKey> = Vec::new();
1594 let mut symbols: Vec<PropertyKey> = Vec::new();
1595 for (key, _) in entries {
1596 match &key {
1597 // A class-private name is never reported by any enumeration: that is the
1598 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1599 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1600 // symbol skip, `Object.assign`) therefore cannot see it.
1601 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1602 PropertyKey::Symbol(_) => symbols.push(key),
1603 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1604 Some(index) => {
1605 if !numeric.contains(&index) {
1606 numeric.push(index);
1607 }
1608 }
1609 None => strings.push(key),
1610 },
1611 }
1612 }
1613 numeric.sort_unstable();
1614 let mut keys: Vec<PropertyKey> = numeric
1615 .into_iter()
1616 .map(|index| PropertyKey::from(index.to_string()))
1617 .collect();
1618 keys.extend(strings);
1619 keys.extend(symbols);
1620 Ok(keys)
1621 }
1622
1623 /// The state behind a promise object, or `None` when `object` is not one.
1624 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1625 object.with(|data| match &data.kind {
1626 ObjectKind::Promise(state) => Some(state.clone()),
1627 _ => None,
1628 })
1629 }
1630
1631 /// A new pending promise.
1632 pub fn new_promise(&mut self) -> Gc<JsObject> {
1633 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1634 // the one place every promise is built, and a subclass that builds its instances
1635 // somewhere else would be invisible to `instanceof`.
1636 let default = self.realm.promise_proto.clone();
1637 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1638 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1639 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1640 // `prototype` getter therefore still gets a working promise; the alternative is a
1641 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1642 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1643 let promise = JsObject::ordinary(self.heap, proto);
1644 promise.with_mut(|data| {
1645 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1646 crate::object::PromiseState::default(),
1647 )));
1648 });
1649 promise
1650 }
1651
1652 /// Fulfil `promise`, unless it has already settled.
1653 ///
1654 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1655 /// after `reject`, changes nothing.
1656 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1657 let Some(state) = self.promise_state(promise) else {
1658 return;
1659 };
1660 let reactions = {
1661 let mut state = state.borrow_mut();
1662 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1663 return;
1664 }
1665 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1666 std::mem::take(&mut state.reactions)
1667 };
1668 self.queue_reactions(reactions, value, false);
1669 }
1670
1671 /// Reject `promise`, unless it has already settled.
1672 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1673 let Some(state) = self.promise_state(promise) else {
1674 return;
1675 };
1676 let reactions = {
1677 let mut state = state.borrow_mut();
1678 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1679 return;
1680 }
1681 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1682 std::mem::take(&mut state.reactions)
1683 };
1684 // Remember it only when nothing is listening *now*; a `then` registered later
1685 // prunes the entry in `perform_then`.
1686 if reactions.is_empty() {
1687 self.unhandled.push((promise.clone(), reason.clone()));
1688 }
1689 self.queue_reactions(reactions, reason, true);
1690 }
1691
1692 /// Queue one job per reaction.
1693 ///
1694 /// This is what makes `then` asynchronous even on an already-settled promise:
1695 /// `p.then(f); g()` calls `g` first.
1696 fn queue_reactions(
1697 &mut self,
1698 reactions: Vec<crate::object::PromiseReaction>,
1699 argument: Value,
1700 rejected: bool,
1701 ) {
1702 for reaction in reactions {
1703 let handler = if rejected {
1704 reaction.on_rejected.clone()
1705 } else {
1706 reaction.on_fulfilled.clone()
1707 };
1708 self.jobs.push_back(Job::Reaction {
1709 handler,
1710 argument: argument.clone(),
1711 rejected,
1712 promise: reaction.promise,
1713 });
1714 }
1715 }
1716
1717 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1718 /// resolve/reject pair.
1719 ///
1720 /// The pair are callable objects rather than Rust closures, because the script gets
1721 /// them and may stash them for later.
1722 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1723 let promise = self.new_promise();
1724 // Both handlers are built-ins with an empty name and length 1, in
1725 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1726 // off `Object.getOwnPropertyNames`.
1727 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1728 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1729 (promise, Value::Object(resolve), Value::Object(reject))
1730 }
1731
1732 /// §27.2.1.5 `NewPromiseCapability(C)`.
1733 ///
1734 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1735 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1736 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1737 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1738 /// silently ignored argument.
1739 ///
1740 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1741 /// the engine's own executor is exactly what `new_promise_capability` builds.
1742 pub fn new_promise_capability_for(
1743 &mut self,
1744 constructor: &Value,
1745 ) -> JsResult<(Value, Value, Value)> {
1746 let Some(object) = constructor.as_object().cloned() else {
1747 return Err(self.type_error("promise constructor is not a constructor"));
1748 };
1749 if !object.is_constructor() {
1750 return Err(self.type_error("promise constructor is not a constructor"));
1751 }
1752 if self
1753 .realm
1754 .promise_constructor
1755 .as_ref()
1756 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1757 {
1758 let (promise, resolve, reject) = self.new_promise_capability();
1759 return Ok((Value::Object(promise), resolve, reject));
1760 }
1761 let state = self.new_object(Some(self.realm.object_proto.clone()));
1762 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1763 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1764 // which only a *custom* constructor can observe, and none of the combinator tests
1765 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1766 let executor = self.builtin_function(
1767 "",
1768 2,
1769 Callable::CapabilityExecutor {
1770 state: state.clone(),
1771 },
1772 );
1773 let promise = self.construct(
1774 Value::Object(object.clone()),
1775 Value::Object(object),
1776 vec![Value::Object(executor)],
1777 )?;
1778 // The pair is read *after* the constructor returns, so a constructor that never
1779 // called its executor, or called it with non-callables, is the spec's step 11
1780 // `TypeError` — not something the engine can paper over.
1781 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1782 return Err(self.type_error("promise executor never ran"));
1783 };
1784 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1785 return Err(self.type_error("promise executor never ran"));
1786 };
1787 for handler in [&resolve, &reject] {
1788 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1789 return Err(self.type_error("promise capability handler is not callable"));
1790 }
1791 }
1792 Ok((promise, resolve, reject))
1793 }
1794
1795 /// §27.2.3.1 `PromiseResolve(C, x)`.
1796 ///
1797 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1798 /// an `x` that is already a promise of exactly this constructor is handed back
1799 /// unchanged, and anything else gets a fresh capability from `C`.
1800 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1801 if let Value::Object(object) = &value
1802 && self.promise_state(object).is_some()
1803 {
1804 // `x.constructor === C` means "already the right kind", so no capability is
1805 // built — which is observable through a `resolve` that counts its calls.
1806 let x_constructor = self.get_property(object, "constructor")?;
1807 let same = match (
1808 x_constructor.as_ref().and_then(Value::as_object),
1809 constructor.as_object(),
1810 ) {
1811 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1812 _ => false,
1813 };
1814 if same {
1815 return Ok(value);
1816 }
1817 }
1818 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1819 self.call_value(resolve, Value::Undefined, vec![value])?;
1820 Ok(promise)
1821 }
1822
1823 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1824 /// promise, as `{ value: completion }`.
1825 ///
1826 /// The three cases are the reference's, and they differ on purpose:
1827 ///
1828 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1829 /// exception before any promise exists;
1830 /// * a **runtime** error rejects the returned promise;
1831 /// * success resolves it with `{ value }`, where the value is the script's completion
1832 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1833 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1834 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1835 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1836 ///
1837 /// # What this does not do
1838 ///
1839 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1840 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1841 /// the parser and the suspension machinery to accept a suspended top-level script, and
1842 /// is not implemented — such source is a syntax error here. Everything else about the
1843 /// flag is reproduced.
1844 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1845 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1846 // too, and the reference truncates that one at the same place as a runtime failure.
1847 if barrier {
1848 let depth = self.frames.len();
1849 self.trace_barriers.push(depth);
1850 }
1851 // Compiled before the promise exists, so a parse failure propagates as a throw
1852 // instead of being folded into a rejection.
1853 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1854 Ok(compiled) => compiled,
1855 Err(error) => {
1856 if barrier {
1857 self.trace_barriers.pop();
1858 }
1859 return Err(error);
1860 }
1861 };
1862 // An async body answers its own promise, and that promise is what the reference
1863 // hands back — the same object, not a wrapper around it. Its resolution value is
1864 // the `{value}` object the compiled epilogue built.
1865 if compiled.kind.is_async() {
1866 let strict = compiled.strict;
1867 let promise = self.run_eval_script(compiled, strict)?;
1868 if barrier {
1869 self.trace_barriers.pop();
1870 }
1871 return Ok(promise);
1872 }
1873 let (promise, resolve, reject) = self.new_promise_capability();
1874 let strict = compiled.strict;
1875 match self.run_eval_script(compiled, strict) {
1876 Ok(value) => {
1877 // `{ value }` is a plain object, so resolving with it adopts nothing even
1878 // when the completion value is itself a promise.
1879 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1880 self.set_property(&wrapped, "value", value)?;
1881 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1882 }
1883 Err(Signal::Throw(error)) => {
1884 self.call_value(reject, Value::Undefined, vec![error])?;
1885 }
1886 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1887 }
1888 if barrier {
1889 self.trace_barriers.pop();
1890 }
1891 Ok(Value::Object(promise))
1892 }
1893
1894 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1895 ///
1896 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1897 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1898 /// timer table, where the collector already scans it.
1899 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1900 let (promise, resolve, _reject) = self.new_promise_capability();
1901 let resolve = self.new_host_function(
1902 "resolve",
1903 1,
1904 Box::new(
1905 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1906 let value = args.first().cloned().unwrap_or(Value::Undefined);
1907 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1908 },
1909 ),
1910 );
1911 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1912 // timer table is part of what the collector walks.
1913 self.schedule_timer(Value::Object(resolve), delay_ms);
1914 Ok(Value::Object(promise))
1915 }
1916
1917 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1918 /// new promise resolved with it.
1919 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1920 if let Value::Object(object) = &value
1921 && self.promise_state(object).is_some()
1922 {
1923 return Ok(value);
1924 }
1925 let promise = self.new_promise();
1926 self.resolve_promise_with(&promise, value)?;
1927 Ok(Value::Object(promise))
1928 }
1929
1930 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
1931 ///
1932 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
1933 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
1934 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
1935 /// therefore observable — which is exactly what
1936 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
1937 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
1938 /// shortcut.
1939 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
1940 if let Value::Object(object) = &value
1941 && self.promise_state(object).is_some()
1942 {
1943 let constructor = self.get_property(object, "constructor")?;
1944 let same = match (&constructor, &self.realm.promise_constructor) {
1945 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
1946 _ => false,
1947 };
1948 if same {
1949 return Ok(value);
1950 }
1951 }
1952 let promise = self.new_promise();
1953 self.resolve_promise_with(&promise, value)?;
1954 Ok(Value::Object(promise))
1955 }
1956
1957 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1958 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1959 // Resolving a promise with itself is a `TypeError`. The check exists because the
1960 // alternative is a chain of self-reactions that never settles.
1961 if let Value::Object(object) = &value
1962 && object.ptr_eq(promise)
1963 {
1964 // The spec rejects *and* throws, so both the promise and the caller see it.
1965 let thrown = self.type_error("cannot resolve a promise with itself");
1966 let Signal::Throw(error) = thrown.clone() else {
1967 unreachable!("type_error always throws")
1968 };
1969 self.reject_promise(promise, error);
1970 return Err(thrown);
1971 }
1972 let then = match &value {
1973 Value::Object(object) => self.get_property(object, "then")?,
1974 _ => None,
1975 };
1976 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1977 if !callable_then {
1978 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1979 self.fulfill_promise(promise, value);
1980 return Ok(());
1981 }
1982 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1983 // inside `resolve`, so a script cannot make a promise settle synchronously.
1984 self.jobs.push_back(Job::Thenable {
1985 then: then.expect("checked callable"),
1986 value,
1987 promise: promise.clone(),
1988 });
1989 Ok(())
1990 }
1991
1992 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1993 ///
1994 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1995 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1996 ///
1997 /// The property read is **not** short-circuitable even for a real promise: the spec says
1998 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1999 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2000 /// the combinator's loop infinite — the test's iterator never sets `done`.
2001 pub fn invoke_then(
2002 &mut self,
2003 thenable: Value,
2004 on_fulfilled: Value,
2005 on_rejected: Value,
2006 ) -> JsResult<()> {
2007 let then = match &thenable {
2008 Value::Object(object) => self.get_property(object, "then")?,
2009 primitive => {
2010 let boxed = self.object_from(primitive)?;
2011 self.get_property(&boxed, "then")?
2012 }
2013 };
2014 let Some(then) = then else {
2015 return Err(self.type_error("thenable has no then method"));
2016 };
2017 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2018 return Err(self.type_error("then is not a function"));
2019 }
2020 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2021 Ok(())
2022 }
2023
2024 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2025 ///
2026 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2027 /// promise.
2028 pub fn perform_then(
2029 &mut self,
2030 promise: &Gc<JsObject>,
2031 on_fulfilled: Option<Value>,
2032 on_rejected: Option<Value>,
2033 ) -> JsResult<Value> {
2034 let Some(state) = self.promise_state(promise) else {
2035 return Err(self.type_error("not a promise"));
2036 };
2037 // Whether a rejection handler is being attached decides whether a recorded
2038 // rejection stops being unhandled, so it is read before the values are moved.
2039 let has_rejection_handler = on_rejected.is_some();
2040 let derived = self.new_promise();
2041 let reaction = crate::object::PromiseReaction {
2042 on_fulfilled,
2043 on_rejected,
2044 promise: derived.clone(),
2045 };
2046 let settled = {
2047 let mut state = state.borrow_mut();
2048 // A rejection somebody reacts to is no longer unhandled.
2049 state.handled = true;
2050 match &state.status {
2051 crate::object::PromiseStatus::Pending => {
2052 state.reactions.push(reaction.clone());
2053 None
2054 }
2055 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2056 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2057 }
2058 };
2059 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2060 // later, means somebody is listening after all.
2061 if has_rejection_handler {
2062 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2063 }
2064 if let Some((argument, rejected)) = settled {
2065 let handler = if rejected {
2066 reaction.on_rejected
2067 } else {
2068 reaction.on_fulfilled
2069 };
2070 self.jobs.push_back(Job::Reaction {
2071 handler,
2072 argument,
2073 rejected,
2074 promise: reaction.promise,
2075 });
2076 }
2077 Ok(Value::Object(derived))
2078 }
2079
2080 /// The rejections nobody listened to, formatted the way the reference reports them.
2081 ///
2082 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2083 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2084 /// unhandled at the point the queue drains, because a `then` may still be attached
2085 /// before the host acts on it.
2086 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2087 let entries = std::mem::take(&mut self.unhandled);
2088 // Somebody may have attached a handler after the rejection was recorded, so the
2089 // promise is the authority rather than the list.
2090 let still_unhandled: Vec<Value> = entries
2091 .into_iter()
2092 .filter_map(|(promise, reason)| {
2093 let handled = self
2094 .promise_state(&promise)
2095 .map(|state| state.borrow().handled)
2096 .unwrap_or(true);
2097 (!handled).then_some(reason)
2098 })
2099 .collect();
2100 still_unhandled
2101 .into_iter()
2102 .map(|reason| {
2103 let text = self.describe_exception(&reason);
2104 let stack = match &reason {
2105 Value::Object(object) => self
2106 .get_property(object, "stack")
2107 .ok()
2108 .flatten()
2109 .map(|value| value.to_js_string())
2110 // `stack` carries a trailing newline of its own, which would leave
2111 // a blank line between two reported rejections.
2112 .map(|text| text.trim_end().to_string())
2113 .unwrap_or_default(),
2114 _ => String::new(),
2115 };
2116 if stack.is_empty() {
2117 format!("Possibly unhandled promise rejection: {text}")
2118 } else {
2119 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2120 }
2121 })
2122 .collect()
2123 }
2124
2125 /// Run the microtask queue to exhaustion.
2126 ///
2127 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2128 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2129 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2130 ///
2131 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2132 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2133 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2134 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2135 crate::builtins::json::parse_text(self, text, true)
2136 }
2137
2138 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2139 ///
2140 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2141 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2142 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2143 ///
2144 /// The callback is called with **no arguments**. The reference stores only the function
2145 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2146 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2147 /// extra arguments arrive as `undefined`.
2148 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2149 let id = self.next_timer_id;
2150 // Wrap rather than grow: the id reaches the script as an `Int32`.
2151 self.next_timer_id = if self.next_timer_id == i32::MAX {
2152 1
2153 } else {
2154 self.next_timer_id + 1
2155 };
2156 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2157 self.tasks.push(Task::Timer {
2158 id,
2159 callback,
2160 due_at,
2161 });
2162 id
2163 }
2164
2165 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2166 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2167 pub fn cancel_timer(&mut self, id: i32) -> bool {
2168 let before = self.tasks.len();
2169 self.tasks.retain(|task| match task {
2170 Task::Timer { id: task_id, .. } => *task_id != id,
2171 });
2172 self.tasks.len() != before
2173 }
2174
2175 /// How long until the earliest pending timer, or `None` when none is pending.
2176 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2177 let now = std::time::Instant::now();
2178 self.tasks
2179 .iter()
2180 .map(|task| match task {
2181 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2182 })
2183 .min()
2184 }
2185
2186 /// Run one turn of the event loop.
2187 ///
2188 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2189 /// run at most one due timer, then drain again. The blocking belongs to the caller
2190 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2191 /// is how it asks.
2192 ///
2193 /// One timer per turn rather than all of them: a timer callback may schedule another
2194 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2195 /// starve the microtask queue.
2196 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2197 self.drain_jobs()?;
2198 let now = std::time::Instant::now();
2199 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2200 // followed by `setTimeout(g, 1)` must run `g` first.
2201 let due = self
2202 .tasks
2203 .iter()
2204 .enumerate()
2205 .filter(|(_, task)| match task {
2206 Task::Timer { due_at, .. } => *due_at <= now,
2207 })
2208 .min_by_key(|(_, task)| match task {
2209 Task::Timer { due_at, .. } => *due_at,
2210 })
2211 .map(|(index, _)| index);
2212 let Some(index) = due else {
2213 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2214 // descriptor is registered but no timer is closer, so a script that never
2215 // touches the descriptor still gets control back. Without a cap a handler on a
2216 // descriptor that is never ready would block for as long as the host allows.
2217 let timeout = self
2218 .next_timeout()
2219 .unwrap_or(std::time::Duration::from_secs(10))
2220 .min(std::time::Duration::from_secs(10));
2221 if !self.fd_handlers.is_empty() {
2222 // Blocking on a timer while descriptors are registered would starve them,
2223 // and blocking on the descriptors while a timer is due would delay it; the
2224 // host polls with the earlier of the two deadlines, which this timeout is.
2225 return Ok(Turn::Poll(timeout));
2226 }
2227 return Ok(match self.next_timeout() {
2228 Some(wait) => Turn::Wait(wait),
2229 None => Turn::Done,
2230 });
2231 };
2232 let Task::Timer { callback, .. } = self.tasks.remove(index);
2233 let this = Value::Undefined;
2234 // A throwing timer callback must not stop the loop: the reference reports it and
2235 // keeps going, because the alternative is that one bad timer silently stops every
2236 // later one.
2237 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2238 match self.call_value(callback, this, Vec::new()) {
2239 Ok(_) => {}
2240 Err(Signal::Throw(value)) => {
2241 let text = self.describe_exception(&value);
2242 self.timer_errors.push(text);
2243 }
2244 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2245 }
2246 self.drain_jobs()?;
2247 Ok(Turn::Ran)
2248 }
2249
2250 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2251 ///
2252 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2253 /// left is removed — the reference does the same, so a script can rely on
2254 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2255 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2256 let entry = self.fd_handlers.entry(fd).or_default();
2257 if readable {
2258 entry.read = callback;
2259 } else {
2260 entry.write = callback;
2261 }
2262 if entry.read.is_none() && entry.write.is_none() {
2263 self.fd_handlers.remove(&fd);
2264 }
2265 }
2266
2267 /// Register or clear an `os.signal` handler.
2268 ///
2269 /// `None` removes it; the host separately restores the default disposition or sets
2270 /// ignore, because which of those happened is the script's choice (`null` versus
2271 /// `undefined`) and not something this table can express.
2272 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2273 match handler {
2274 Some(handler) => {
2275 self.signal_handlers.insert(signal, handler);
2276 }
2277 None => {
2278 self.signal_handlers.remove(&signal);
2279 }
2280 }
2281 }
2282
2283 /// Run the handler for `signal`, reporting whether one ran.
2284 ///
2285 /// A throwing handler is reported and the loop continues, like a timer's.
2286 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2287 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2288 return Ok(false);
2289 };
2290 match self.call_value(handler, Value::Undefined, Vec::new()) {
2291 Ok(_) => {}
2292 Err(Signal::Throw(value)) => {
2293 let text = self.describe_exception(&value);
2294 self.timer_errors.push(text);
2295 }
2296 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2297 }
2298 self.drain_jobs()?;
2299 Ok(true)
2300 }
2301
2302 /// The descriptors the host has to poll, and in which direction.
2303 ///
2304 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2305 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2306 /// `os_poll` asks for.
2307 pub fn pending_fds(&self) -> Vec<FdInterest> {
2308 self.fd_handlers
2309 .iter()
2310 .map(|(fd, entry)| FdInterest {
2311 fd: *fd,
2312 read: entry.read.is_some(),
2313 write: entry.write.is_some(),
2314 })
2315 .collect()
2316 }
2317
2318 /// Call the handler registered for `fd`, reporting whether one ran.
2319 ///
2320 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2321 /// poll iteration and then restarts the loop, because the handler may have changed the
2322 /// registration list underneath it; doing the same here keeps a handler that
2323 /// unregisters itself from being called with stale state.
2324 ///
2325 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2326 /// every later one, exactly as with timers.
2327 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2328 let Some(entry) = self.fd_handlers.get(&fd) else {
2329 return Ok(false);
2330 };
2331 let callback = if readable {
2332 entry.read.clone()
2333 } else if writable {
2334 entry.write.clone()
2335 } else {
2336 None
2337 };
2338 let Some(callback) = callback else {
2339 return Ok(false);
2340 };
2341 self.drain_jobs()?;
2342 match self.call_value(callback, Value::Undefined, Vec::new()) {
2343 Ok(_) => {}
2344 Err(Signal::Throw(value)) => {
2345 let text = self.describe_exception(&value);
2346 self.timer_errors.push(text);
2347 }
2348 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2349 }
2350 self.drain_jobs()?;
2351 Ok(true)
2352 }
2353
2354 /// Take the errors timer callbacks threw, leaving the list empty.
2355 pub fn take_timer_errors(&mut self) -> Vec<String> {
2356 std::mem::take(&mut self.timer_errors)
2357 }
2358
2359 /// Whether anything is still pending: a microtask or a timer.
2360 pub fn has_pending_work(&self) -> bool {
2361 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2362 }
2363
2364 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2365 pub fn has_pending_timers_or_jobs(&self) -> bool {
2366 !self.jobs.is_empty() || !self.tasks.is_empty()
2367 }
2368
2369 /// Run every queued microtask, including ones queued while draining.
2370 pub fn drain_jobs(&mut self) -> JsResult<()> {
2371 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2372 // would spin forever, so the drain is bounded the way the call stack is.
2373 let mut budget = 1_000_000usize;
2374 while let Some(job) = self.jobs.pop_front() {
2375 if budget == 0 {
2376 return Err(Signal::Throw(
2377 self.make_error("InternalError", "promise job queue did not drain"),
2378 ));
2379 }
2380 budget -= 1;
2381 self.run_job(job)?;
2382 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2383 // engine may run script that the script itself did not ask for. Doing it here
2384 // rather than from a drop hook is what keeps the callback out of arbitrary
2385 // engine bookkeeping — see `builtins::weak`'s header.
2386 crate::builtins::weak::drain_finalizers(self)?;
2387 }
2388 // A script that queued no jobs may still have dropped targets, so the checkpoint
2389 // runs once more after the queue empties.
2390 crate::builtins::weak::drain_finalizers(self)?;
2391 Ok(())
2392 }
2393
2394 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2395 ///
2396 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2397 /// `None` and is swept out here. This is also where the realm learns that a registry
2398 /// died, which is why it is a mutation rather than a read.
2399 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2400 let handles = std::mem::take(&mut self.realm.finalization_registries);
2401 let mut live = Vec::with_capacity(handles.len());
2402 for handle in handles {
2403 let Some(object) = handle.upgrade() else {
2404 continue;
2405 };
2406 let Some(state) = object.finalization_state() else {
2407 continue;
2408 };
2409 live.push((object.clone(), *state));
2410 self.realm.finalization_registries.push(object.downgrade());
2411 }
2412 live
2413 }
2414
2415 /// Run one microtask.
2416 fn run_job(&mut self, job: Job) -> JsResult<()> {
2417 match job {
2418 Job::Reaction {
2419 handler: None,
2420 argument,
2421 rejected,
2422 promise,
2423 } => {
2424 // No handler: the settlement passes straight through to the derived
2425 // promise, which is why `p.catch(f)` ignores fulfilments.
2426 if rejected {
2427 self.reject_promise(&promise, argument);
2428 } else {
2429 self.fulfill_promise(&promise, argument);
2430 }
2431 Ok(())
2432 }
2433 Job::Reaction {
2434 handler: Some(handler),
2435 argument,
2436 promise,
2437 ..
2438 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2439 Ok(answer) => {
2440 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2441 self.reject_promise(&promise, error);
2442 }
2443 Ok(())
2444 }
2445 Err(Signal::Throw(reason)) => {
2446 self.reject_promise(&promise, reason);
2447 Ok(())
2448 }
2449 Err(other) => Err(other),
2450 },
2451 Job::Thenable {
2452 then,
2453 value,
2454 promise,
2455 } => {
2456 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2457 // the value it produces settles `promise`.
2458 // The thenable's `then` gets this promise's own pair, so whatever it
2459 // produces settles `promise`.
2460 let resolve = JsObject::function(
2461 self.heap,
2462 Some(self.realm.function_proto.clone()),
2463 Callable::PromiseResolve(promise.clone()),
2464 );
2465 let reject = JsObject::function(
2466 self.heap,
2467 Some(self.realm.function_proto.clone()),
2468 Callable::PromiseReject(promise.clone()),
2469 );
2470 match self.call_value(
2471 then,
2472 value,
2473 vec![Value::Object(resolve), Value::Object(reject)],
2474 ) {
2475 Ok(_) => Ok(()),
2476 Err(Signal::Throw(reason)) => {
2477 self.reject_promise(&promise, reason);
2478 Ok(())
2479 }
2480 Err(other) => Err(other),
2481 }
2482 }
2483 Job::Resume {
2484 coroutine,
2485 promise,
2486 kind,
2487 value,
2488 } => self.drive_async(&coroutine, &promise, kind, value),
2489 Job::GeneratorResume {
2490 generator,
2491 promise,
2492 kind,
2493 value,
2494 } => self.step_async_generator(&generator, &promise, kind, value),
2495 Job::Import {
2496 specifier,
2497 referrer,
2498 promise,
2499 } => {
2500 self.run_dynamic_import(&specifier, &referrer, &promise);
2501 Ok(())
2502 }
2503 }
2504 }
2505
2506 /// One element of a `Promise` combinator settled.
2507 ///
2508 /// The shared state object holds the result array, the number still outstanding, and
2509 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2510 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2511 /// to settle, only whatever `Sub` said a capability is.
2512 ///
2513 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2514 /// and `any` must ignore every later settlement, and `all` must not report a second
2515 /// rejection after the first.
2516 fn settle_combinator(
2517 &mut self,
2518 state: &Gc<JsObject>,
2519 index: usize,
2520 fulfilled: bool,
2521 value: Value,
2522 ) -> JsResult<()> {
2523 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2524 // Each element settles at most once: a thenable may call `onFulfilled` twice
2525 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2526 // call a no-op. Without it the second call decremented `remaining` again and settled
2527 // `all` with a short values array (`call-resolve-element-items`).
2528 let done = field("done");
2529 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2530 let settled = field("settled").is_some_and(|value| value.to_boolean());
2531 if settled {
2532 return Ok(());
2533 }
2534 if let Some(Value::Object(done)) = &done {
2535 if done
2536 .array_get(index)
2537 .is_some_and(|value| value.to_boolean())
2538 {
2539 return Ok(());
2540 }
2541 done.array_set(self.heap, index, Value::Bool(true));
2542 }
2543 let resolve = field("resolve");
2544 let reject = field("reject");
2545 let keys = field("keys");
2546 let results = field("results").and_then(|value| value.as_object().cloned());
2547 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2548 // promise: the handler is a plain function the constructor chose.
2549 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2550 if let Some(handler) = handler {
2551 interp.call_value(handler, Value::Undefined, vec![value])?;
2552 }
2553 Ok(())
2554 };
2555 match kind {
2556 // `race`: the first settlement wins and stops the rest.
2557 3 => {
2558 state.define_data("settled", Value::Bool(true));
2559 let handler = if fulfilled { resolve } else { reject };
2560 settle_with(self, handler, value)?;
2561 return Ok(());
2562 }
2563 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2564 // the first rejection wins outright.
2565 0 | 4 if !fulfilled => {
2566 state.define_data("settled", Value::Bool(true));
2567 settle_with(self, reject, value)?;
2568 return Ok(());
2569 }
2570 // `any`: the first fulfilment wins.
2571 2 if fulfilled => {
2572 state.define_data("settled", Value::Bool(true));
2573 settle_with(self, resolve, value)?;
2574 return Ok(());
2575 }
2576 _ => {}
2577 }
2578 let Some(results) = &results else {
2579 return Ok(());
2580 };
2581 match kind {
2582 4 => {
2583 results.array_set(self.heap, index, value);
2584 }
2585 0 => {
2586 results.array_set(self.heap, index, value);
2587 }
2588 // `allSettled` (and its keyed twin) never rejects; each slot records what
2589 // happened.
2590 1 | 5 => {
2591 let record = self.new_object(Some(self.realm.object_proto.clone()));
2592 if fulfilled {
2593 record.define_data("status", self.string("fulfilled"));
2594 record.define_data("value", value);
2595 } else {
2596 record.define_data("status", self.string("rejected"));
2597 record.define_data("reason", value);
2598 }
2599 results.array_set(self.heap, index, Value::Object(record));
2600 }
2601 // `any`: a rejection is parked in the errors array and the sweep continues.
2602 2 => {
2603 results.array_set(self.heap, index, value);
2604 }
2605 _ => {}
2606 }
2607 let remaining = field("remaining")
2608 .map(|value| value.to_int32())
2609 .unwrap_or(0);
2610 let left = remaining - 1;
2611 state.define_data("remaining", Value::Int(left));
2612 if left != 0 {
2613 return Ok(());
2614 }
2615 state.define_data("settled", Value::Bool(true));
2616 match kind {
2617 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2618 // The keyed result: an ordinary object with a **null** prototype, holding the
2619 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2620 4 | 5 => {
2621 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2622 settle_with(self, resolve, keyed)?;
2623 }
2624 2 => {
2625 // The rejection is an `AggregateError` whose `errors` is the results array
2626 // itself — the slots are the reasons, in input order.
2627 let errors = results.array_elements().unwrap_or_default();
2628 let error = self.aggregate_error(errors, "all promises were rejected");
2629 settle_with(self, reject, error)?;
2630 }
2631 _ => {}
2632 }
2633 Ok(())
2634 }
2635
2636 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2637 ///
2638 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2639 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2640 /// prototype is load-bearing in both directions: a key called `toString` must not
2641 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2642 /// (`resolves-empty-object.js`).
2643 pub(crate) fn keyed_result_object(
2644 &mut self,
2645 keys: Option<&Value>,
2646 values: &Gc<JsObject>,
2647 ) -> JsResult<Value> {
2648 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2649 return Ok(Value::Object(self.new_object(None)));
2650 };
2651 let result = self.new_object(None);
2652 let count = values.array_length().unwrap_or(0);
2653 for index in 0..count {
2654 let Some(key) = keys.array_get(index) else {
2655 continue;
2656 };
2657 let Some(value) = values.array_get(index) else {
2658 continue;
2659 };
2660 let property = Property::with_attributes(value, true, true);
2661 match &key {
2662 Value::Symbol(symbol) => {
2663 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2664 }
2665 other => {
2666 let text = self.to_js_string(other)?;
2667 result.define_key(&PropertyKey::from(text.as_str()), property);
2668 }
2669 }
2670 }
2671 Ok(Value::Object(result))
2672 }
2673
2674 /// Build an async function's result: a promise whose body runs as a coroutine.
2675 pub fn new_async_function(
2676 &mut self,
2677 function: Value,
2678 this: Value,
2679 args: Vec<Value>,
2680 ) -> JsResult<Value> {
2681 let promise = self.new_promise();
2682 let coroutine = self.new_coroutine(function, this, args)?;
2683 if let Err(Signal::Throw(reason)) =
2684 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2685 {
2686 self.reject_promise(&promise, reason);
2687 }
2688 Ok(Value::Object(promise))
2689 }
2690
2691 /// The coroutine an async body runs in.
2692 ///
2693 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2694 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2695 /// than growing a second state machine. The difference is only in the ending — a
2696 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2697 /// Run `code` as an async function body, answering the promise it settles.
2698 ///
2699 /// Used for a module with top-level `await`: its body is an async function whose
2700 /// caller is the host, so there is no function object to pass through
2701 /// [`Interp::new_async_function`].
2702 pub fn run_async_body(
2703 &mut self,
2704 code: Gc<CompiledCode>,
2705 env: Gc<ClosureEnv>,
2706 this: Value,
2707 ) -> JsResult<Value> {
2708 let promise = self.new_promise();
2709 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2710 if let Err(Signal::Throw(reason)) =
2711 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2712 {
2713 self.reject_promise(&promise, reason);
2714 }
2715 Ok(Value::Object(promise))
2716 }
2717
2718 fn new_coroutine(
2719 &mut self,
2720 function: Value,
2721 this: Value,
2722 args: Vec<Value>,
2723 ) -> JsResult<Gc<JsObject>> {
2724 let Some(object) = function.as_object().cloned() else {
2725 return Err(self.type_error("not a function"));
2726 };
2727 let Some((code, env)) = bytecode_of(&object) else {
2728 return Err(self.type_error("not a function"));
2729 };
2730 self.new_coroutine_from(code, env, this, args)
2731 }
2732
2733 /// Build a coroutine over an already-resolved body.
2734 fn new_coroutine_from(
2735 &mut self,
2736 code: Gc<CompiledCode>,
2737 env: Gc<ClosureEnv>,
2738 this: Value,
2739 args: Vec<Value>,
2740 ) -> JsResult<Gc<JsObject>> {
2741 let function = Value::Undefined;
2742 self.push_frame(code, env, this, args, function)?;
2743 let frame = self.frames.pop().expect("push_frame just pushed it");
2744 let state = GeneratorState {
2745 frame: Some(frame),
2746 phase: GeneratorPhase::SuspendedStart,
2747 parked_on_await: false,
2748 parked_on_yield_star: false,
2749 requests: std::collections::VecDeque::new(),
2750 async_busy: false,
2751 // An `async function` body is driven by `drive_async`, never by the generator
2752 // protocol, and the object is not reachable from script.
2753 is_async: false,
2754 };
2755 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2756 coroutine.with_mut(|data| {
2757 data.kind = ObjectKind::Generator(Box::new(state));
2758 });
2759 Ok(coroutine)
2760 }
2761
2762 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2763 /// `await` and `value` is what it awaited.
2764 fn resume_coroutine(
2765 &mut self,
2766 coroutine: &Gc<JsObject>,
2767 kind: ResumeKind,
2768 value: Value,
2769 ) -> JsResult<(Value, bool)> {
2770 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2771 ObjectKind::Generator(state) => {
2772 let is_async = state.is_async;
2773 Some(std::mem::replace(
2774 state.as_mut(),
2775 GeneratorState {
2776 frame: None,
2777 phase: GeneratorPhase::Executing,
2778 parked_on_await: false,
2779 parked_on_yield_star: false,
2780 requests: std::collections::VecDeque::new(),
2781 async_busy: false,
2782 is_async,
2783 },
2784 ))
2785 }
2786 _ => None,
2787 }) else {
2788 return Err(self.type_error("not a coroutine"));
2789 };
2790 let result = self.step_generator(&mut state, kind, value);
2791 coroutine.with_mut(|data| {
2792 data.kind = ObjectKind::Generator(Box::new(state));
2793 });
2794 let (value, done, _ready, _reason) = result?;
2795 Ok((value, done))
2796 }
2797
2798 /// Advance an async body and settle its promise with the outcome.
2799 fn drive_async(
2800 &mut self,
2801 coroutine: &Gc<JsObject>,
2802 promise: &Gc<JsObject>,
2803 kind: ResumeKind,
2804 value: Value,
2805 ) -> JsResult<()> {
2806 match self.resume_coroutine(coroutine, kind, value) {
2807 Ok((value, true)) => {
2808 // `Ok` with `done` means the body finished *normally*, even when it was
2809 // resumed by a `throw` — `try { await p } catch {}` completes by
2810 // returning. Only the `Err` arm below is a rejection.
2811 //
2812 // Resolving rather than fulfilling matters: `return promise` in an async
2813 // body adopts the inner promise, so `async function f(){ return
2814 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2815 // promise.
2816 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2817 self.reject_promise(promise, reason);
2818 }
2819 Ok(())
2820 }
2821 Ok((value, false)) => {
2822 // Parked on `await`: follow what it awaited and resume with the outcome.
2823 let awaited = match self.promise_resolve_value(value) {
2824 Ok(awaited) => awaited,
2825 Err(Signal::Throw(error)) => {
2826 self.reject_promise(promise, error);
2827 return Ok(());
2828 }
2829 Err(other) => return Err(other),
2830 };
2831 self.hook_await(awaited, coroutine, promise)
2832 }
2833 Err(Signal::Throw(reason)) => {
2834 self.reject_promise(promise, reason);
2835 Ok(())
2836 }
2837 Err(other) => Err(other),
2838 }
2839 }
2840
2841 /// Arrange for `coroutine` to resume when `awaited` settles.
2842 fn hook_await(
2843 &mut self,
2844 awaited: Value,
2845 coroutine: &Gc<JsObject>,
2846 promise: &Gc<JsObject>,
2847 ) -> JsResult<()> {
2848 let resumed = JsObject::function(
2849 self.heap,
2850 Some(self.realm.function_proto.clone()),
2851 Callable::AwaitResume {
2852 coroutine: coroutine.clone(),
2853 promise: promise.clone(),
2854 kind: ResumeKind::Next,
2855 },
2856 );
2857 let raised = JsObject::function(
2858 self.heap,
2859 Some(self.realm.function_proto.clone()),
2860 Callable::AwaitResume {
2861 coroutine: coroutine.clone(),
2862 promise: promise.clone(),
2863 kind: ResumeKind::Throw,
2864 },
2865 );
2866 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2867 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2868 let Value::Object(awaited) = &awaited else {
2869 self.jobs.push_back(Job::Resume {
2870 coroutine: coroutine.clone(),
2871 promise: promise.clone(),
2872 kind: ResumeKind::Next,
2873 value: awaited,
2874 });
2875 return Ok(());
2876 };
2877 self.perform_then(
2878 awaited,
2879 Some(Value::Object(resumed)),
2880 Some(Value::Object(raised)),
2881 )?;
2882 Ok(())
2883 }
2884
2885 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2886 /// things an engine keeps outside it — array elements and an array's `length`.
2887 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2888 if let Some(property) = object.own_property_key(key) {
2889 return Some(property);
2890 }
2891 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2892 // be synthesized too — and every one of them is a plain writable, enumerable,
2893 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2894 // `undefined` before this, which made `key-is-numericindex` fail on its own
2895 // side effect check.
2896 //
2897 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2898 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2899 // likewise not elements however numeric they look.
2900 if object.typed_array_element_type().is_some()
2901 && let Some(numeric) = canonical_numeric_index(key)
2902 && numeric.is_finite()
2903 && numeric.fract() == 0.0
2904 && !(numeric == 0.0 && numeric.is_sign_negative())
2905 && numeric >= 0.0
2906 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
2907 {
2908 let value = object.typed_array_element(numeric as usize)?;
2909 return Some(Property::data(value));
2910 }
2911 // An array's elements live in their own vector rather than the property table, so
2912 // a descriptor for one has to be synthesized — with the attributes an element has.
2913 if let Some(index) = key.as_str().and_then(array_index)
2914 && let Some(value) = object.array_get(index as usize)
2915 && !matches!(value, Value::Hole)
2916 {
2917 return Some(Property::data(value));
2918 }
2919 // `length` is an own property of an array that is not in its property table
2920 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2921 // and non-enumerable.
2922 if key.as_str() == Some("length")
2923 && let Some(length) = object.array_length()
2924 {
2925 return Some(Property {
2926 value: Some(crate::object::length_value(length)),
2927 writable: object.length_writable(),
2928 enumerable: false,
2929 configurable: false,
2930 getter: None,
2931 setter: None,
2932 descriptor_fields: None,
2933 });
2934 }
2935 None
2936 }
2937
2938 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2939 pub fn object_get_own_property(
2940 &mut self,
2941 object: &Gc<JsObject>,
2942 key: &PropertyKey,
2943 ) -> JsResult<Option<Property>> {
2944 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2945 return Ok(answer);
2946 }
2947 if let Some(exotic) = object.exotic()
2948 && let Some(answer) = exotic.get_own_property(self, object, key)?
2949 {
2950 return Ok(answer);
2951 }
2952 // A mapped `arguments` index is a data property as far as script can see: the
2953 // accessor pair that aliases the parameter is plumbing, and exposing it would
2954 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2955 // report a `get` where the spec has a `[[Value]]`.
2956 if let Some(index) = key.as_str().and_then(crate::object::array_index)
2957 && let Some(cell) = object.mapped_argument_cell(index as usize)
2958 {
2959 // Non-configurable is *not* the default: an ordinary mapped index is
2960 // configurable, and only becomes non-configurable once something
2961 // redefines it. Preserve whatever the property table currently says.
2962 // The attributes come from whatever the property table holds, because they
2963 // can be changed independently of the mapping; only the *value* and the
2964 // data-property *kind* are the accessor's secret.
2965 let flags = Self::ordinary_own_property(object, key);
2966 if let Some(existing) = &flags
2967 && !existing.is_accessor()
2968 {
2969 // Already demapped: the table entry is the answer, not the cell.
2970 return Ok(flags);
2971 }
2972 return Ok(Some(Property {
2973 value: Some(cell.get()),
2974 writable: true,
2975 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2976 configurable: flags.as_ref().is_some_and(|p| p.configurable),
2977 ..Property::default()
2978 }));
2979 }
2980 Ok(Self::ordinary_own_property(object, key))
2981 }
2982
2983 /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
2984 ///
2985 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
2986 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
2987 /// abstract operation here rather than a private helper in `error.rs`.
2988 ///
2989 /// The name is the whole point: the setter must behave as if the prototype were not
2990 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
2991 /// the accessor for every error object in the realm. Everything below follows from that:
2992 ///
2993 /// 1. `thisValue` must be an object — otherwise `TypeError`.
2994 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
2995 /// accessor's own home an error rather than a self-shadow.
2996 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
2997 /// either has a string or has made a mistake.
2998 /// 4. An existing *own* property decides the path — an own setter is called, an own
2999 /// non-writable data property is a `TypeError` — and only a missing own property
3000 /// falls through to defining one.
3001 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3002 /// traps and a non-extensible receiver is a `TypeError`.
3003 ///
3004 /// The installed shape is writable + configurable, not enumerable.
3005 pub fn setter_that_ignores_prototype_properties(
3006 &mut self,
3007 this_value: Value,
3008 home: &Gc<JsObject>,
3009 property_key: &str,
3010 args: &[Value],
3011 ) -> JsResult<Value> {
3012 let Some(receiver) = this_value.as_object().cloned() else {
3013 return Err(self.type_error("setter called on a non-object"));
3014 };
3015 if Gc::ptr_eq(&receiver, home) {
3016 return Err(self.type_error("cannot assign to the accessor's own home object"));
3017 }
3018 // No type check here: §7.3.40 takes an arbitrary `v`, and
3019 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3020 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3021 // before calling this.
3022 let value = args.first().cloned().unwrap_or(Value::Undefined);
3023 let key = PropertyKey::from(property_key);
3024 // Step 4: an own property on the receiver changes what happens, and there are three
3025 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3026 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3027 // `Set` with `throw = true`, and a test exists for each.
3028 if let Some(existing) = self.object_get_own_property(&receiver, &key)? {
3029 if existing.is_accessor() && existing.setter.is_none() {
3030 // A getter-only own accessor cannot be written through.
3031 return Err(self.type_error("no setter for the own property"));
3032 }
3033 // Everything else — an own data property, or an own accessor *with* a setter —
3034 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3035 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3036 // an own user setter receives the value (`setter-own-accessor`), because
3037 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3038 // setter directly is the difference between one code path and two that can
3039 // disagree.
3040 self.set_property(&receiver, property_key, value.clone())?;
3041 return Ok(Value::Undefined);
3042 }
3043 let property = Property {
3044 value: Some(value.clone()),
3045 writable: true,
3046 // Enumerable, despite the accessor it shadows not being. The reference installs
3047 // it that way and six cases check it (`setter-creates-own-property` and friends).
3048 enumerable: true,
3049 configurable: true,
3050 ..Property::default()
3051 };
3052 if !self.object_define_own_property(&receiver, &key, property)? {
3053 return Err(self.type_error("the receiver refused the definition"));
3054 }
3055 Ok(Value::Undefined)
3056 }
3057
3058 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3059 ///
3060 /// The indices of a typed array are not properties at all — they are bytes in the
3061 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3062 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3063 /// enumerable and configurable, so a definition can only ever change the *value*, and
3064 /// every other descriptor is refused rather than applied.
3065 ///
3066 /// The order of the checks is the spec's, and two of them are load-bearing:
3067 ///
3068 /// * the index is validated **before** the value is converted, because the conversion
3069 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3070 /// detaches from a `valueOf` and still expects `true` with no store, which only
3071 /// happens when the index was valid on the way in;
3072 /// * the store is attempted even when the index has gone out of bounds by the time the
3073 /// conversion finishes, because the store is a silent no-op rather than a failure —
3074 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3075 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3076 ///
3077 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3078 /// the existing element, which is harmless here: every valid index is already
3079 /// writable, enumerable and configurable, so a `false` in the merged property can only
3080 /// have come from the descriptor having named `false`.
3081 fn integer_indexed_define_own_property(
3082 &mut self,
3083 object: &Gc<JsObject>,
3084 numeric: f64,
3085 property: &Property,
3086 ) -> JsResult<bool> {
3087 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3088 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3089 if !typed_array_index_is_valid(object, numeric) {
3090 return Ok(false);
3091 }
3092 // Step 6: the indices are data properties, so an accessor descriptor is refused
3093 // rather than converted. `Object.defineProperty` turns the `false` into a
3094 // `TypeError`; `Reflect.defineProperty` reports it.
3095 if property.is_accessor() {
3096 return Ok(false);
3097 }
3098 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3099 // definition that asks for anything else cannot be honoured.
3100 if !property.writable || !property.enumerable || !property.configurable {
3101 return Ok(false);
3102 }
3103 // Step 10: only a descriptor that names a value stores anything.
3104 let Some(value) = property.value.clone() else {
3105 return Ok(true);
3106 };
3107 let Some(element) = object.typed_array_element_type() else {
3108 return Ok(false);
3109 };
3110 let stored = self.element_value(element, value)?;
3111 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3112 return Err(self.type_error(reason));
3113 }
3114 Ok(true)
3115 }
3116
3117 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3118 pub fn object_define_own_property(
3119 &mut self,
3120 object: &Gc<JsObject>,
3121 key: &PropertyKey,
3122 property: Property,
3123 ) -> JsResult<bool> {
3124 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3125 return Ok(accepted);
3126 }
3127 // A proxy always answers above — with `Some` from its trap, or with `None` when
3128 // the trap is absent, and then the definition belongs to the **target**
3129 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3130 // when there is no trap). Falling through to the ordinary path here defined the
3131 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3132 // property the target never saw.
3133 if object.proxy_state().is_some() {
3134 let Some((target, _handler)) = self.proxy_parts(object)? else {
3135 return Err(self.type_error("cannot use a proxy that has been revoked"));
3136 };
3137 return self.object_define_own_property(&target, key, property);
3138 }
3139 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3140 // they accept exactly one descriptor shape. This has to happen before the
3141 // ordinary path, which would happily store a data property next to the buffer —
3142 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3143 // and `TypedArray/prototype/set` are about this section.
3144 if object.typed_array_element_type().is_some()
3145 && let Some(index) = canonical_numeric_index(key)
3146 {
3147 return self.integer_indexed_define_own_property(object, index, &property);
3148 }
3149 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3150 // non-extensible object. The check lives here rather than in the callers because
3151 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3152 // `Array.prototype.filter` uses to store its result, and a species object made
3153 // non-extensible by its own constructor must make that a `TypeError`
3154 // (`target-array-non-extensible`).
3155 // Note the `is_none()`: an already-present property may still be **redefined** on a
3156 // non-extensible object, and only *adding* one is refused (as Distinct from
3157 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3158 // properties — testing extensibility before looking for the property made every
3159 // `Object.freeze` of an ordinary object refuse its own second step).
3160 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3161 return Ok(false);
3162 }
3163 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3164 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3165 // an omitted field is left alone). Merging here rather than at each call site is
3166 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3167 // the value and `enumerable` in place.
3168 //
3169 // The merge is a no-op when the property is absent: there is nothing to keep.
3170 let was_partial = property.descriptor_fields.is_some();
3171 let property = match property.descriptor_fields {
3172 None => property,
3173 Some(fields) => {
3174 let base = self.object_get_own_property(object, key)?;
3175 let mut merged = base.clone().unwrap_or_default();
3176 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3177 // descriptor names, and switching kind discards the other half —
3178 // `{set: f}` on a data property is an accessor with no getter, not a data
3179 // property whose `get` happens to be absent.
3180 let wants_accessor = fields.get || fields.set;
3181 let wants_data = fields.value || fields.writable;
3182 if wants_accessor {
3183 merged.value = None;
3184 merged.writable = false;
3185 merged.getter = property.getter.clone();
3186 merged.setter = property.setter.clone();
3187 } else if wants_data {
3188 merged.getter = None;
3189 merged.setter = None;
3190 if fields.value {
3191 merged.value = property.value.clone();
3192 }
3193 if fields.writable {
3194 merged.writable = property.writable;
3195 }
3196 }
3197 if fields.enumerable {
3198 merged.enumerable = property.enumerable;
3199 }
3200 if fields.configurable {
3201 merged.configurable = property.configurable;
3202 }
3203 merged.descriptor_fields = None;
3204 merged
3205 }
3206 };
3207 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3208 // descriptor. `define_property_on` runs the same check before it calls here, so an
3209 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3210 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3211 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3212 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3213 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3214 // own define would have refused.
3215 //
3216 // Only partial descriptors are validated here. A whole `Property` passed by an
3217 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3218 // what the descriptor "named", and those callers rely on the write landing.
3219 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3220 // Every branch below is gated on `!existing.configurable`: a *configurable*
3221 // property may be reshaped however the descriptor likes, which is why an
3222 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3223 // must succeed. Testing only `writable` refused that and broke
3224 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3225 let same_kind = existing.is_accessor() == property.is_accessor();
3226 if !same_kind {
3227 // Step 4: a non-configurable property may not change kind.
3228 if !existing.configurable {
3229 return Ok(false);
3230 }
3231 } else if existing.is_accessor() {
3232 // Step 6: an accessor's halves are its value.
3233 if !existing.configurable
3234 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3235 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3236 {
3237 return Ok(false);
3238 }
3239 } else if !existing.configurable && !existing.writable {
3240 // Step 7: a non-configurable *and* non-writable data property's value is
3241 // fixed, and it may not become writable again.
3242 if property.writable {
3243 return Ok(false);
3244 }
3245 let current = existing.value.clone().unwrap_or(Value::Undefined);
3246 let requested = property.value.clone().unwrap_or(Value::Undefined);
3247 if !current.same_value(&requested) {
3248 return Ok(false);
3249 }
3250 }
3251 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3252 // is frozen with it.
3253 if !existing.configurable
3254 && (property.configurable || property.enumerable != existing.enumerable)
3255 {
3256 return Ok(false);
3257 }
3258 }
3259 // A host class that intercepts definitions owns the attributes of the properties it
3260 // defines: `_class`-style storage on the native side is the usual reason.
3261 if let Some(exotic) = object.exotic()
3262 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3263 {
3264 return Ok(accepted);
3265 }
3266 // An array index is stored in the element vector, which can hold a plain value and
3267 // nothing else. An accessor — or a data property with non-default attributes —
3268 // therefore has to live in the property table, and the element slot is blanked so
3269 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3270 // {get})` stored the accessor where no read ever looked, and the array kept
3271 // answering its old value.
3272 // An array's `length` is not stored in the property table, so defining it has to
3273 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3274 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3275 // {value: 1})` reported success and changed nothing.
3276 if key.as_str() == Some("length") && object.is_array() {
3277 // `{writable: false}` on `length` does not change the length, but it does make
3278 // it read-only — after which neither a later `{writable: true}` nor a store
3279 // past the end may succeed.
3280 if property.value.is_none() {
3281 if !object.length_writable() && property.writable {
3282 return Ok(false);
3283 }
3284 object.set_length_writable(property.writable);
3285 return Ok(true);
3286 }
3287 if !object.length_writable() {
3288 return Ok(false);
3289 }
3290 }
3291 if key.as_str() == Some("length")
3292 && object.is_array()
3293 && let Some(value) = property.value.clone()
3294 {
3295 let requested = value.to_number();
3296 let valid = requested.is_finite()
3297 && requested >= 0.0
3298 && requested.fract() == 0.0
3299 && requested <= u32::MAX as f64;
3300 if !valid {
3301 return Err(self.range_error("invalid array length"));
3302 }
3303 // Truncating deletes the elements above the new length, and a non-configurable
3304 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3305 // makes `a.length = 2` fail rather than quietly drop it.
3306 let current = object.array_length().unwrap_or(0);
3307 let requested = requested as usize;
3308 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3309 return Ok(false);
3310 }
3311 object.array_set_length(self.heap, requested);
3312 return Ok(true);
3313 }
3314 let plain = property.writable
3315 && property.enumerable
3316 && property.configurable
3317 && !property.is_accessor();
3318 if let Some(index) = key.as_str().and_then(array_index)
3319 && object.is_array()
3320 {
3321 // Growing the array needs a writable `length`: after
3322 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3323 // be added.
3324 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3325 return Ok(false);
3326 }
3327 if plain && property.value.is_some() {
3328 // An ordinary element: the vector is where a read looks first, so it has
3329 // to be the vector that changes — unless the index is too far out to be
3330 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3331 // one property, because past its own limit it stores the index as an
3332 // ordinary key. Falling through to `define_key` below is the same choice,
3333 // and the alternative was worse: the store used to be *dropped* and the
3334 // length left at 0, which is a silent wrong answer.
3335 let value = property.value.clone().unwrap_or(Value::Undefined);
3336 object.delete_key(key);
3337 if object.array_set(self.heap, index as usize, value) {
3338 return Ok(true);
3339 }
3340 // Past the dense limit the element lives in the table like any property.
3341 object.note_element_descriptor();
3342 object.define_key(key, property);
3343 // A sparse store past the dense limit still extends `length`, which is what
3344 // `a[a.length] = v` relies on — but only extends: shortening would delete
3345 // the sparse properties above the index, including this one.
3346 if index as usize + 1 > object.array_length().unwrap_or(0) {
3347 object.array_set_length(self.heap, index as usize + 1);
3348 }
3349 return Ok(true);
3350 }
3351 // A non-plain element — an accessor, or an attribute that is not the default —
3352 // lives in the table while the slot becomes a hole. Recording it keeps every
3353 // later `a[i] = v` off the dense path, where the write would have shadowed the
3354 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3355 // replace the accessor with a plain data property.
3356 object.note_element_descriptor();
3357 object.define_key(key, property);
3358 // The slot stays, so `length` does not shrink; a hole is not an element, so
3359 // the table entry is now what a read finds.
3360 object.array_set(self.heap, index as usize, Value::Hole);
3361 return Ok(true);
3362 }
3363 object.define_key(key, property);
3364 Ok(true)
3365 }
3366
3367 /// Build a proxy object over `target`, with its traps read from `handler`.
3368 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3369 JsObject::proxy(self.heap, target, handler)
3370 }
3371
3372 /// The `revoke` function for a proxy's slots.
3373 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3374 let revoke = JsObject::function(
3375 self.heap,
3376 Some(self.realm.function_proto.clone()),
3377 Callable::Revoker(slots),
3378 );
3379 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3380 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3381 // inherited from `Function.prototype` reads the same but fails the three cases that
3382 // check the own-property list (`revocation-function-{length,name,property-order}`).
3383 revoke.define("length", Property::name_or_length(Value::Int(0)));
3384 revoke.define("name", Property::name_or_length(self.string("")));
3385 revoke
3386 }
3387
3388 /// A new array.
3389 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3390 let array = JsObject::array(
3391 self.heap,
3392 Some(self.realm.array_proto.clone()),
3393 elements.len(),
3394 );
3395 for (index, element) in elements.into_iter().enumerate() {
3396 array.array_set(self.heap, index, element);
3397 }
3398 array
3399 }
3400
3401 /// A new native function object.
3402 ///
3403 /// The observable `name` and `length` are installed as properties here, which is
3404 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3405 /// so `f.name = "x"` behaves like the writable property it is.
3406 /// A native constructor that builds its own instance after validating its arguments.
3407 ///
3408 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3409 /// check runs before `new.target.prototype` is read.
3410 pub fn new_native_ctor(
3411 &self,
3412 name: impl Into<String>,
3413 length: u32,
3414 func: NativeFn,
3415 ) -> Gc<JsObject> {
3416 let function = JsObject::function(
3417 self.heap,
3418 Some(self.realm.function_proto.clone()),
3419 Callable::Native {
3420 func,
3421 own_instance: true,
3422 },
3423 );
3424 function.set_constructible(true);
3425 function.define(
3426 "length",
3427 Property::name_or_length(Value::Int(length as i32)),
3428 );
3429 function.define("name", Property::name_or_length(self.string(name)));
3430 function
3431 }
3432
3433 /// A native constructor that lets `new` build the instance first.
3434 ///
3435 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3436 /// validation that must precede reading `new.target.prototype`, so the object can be
3437 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3438 /// which makes a *method* and therefore not a constructor at all.
3439 pub fn new_native_constructor(
3440 &self,
3441 name: impl Into<String>,
3442 length: u32,
3443 func: NativeFn,
3444 ) -> Gc<JsObject> {
3445 let function = self.new_native(name, length, func);
3446 function.set_constructible(true);
3447 function
3448 }
3449
3450 /// A new host function object: a native closure that carries its own state.
3451 ///
3452 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3453 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3454 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3455 /// this safe: the closure must not capture a `Gc`.
3456 pub fn new_host_function(
3457 &self,
3458 name: impl Into<String>,
3459 length: u32,
3460 func: crate::object::HostFn,
3461 ) -> Gc<JsObject> {
3462 self.new_host_inner(name.into(), length, func, false)
3463 }
3464
3465 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3466 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3467 pub fn new_host_ctor(
3468 &self,
3469 name: impl Into<String>,
3470 length: u32,
3471 func: crate::object::HostFn,
3472 ) -> Gc<JsObject> {
3473 let function = self.new_host_inner(name.into(), length, func, true);
3474 function.set_constructible(true);
3475 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3476 // installs its own methods on it, so it starts as a plain object.
3477 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3478 function.define(
3479 "prototype",
3480 Property {
3481 value: Some(Value::Object(proto)),
3482 writable: true,
3483 enumerable: false,
3484 configurable: false,
3485 ..Property::default()
3486 },
3487 );
3488 function
3489 }
3490
3491 fn new_host_inner(
3492 &self,
3493 name: String,
3494 length: u32,
3495 func: crate::object::HostFn,
3496 own_instance: bool,
3497 ) -> Gc<JsObject> {
3498 let function = JsObject::function(
3499 self.heap,
3500 Some(self.realm.function_proto.clone()),
3501 Callable::Host {
3502 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3503 own_instance,
3504 },
3505 );
3506 function.define(
3507 "length",
3508 Property::name_or_length(Value::Int(length as i32)),
3509 );
3510 function.define("name", Property::name_or_length(self.string(name)));
3511 function
3512 }
3513
3514 /// A callable object with the `length`/`name` a built-in function has, in that order.
3515 ///
3516 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3517 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3518 /// [`JsObject::function`] defines neither, which is why every capability helper built
3519 /// with it reported no own `length` and no own `name` at all.
3520 ///
3521 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3522 /// configurable.
3523 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3524 let function =
3525 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3526 function.define(
3527 "length",
3528 Property::name_or_length(Value::Int(length as i32)),
3529 );
3530 function.define("name", Property::name_or_length(self.string(name)));
3531 function
3532 }
3533
3534 /// A new native function object.
3535 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3536 let function = JsObject::function(
3537 self.heap,
3538 Some(self.realm.function_proto.clone()),
3539 Callable::Native {
3540 func,
3541 own_instance: false,
3542 },
3543 );
3544 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3545 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3546 // `length,name` and this listed `name,length`. A bytecode function already gets it
3547 // the right way round; only native ones were built backwards.
3548 function.define(
3549 "length",
3550 Property::name_or_length(Value::Int(length as i32)),
3551 );
3552 function.define("name", Property::name_or_length(self.string(name)));
3553 function
3554 }
3555
3556 /// A new bound function.
3557 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3558 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3559 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3560 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3561 let constructible = target
3562 .as_object()
3563 .is_some_and(|target| target.is_constructor());
3564 let bound = JsObject::function(
3565 self.heap,
3566 Some(self.realm.function_proto.clone()),
3567 Callable::Bound { target, this, args },
3568 );
3569 bound.set_constructible(constructible);
3570 bound
3571 }
3572
3573 /// A new reference cell.
3574 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3575 Gc::new(self.heap, Cell::new(value))
3576 }
3577
3578 // -- running ------------------------------------------------------------
3579
3580 /// Evaluate `code` as a script body and return its completion value.
3581 /// Compile and run `source` for the engine's own use, returning its completion value.
3582 ///
3583 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3584 /// needs to be a real async function, and the engine already runs those as coroutines,
3585 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3586 ///
3587 /// Differences from [`Self::eval_in_global`], both deliberate:
3588 ///
3589 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3590 /// being built, and the source is an IIFE that only constructs a closure, so there
3591 /// is nothing to drain — and draining here would run script-queued jobs in the
3592 /// middle of `install`.
3593 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3594 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3595 /// and it should not look like the user wrote something wrong.
3596 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3597 let program = match js_parse::parse_script(source) {
3598 Ok(program) => program,
3599 Err(error) => {
3600 let message = format!("builtin source does not parse: {error}");
3601 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3602 }
3603 };
3604 let mut code = match js_compile::compile_script_with_source(&program, source) {
3605 Ok(code) => code,
3606 Err(error) => {
3607 let message = format!("builtin source does not compile: {}", error.message);
3608 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3609 }
3610 };
3611 // The frame has to name something, and `<builtin>` is what a stack trace through
3612 // this code should say.
3613 code.set_filename("<builtin>");
3614 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3615 let closure_vars = compiled.code.closure_vars.clone();
3616 let env = self.global_env(&closure_vars);
3617 let this = Value::Object(self.realm.global.clone());
3618 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3619 }
3620
3621 /// Run an already-parsed script and drain the microtasks it queued.
3622 ///
3623 /// The drain is what lets an `async` function's body advance past its first `await`
3624 /// before the host sees the result: nothing else pumps the job queue.
3625 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3626 let this = Value::Object(self.realm.global.clone());
3627 self.run_script_with_this(code, this)
3628 }
3629
3630 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3631 ///
3632 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3633 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3634 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3635 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3636 /// state the next script evaluation tripped over.
3637 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3638 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3639 let closure_vars = compiled.code.closure_vars.clone();
3640 let env = self.global_env(&closure_vars);
3641 let callee = Value::Undefined;
3642 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3643 // The script is done, so the microtasks it queued run before the host sees the
3644 // result. Without this an `async` function's body would never advance past its
3645 // first `await`, because nothing else drains the queue.
3646 self.drain_jobs()?;
3647 Ok(result)
3648 }
3649
3650 /// Compile and run `source` in global scope, returning its completion value.
3651 ///
3652 /// This is what `eval` and `new Function` use. Running it as a script means it
3653 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3654 /// for a `Function` body; a *direct* eval that reads a local variable would need
3655 /// the compiler to hand its variable environment over, which is not implemented.
3656 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3657 self.eval_in_global_named(source, EVAL_FILE, false)
3658 }
3659
3660 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3661 ///
3662 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3663 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3664 /// through the code, so they cannot share one constant.
3665 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3666 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3667 }
3668
3669 /// Evaluate `source` as a global script, reported under `file`.
3670 ///
3671 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3672 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3673 /// from inside a C callback, where the interpreter is the running one rather than a
3674 /// context's own.
3675 pub fn eval_in_global_named(
3676 &mut self,
3677 source: &str,
3678 file: &str,
3679 barrier: bool,
3680 ) -> JsResult<Value> {
3681 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3682 // eval-created global binding — configurable, unlike a script's own `var`.
3683 self.eval_depth += 1;
3684 if barrier {
3685 let depth = self.frames.len();
3686 self.trace_barriers.push(depth);
3687 }
3688 let result = self.eval_in_global_inner(source, file);
3689 if barrier {
3690 self.trace_barriers.pop();
3691 }
3692 self.eval_depth -= 1;
3693 result
3694 }
3695
3696 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3697 let compiled = self.compile_global_script(source, file, false)?;
3698 let strict = compiled.strict;
3699 self.run_eval_script(compiled, strict)
3700 }
3701
3702 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3703 ///
3704 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3705 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3706 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3707 /// direct eval's is.
3708 pub fn eval_script_with_this(
3709 &mut self,
3710 source: &str,
3711 file: &str,
3712 this: Value,
3713 ) -> JsResult<Value> {
3714 let program = match js_parse::parse_script(source) {
3715 Ok(program) => program,
3716 Err(error) => {
3717 return Err(Signal::Throw(self.syntax_error_at(
3718 file,
3719 error.span.start.line,
3720 error.span.start.column,
3721 &error.message,
3722 )));
3723 }
3724 };
3725 let mut compiled = match js_compile::compile_script(&program) {
3726 Ok(compiled) => compiled,
3727 Err(error) => {
3728 return Err(Signal::Throw(self.syntax_error_at(
3729 file,
3730 error.span.start.line,
3731 error.span.start.column,
3732 &error.message,
3733 )));
3734 }
3735 };
3736 compiled.set_filename(file);
3737 self.run_script_with_this(compiled, this)
3738 }
3739
3740 /// Parse and compile `source` as a global script, without running it.
3741 ///
3742 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3743 /// before a promise exists to reject — while still evaluating in the same eval context
3744 /// (direct-eval strictness, `new.target`, `super`).
3745 fn compile_global_script(
3746 &mut self,
3747 source: &str,
3748 file: &str,
3749 async_body: bool,
3750 ) -> JsResult<CompiledFunction> {
3751 // A *direct* eval inherits the strictness of the code that called it, which is
3752 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3753 // implicit global. The caller's frame is the innermost one here, because a
3754 // native function does not push a frame of its own.
3755 let strict = self.current_strict();
3756 // `eval` runs in the caller's function context, so `new.target` is legal here
3757 // even though the source is a bare script — and so is `super.x` when the caller
3758 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3759 // caller's, which is what `special_object 4` already does.
3760 let context = js_parse::EvalContext {
3761 in_method: self.enclosing_home_object().is_some(),
3762 // `super()` belongs to a derived constructor, and an eval'd body is not a
3763 // constructor at all: the caller frame's `this` is already built.
3764 in_derived_constructor: false,
3765 };
3766 // A *global* eval is not a function body: `new.target` and `super` are out of
3767 // reach there. Its `{async: true}` form differs in the other direction — the body
3768 // may `await` — so the two flags are independent and the reference sets both from
3769 // the eval type rather than from the caller.
3770 let parsed = if async_body {
3771 js_parse::parse_suspensible_global_eval(source, strict)
3772 } else {
3773 js_parse::parse_eval_script_in(source, strict, context)
3774 };
3775 let program = match parsed {
3776 Ok(program) => program,
3777 Err(error) => {
3778 // The message is bare: the position lives in `fileName`,
3779 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3780 // the reference puts it. An `invalid source: L:C: ` prefix made
3781 // `e.message` differ from the reference while the stack already agreed.
3782 return Err(Signal::Throw(self.syntax_error_at(
3783 file,
3784 error.span.start.line,
3785 error.span.start.column,
3786 &error.message,
3787 )));
3788 }
3789 };
3790 let mut compiled = match if async_body {
3791 js_compile::compile_script_suspensible(&program)
3792 } else {
3793 js_compile::compile_script(&program)
3794 } {
3795 Ok(compiled) => compiled,
3796 // A construct the compiler does not handle yet is reported the same way a
3797 // parse error is: it happens before anything runs, so the trace is the
3798 // position in the source followed by the caller.
3799 Err(error) => {
3800 return Err(Signal::Throw(self.syntax_error_at(
3801 file,
3802 error.span.start.line,
3803 error.span.start.column,
3804 &error.message,
3805 )));
3806 }
3807 };
3808 compiled.set_filename(file);
3809 Ok(compiled)
3810 }
3811
3812 /// Run an `eval`'d script in the caller's scope.
3813 ///
3814 /// Three things have to come from the calling frame, because the eval'd code is a
3815 /// script and would otherwise see only the global object:
3816 ///
3817 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3818 /// * `arguments`, exposed as a binding of the eval's own scope, so
3819 /// `f("arguments.length", 1)` sees the caller's arguments;
3820 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3821 /// `eval("var v = 1")` into the global object.
3822 ///
3823 /// Locals of the calling function are *not* reachable: that needs the compiler to
3824 /// hand its variable environment over, which this milestone does not do.
3825 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3826 // `this` and `arguments` come from the innermost frame only — those are not
3827 // lexical — while the name bindings come from the whole chain of frames, part
3828 // of it being ordinary scope resolution.
3829 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3830 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3831 // read from its closure.
3832 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3833 // variable environment is the innermost frame of all: an arrow's own body is where
3834 // `var`s declared by an `eval` inside it belong.
3835 let caller_index = self
3836 .frames
3837 .iter()
3838 .rposition(|frame| !frame.code.code.is_arrow)
3839 .or_else(|| self.frames.len().checked_sub(1));
3840 let env_index = self.frames.len().checked_sub(1);
3841 let caller = caller_index.and_then(|index| self.frames.get(index));
3842 let (this, passed) = match caller {
3843 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3844 // No frame at all: the eval is running at the top level, so there is
3845 // nothing to inherit and the global receiver is right.
3846 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3847 };
3848 // Innermost frame first, so the first binding found for a name is the one that
3849 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3850 let mut bindings: Vec<EvalBinding> = Vec::new();
3851 // The calling function's own bindings, resolved by the compiler at the call
3852 // site. That table is the only reliable answer when a name is declared twice in
3853 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3854 // body means, and guessing by declaration order picks the wrong one as soon as
3855 // two loops in a row use the same name.
3856 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3857 // every direct call — a bare `eval(...)` callee — so finding one at the current
3858 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3859 // callee to a value first and leave no site behind.
3860 let mut direct = false;
3861 let mut resolved_here = false;
3862 if let Some(frame) = self.frames.last() {
3863 let (line, column) = frame
3864 .code
3865 .code
3866 .position_at(frame.at as u32)
3867 .unwrap_or_default();
3868 // The nearest site at or before the current position, not an exact match:
3869 // the recorded position of the `call` instruction is the callee's, which
3870 // sits a few columns inside the call expression the compiler recorded. A
3871 // site is unique per call, so "the closest one behind us" identifies it.
3872 if let Some(site) = frame
3873 .code
3874 .code
3875 .eval_sites
3876 .iter()
3877 .filter(|site| (site.line, site.column) <= (line, column))
3878 .max_by_key(|site| (site.line, site.column))
3879 {
3880 direct = true;
3881 resolved_here = true;
3882 for binding in &site.bindings {
3883 // An enclosing function's frame sits `owner` levels below the one
3884 // running the call.
3885 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3886 else {
3887 continue;
3888 };
3889 bindings.push(EvalBinding {
3890 name: binding.name.clone(),
3891 frame,
3892 slot: if binding.is_arg {
3893 EvalSlot::Arg
3894 } else {
3895 EvalSlot::Local
3896 },
3897 index: binding.index as usize,
3898 });
3899 }
3900 }
3901 }
3902 for frame_index in (0..self.frames.len()).rev() {
3903 // Skip the innermost frame's flat scan when the compiler already answered
3904 // for it; an enclosing frame still needs one, because the eval resolves
3905 // those names dynamically.
3906 if resolved_here && frame_index == self.frames.len() - 1 {
3907 continue;
3908 }
3909 let frame = &self.frames[frame_index];
3910 for (index, arg) in frame.code.code.args.iter().enumerate() {
3911 bindings.push(EvalBinding {
3912 name: arg.name.clone(),
3913 frame: frame_index,
3914 slot: EvalSlot::Arg,
3915 index,
3916 });
3917 }
3918 for (index, local) in frame.code.code.vars.iter().enumerate() {
3919 bindings.push(EvalBinding {
3920 name: local.name.clone(),
3921 frame: frame_index,
3922 slot: EvalSlot::Local,
3923 index,
3924 });
3925 }
3926 }
3927 let mut seen = BTreeSet::new();
3928 bindings.retain(|binding| seen.insert(binding.name.clone()));
3929
3930 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3931 // elements is all the spec's ordinary uses need.
3932 //
3933 // Known divergence: this is bound for a *global* eval too, where there is no
3934 // caller and the reference throws `'arguments' is not defined`. Deciding properly
3935 // needs "does the calling frame have an `arguments` of its own", which is not
3936 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3937 // script or eval body does not, and `eval(b)` passes the callee as a value so even
3938 // the call-site detection does not answer it. Modelled as a binding in the caller's
3939 // variable environment, this would fall out; that is a larger change than the one
3940 // this comment is attached to.
3941 let arguments = Value::Object(self.new_array(passed));
3942
3943 // Only a *strict* eval gets a variable environment of its own. A sloppy one
3944 // declares its `var`s in the caller's — which for a top-level eval is the global
3945 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3946 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3947 // vanish into a scope nobody reads back from.
3948 let previous_scope = if code_strict {
3949 self.eval_scope.replace(BTreeMap::new())
3950 } else {
3951 None
3952 };
3953 let previous_arguments = self.eval_arguments.replace(arguments);
3954 let previous_with = self.eval_with.replace(self.with_objects());
3955 let inherited_new_target = self
3956 .frames
3957 .iter()
3958 .rev()
3959 .find(|frame| !frame.code.code.is_arrow)
3960 .map(|frame| frame.new_target.clone());
3961 let previous_new_target = self
3962 .eval_new_target
3963 .replace(inherited_new_target.unwrap_or(Value::Undefined));
3964 let eval_cells = self.eval_cells_for(&bindings);
3965 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3966 // A sloppy direct eval declares its `var`s in the caller's variable environment;
3967 // `declare_eval_local` needs to know which frame that is.
3968 // An indirect eval gets the global environment, so nothing of the caller's is
3969 // recorded as the place its `var`s belong.
3970 let previous_caller = self
3971 .eval_caller
3972 .replace(if direct { env_index } else { None });
3973 // The cell-based view of the same bindings, which is what a closure created
3974 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3975 // whose compiler did not put a binding in a cell simply does not appear here —
3976 // reads and writes still work through `eval_bindings`, they just cannot outlive
3977 // the eval.
3978 let previous_eval_scope = self
3979 .active_eval_scope
3980 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3981 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3982 let closure_vars = compiled.code.closure_vars.clone();
3983 let env = self.global_env(&closure_vars);
3984 let callee = Value::Undefined;
3985 // An async body does not run here: it becomes a coroutine and answers a promise,
3986 // which is what makes `await` legal in it. `this` still has to be the caller's
3987 // (for a global eval, the global object), because `this` is not part of `await`.
3988 let result = if compiled.code.kind.is_async() {
3989 self.run_async_body(compiled, env, this)
3990 } else {
3991 self.execute(compiled, env, this, Vec::new(), callee)
3992 };
3993 self.eval_scope = previous_scope;
3994 self.eval_arguments = previous_arguments;
3995 self.eval_with = previous_with;
3996 self.eval_new_target = previous_new_target;
3997 self.eval_bindings = previous_bindings;
3998 self.eval_caller = previous_caller;
3999 self.active_eval_scope = previous_eval_scope;
4000 result
4001 }
4002
4003 /// The cell-backed subset of `bindings`, in the same priority order.
4004 ///
4005 /// Both lookup routes have to agree — the eval's own reads go through
4006 /// [`Interp::eval_binding_value`] and the closures it builds go through
4007 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4008 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4009 /// is not in a cell simply does not appear: reads and writes still work, they just
4010 /// cannot be handed to a closure that outlives the eval.
4011 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4012 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4013 for binding in bindings {
4014 let Some(frame) = self.frames.get(binding.frame) else {
4015 continue;
4016 };
4017 let cell = match binding.slot {
4018 EvalSlot::Arg => frame
4019 .code
4020 .arg_cell
4021 .get(binding.index)
4022 .copied()
4023 .unwrap_or(-1),
4024 EvalSlot::Local => frame
4025 .code
4026 .loc_cell
4027 .get(binding.index)
4028 .copied()
4029 .unwrap_or(-1),
4030 };
4031 if cell < 0 {
4032 continue;
4033 }
4034 if let Some(cell) = frame.cells.get(cell as usize) {
4035 names.push((binding.name.clone(), cell.clone()));
4036 }
4037 }
4038 names
4039 }
4040
4041 /// A `SyntaxError` that reports where in the source it happened.
4042 ///
4043 /// Compile-time failures never run, so they have no frame of their own; the
4044 /// reference still puts the position first in the trace, with no function name and
4045 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4046 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4047 /// reference borrows), which is how a script reads the position without parsing
4048 /// the trace.
4049 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4050 ///
4051 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4052 /// `columnNumber`, which is how the reference prints one. A positionless error
4053 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4054 /// the reference raises it from `js_resolve_module`, where there is no position.
4055 pub(crate) fn syntax_error_plain(
4056 &mut self,
4057 error: &js_parse::SyntaxError,
4058 file: &str,
4059 ) -> Value {
4060 if error.positionless {
4061 return self.make_error("SyntaxError", &error.message);
4062 }
4063 self.syntax_error_at(
4064 file,
4065 error.span.start.line,
4066 error.span.start.column,
4067 &error.message,
4068 )
4069 }
4070
4071 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4072 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4073 let value = self.make_error("SyntaxError", message);
4074 if let Value::Object(object) = &value {
4075 let text = self.string(blamed);
4076 // `stack` is an own data property, and the reference keeps it
4077 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4078 object.define("stack", Property::with_attributes(text, true, false));
4079 let name = self.string(file);
4080 object.define("fileName", Property::with_attributes(name, true, true));
4081 object.define(
4082 "lineNumber",
4083 Property::with_attributes(Value::Int(line as i32), true, true),
4084 );
4085 object.define(
4086 "columnNumber",
4087 Property::with_attributes(Value::Int(column as i32), true, true),
4088 );
4089 }
4090 value
4091 }
4092
4093 /// Run a compiled script whose completion value is a function, returning it.
4094 ///
4095 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4096 /// get the closure out, which keeps the constant-pool plumbing in one place.
4097 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4098 self.run_script(code)
4099 }
4100
4101 /// The environment of a script or of any function compiled at global scope:
4102 /// every entry is a global binding, so each one resolves to the realm's cell.
4103 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4104 let mut cells = Vec::with_capacity(closure_vars.len());
4105 for closure_var in closure_vars {
4106 let cell = match closure_var.closure_type {
4107 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4108 if closure_var.is_lexical =>
4109 {
4110 // A lexical declaration: the cell is created here holding the
4111 // dead-zone marker, which is what makes the binding exist and
4112 // unreadable before its initialiser runs.
4113 self.declare_global(&closure_var.name, closure_var.is_const);
4114 self.realm.globals[&closure_var.name].clone()
4115 }
4116 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4117 // A `var` or function declaration becomes a property of the global
4118 // object, and it exists from here on — which is why
4119 // `print(v); var v = 1` prints `undefined` instead of raising.
4120 // Declaring it at instantiation time (rather than at the
4121 // initialiser) is also what makes it non-configurable: the store
4122 // then lands on an existing property instead of creating one.
4123 self.declare_var_global(&closure_var.name);
4124 // The cell is a placeholder that nothing indexes; it cannot be
4125 // omitted because the slot has to hold something.
4126 self.new_cell(Value::Undefined)
4127 }
4128 _ => {
4129 // An undeclared global is read by name; the cell is a
4130 // placeholder that nothing indexes.
4131 self.new_cell(Value::Undefined)
4132 }
4133 };
4134 cells.push(cell);
4135 }
4136 Gc::new(
4137 self.heap,
4138 ClosureEnv {
4139 cells,
4140 eval_scope: None,
4141 local_vars: None,
4142 local_phase: 1,
4143 },
4144 )
4145 }
4146
4147 /// Push a frame and run until it returns.
4148 pub(crate) fn execute(
4149 &mut self,
4150 code: Gc<CompiledCode>,
4151 env: Gc<ClosureEnv>,
4152 this: Value,
4153 args: Vec<Value>,
4154 callee: Value,
4155 ) -> JsResult<Value> {
4156 let depth = self.frames.len();
4157 if depth == 0 {
4158 // A throw that reached the host ends the *active* mode: the next one is catchable
4159 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4160 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4161 // for the throw that evaluation will raise.
4162 self.uncatchable = false;
4163 }
4164 self.push_frame(code, env, this, args, callee)?;
4165 loop {
4166 // The fast loop first: it runs whole runs of records with `pc` in a register.
4167 //
4168 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4169 // reads it again — a store, a load and two bounds checks that a loop body does
4170 // not need, because nothing outside the loop can run in between. This is the
4171 // classic split: advance a register, and only spill it when leaving.
4172 //
4173 // `Some(value)` means the function ended by running off the end of its
4174 // instruction array, which is a normal return.
4175 let step = match self.run_fast() {
4176 Ok(Some(value)) => Ok(Step::Return(value)),
4177 Ok(None) => self.step(),
4178 Err(signal) => Err(signal),
4179 };
4180 match step {
4181 Ok(Step::Continue) => {}
4182 Ok(Step::Return(value)) => {
4183 self.pop_frame();
4184 // A frame that ended in a `tail_call` hands its value straight to
4185 // its caller: nothing after the call can run, so every frame above
4186 // the callee unwinds with the same value. See [`Frame::tail`] —
4187 // the reference does not reuse frames either, so recursion depth
4188 // and the stack-overflow limit behave the same way.
4189 while self.frames.len() > depth && self.frame().tail {
4190 self.pop_frame();
4191 }
4192 if self.frames.len() == depth {
4193 return Ok(value);
4194 }
4195 // The caller resumes with the value on its stack.
4196 self.frames
4197 .last_mut()
4198 .expect("a caller is live")
4199 .stack
4200 .push(value);
4201 }
4202 Err(Signal::Throw(value)) => {
4203 // The host's standing request becomes the active mode for this unwind,
4204 // and is consumed here so it does not leak into the next throw.
4205 if self.uncatchable_next {
4206 self.uncatchable_next = false;
4207 self.uncatchable = true;
4208 }
4209 // An uncatchable throw walks past every `catch` on the way out. The
4210 // frames are still popped, because the values they hold have to be
4211 // dropped — only the search for a handler is skipped.
4212 if self.uncatchable {
4213 while self.frames.len() > depth {
4214 self.frames.pop();
4215 }
4216 return Err(Signal::Throw(value));
4217 }
4218 // A handler lives on the stack of the frame that is throwing —
4219 // `catch` pushed it there — so this frame gets the first chance
4220 // to catch before it is popped.
4221 let value = value;
4222 loop {
4223 if self.frames.len() <= depth {
4224 return Err(Signal::Throw(value));
4225 }
4226 if self.catch_here(value.clone()).is_some() {
4227 break;
4228 }
4229 self.frames.pop();
4230 }
4231 }
4232 // A `yield` in a frame that `execute` is running directly means a
4233 // generator body was entered as an ordinary call, which only happens if
4234 // the generator check in `call_or_push` was bypassed.
4235 Ok(Step::Suspend(_)) => {
4236 return Err(Signal::Throw(self.make_error(
4237 "InternalError",
4238 "a generator body ran as an ordinary call",
4239 )));
4240 }
4241 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4242 }
4243 }
4244 }
4245
4246 /// Install a handler for `value` if this frame has one, resuming at it.
4247 ///
4248 /// The scan is the reference's: walk the frame's stack downwards looking for the
4249 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4250 /// `0` is an enumerator marker rather than a handler — it exists so that a
4251 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4252 /// here and the unwinding continues.
4253 fn catch_here(&mut self, value: Value) -> Option<()> {
4254 let frame = self.frames.last_mut()?;
4255 while let Some(top) = frame.stack.pop() {
4256 if let Value::CatchOffset(offset) = top {
4257 if offset == 0 {
4258 continue;
4259 }
4260 frame.stack.push(value);
4261 frame.pc = offset as usize;
4262 return Some(());
4263 }
4264 }
4265 None
4266 }
4267
4268 fn push_frame(
4269 &mut self,
4270 code: Gc<CompiledCode>,
4271 env: Gc<ClosureEnv>,
4272 this: Value,
4273 mut args: Vec<Value>,
4274 callee: Value,
4275 ) -> JsResult<()> {
4276 // Two bounds, and the byte budget is the one that decides in practice. The
4277 // reference's message is `stack overflow` on an `InternalError`, not V8's
4278 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4279 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4280 let frame_cost = Self::frame_cost(&code);
4281 let stack_base = self.stack_used();
4282 if self.frames.len() >= self.max_frames
4283 || stack_base.saturating_add(frame_cost) > self.stack_limit
4284 {
4285 return Err(Signal::Throw(
4286 self.make_error("InternalError", "stack overflow"),
4287 ));
4288 }
4289 let arg_count = code.code.args.len();
4290 // How many were actually passed, which `arguments.length` reports and
4291 // `assert(x)` depends on: a call with one argument must not look like a call
4292 // with one argument and an explicit `undefined`.
4293 let passed = args.len();
4294 // Missing arguments are `undefined` in their slots; extra ones are dropped
4295 // from the slots but still reachable through `arguments`.
4296 //
4297 // A call that passes no more than the declared parameters needs **no** copy:
4298 // after the resize below, `args[..passed]` *is* the passed values. Only the
4299 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4300 // the rare case. This used to copy every call: one `Value` clone per argument
4301 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4302 let passed_overflow = (passed > arg_count).then(|| {
4303 let mut values = self.take_values(passed, Value::Undefined);
4304 values[..passed].clone_from_slice(&args[..passed]);
4305 values
4306 });
4307 // Only when the counts differ, which for the overwhelmingly common call — as many
4308 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4309 // lengths is two length compares and nothing else, but this is the hottest few
4310 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4311 if passed != arg_count {
4312 args.resize(arg_count, Value::Undefined);
4313 args.truncate(arg_count);
4314 }
4315 let cell_count = code.code.var_ref_count as usize;
4316 let mut cells = Vec::with_capacity(cell_count);
4317 for _ in 0..cell_count {
4318 cells.push(self.new_cell(Value::Undefined));
4319 }
4320 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4321 // A captured argument lives in its cell, not in the argument slot, so the
4322 // incoming value has to be moved there before the body runs.
4323 for (slot, cell) in code.arg_cell.iter().enumerate() {
4324 if *cell >= 0
4325 && let Some(value) = args.get(slot).cloned()
4326 {
4327 cells[*cell as usize].set(value);
4328 }
4329 }
4330 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4331 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4332 // reports `object`. Strict mode passes the value through untouched.
4333 let this = if code.code.strict {
4334 this
4335 } else if this.is_nullish() {
4336 Value::Object(self.realm.global.clone())
4337 } else if matches!(this, Value::Object(_)) {
4338 this
4339 } else {
4340 match crate::builtins::this_object(self, &this) {
4341 Ok(boxed) => Value::Object(boxed),
4342 Err(_) => this,
4343 }
4344 };
4345 let stack_depth = code.code.stack_size as usize + 1;
4346 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4347 // out of the same recycle pool the locals did.
4348 let stack = self.take_values(stack_depth, Value::Undefined);
4349 self.frames.push(Frame {
4350 code,
4351 env,
4352 this,
4353 args,
4354 passed_count: passed,
4355 passed_overflow: passed_overflow.map(Box::new),
4356 locals,
4357 cells,
4358 local_vars: None,
4359 // Exactly the depth the compiler computed, so the operand stack never
4360 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4361 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4362 // the buffer between calls, so "exactly" costs nothing after the first one.
4363 stack,
4364 pc: 0,
4365 at: 0,
4366 callee,
4367 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4368 cost: frame_cost,
4369 stack_base,
4370 tail: false,
4371 });
4372 Ok(())
4373 }
4374
4375 /// A value buffer of `len` slots, from the recycle pool when there is one.
4376 ///
4377 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4378 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4379 // A frame with no locals asks for nothing, and that is most frames: taking a
4380 // buffer out of the pool, clearing it and resizing it to zero is four operations
4381 // and a pool pop for an empty `Vec`, which is free to construct.
4382 if len == 0 {
4383 return Vec::new();
4384 }
4385 let mut buffer = self.free_values.pop().unwrap_or_default();
4386 buffer.clear();
4387 buffer.resize(len, fill);
4388 buffer
4389 }
4390
4391 /// Return a finished frame's value buffers for the next call to reuse.
4392 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4393 for mut buffer in [
4394 std::mem::take(&mut frame.locals),
4395 frame
4396 .passed_overflow
4397 .take()
4398 .map(|buffer| *buffer)
4399 .unwrap_or_default(),
4400 std::mem::take(&mut frame.stack),
4401 ] {
4402 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4403 // GC root: it kept every value the frame held reachable, which is invisible
4404 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4405 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4406 // exactly that within one run — the target `{}` of a finished IIFE was still
4407 // in its operand stack, in the pool.
4408 buffer.clear();
4409 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4410 // fill the pool with nothing to offer.
4411 if free_values.len() < RECYCLE_SLOTS
4412 && buffer.capacity() > 0
4413 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4414 {
4415 free_values.push(buffer);
4416 }
4417 }
4418 }
4419
4420 /// Pop a finished frame and keep its buffers.
4421 ///
4422 /// Every place that drops a frame goes through here: a recycled buffer is also where
4423 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4424 /// nothing but the reuse.
4425 fn pop_frame(&mut self) -> Option<()> {
4426 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4427 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4428 let last = self.frames.len().checked_sub(1)?;
4429 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4430 self.frames.truncate(last);
4431 Some(())
4432 }
4433
4434 /// Poll the host's interrupt handler, if one is installed.
4435 ///
4436 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4437 /// one `Option` test, and with no handler installed the whole function is that test —
4438 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4439 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4440 #[inline]
4441 fn check_interrupt(&mut self) -> JsResult<()> {
4442 if self.interrupt.is_none() {
4443 return Ok(());
4444 }
4445 if self.interrupt_counter > 0 {
4446 self.interrupt_counter -= 1;
4447 return Ok(());
4448 }
4449 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4450 // The closure is taken out for the duration so that a handler which re-enters the
4451 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4452 let mut handler = self.interrupt.take().expect("checked above");
4453 let abort = handler();
4454 self.interrupt = Some(handler);
4455 if abort {
4456 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4457 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4458 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4459 // documentation says.
4460 self.uncatchable = true;
4461 return Err(Signal::Throw(
4462 self.make_error("InternalError", "interrupted"),
4463 ));
4464 }
4465 Ok(())
4466 }
4467
4468 /// A memory checkpoint: does the heap still fit under its limit?
4469 ///
4470 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4471 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4472 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4473 /// only at calls would let it run until the machine died, which is the exact failure
4474 /// `--memory-limit` exists to prevent.
4475 ///
4476 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4477 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4478 /// script that catches it, drops the reference and carries on is legitimate: measured
4479 /// on `qjs --memory-limit 1M`, the engine recovers.
4480 fn check_memory(&mut self) -> JsResult<()> {
4481 // One `Cell` read and a predictable branch when no limit is set, and an integer
4482 // compare when one is. Containers report their own growth as it happens
4483 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4484 // walking it here was the first version and it was O(live) per 256 instructions,
4485 // which turned a 100k-element push loop into a five-minute one.
4486 let Some(limit) = self.heap.memory_limit() else {
4487 return Ok(());
4488 };
4489 let used = self.heap.used_bytes();
4490 if used <= limit {
4491 // Back under the limit — a collection or a dropped reference did it. The next
4492 // time it goes over is a new failure, not a repeat of this one.
4493 self.oom_reported_at = 0;
4494 return Ok(());
4495 }
4496 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4497 // block runs normally after `out of memory` — it allocates nothing, so nothing
4498 // fails. A check that re-fired on every instruction made the handler itself throw,
4499 // which is a dead end: the error became unobservable from script.
4500 //
4501 // Comparing against the total at the last report gives the same behaviour: the
4502 // handler runs while the total is unchanged, and the very next allocation over the
4503 // limit fails.
4504 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4505 {
4506 return Ok(());
4507 }
4508 self.oom_reported_at = used;
4509 Err(Signal::Throw(
4510 self.make_error("InternalError", "out of memory"),
4511 ))
4512 }
4513
4514 /// Fail before allocating `payload` bytes, if they would not fit.
4515 ///
4516 /// For the allocations whose size comes from script data — `new Array(n)`,
4517 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4518 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4519 /// answering NULL for the one big request.
4520 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4521 if self.heap.fits(payload) {
4522 return Ok(());
4523 }
4524 Err(Signal::Throw(
4525 self.make_error("InternalError", "out of memory"),
4526 ))
4527 }
4528
4529 /// Bytes of frame state the live call chain accounts for.
4530 pub fn stack_used(&self) -> usize {
4531 match self.frames.last() {
4532 Some(frame) => frame.stack_base + frame.cost,
4533 None => 0,
4534 }
4535 }
4536
4537 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4538 ///
4539 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4540 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4541 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4542 /// instead. That is the whole difference between the two models: it rations C stack, we
4543 /// ration frame state, and both quantities are dominated by the value slots — which is
4544 /// why the two depths come out comparable rather than merely proportional.
4545 fn frame_cost(code: &CompiledCode) -> usize {
4546 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4547 std::mem::size_of::<Frame>()
4548 + std::mem::size_of::<Value>() * slots
4549 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4550 }
4551
4552 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4553 ///
4554 /// Only names the eval created are here: a name the frame already declared statically
4555 /// is written through to its own slot instead, so this cannot shadow a real local.
4556 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4557 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4558 let (local_vars, phase) = self.visible_local_vars()?;
4559 if !local_vars.contains(name) {
4560 return None;
4561 }
4562 local_vars.get(name, phase)
4563 }
4564
4565 /// The variables a direct `eval` declared, as the code currently running sees them.
4566 ///
4567 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4568 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4569 /// else it is the current frame's, falling back to the frame the closure was created
4570 /// in.
4571 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4572 ///
4573 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4574 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4575 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4576 /// just to be asked `is_none`.
4577 fn has_visible_local_vars(&self) -> bool {
4578 let index = match self.eval_caller.flatten() {
4579 Some(caller) => caller,
4580 None => match self.frames.len().checked_sub(1) {
4581 Some(top) => top,
4582 None => return false,
4583 },
4584 };
4585 match self.frames.get(index) {
4586 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4587 None => false,
4588 }
4589 }
4590
4591 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4592 // While an `eval` runs, its own frame is on top but its variable environment is
4593 // the *caller's* — so the caller is what the lookup has to start from.
4594 let (index, phase) = match self.eval_caller.flatten() {
4595 Some(caller) => (
4596 caller,
4597 if self.in_parameter_list_at(caller) {
4598 0
4599 } else {
4600 1
4601 },
4602 ),
4603 None => (
4604 self.frames.len().checked_sub(1)?,
4605 if self.in_parameter_list() { 0 } else { 1 },
4606 ),
4607 };
4608 let frame = self.frames.get(index)?;
4609 // The frame's own variables, or — for an arrow, which has no variable environment
4610 // of its own — the one it was created in, which `ClosureEnv` carries.
4611 if let Some(local_vars) = frame.local_vars.clone() {
4612 return Some((local_vars, phase));
4613 }
4614 frame
4615 .env
4616 .local_vars
4617 .clone()
4618 .map(|local_vars| (local_vars, frame.env.local_phase))
4619 }
4620
4621 /// Whether the innermost frame is still evaluating its parameter list.
4622 ///
4623 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4624 /// and a closure created there may only see that much of [`LocalVars`].
4625 fn in_parameter_list(&self) -> bool {
4626 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4627 }
4628
4629 /// [`Interp::in_parameter_list`] for a specific frame.
4630 fn in_parameter_list_at(&self, frame: usize) -> bool {
4631 let Some(frame) = self.frames.get(frame) else {
4632 return false;
4633 };
4634 let code = &frame.code.code;
4635 if !code.has_parameter_expressions {
4636 return false;
4637 }
4638 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4639 // function as its body and let a direct `eval` act accordingly.
4640 if code.body_start == (0, 0) {
4641 return false;
4642 }
4643 match code.position_at(frame.at as u32) {
4644 Some(position) => position < code.body_start,
4645 None => false,
4646 }
4647 }
4648
4649 fn frame(&self) -> &Frame {
4650 self.frames.last().expect("a frame is live")
4651 }
4652
4653 fn frame_mut(&mut self) -> &mut Frame {
4654 self.frames.last_mut().expect("a frame is live")
4655 }
4656
4657 // -- slot access --------------------------------------------------------
4658
4659 /// Move a local's value out, leaving `undefined` in the slot.
4660 ///
4661 /// `None` for a captured slot: its value lives in a cell shared with every closure
4662 /// that closed over it, so it can never be exclusively ours and must not be taken.
4663 ///
4664 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4665 /// for every read and fatal for this one — a clone is exactly the second handle that
4666 /// rules out growing the string in place.
4667 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4668 let frame = self.frames.last_mut()?;
4669 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4670 return None;
4671 }
4672 frame
4673 .locals
4674 .get_mut(slot)
4675 .map(|value| std::mem::replace(value, Value::Undefined))
4676 }
4677
4678 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4679 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4680 ///
4681 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4682 /// it** — the value is put back before the general path runs — so a `valueOf` that
4683 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4684 /// error as it would have without the fusion. This is why the in-place attempt is a
4685 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4686 /// a wrong answer with a good excuse.
4687 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4688 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4689 // is put back on every path that does not append. An earlier version wrote the two
4690 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4691 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4692 // through with its value already taken and dropped: the general path below then
4693 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4694 // A wrong answer, from an optimisation, with every test green.
4695 if matches!(right, Value::String(_))
4696 && let Some(taken) = self.take_loc(slot)
4697 {
4698 if let Value::String(mut left) = taken {
4699 let appended = match left.get_mut() {
4700 Some(string) => string.append_in_place(
4701 // The pattern is the one `matches!` just checked.
4702 match &right {
4703 Value::String(text) => text,
4704 _ => unreachable!("guarded above"),
4705 },
4706 ),
4707 None => None,
4708 };
4709 self.put_loc(slot, Value::String(left));
4710 if let Some(added) = appended {
4711 // The buffer grew where it stood, so the heap's running total has to
4712 // be told: `measure_used` would report the new length, and the two must
4713 // agree or the subtraction at free time leaves the counter wrong.
4714 self.heap.adjust_payload(added as isize);
4715 return Ok(());
4716 }
4717 } else {
4718 self.put_loc(slot, taken);
4719 }
4720 }
4721 // The two-number case, without an operand stack round trip. Everything below
4722 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4723 // store it — five operations and two `Value` clones for what is one integer add.
4724 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4725 // for string append and never got the numeric half, so `t += i` — a counting loop
4726 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4727 let left = self.get_loc(slot);
4728 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4729 self.put_loc(
4730 slot,
4731 match a.checked_add(*b) {
4732 Some(sum) => Value::Int(sum),
4733 None => Value::Float(*a as f64 + *b as f64),
4734 },
4735 );
4736 return Ok(());
4737 }
4738 self.push(left);
4739 self.push(right);
4740 self.binary_add()?;
4741 let value = self.pop();
4742 self.put_loc(slot, value);
4743 Ok(())
4744 }
4745
4746 fn get_arg(&self, slot: usize) -> Value {
4747 self.frame().read_arg(slot)
4748 }
4749
4750 fn put_arg(&mut self, slot: usize, value: Value) {
4751 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4752 if cell == -1 {
4753 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4754 *slot = value;
4755 }
4756 } else {
4757 self.frame().cells[cell as usize].set(value);
4758 }
4759 }
4760
4761 fn get_loc(&self, slot: usize) -> Value {
4762 // The cell mapping is `-1` for every slot that was not captured — which is all of
4763 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4764 // so the common case is one array read and a clone: 20% of every loop iteration
4765 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4766 // sample of `dispatch:arith`).
4767 self.frame().read_loc(slot)
4768 }
4769
4770 fn put_loc(&mut self, slot: usize, value: Value) {
4771 // One borrow instead of three, and the cell check on the frame we already hold.
4772 let frame = self.frames.last_mut().expect("a frame is live");
4773 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4774 if cell < 0 {
4775 if let Some(slot) = frame.locals.get_mut(slot) {
4776 *slot = value;
4777 }
4778 } else if let Some(cell) = frame.cells.get(cell as usize) {
4779 cell.set(value);
4780 }
4781 }
4782
4783 // -- globals ------------------------------------------------------------
4784
4785 /// The name a global-slot operand refers to.
4786 fn global_name(&self, slot: usize) -> String {
4787 self.frame()
4788 .code
4789 .code
4790 .closure_vars
4791 .get(slot)
4792 .map(|c| c.name.clone())
4793 .unwrap_or_default()
4794 }
4795
4796 /// The facts about a global binding that decide where it lives.
4797 ///
4798 /// A script's globals split in two, and the split is observable: `var` and
4799 /// function declarations become properties of the global object (`globalThis.v`
4800 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4801 /// declarations live in the global *lexical* environment and are invisible there
4802 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4803 /// `is_lexical` flag means the answer is already in the bytecode.
4804 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4805 let name = self.global_name(slot);
4806 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4807 // while forwarding a reference through a nested function is built with the
4808 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4809 // closure. Presence in the realm's lexical table is the same fact, recorded
4810 // once, and every slot sees it.
4811 let lexical = self.realm.globals.contains_key(&name);
4812 let is_const = self.realm.lexical_consts.contains(&name);
4813 (name, lexical, is_const)
4814 }
4815
4816 /// The value of `name` in the innermost active `with` object, if any.
4817 ///
4818 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4819 /// innermost frame first and innermost block first within one. Walking frames rather
4820 /// than keeping a separate stack is what makes a closure called from inside a `with`
4821 /// see it, and what keeps the object alive only as long as the block is.
4822 /// The innermost active `with` object that has `name`, if any.
4823 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4824 let objects = self.eval_with.clone().unwrap_or_default();
4825 for object in objects {
4826 let key = self.string(name.to_string());
4827 if self
4828 .has_property(&key, &Value::Object(object.clone()))
4829 .ok()?
4830 {
4831 return Some(object);
4832 }
4833 }
4834 None
4835 }
4836
4837 /// Every active `with` object, innermost first.
4838 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4839 let mut objects = Vec::new();
4840 for frame in self.frames.iter().rev() {
4841 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4842 if var.kind != js_compile::VarKind::With {
4843 continue;
4844 }
4845 // A captured binding lives in its cell and not in the slot list, so the
4846 // cell is consulted first — a closure created inside the block is exactly
4847 // what makes the object captured. Before the store runs the slot still
4848 // holds `undefined`, and a `with` object is always boxed, so a non-object
4849 // entry is simply not in scope yet.
4850 let value = frame
4851 .code
4852 .loc_cell
4853 .get(index)
4854 .copied()
4855 .filter(|cell| *cell >= 0)
4856 .and_then(|cell| frame.cells.get(cell as usize))
4857 .map(|cell| cell.get())
4858 .or_else(|| frame.locals.get(index).cloned());
4859 if let Some(Value::Object(object)) = value {
4860 objects.push(object);
4861 }
4862 }
4863 }
4864 objects
4865 }
4866
4867 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4868 for object in self.eval_with.clone().unwrap_or_default() {
4869 let key = self.string(name.to_string());
4870 if self.has_property(&key, &Value::Object(object.clone()))? {
4871 return Ok(Some(self.read_field(&Value::Object(object), name)?));
4872 }
4873 }
4874 Ok(None)
4875 }
4876
4877 /// Whether every scope between here and the global object is an ordinary one.
4878 ///
4879 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4880 /// bytecode resolved; when any is live the general path has to run in full order. When
4881 /// none is — every ordinary program — a global read is a property read and nothing
4882 /// else, and that is worth caching.
4883 fn scopes_are_plain(&self) -> bool {
4884 self.eval_caller.is_none()
4885 && self.eval_with.is_none()
4886 && self.eval_arguments.is_none()
4887 && self.eval_bindings.is_empty()
4888 && self.eval_scope.is_none()
4889 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4890 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4891 // its `ClosureEnv`, so the test has to be the same one the general path makes.
4892 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4893 // upstream corpus caught and no unit test did.
4894 && !self.has_visible_local_vars()
4895 && self.frame().env.eval_scope.is_none()
4896 }
4897
4898 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4899 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4900 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4901 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4902 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4903 // borrow outlive the `&mut self` the lookup needs.
4904 //
4905 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4906 // forwarded through a nested function has its flags cleared, so the flag cannot
4907 // be believed.
4908 let code = self.frame().code.clone();
4909 let name = code
4910 .code
4911 .closure_vars
4912 .get(slot)
4913 .map(|c| c.name.as_str())
4914 .unwrap_or_default();
4915 let lexical = self.realm.globals.contains_key(name);
4916 // The common case, first: an ordinary global `var`, with a cache in front of the
4917 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4918 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4919 // cache hit and return without touching any of it.
4920 if !lexical && self.scopes_are_plain() {
4921 return self.get_plain_global(name, slot);
4922 }
4923 if name == "arguments"
4924 && let Some(arguments) = &self.eval_arguments
4925 {
4926 return Ok(arguments.clone());
4927 }
4928 // A `with` block around the *call site* is part of the scope an `eval` sees, so
4929 // the objects live when the eval started are consulted before anything else. The
4930 // snapshot is taken at entry rather than scanning the frames on every read: a
4931 // block that has already finished still leaves its object in the slot, and a
4932 // bytecode read outside the block must not see it.
4933 if let Some(value) = self.with_lookup(name)? {
4934 return Ok(value);
4935 }
4936 // A variable a direct `eval` declared shadows everything the compiler resolved,
4937 // including an enclosing function's binding: the eval put it in the caller's own
4938 // variable environment, which is nearer than any captured scope.
4939 if let Some((local_vars, phase)) = self.visible_local_vars()
4940 && let Some(cell) = local_vars.get(name, phase)
4941 {
4942 return Ok(cell.get());
4943 }
4944 // The frame that called `eval` is the innermost scope the eval'd code sees, so
4945 // its local `a` wins over a global `a`.
4946 if let Some(value) = self.eval_binding_value(name) {
4947 return Ok(value);
4948 }
4949 // A closure created by an `eval` resolves its free names against the bindings
4950 // that eval saw, even after the eval (and its frames) are gone.
4951 if let Some(cell) = self
4952 .frame()
4953 .env
4954 .eval_scope
4955 .as_ref()
4956 .and_then(|scope| scope.get(name))
4957 {
4958 let value = cell.get();
4959 if matches!(value, Value::Uninitialized) {
4960 return Err(self.throw_reference(name));
4961 }
4962 return Ok(value);
4963 }
4964 // A binding declared by the strict `eval` currently running shadows anything
4965 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4966 if let Some(scope) = &self.eval_scope
4967 && let Some(value) = scope.get(name)
4968 {
4969 return Ok(value.clone());
4970 }
4971 if lexical {
4972 // A lexical global is a binding in a side table, so the dead zone is
4973 // visible and it is nowhere on the global object.
4974 if let Some(cell) = self.realm.globals.get(name) {
4975 let value = cell.get();
4976 if matches!(value, Value::Uninitialized) {
4977 return Err(self.throw_reference(name));
4978 }
4979 return Ok(value);
4980 }
4981 return Err(self.throw_reference(name));
4982 }
4983 // A `var` global is an ordinary property, so the prototype chain and the
4984 // global object's own builtins are all reachable through it.
4985 match self.get_property(&self.realm.global.clone(), name)? {
4986 Some(value) => Ok(value),
4987 None => Err(self.throw_reference(name)),
4988 }
4989 }
4990
4991 /// Read a plain global `var`: a cached own data property, or the full lookup.
4992 ///
4993 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4994 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4995 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4996 let object = self.realm.global.clone();
4997 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4998 if let Some(cached) = &self.global_cache[site]
4999 && object.upgrades_to(&cached.object)
5000 && let Some(value) = object.data_property_at(cached.index, name)
5001 {
5002 return Ok(value);
5003 }
5004 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5005 // chain exactly as before, then remember the answer if it is worth remembering.
5006 let Some(value) = self.get_property(&object, name)? else {
5007 return Err(self.throw_reference(name));
5008 };
5009 if let Some(index) = object.own_data_index(name) {
5010 self.global_cache[site] = Some(GlobalCache {
5011 object: object.downgrade(),
5012 index,
5013 });
5014 }
5015 Ok(value)
5016 }
5017
5018 /// Store to a global binding.
5019 ///
5020 /// Returns a signal when the store is refused: a `const` global may only be
5021 /// written by its initialiser, and a non-configurable `var` global may not be
5022 /// deleted but is always writable.
5023 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5024 let (name, lexical, is_const) = self.global_binding(slot);
5025
5026 // An assignment inside a `with` writes through to the object that supplies the
5027 // name, which for an `eval` means consulting the same chain `get_global` does.
5028 if let Some(owner) = self.with_owner(&name) {
5029 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5030 return Ok(());
5031 }
5032 // A variable the running eval *declared* takes the write before any caller
5033 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5034 // environment even when an enclosing function has a `var c` of its own.
5035 if self.eval_caller.flatten().is_some()
5036 && let Some((local_vars, phase)) = self.visible_local_vars()
5037 && local_vars.contains(&name)
5038 && let Some(cell) = local_vars.get(&name, phase)
5039 {
5040 cell.set(value);
5041 return Ok(());
5042 }
5043 // A binding of the frame that called `eval` takes the write, which is what
5044 // makes `f("a = 3")` change the caller's `a`.
5045 if self.set_eval_binding(&name, &value)? {
5046 return Ok(());
5047 }
5048 // A closure that outlived its `eval` writes through to the same cell it reads.
5049 if let Some(cell) = self
5050 .frame()
5051 .env
5052 .eval_scope
5053 .as_ref()
5054 .and_then(|scope| scope.get(&name))
5055 .cloned()
5056 {
5057 cell.set(value);
5058 return Ok(());
5059 }
5060 // Inside a strict `eval`, a name it declared itself is stored there. An
5061 // *assignment* to a name nobody declared is not a declaration, so it falls
5062 // through: strict mode raises `ReferenceError` for it, which is what
5063 // `eval("1 + (@not_def = 1)")` has to do.
5064 if let Some(scope) = self.eval_scope.as_mut()
5065 && scope.contains_key(&name)
5066 {
5067 scope.insert(name, value);
5068 return Ok(());
5069 }
5070 if lexical {
5071 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5072 if is_const && !matches!(cell.get(), Value::Uninitialized) {
5073 return Err(self.read_only_global(&name));
5074 }
5075 cell.set(value);
5076 return Ok(());
5077 }
5078 // Writing an undeclared lexical global is a `ReferenceError` in strict
5079 // mode and a silent global creation otherwise; creating the cell here
5080 // keeps both paths from losing the value.
5081 let cell = self.new_cell(value);
5082 self.realm.globals.insert(name, cell);
5083 return Ok(());
5084 }
5085 // A variable a direct `eval` declared in this call shadows the global object, even
5086 // when the global already has a property of that name — `var c = "global"` at the
5087 // top level must not capture `eval("var c = 1")` inside a function.
5088 if let Some((local_vars, phase)) = self.visible_local_vars()
5089 && local_vars.contains(&name)
5090 && let Some(cell) = local_vars.get(&name, phase)
5091 {
5092 cell.set(value);
5093 return Ok(());
5094 }
5095 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5096 // remembered a global's slot index since M12b, but the *store* side never did: it
5097 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5098 // global object's whole table — which holds every builtin — on every assignment to
5099 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5100 // full global lookup per iteration; measured with a counter, `s` as a global made
5101 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5102 //
5103 // Re-validated exactly like the read: same object, same index, still the name, and
5104 // — the one extra check a store needs — still writable. A global that is an
5105 // accessor, non-writable, or inherited fails here and falls through to the full
5106 // path below, which reports the failure the way it always did.
5107 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5108 let global = self.realm.global.clone();
5109 if let Some(cached) = &self.global_cache[site]
5110 && global.upgrades_to(&cached.object)
5111 && global.write_data_at(cached.index, &name, value.clone())
5112 {
5113 return Ok(());
5114 }
5115 match global.own_property(&name) {
5116 // A `var` global is writable, so the store goes straight through — but
5117 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5118 // store (a non-writable or accessor-without-setter global) is a silent
5119 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5120 // split every other assignment has.
5121 Some(_) => {
5122 let on_failure = if self.current_strict() {
5123 DeleteFailure::Throw
5124 } else {
5125 DeleteFailure::Ignore
5126 };
5127 let result = self.set_property_with(&global, &name, value, on_failure);
5128 // Teach the cache the slot for a plain writable own data property, which is
5129 // what a declared `var` is. Without this the fast path above could never
5130 // fire for a global that is only ever *written* — its entry would have to
5131 // be put there by a read of the same slot, and a write-only loop has none.
5132 if result.is_ok()
5133 && let Some(index) = global.own_data_index(&name)
5134 {
5135 self.global_cache[site] = Some(GlobalCache {
5136 object: global.downgrade(),
5137 index,
5138 });
5139 }
5140 result
5141 }
5142 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5143 // declaration creates a *configurable* property, which is what makes it
5144 // deletable and is the one way a global differs from a declared `var`.
5145 // In strict mode the same store is a `ReferenceError` instead: that is the
5146 // whole point of strict mode, and creating the global silently meant
5147 // `"use strict"; x = 1` looked like it worked.
5148 None => {
5149 if self.current_strict() {
5150 return Err(self.throw_reference(&name));
5151 }
5152 // A direct eval declares here rather than on the global object: its
5153 // `var`s belong to the caller's variable environment. `declare_eval_local`
5154 // also covers a plain assignment to a variable an earlier eval made.
5155 if let Some(cell) = self.declare_eval_local(&name) {
5156 cell.set(value);
5157 return Ok(());
5158 }
5159 global.define_data(&name, value);
5160 Ok(())
5161 }
5162 }
5163 }
5164
5165 /// The value of a binding of the frame that called `eval`, if there is one.
5166 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5167 let binding = self
5168 .eval_bindings
5169 .iter()
5170 .find(|binding| binding.name == name)?;
5171 let owner = self.frames.get(binding.frame)?;
5172 let (slot, index) = (binding.slot, binding.index);
5173 Some(match slot {
5174 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5175 cell if cell >= 0 => owner
5176 .cells
5177 .get(cell as usize)
5178 .map(|cell| cell.get())
5179 .unwrap_or(Value::Undefined),
5180 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5181 },
5182 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5183 cell if cell >= 0 => owner
5184 .cells
5185 .get(cell as usize)
5186 .map(|cell| cell.get())
5187 .unwrap_or(Value::Undefined),
5188 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5189 },
5190 })
5191 }
5192
5193 /// Write to a binding of the frame that called `eval`.
5194 ///
5195 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5196 /// matched binding can still refuse the store, which is why this is fallible: a
5197 /// `const` is read-only everywhere, and a named function expression's own name is
5198 /// read-only in strict mode.
5199 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5200 let Some(binding) = self
5201 .eval_bindings
5202 .iter()
5203 .find(|binding| binding.name == name)
5204 else {
5205 return Ok(false);
5206 };
5207 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5208 let strict = self.current_strict();
5209 let Some(owner) = self.frames.get_mut(frame) else {
5210 return Ok(false);
5211 };
5212 match slot {
5213 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5214 cell if cell >= 0 => {
5215 if let Some(cell) = owner.cells.get(cell as usize) {
5216 cell.set(value.clone());
5217 }
5218 }
5219 _ => {
5220 if let Some(slot) = owner.args.get_mut(index) {
5221 *slot = value.clone();
5222 }
5223 }
5224 },
5225 EvalSlot::Local => {
5226 let declared = owner.code.code.vars.get(index);
5227 // A `const` is read-only even through `eval`. The realm records this for
5228 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5229 // the bytecode, so this is where it has to be enforced.
5230 if declared.is_some_and(|var| var.is_const) {
5231 return Err(self.read_only_local(name));
5232 }
5233 // The name of a named function expression is read-only too, but only
5234 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5235 // such a name is ignored, the same as a direct store would be.
5236 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5237 return if strict {
5238 Err(self.read_only_local(name))
5239 } else {
5240 Ok(true)
5241 };
5242 }
5243 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5244 cell if cell >= 0 => {
5245 if let Some(cell) = owner.cells.get(cell as usize) {
5246 cell.set(value.clone());
5247 }
5248 }
5249 _ => {
5250 if let Some(slot) = owner.locals.get_mut(index) {
5251 *slot = value.clone();
5252 }
5253 }
5254 }
5255 }
5256 }
5257 Ok(true)
5258 }
5259
5260 /// The `TypeError` an assignment to a read-only binding raises.
5261 fn read_only_local(&self, name: &str) -> Signal {
5262 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5263 }
5264
5265 /// Declare `name` as a variable of the frame that called the running `eval`.
5266 ///
5267 /// `None` when there is no direct eval in progress, or it was called from the top
5268 /// level — then the caller's variable environment *is* the global one and the
5269 /// existing path is right.
5270 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5271 let caller = self.eval_caller.flatten()?;
5272 // The bottom frame is the top-level script, whose variable environment *is* the
5273 // global one — so `eval("var x = 1")` at the top level still creates a global.
5274 if caller == 0 {
5275 return None;
5276 }
5277 // A name the eval's *own* variable environment already binds is not a new
5278 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5279 // `arguments`, and creating a second binding would leave the first — the one
5280 // closures read — untouched. A binding of an *outer* frame does not count: a
5281 // declaration shadows it rather than writing through.
5282 if self
5283 .eval_bindings
5284 .iter()
5285 .any(|binding| binding.name == name && binding.frame == caller)
5286 {
5287 return None;
5288 }
5289 let phase = if self.in_parameter_list_at(caller) {
5290 0
5291 } else {
5292 1
5293 };
5294 self.frame_local_vars(caller)?;
5295 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5296 if let Some(cell) = local_vars.get(name, 1) {
5297 return Some(cell);
5298 }
5299 let cell = self.new_cell(Value::Undefined);
5300 Some(local_vars.declare(name, phase, cell))
5301 }
5302
5303 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5304 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5305 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5306 return Some(local_vars.clone());
5307 }
5308 let local_vars = Gc::new(self.heap, LocalVars::new());
5309 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5310 Some(local_vars)
5311 }
5312
5313 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5314 /// property of the global object. Used to decide whether a store inside an
5315 /// `eval` writes through to the realm or declares a binding of its own.
5316 ///
5317 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5318 /// write to `Object.prototype.toString`, and must not shadow it either.
5319 fn global_knows(&mut self, name: &str) -> bool {
5320 if self.realm.globals.contains_key(name) {
5321 return true;
5322 }
5323 self.realm.global.own_property(name).is_some()
5324 }
5325
5326 /// Whether the code currently running is strict.
5327 ///
5328 /// Read off the frame's function, which is where the parser's answer ended up; a
5329 /// native function never runs strict-only checks, and there is no frame at all
5330 /// before the first script.
5331 pub fn current_strict(&self) -> bool {
5332 self.frames
5333 .last()
5334 .is_some_and(|frame| frame.code.code.strict)
5335 }
5336
5337 /// Initialise a declared global, which is what ends its dead zone.
5338 ///
5339 /// A `var` global becomes a property of the global object: writable, so a later
5340 /// assignment goes through, and non-configurable, so `delete` refuses.
5341 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5342 let (name, lexical, _) = self.global_binding(slot);
5343 // A `var` declared by the strict `eval` currently running belongs to the
5344 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5345 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5346 // initialised in place, which is what a re-declaration inside eval does.
5347 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5348 self.eval_scope
5349 .as_mut()
5350 .expect("checked above")
5351 .insert(name, value);
5352 return Ok(());
5353 }
5354 if let Some(scope) = self.eval_scope.as_mut()
5355 && scope.contains_key(&name)
5356 {
5357 scope.insert(name, value);
5358 return Ok(());
5359 }
5360 if lexical {
5361 // The cell exists (created at declaration time) holding the dead-zone
5362 // marker; storing the value is what makes the binding readable.
5363 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5364 cell.set(value);
5365 return Ok(());
5366 }
5367 let cell = self.new_cell(value);
5368 self.realm.globals.insert(name, cell);
5369 return Ok(());
5370 }
5371 let global = self.realm.global.clone();
5372 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5373 // to answer `false` and leave the binding in place. `with_attributes` ties
5374 // `configurable` to `writable`, so the property is built field by field.
5375 global.define(
5376 &name,
5377 Property {
5378 value: Some(value),
5379 writable: true,
5380 enumerable: true,
5381 configurable: false,
5382 ..Property::default()
5383 },
5384 );
5385 Ok(())
5386 }
5387
5388 /// The `TypeError` a store to a `const` global raises.
5389 fn read_only_global(&self, name: &str) -> Signal {
5390 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5391 }
5392
5393 // -- properties ---------------------------------------------------------
5394
5395 /// Read `object[key]`, following the prototype chain.
5396 ///
5397 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5398 /// lookup returns the owner rather than just the value.
5399 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5400 self.get_property_key(object, &PropertyKey::from(key))
5401 }
5402
5403 /// [`Interp::get_property`] with a key that may be a symbol.
5404 pub fn get_property_key(
5405 &mut self,
5406 object: &Gc<JsObject>,
5407 key: &PropertyKey,
5408 ) -> JsResult<Option<Value>> {
5409 self.get_property_key_for(object, None, key)
5410 }
5411
5412 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5413 ///
5414 /// The receiver matters when the property is found on a *prototype*: a getter has to
5415 /// see the object the read started from. For a primitive that is the primitive
5416 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5417 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5418 /// the owner.
5419 pub fn get_property_key_for(
5420 &mut self,
5421 object: &Gc<JsObject>,
5422 receiver: Option<&Value>,
5423 key: &PropertyKey,
5424 ) -> JsResult<Option<Value>> {
5425 // A proxy answers for itself, before any of the shortcuts below: `new
5426 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5427 // have.
5428 if object.proxy_state().is_some() {
5429 let receiver = receiver
5430 .cloned()
5431 .unwrap_or_else(|| Value::Object(object.clone()));
5432 return self.proxy_get(object, &receiver, key);
5433 }
5434 // A host class's `get_property` trap replaces the whole read, prototype walk
5435 // included — that is what makes a native accessor free rather than a JavaScript
5436 // getter call.
5437 if let Some(exotic) = object.exotic() {
5438 let receiver_value = receiver
5439 .cloned()
5440 .unwrap_or_else(|| Value::Object(object.clone()));
5441 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5442 return Ok(Some(value));
5443 }
5444 // With no `get_property` trap, a `get_own_property` trap still answers for the
5445 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5446 // and the hook lives exactly there. A key the trap reports as absent is still
5447 // looked for on the prototype, which is why the search resumes *above*.
5448 if let Some(property) = exotic.get_own_property(self, object, key)? {
5449 return match property {
5450 Some(property) => self.read_property(property, object, receiver),
5451 None => match lookup_key_above(object, key) {
5452 Some((_, property)) => self.read_property(property, object, receiver),
5453 None => Ok(None),
5454 },
5455 };
5456 }
5457 }
5458 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5459 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5460 // The `[[Get]]` short-circuit therefore belongs to this one arm.
5461 //
5462 // Constructibility is exactly the split the reference makes: `function f(){}` and
5463 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5464 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5465 // function" — it *is* the predicate, which is why no extra marker is needed.
5466 if let Some(text) = key.as_str()
5467 && (text == "caller" || text == "arguments")
5468 && object.is_constructor()
5469 && object.is_callable()
5470 && !object.is_bound_function()
5471 && object.own_property(text).is_none()
5472 {
5473 return Ok(Some(Value::Undefined));
5474 }
5475 // The element-vector and `length` shortcuts are string-only: an array index
5476 // has no symbol spelling.
5477 if let Some(text) = key.as_str() {
5478 if let Some(value) = self.own_element(object, text) {
5479 return Ok(Some(value));
5480 }
5481 // `length` is not stored as a property: an array's length is its element
5482 // count, and keeping one copy of it is what makes `push`/`pop` and
5483 // `a.length = n` agree.
5484 if let Some(length) = object.array_length()
5485 && text == "length"
5486 {
5487 // Not `Value::Int(length as i32)`: see [`length_value`].
5488 return Ok(Some(crate::object::length_value(length)));
5489 }
5490 }
5491 // A proxy or a hooked exotic object anywhere above `object` makes the static
5492 // table walk below wrong: a proxy's own table is *empty by design* (the properties
5493 // live on its target), so the walk skipped that link entirely and everything behind
5494 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5495 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5496 // -target-is-proxy.js` are the four.
5497 if Self::chain_needs_dispatch(object) {
5498 return self.walk_get(object, receiver, key);
5499 }
5500 match lookup_key(object, key) {
5501 Some((_, property)) => self.read_property(property, object, receiver),
5502 None => Ok(None),
5503 }
5504 }
5505
5506 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5507 /// answer for itself.
5508 ///
5509 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5510 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5511 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5512 /// an inherited getter the object the read started from.
5513 fn walk_get(
5514 &mut self,
5515 start: &Gc<JsObject>,
5516 receiver: Option<&Value>,
5517 key: &PropertyKey,
5518 ) -> JsResult<Option<Value>> {
5519 let receiver = receiver
5520 .cloned()
5521 .unwrap_or_else(|| Value::Object(start.clone()));
5522 let mut current = Some(start.clone());
5523 while let Some(holder) = current {
5524 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5525 // has to ask it, not read its (empty) own-property table. `Object.create(new
5526 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5527 // instead found nothing.
5528 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5529 return Ok(Some(value));
5530 }
5531 // A host class's `get_property` trap replaces the whole read for that holder,
5532 // prototype walk included — the same rule `get_property_key_for` applies to the
5533 // first object.
5534 if let Some(exotic) = holder.exotic()
5535 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5536 {
5537 return Ok(Some(value));
5538 }
5539 if let Some(property) = self.object_get_own_property(&holder, key)? {
5540 return self.read_property(property, &holder, Some(&receiver));
5541 }
5542 current = self.object_prototype_of(&holder)?;
5543 }
5544 Ok(None)
5545 }
5546
5547 /// Whether `object` or anything above it has properties that cannot be read out of a
5548 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
5549 ///
5550 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
5551 /// is the hot path for every property read; this is the check that decides whether it
5552 /// is safe to take it.
5553 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
5554 object
5555 .chain()
5556 .iter()
5557 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
5558 }
5559
5560 /// The value a property read answers.
5561 ///
5562 /// One place rather than three, because an accessor has to run with the *receiver* as
5563 /// `this` whether the descriptor came from the property table, an exotic
5564 /// `get_own_property` trap, or a prototype above one.
5565 fn read_property(
5566 &mut self,
5567 property: Property,
5568 object: &Gc<JsObject>,
5569 receiver: Option<&Value>,
5570 ) -> JsResult<Option<Value>> {
5571 if property.is_accessor() {
5572 match &property.getter {
5573 Some(getter) if !matches!(getter, Value::Undefined) => {
5574 let receiver = receiver
5575 .cloned()
5576 .unwrap_or_else(|| Value::Object(object.clone()));
5577 self.call_value(getter.clone(), receiver, Vec::new())
5578 .map(Some)
5579 }
5580 // An accessor with no getter reads as `undefined`.
5581 _ => Ok(Some(Value::Undefined)),
5582 }
5583 } else {
5584 Ok(property.value)
5585 }
5586 }
5587
5588 /// `super.key` — start the search at `proto`, but report to `receiver`.
5589 ///
5590 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5591 /// found on the prototype of a class has to see the *instance* as `this`, and a
5592 /// plain property read off `proto` would lose that.
5593 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5594 let start = self.require_object(proto)?;
5595 let key = self.propkey(key)?;
5596 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5597 if matches!(proto, Value::Null) {
5598 return Ok(Value::Undefined);
5599 }
5600 match lookup_key(&start, &key) {
5601 Some((_, property)) if property.is_accessor() => match &property.getter {
5602 Some(getter) if !matches!(getter, Value::Undefined) => {
5603 self.call_value(getter.clone(), receiver.clone(), Vec::new())
5604 }
5605 _ => Ok(Value::Undefined),
5606 },
5607 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5608 None => Ok(Value::Undefined),
5609 }
5610 }
5611
5612 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5613 ///
5614 /// A setter found on the prototype runs with `receiver` as `this`; a data property
5615 /// is shadowed by a new own property on the receiver, the same rule an ordinary
5616 /// assignment follows.
5617 fn super_write(
5618 &mut self,
5619 receiver: &Value,
5620 proto: &Value,
5621 key: &Value,
5622 value: Value,
5623 ) -> JsResult<()> {
5624 let target = self.require_object(receiver)?;
5625 let key = self.propkey(key)?;
5626 if !matches!(proto, Value::Null)
5627 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5628 {
5629 if property.is_accessor() {
5630 if let Some(setter) = &property.setter
5631 && !matches!(setter, Value::Undefined)
5632 {
5633 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5634 }
5635 return Ok(());
5636 }
5637 // A data property on the prototype is writable or not; reading `owner` at
5638 // all is only for the attribute check.
5639 if !property.writable {
5640 return Err(self.type_error(format!("'{key}' is read-only")));
5641 }
5642 let _ = owner;
5643 }
5644 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5645 }
5646
5647 /// The object a `super` operation needs, or the `TypeError` the spec raises.
5648 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5649 match value.as_object() {
5650 Some(object) => Ok(object.clone()),
5651 None => Err(Signal::Throw(
5652 self.make_error("TypeError", "value is not an object"),
5653 )),
5654 }
5655 }
5656
5657 /// Build the class object `define_class` produces.
5658 ///
5659 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5660 /// whose prototype property is a fresh object inheriting from the parent's
5661 /// prototype, and whose own prototype is the parent constructor — which is what makes
5662 /// a static method inherited too.
5663 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5664 let ctor = self.pop();
5665 let parent = self.pop();
5666 let Value::Object(function) = &ctor else {
5667 return Err(Signal::Throw(
5668 self.make_error("TypeError", "class constructor must be a function"),
5669 ));
5670 };
5671 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5672 // but gives the instances no prototype at all.
5673 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5674 match &parent {
5675 Value::Null => (Some(self.realm.function_proto.clone()), None),
5676 Value::Object(parent_class) => {
5677 if !parent_class.is_callable() {
5678 return Err(Signal::Throw(
5679 self.make_error("TypeError", "parent class must be constructor"),
5680 ));
5681 }
5682 let proto = self.get_property(parent_class, "prototype")?;
5683 match proto {
5684 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5685 Some(Value::Null) => (Some(parent_class.clone()), None),
5686 _ => {
5687 return Err(Signal::Throw(self.make_error(
5688 "TypeError",
5689 "parent prototype must be an object or null",
5690 )));
5691 }
5692 }
5693 }
5694 _ => {
5695 return Err(Signal::Throw(
5696 self.make_error("TypeError", "parent class must be constructor"),
5697 ));
5698 }
5699 }
5700 } else {
5701 (
5702 Some(self.realm.function_proto.clone()),
5703 Some(self.realm.object_proto.clone()),
5704 )
5705 };
5706 let proto = self.new_object(parent_proto);
5707 function.set_proto(parent_ctor);
5708 // A class is not callable without `new`, and its `prototype` is not writable —
5709 // both follow from being a class and are what `class A {}; A()` throws on.
5710 function.set_class_constructor(true);
5711 function.set_home_object(None);
5712 self.set_function_name(&ctor, name);
5713 self.define_class_properties(function, &ctor, &proto)?;
5714 Ok((ctor, proto))
5715 }
5716
5717 /// Give the constructor its `prototype` and `length`, and the prototype its
5718 /// `constructor` back-pointer.
5719 fn define_class_properties(
5720 &mut self,
5721 function: &Gc<JsObject>,
5722 ctor: &Value,
5723 proto: &Gc<JsObject>,
5724 ) -> JsResult<()> {
5725 proto.define(
5726 "constructor",
5727 Property::with_attributes(ctor.clone(), true, false),
5728 );
5729 function.define(
5730 "prototype",
5731 Property::prototype_of(Value::Object(proto.clone()), false),
5732 );
5733 if let Some((code, _)) = bytecode_of(function) {
5734 let length = code.code.defined_args;
5735 function.define(
5736 "length",
5737 Property::name_or_length(Value::Int(length as i32)),
5738 );
5739 }
5740 Ok(())
5741 }
5742
5743 /// The own array element `key` names, if this object has one.
5744 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5745 // A typed array's elements live in its buffer, not in a property list: reading one
5746 // goes through the view's element type so a bounds check and a detached buffer are
5747 // both handled there.
5748 //
5749 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5750 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5751 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5752 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5753 // consulted. Testing with `array_index` rejected all three, which let a throwing
5754 // getter installed on `TypedArray.prototype["-1"]` run.
5755 if object.typed_array_parts().is_some() {
5756 let property_key = PropertyKey::from(key);
5757 let numeric = canonical_numeric_index(&property_key)?;
5758 if typed_array_index_is_valid(object, numeric) {
5759 return object.typed_array_element(numeric as usize);
5760 }
5761 // Canonical, but not a valid index: `undefined`, and *final*.
5762 return Some(Value::Undefined);
5763 }
5764 let index = array_index(key)?;
5765 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5766 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5767 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5768 // `[1,,3][1]`.
5769 match object.array_get(index as usize) {
5770 Some(Value::Hole) | None => None,
5771 other => other,
5772 }
5773 }
5774
5775 /// Store `object[key] = value`, honouring setters and inherited properties.
5776 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5777 self.set_property_with(object, key, value, DeleteFailure::Throw)
5778 }
5779
5780 /// Store a property, choosing what to do when the object refuses.
5781 ///
5782 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5783 /// mode, which is the one place assignment differs by mode. Native code (the array
5784 /// methods, `JSON`) always asks for the throw.
5785 pub fn set_property_with(
5786 &mut self,
5787 object: &Gc<JsObject>,
5788 key: &str,
5789 value: Value,
5790 on_failure: DeleteFailure,
5791 ) -> JsResult<()> {
5792 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5793 }
5794
5795 /// [`Interp::set_property_with`] with a key that may be a symbol.
5796 pub fn set_property_with_key(
5797 &mut self,
5798 object: &Gc<JsObject>,
5799 key: &PropertyKey,
5800 value: Value,
5801 on_failure: DeleteFailure,
5802 ) -> JsResult<()> {
5803 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5804 }
5805
5806 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5807 ///
5808 /// The receiver split lives one level up, in
5809 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5810 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5811 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5812 /// stores into `object` itself, which is why the element branch below converts `V`
5813 /// before asking whether the index is valid: `V` may put it back in bounds
5814 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5815 fn set_property_with_key_receiver_aware(
5816 &mut self,
5817 object: &Gc<JsObject>,
5818 key: &PropertyKey,
5819 value: Value,
5820 on_failure: DeleteFailure,
5821 ) -> JsResult<()> {
5822 // A proxy's `set` trap decides, and its `false` means the same thing an
5823 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5824 if object.proxy_state().is_some() {
5825 let receiver = Value::Object(object.clone());
5826 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5827 return match (accepted, on_failure) {
5828 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5829 (false, DeleteFailure::Throw) => {
5830 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5831 }
5832 };
5833 }
5834 }
5835 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5836 // refusal and means exactly what a proxy's `false` means.
5837 if let Some(exotic) = object.exotic() {
5838 let receiver = Value::Object(object.clone());
5839 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5840 return match (accepted, on_failure) {
5841 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5842 (false, DeleteFailure::Throw) => {
5843 Err(self.type_error(format!("property '{key}' is read-only")))
5844 }
5845 };
5846 }
5847 }
5848 // The element and `length` shortcuts only exist for string keys: an array
5849 // index has no symbol spelling, and a symbol named `length` is an ordinary
5850 // property.
5851 let text = key.as_str();
5852 // A typed array's elements are a window onto its buffer: the store has to go
5853 // through the view's element type so the value is wrapped (or clamped) and so an
5854 // out-of-range or detached write is a silent no-op, as the spec says.
5855 //
5856 // The key test is `CanonicalNumericIndexString`, like every other index operation
5857 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
5858 // does not exist, so they do nothing and leave no own property behind
5859 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
5860 // path, which created a property named `"-0"`.
5861 //
5862 // The conversion comes **first**, before the index is checked at all, and that
5863 // order is observable twice over:
5864 //
5865 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
5866 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
5867 // then store the converted value;
5868 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
5869 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
5870 // run and its exception to escape.
5871 //
5872 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
5873 // validity check, not a validity check that skips the conversion. The store itself
5874 // is a no-op when the index is invalid by then, which is why no extra guard is
5875 // needed around `typed_array_set`.
5876 if let Some(element) = object.typed_array_element_type()
5877 && let Some(numeric) = canonical_numeric_index(key)
5878 {
5879 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5880 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5881 // in `Interp`, because it is script-observable and the storage borrow inside
5882 // `typed_array_set` must not be held across it.
5883 let stored = self.element_value(element, value)?;
5884 if typed_array_index_is_valid(object, numeric)
5885 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
5886 {
5887 return Err(self.type_error(reason));
5888 }
5889 return Ok(());
5890 }
5891 if let Some(text) = text
5892 && let Some(index) = array_index(text)
5893 && object.is_array()
5894 {
5895 // An accessor defined on an index lives in the property table while the
5896 // element slot is a hole, so the store has to go through the property first.
5897 // Writing the vector directly skipped the setter entirely.
5898 if let Some(existing) = object.own_property_key(key) {
5899 if existing.is_accessor() {
5900 return match existing.setter.clone() {
5901 Some(setter) if !matches!(setter, Value::Undefined) => {
5902 let receiver = Value::Object(object.clone());
5903 self.call_value(setter, receiver, vec![value]).map(|_| ())
5904 }
5905 _ => match on_failure {
5906 DeleteFailure::Throw => Err(self.type_error(format!(
5907 "cannot set property '{text}', it has only a getter"
5908 ))),
5909 DeleteFailure::Ignore => Ok(()),
5910 },
5911 };
5912 }
5913 if !existing.writable {
5914 return match on_failure {
5915 DeleteFailure::Throw => {
5916 Err(self.type_error(format!("'{text}' is read-only")))
5917 }
5918 DeleteFailure::Ignore => Ok(()),
5919 };
5920 }
5921 }
5922 {
5923 // Growing the array needs a writable `length`.
5924 if (index as usize) >= object.array_length().unwrap_or(0)
5925 && !object.length_writable()
5926 {
5927 return match on_failure {
5928 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5929 DeleteFailure::Ignore => Ok(()),
5930 };
5931 }
5932 // Adding an index past the end makes the array longer, which a
5933 // non-extensible array refuses.
5934 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5935 return match on_failure {
5936 DeleteFailure::Throw => Err(self.type_error(format!(
5937 "cannot add property '{key}', object is not extensible"
5938 ))),
5939 DeleteFailure::Ignore => Ok(()),
5940 };
5941 }
5942 if object.element_is_locked(index) {
5943 return match on_failure {
5944 DeleteFailure::Throw => {
5945 Err(self.type_error(format!("'{key}' is read-only")))
5946 }
5947 DeleteFailure::Ignore => Ok(()),
5948 };
5949 }
5950 // The element vector is only half of `[[Set]]` for an index: the
5951 // prototype chain is consulted first, and a setter there answers instead
5952 // of the element store. This branch used to write the element directly, so
5953 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5954 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5955 // the reference calls the setter and the array keeps no own index.
5956 //
5957 // An *exotic* prototype has no entry to find, because its indices live
5958 // outside the property table — `Object.setPrototypeOf([], typedArray)`
5959 // then looked like "nothing on the chain" and the store created the
5960 // element, where the view's `[[Set]]` answers `true` and does nothing for
5961 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
5962 // checks the array's `length` stays 0). So the dispatch comes first.
5963 if !object.has_own_key(key)
5964 && let Some(proto) = object.proto()
5965 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
5966 {
5967 let receiver = Value::Object(object.clone());
5968 let accepted =
5969 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
5970 return if accepted {
5971 Ok(())
5972 } else {
5973 match on_failure {
5974 DeleteFailure::Throw => {
5975 Err(self.type_error(format!("'{key}' is read-only")))
5976 }
5977 DeleteFailure::Ignore => Ok(()),
5978 }
5979 };
5980 }
5981 if let Some((owner, property)) = lookup_key(object, key)
5982 && !owner.ptr_eq(object)
5983 {
5984 match &property {
5985 property if property.is_accessor() => {
5986 match &property.setter {
5987 Some(setter) if !matches!(setter, Value::Undefined) => {
5988 let receiver = Value::Object(object.clone());
5989 self.call_value(setter.clone(), receiver, vec![value])?;
5990 }
5991 _ => {
5992 return match on_failure {
5993 DeleteFailure::Throw => Err(self.type_error(format!(
5994 "cannot set property '{text}', it has only a getter"
5995 ))),
5996 DeleteFailure::Ignore => Ok(()),
5997 };
5998 }
5999 }
6000 return Ok(());
6001 }
6002 property if !property.writable => {
6003 return match on_failure {
6004 DeleteFailure::Throw => {
6005 Err(self.type_error(format!("'{text}' is read-only")))
6006 }
6007 DeleteFailure::Ignore => Ok(()),
6008 };
6009 }
6010 _ => {}
6011 }
6012 }
6013 if object.array_set(self.heap, index as usize, value.clone()) {
6014 return Ok(());
6015 }
6016 // Past the dense limit the slot is too far out to be worth one `Value`
6017 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6018 // constant time by keeping the index as an ordinary property. The store
6019 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6020 // to a legal program.
6021 object.define_key(key, Property::with_attributes(value, true, true));
6022 // Extend, never shorten: the index may be *inside* the current length (a
6023 // huge `length` with a sparse store), and shortening would delete the
6024 // sparse properties above it — including the one just stored.
6025 if index as usize + 1 > object.array_length().unwrap_or(0) {
6026 object.array_set_length(self.heap, index as usize + 1);
6027 }
6028 return Ok(());
6029 }
6030 }
6031 if text == Some("length") && object.is_array() {
6032 if !object.length_writable() {
6033 return match on_failure {
6034 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6035 DeleteFailure::Ignore => Ok(()),
6036 };
6037 }
6038 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6039 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6040 // answered `NaN`, which left the assignment silently ignored
6041 // (`S15.4.5.2_A3_T2`).
6042 let length = self.to_js_number(&value)?;
6043 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6044 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6045 // `RangeError`s; the old code only tested "finite and non-negative" and then
6046 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6047 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6048 let valid = length.is_finite()
6049 && length >= 0.0
6050 && length.fract() == 0.0
6051 && length <= u32::MAX as f64;
6052 if !valid {
6053 return Err(self.range_error("invalid array length"));
6054 }
6055 {
6056 let length = length as usize;
6057 // `a.length = n` with `n` below a non-configurable element cannot
6058 // drop that element, so the whole assignment fails. The spec makes
6059 // this a `TypeError` rather than a silent no-op, in any mode.
6060 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6061 // Sloppy mode stops the truncation at the blocking element
6062 // instead of failing; strict mode raises.
6063 // Both modes stop at the blocking element; they differ in
6064 // whether that is reported. The reference truncates *then*
6065 // throws, so the array is left in the shortened state.
6066 object.array_truncate(self.heap, blocked + 1);
6067 return match on_failure {
6068 DeleteFailure::Throw => {
6069 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6070 }
6071 DeleteFailure::Ignore => Ok(()),
6072 };
6073 }
6074 object.array_set_length(self.heap, length);
6075 return Ok(());
6076 }
6077 }
6078 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6079 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6080 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6081 //
6082 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6083 // applying whatever came back is the same thing for an ordinary prototype and
6084 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6085 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6086 // answers "not mine, the receiver is not me" without touching the buffer. This
6087 // code used to find nothing owned by `o`, find no property on the view either,
6088 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6089 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6090 // `key-is-canonical-invalid-index-prototype-chain-set`).
6091 //
6092 // The read-only and accessor rules of step 1 are what make
6093 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6094 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6095 let own = match self.lookup_for_write(object, key)? {
6096 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6097 _ => None,
6098 };
6099 if let Some(property) = own {
6100 if property.is_accessor() {
6101 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6102 Some(setter) => {
6103 let receiver = Value::Object(object.clone());
6104 self.call_value(setter, receiver, vec![value])?;
6105 Ok(())
6106 }
6107 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6108 // Sloppy code swallows that refusal, strict code raises — the same
6109 // rule the read-only *data* property below follows, and skipping it
6110 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6111 // return silently. The reference answers `TypeError: 'x' is
6112 // read-only`.
6113 None => match on_failure {
6114 DeleteFailure::Throw => {
6115 Err(self.type_error(format!("'{key}' is read-only")))
6116 }
6117 DeleteFailure::Ignore => Ok(()),
6118 },
6119 };
6120 }
6121 // An own non-writable data property stops here: nothing may change it.
6122 if !property.writable {
6123 return match on_failure {
6124 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6125 DeleteFailure::Ignore => Ok(()),
6126 };
6127 }
6128 // An existing writable own property keeps its attributes: only the value
6129 // moves. Redefining instead would reset them, which is how a
6130 // non-configurable global `var` used to become deletable.
6131 if object.write_value_key(key, value.clone()) {
6132 return Ok(());
6133 }
6134 }
6135 // Step 2: hand the store to the prototype, with `object` as the receiver.
6136 if let Some(proto) = object.proto() {
6137 let receiver = Value::Object(object.clone());
6138 let accepted =
6139 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6140 return if accepted {
6141 Ok(())
6142 } else {
6143 match on_failure {
6144 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6145 DeleteFailure::Ignore => Ok(()),
6146 }
6147 };
6148 }
6149 // Step 3: create one, and a non-extensible object cannot.
6150 if !object.is_extensible() {
6151 return match on_failure {
6152 DeleteFailure::Throw => Err(self.type_error(format!(
6153 "cannot add property {key}, object is not extensible"
6154 ))),
6155 DeleteFailure::Ignore => Ok(()),
6156 };
6157 }
6158 object.define_data_key(key, value);
6159 Ok(())
6160 }
6161
6162 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6163 ///
6164 /// The distinction the fast path above does not need: it is called with the store's
6165 /// receiver already being the object it writes to. Here `object` is the one whose
6166 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6167 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6168 /// and not a write to `object`.
6169 ///
6170 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6171 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6172 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6173 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6174 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6175 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6176 ///
6177 /// Answers `false` where the spec says `false`; the caller turns that into the
6178 /// strict-mode `TypeError` or the sloppy-mode silence.
6179 fn ordinary_set_with_receiver(
6180 &mut self,
6181 object: &Gc<JsObject>,
6182 receiver: &Value,
6183 key: &PropertyKey,
6184 value: Value,
6185 on_failure: DeleteFailure,
6186 ) -> JsResult<bool> {
6187 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6188 if object.proxy_state().is_some() {
6189 return Ok(self
6190 .proxy_set(object, key, value, receiver)?
6191 .unwrap_or(true));
6192 }
6193 // A host class decides for itself, with the receiver the caller named.
6194 if let Some(exotic) = object.exotic()
6195 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6196 {
6197 return Ok(accepted);
6198 }
6199 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6200 // rather than the receiver, but the receiver may still *be* the view:
6201 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6202 // itself as receiver, and then the first half applies — convert `V` once, store
6203 // if the index is valid, answer `true` either way. The conversion is the observable
6204 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6205 //
6206 // Only the second half, a view that is *not* the receiver, skips the conversion
6207 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6208 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6209 // below with the value still unconverted.
6210 if object.typed_array_element_type().is_some()
6211 && let Some(numeric) = canonical_numeric_index(key)
6212 {
6213 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6214 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6215 return Ok(true);
6216 }
6217 if !typed_array_index_is_valid(object, numeric) {
6218 return Ok(true);
6219 }
6220 }
6221 let own = self.object_get_own_property(object, key)?;
6222 if let Some(own) = own {
6223 if own.is_accessor() {
6224 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6225 Some(setter) => {
6226 self.call_value(setter, receiver.clone(), vec![value])?;
6227 Ok(true)
6228 }
6229 None => Ok(false),
6230 };
6231 }
6232 // A non-writable data descriptor refuses, own or inherited. Either way the
6233 // receiver must not gain a shadowing property.
6234 if !own.writable {
6235 return Ok(false);
6236 }
6237 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6238 // created or written, and it is created as an ordinary data property.
6239 let Some(receiver_object) = receiver.as_object().cloned() else {
6240 return Ok(false);
6241 };
6242 return match self.object_get_own_property(&receiver_object, key)? {
6243 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6244 Some(existing) => self.object_define_own_property(
6245 &receiver_object,
6246 key,
6247 Property {
6248 value: Some(value),
6249 ..existing
6250 },
6251 ),
6252 None => {
6253 self.object_define_own_property(&receiver_object, key, Property::data(value))
6254 }
6255 };
6256 }
6257 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6258 if let Some(proto) = object.proto() {
6259 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6260 }
6261 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6262 // *default* data descriptor here, so control falls into step 2 exactly as if the
6263 // target had owned a writable property — which means the **receiver's** own
6264 // descriptor is asked for before the write. Skipping that question went straight to
6265 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6266 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6267 // exactly those calls).
6268 let Some(receiver_object) = receiver.as_object().cloned() else {
6269 return Ok(false);
6270 };
6271 match self.object_get_own_property(&receiver_object, key)? {
6272 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6273 Some(existing) => self.object_define_own_property(
6274 &receiver_object,
6275 key,
6276 Property {
6277 value: Some(value),
6278 ..existing
6279 },
6280 ),
6281 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6282 }
6283 }
6284
6285 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6286 ///
6287 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6288 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6289 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6290 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6291 /// the prototype, so the walk resumes above the object.
6292 fn lookup_for_write(
6293 &mut self,
6294 object: &Gc<JsObject>,
6295 key: &PropertyKey,
6296 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6297 let Some(exotic) = object.exotic() else {
6298 return Ok(lookup_key(object, key));
6299 };
6300 Ok(match exotic.get_own_property(self, object, key)? {
6301 Some(Some(property)) => Some((object.clone(), property)),
6302 Some(None) => lookup_key_above(object, key),
6303 None => lookup_key(object, key),
6304 })
6305 }
6306
6307 /// Delete `object[key]`.
6308 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6309 self.delete_property_key(object, &PropertyKey::from(key))
6310 }
6311
6312 /// [`Interp::delete_property`] with a key that may be a symbol.
6313 pub fn delete_property_key(
6314 &mut self,
6315 object: &Gc<JsObject>,
6316 key: &PropertyKey,
6317 ) -> JsResult<bool> {
6318 // A proxy decides for itself, and may even throw; the invariant checks live in
6319 // `proxy_delete`.
6320 if let Some(answer) = self.proxy_delete(object, key)? {
6321 return Ok(answer);
6322 }
6323 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6324 // caller reports as a failed delete.
6325 if let Some(exotic) = object.exotic()
6326 && let Some(answer) = exotic.delete_property(self, object, key)?
6327 {
6328 return Ok(answer);
6329 }
6330 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6331 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6332 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6333 // one answers `false` because the elements are non-configurable. The prototype
6334 // chain is not consulted either, which is what makes a throwing getter on
6335 // `TypedArray.prototype["-1"]` stay unrun.
6336 if object.typed_array_parts().is_some()
6337 && object.proxy_state().is_none()
6338 && let Some(numeric) = canonical_numeric_index(key)
6339 {
6340 return Ok(!typed_array_index_is_valid(object, numeric));
6341 }
6342 let mapped_index = key.as_str().and_then(array_index);
6343 if let Some(index) = mapped_index
6344 && let Some(length) = object.array_length()
6345 && (index as usize) < length
6346 {
6347 // An accessor defined on an index lives in the property table rather than the
6348 // element vector, so both have to be cleared: `delete` after
6349 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6350 object.delete_key(key);
6351 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6352 // index stops answering `in`.
6353 if object.element_is_undeletable(index) {
6354 return Ok(false);
6355 }
6356 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6357 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6358 // and no longer through to the parameter. A refused delete leaves the
6359 // mapping alone.
6360 object.drop_mapped_argument(index as usize);
6361 object.array_set(self.heap, index as usize, Value::Hole);
6362 return Ok(true);
6363 }
6364 // An array's `length` is a non-configurable own property that lives outside the
6365 // property table, so `delete_key` finds nothing and reports success — `Reflect
6366 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6367 // §10.4.4.1 step 3 refuses it.
6368 if key.as_str() == Some("length") && object.array_length().is_some() {
6369 return Ok(false);
6370 }
6371 // The same for an object that is not an array: only a delete that actually
6372 // removed the property ends the alias.
6373 let deleted = object.delete_key(key);
6374 if deleted && let Some(index) = mapped_index {
6375 object.drop_mapped_argument(index as usize);
6376 }
6377 Ok(deleted)
6378 }
6379
6380 // -- proxy traps --------------------------------------------------------
6381 //
6382 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6383 // with the target and the operation's own arguments, then check the answer against
6384 // the target. The checks are not decoration — they are what stops a proxy from
6385 // reporting a `non-configurable` property as missing, which would let a frozen object
6386 // be rewritten by standing in front of it.
6387
6388 /// The target and handler of `object`, or `None` when it is not a proxy.
6389 ///
6390 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6391 /// one has to fail: the slots the traps would have been read from are gone.
6392 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6393 let Some(state) = object.proxy_state() else {
6394 return Ok(None);
6395 };
6396 let state = state.borrow();
6397 match (&state.target, &state.handler) {
6398 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6399 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6400 }
6401 }
6402
6403 /// Call `handler[name]`, or answer `None` when the trap is absent.
6404 ///
6405 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6406 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6407 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6408 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6409 /// one per trap plus the `target-is-proxy` variants.
6410 ///
6411 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6412 /// this cannot simply be "any non-callable means no trap".
6413 fn proxy_trap(
6414 &mut self,
6415 handler: &Value,
6416 name: &str,
6417 args: Vec<Value>,
6418 ) -> JsResult<Option<Value>> {
6419 let Value::Object(table) = handler else {
6420 return Err(self.type_error("proxy handler is not an object"));
6421 };
6422 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6423 match trap {
6424 Value::Undefined | Value::Null => Ok(None),
6425 Value::Object(function) if function.is_callable() => {
6426 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6427 Ok(Some(answer))
6428 }
6429 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6430 }
6431 }
6432
6433 /// Whether the target's own property `key` is one it refuses to lose.
6434 ///
6435 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6436 /// its value behind the target's back.
6437 ///
6438 /// A **method**, not a free function, because §10.5.1's invariants say
6439 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6440 /// property table directly finds nothing (a proxy's table is empty by design), so every
6441 /// invariant check silently passed for a proxy target. That is what
6442 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6443 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6444 /// where an array's elements and its `length` — both fixed, both outside the table —
6445 /// are covered.
6446 fn fixed_property(
6447 &mut self,
6448 target: &Gc<JsObject>,
6449 key: &PropertyKey,
6450 ) -> JsResult<Option<Property>> {
6451 Ok(self
6452 .object_get_own_property(target, key)?
6453 .filter(|property| !property.configurable))
6454 }
6455
6456 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6457 fn proxy_get(
6458 &mut self,
6459 object: &Gc<JsObject>,
6460 receiver: &Value,
6461 key: &PropertyKey,
6462 ) -> JsResult<Option<Value>> {
6463 let Some((target, handler)) = self.proxy_parts(object)? else {
6464 return Ok(None);
6465 };
6466 let key_value = self.key_value(key);
6467 let Some(result) = self.proxy_trap(
6468 &handler,
6469 "get",
6470 vec![Value::Object(target.clone()), key_value, receiver.clone()],
6471 )?
6472 else {
6473 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6474 // inherited getter still sees the proxy.
6475 return Ok(Some(
6476 self.get_property_key_for(&target, Some(receiver), key)?
6477 .unwrap_or(Value::Undefined),
6478 ));
6479 };
6480 if let Some(fixed) = self.fixed_property(&target, key)? {
6481 if fixed.is_accessor() {
6482 // A fixed accessor with no getter must read as `undefined`.
6483 let has_getter = fixed
6484 .getter
6485 .as_ref()
6486 .is_some_and(|getter| !matches!(getter, Value::Undefined));
6487 if !has_getter && !matches!(result, Value::Undefined) {
6488 return Err(self.type_error(format!(
6489 "proxy 'get' must report undefined for the non-configurable property '{key}'"
6490 )));
6491 }
6492 } else if !fixed.writable {
6493 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6494 if !fixed_value.same_value(&result) {
6495 return Err(self.type_error(format!(
6496 "proxy 'get' disagrees with the non-configurable property '{key}'"
6497 )));
6498 }
6499 }
6500 }
6501 Ok(Some(result))
6502 }
6503
6504 /// `[[Set]]` on a proxy.
6505 ///
6506 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6507 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6508 /// read-only store has.
6509 fn proxy_set(
6510 &mut self,
6511 object: &Gc<JsObject>,
6512 key: &PropertyKey,
6513 value: Value,
6514 receiver: &Value,
6515 ) -> JsResult<Option<bool>> {
6516 let Some((target, handler)) = self.proxy_parts(object)? else {
6517 return Ok(None);
6518 };
6519 let key_value = self.key_value(key);
6520 let Some(result) = self.proxy_trap(
6521 &handler,
6522 "set",
6523 vec![
6524 Value::Object(target.clone()),
6525 key_value,
6526 value.clone(),
6527 receiver.clone(),
6528 ],
6529 )?
6530 else {
6531 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6532 // given — not the target. `OrdinarySet` step 3 is
6533 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6534 // object whose prototype is a typed array has to reach the proxy's own
6535 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6536 // calls and expects exactly one. Storing on the target instead put the value
6537 // in the target and never consulted the trap.
6538 let accepted = self.ordinary_set_with_receiver(
6539 &target,
6540 receiver,
6541 key,
6542 value,
6543 DeleteFailure::Ignore,
6544 )?;
6545 return Ok(Some(accepted));
6546 };
6547 if !result.to_boolean() {
6548 return Ok(Some(false));
6549 }
6550 if let Some(fixed) = self.fixed_property(&target, key)? {
6551 if fixed.is_accessor() {
6552 let has_setter = fixed
6553 .setter
6554 .as_ref()
6555 .is_some_and(|setter| !matches!(setter, Value::Undefined));
6556 if !has_setter {
6557 return Err(self.type_error(format!(
6558 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6559 )));
6560 }
6561 } else if !fixed.writable {
6562 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6563 if !fixed_value.same_value(&value) {
6564 return Err(self.type_error(format!(
6565 "proxy 'set' changed the non-configurable property '{key}'"
6566 )));
6567 }
6568 }
6569 }
6570 // A new property cannot appear on a target that refuses new properties.
6571 if self.object_get_own_property(&target, key)?.is_none()
6572 && !self.object_is_extensible(&target)?
6573 {
6574 return Err(self.type_error(format!(
6575 "proxy 'set' added '{key}' to a non-extensible target"
6576 )));
6577 }
6578 Ok(Some(true))
6579 }
6580
6581 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6582 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6583 let Some((target, handler)) = self.proxy_parts(object)? else {
6584 return Ok(None);
6585 };
6586 let key_value = self.key_value(key);
6587 let Some(result) = self.proxy_trap(
6588 &handler,
6589 "has",
6590 vec![Value::Object(target.clone()), key_value],
6591 )?
6592 else {
6593 return Ok(Some(self.has_own_or_inherited(&target, key)?));
6594 };
6595 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6596 return Err(self.type_error(format!(
6597 "proxy 'has' denied the non-configurable property '{key}'"
6598 )));
6599 }
6600 // A non-extensible target cannot grow, so every own property it *has* is fixed.
6601 if !result.to_boolean()
6602 && !self.object_is_extensible(&target)?
6603 && self.object_get_own_property(&target, key)?.is_some()
6604 {
6605 return Err(self.type_error(format!(
6606 "proxy 'has' denied the own property '{key}' of a non-extensible target"
6607 )));
6608 }
6609 Ok(Some(result.to_boolean()))
6610 }
6611
6612 /// `[[Delete]]` on a proxy.
6613 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6614 let Some((target, handler)) = self.proxy_parts(object)? else {
6615 return Ok(None);
6616 };
6617 let key_value = self.key_value(key);
6618 let Some(result) = self.proxy_trap(
6619 &handler,
6620 "deleteProperty",
6621 vec![Value::Object(target.clone()), key_value],
6622 )?
6623 else {
6624 return Ok(Some(self.delete_property_key(&target, key)?));
6625 };
6626 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6627 return Err(self.type_error(format!(
6628 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6629 )));
6630 }
6631 if result.to_boolean()
6632 && !self.object_is_extensible(&target)?
6633 && self.object_get_own_property(&target, key)?.is_some()
6634 {
6635 return Err(self.type_error(format!(
6636 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6637 )));
6638 }
6639 Ok(Some(result.to_boolean()))
6640 }
6641
6642 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6643 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6644 let Some((target, handler)) = self.proxy_parts(object)? else {
6645 return Ok(None);
6646 };
6647 let Some(result) =
6648 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6649 else {
6650 // No trap: the target's own keys, already in the order an object reports.
6651 return Ok(Some(self.object_own_property_keys(&target)?));
6652 };
6653 // `CreateListFromArrayLike` with the string-or-symbol restriction.
6654 let list = self.list_from_array_like(&result, true)?;
6655 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6656 for value in list {
6657 let key = self.propkey(&value)?;
6658 if keys.contains(&key) {
6659 return Err(self.type_error(format!(
6660 "proxy 'ownKeys' returned the duplicate key '{key}'"
6661 )));
6662 }
6663 keys.push(key);
6664 }
6665 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
6666 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
6667 // table is empty, which made every check below vacuous.
6668 let target_keys = self.object_own_property_keys(&target)?;
6669 let extensible = self.object_is_extensible(&target)?;
6670 for key in &target_keys {
6671 if keys.contains(key) {
6672 continue;
6673 }
6674 if self.fixed_property(&target, key)?.is_some() {
6675 return Err(self.type_error(format!(
6676 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6677 )));
6678 }
6679 if !extensible {
6680 return Err(self.type_error(format!(
6681 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6682 )));
6683 }
6684 }
6685 if !extensible {
6686 // §10.5.11 step 12: the lists must match one for one, in any order.
6687 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
6688 {
6689 return Err(
6690 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6691 );
6692 }
6693 }
6694 Ok(Some(keys))
6695 }
6696
6697 /// `[[GetOwnProperty]]` on a proxy.
6698 fn proxy_get_own_property(
6699 &mut self,
6700 object: &Gc<JsObject>,
6701 key: &PropertyKey,
6702 ) -> JsResult<Option<Option<Property>>> {
6703 let Some((target, handler)) = self.proxy_parts(object)? else {
6704 return Ok(None);
6705 };
6706 let key_value = self.key_value(key);
6707 let Some(result) = self.proxy_trap(
6708 &handler,
6709 "getOwnPropertyDescriptor",
6710 vec![Value::Object(target.clone()), key_value],
6711 )?
6712 else {
6713 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
6714 // property table. Two things ride on that choice: a target that is itself a
6715 // proxy has to re-dispatch (its own table is empty, so reading it reported
6716 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
6717 // indices and `length` live outside the table and need the ordinary synthesis.
6718 // `object_get_own_property` does both.
6719 return Ok(Some(self.object_get_own_property(&target, key)?));
6720 };
6721 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
6722 // `ToPropertyDescriptor` runs, because that operation would box the primitive
6723 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
6724 // empty descriptor instead of refusing.
6725 if !matches!(result, Value::Undefined | Value::Object(_)) {
6726 return Err(self.type_error(
6727 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
6728 ));
6729 }
6730 let target_desc = self.object_get_own_property(&target, key)?;
6731 let extensible = self.object_is_extensible(&target)?;
6732 let Some(descriptor) = (match result {
6733 Value::Undefined => None,
6734 _ => Some(self.property_from_descriptor(&result)?),
6735 }) else {
6736 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
6737 // descriptor is configurable *and* the target can still grow back.
6738 if let Some(target_desc) = &target_desc {
6739 if !target_desc.configurable {
6740 return Err(self.type_error(format!(
6741 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6742 )));
6743 }
6744 if !extensible {
6745 return Err(self.type_error(format!(
6746 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
6747 )));
6748 }
6749 }
6750 return Ok(Some(None));
6751 };
6752 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
6753 // which is a stronger requirement than "the target is not contradicting it" — the
6754 // four branches below are each one test262 case.
6755 if !descriptor.configurable {
6756 let Some(target_desc) = &target_desc else {
6757 return Err(self.type_error(format!(
6758 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
6759 )));
6760 };
6761 if target_desc.configurable {
6762 return Err(self.type_error(format!(
6763 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
6764 )));
6765 }
6766 let target_is_data = !target_desc.is_accessor();
6767 let result_is_data = !descriptor.is_accessor();
6768 if result_is_data && !target_is_data {
6769 return Err(self.type_error(format!(
6770 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6771 )));
6772 }
6773 if target_is_data && !target_desc.writable {
6774 if !result_is_data {
6775 return Err(self.type_error(format!(
6776 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6777 )));
6778 }
6779 if descriptor.writable {
6780 return Err(self.type_error(format!(
6781 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6782 )));
6783 }
6784 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
6785 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6786 if !fixed_value.same_value(&reported) {
6787 return Err(self.type_error(format!(
6788 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6789 )));
6790 }
6791 }
6792 // Step 16.d: a reported *read-only* data property needs a real read-only data
6793 // property behind it. Missing this let a trap bolt a frozen property onto a
6794 // writable target intent (`resultdesc-is-not-configurable-not-writable-
6795 // targetdesc-is-writable`).
6796 if result_is_data && !descriptor.writable {
6797 if !target_is_data {
6798 return Err(self.type_error(format!(
6799 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6800 )));
6801 }
6802 if target_desc.writable {
6803 return Err(self.type_error(format!(
6804 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
6805 )));
6806 }
6807 }
6808 if descriptor.is_accessor() {
6809 // Step 16.e: a getter the target does not have may not be invented, and
6810 // vice versa.
6811 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6812 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6813 (Some(a), Some(b)) => a.same_value(b),
6814 _ => false,
6815 };
6816 if !same(&target_desc.getter, &descriptor.getter)
6817 || !same(&target_desc.setter, &descriptor.setter)
6818 {
6819 return Err(self.type_error(format!(
6820 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6821 )));
6822 }
6823 }
6824 }
6825 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
6826 // where the target's own is locked. Without it a handler could advertise
6827 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
6828 // that believed it would try to redefine something it cannot.
6829 if descriptor.configurable
6830 && let Some(target_desc) = &target_desc
6831 && !target_desc.configurable
6832 {
6833 return Err(self.type_error(format!(
6834 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6835 )));
6836 }
6837 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
6838 // through the trap either, however well-formed the descriptor is. This is the
6839 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
6840 // the frozen target does not own.
6841 if !extensible {
6842 let Some(target_desc) = &target_desc else {
6843 return Err(self.type_error(format!(
6844 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
6845 )));
6846 };
6847 if target_desc.is_accessor() == descriptor.is_accessor() {
6848 let target_is_data = !target_desc.is_accessor();
6849 let result_is_data = !descriptor.is_accessor();
6850 if target_is_data && !target_desc.writable && descriptor.writable {
6851 return Err(self.type_error(format!(
6852 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6853 )));
6854 }
6855 if !result_is_data && !target_is_data {
6856 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6857 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6858 (Some(a), Some(b)) => a.same_value(b),
6859 _ => false,
6860 };
6861 if !same(&target_desc.getter, &descriptor.getter)
6862 || !same(&target_desc.setter, &descriptor.setter)
6863 {
6864 return Err(self.type_error(format!(
6865 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6866 )));
6867 }
6868 }
6869 }
6870 }
6871 Ok(Some(Some(descriptor)))
6872 }
6873
6874 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
6875 ///
6876 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
6877 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
6878 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
6879 /// for a data property. `Property` cannot express "this field is absent", so the whole
6880 /// property path is skipped and the descriptor is assembled here field by field.
6881 ///
6882 /// `current` is the property the trap reported, used only to tell a data property from
6883 /// an accessor.
6884 pub fn proxy_seal_property(
6885 &mut self,
6886 object: &Gc<JsObject>,
6887 key: &PropertyKey,
6888 frozen: bool,
6889 current: &Property,
6890 ) -> JsResult<bool> {
6891 let Some((_target, handler)) = self.proxy_parts(object)? else {
6892 return Err(self.type_error("not a proxy"));
6893 };
6894 let descriptor = self.new_object(None);
6895 descriptor.define_data("configurable", Value::Bool(false));
6896 if frozen && !current.is_accessor() {
6897 descriptor.define_data("writable", Value::Bool(false));
6898 }
6899 let key_value = self.key_value(key);
6900 let target = object
6901 .proxy_state()
6902 .and_then(|state| state.borrow().target.clone());
6903 let Some(target) = target else {
6904 return Err(self.type_error("cannot use a proxy that has been revoked"));
6905 };
6906 let Some(result) = self.proxy_trap(
6907 &handler,
6908 "defineProperty",
6909 vec![Value::Object(target), key_value, Value::Object(descriptor)],
6910 )?
6911 else {
6912 // No trap means the definition belongs to the target; `false` is its answer.
6913 return Ok(false);
6914 };
6915 Ok(result.to_boolean())
6916 }
6917
6918 /// `[[DefineOwnProperty]]` on a proxy.
6919 fn proxy_define_property(
6920 &mut self,
6921 object: &Gc<JsObject>,
6922 key: &PropertyKey,
6923 property: Property,
6924 ) -> JsResult<Option<bool>> {
6925 let Some((target, handler)) = self.proxy_parts(object)? else {
6926 return Ok(None);
6927 };
6928 let key_value = self.key_value(key);
6929 let descriptor = self.descriptor_from_property(&property);
6930 let Some(result) = self.proxy_trap(
6931 &handler,
6932 "defineProperty",
6933 vec![Value::Object(target.clone()), key_value, descriptor],
6934 )?
6935 else {
6936 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
6937 // going" answer and `object_define_own_property` turns it into exactly that
6938 // forwarding — see the note there. (Reading it as "not a proxy" would define
6939 // the property on the proxy object itself, whose table is empty and which no
6940 // read ever consults.)
6941 return Ok(None);
6942 };
6943 if !result.to_boolean() {
6944 return Ok(Some(false));
6945 }
6946 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
6947 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
6948 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
6949 // and treating them alike made four cases pass a descriptor the target contradicts.
6950 let target_desc = self.object_get_own_property(&target, key)?;
6951 let extensible = self.object_is_extensible(&target)?;
6952 let named = property
6953 .descriptor_fields
6954 .unwrap_or(crate::object::DescriptorFields {
6955 value: false,
6956 writable: false,
6957 enumerable: false,
6958 configurable: false,
6959 get: false,
6960 set: false,
6961 });
6962 if named.configurable && !property.configurable {
6963 let Some(target_desc) = &target_desc else {
6964 return Err(self.type_error(format!(
6965 "proxy 'defineProperty' invented the non-configurable '{key}'"
6966 )));
6967 };
6968 if target_desc.configurable {
6969 return Err(self.type_error(format!(
6970 "proxy 'defineProperty' made '{key}' non-configurable"
6971 )));
6972 }
6973 }
6974 // Step 11's other half: reporting that a property was made *configurable* needs a
6975 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
6976 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
6977 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
6978 // target`).
6979 if named.configurable
6980 && property.configurable
6981 && let Some(target_desc) = &target_desc
6982 && !target_desc.configurable
6983 {
6984 return Err(
6985 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
6986 );
6987 }
6988 // Step 12: a property cannot be reported *made writable* when the target's copy is
6989 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
6990 // the trap is allowed to claim a definition it did not perform, as long as the
6991 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
6992 // legal, and refusing it broke the commonest way to seed a proxy).
6993 if named.writable
6994 && property.writable
6995 && let Some(target_desc) = &target_desc
6996 && !target_desc.writable
6997 {
6998 return Err(self.type_error(format!(
6999 "proxy 'defineProperty' made the read-only '{key}' writable"
7000 )));
7001 }
7002 // Step 13: making a property read-only needs an existing read-only property.
7003 if named.writable
7004 && !property.writable
7005 && let Some(target_desc) = &target_desc
7006 && !target_desc.is_accessor()
7007 && target_desc.writable
7008 {
7009 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7010 }
7011 // Step 14: a non-writable, non-configurable property's value is fixed.
7012 if named.value
7013 && let Some(target_desc) = &target_desc
7014 && !target_desc.is_accessor()
7015 && !target_desc.writable
7016 && !target_desc.configurable
7017 {
7018 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7019 let reported = property.value.clone().unwrap_or(Value::Undefined);
7020 if !fixed_value.same_value(&reported) {
7021 return Err(self.type_error(format!(
7022 "proxy 'defineProperty' changed the value of '{key}'"
7023 )));
7024 }
7025 }
7026 // Step 15: a non-extensible target cannot grow.
7027 if target_desc.is_none() && !extensible {
7028 return Err(self.type_error(format!(
7029 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7030 )));
7031 }
7032 Ok(Some(true))
7033 }
7034
7035 /// `[[GetPrototypeOf]]` on a proxy.
7036 fn proxy_get_prototype_of(
7037 &mut self,
7038 object: &Gc<JsObject>,
7039 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7040 let Some((target, handler)) = self.proxy_parts(object)? else {
7041 return Ok(None);
7042 };
7043 let Some(result) = self.proxy_trap(
7044 &handler,
7045 "getPrototypeOf",
7046 vec![Value::Object(target.clone())],
7047 )?
7048 else {
7049 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7050 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7051 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7052 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7053 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7054 return Ok(Some(self.object_prototype_of(&target)?));
7055 };
7056 let proto = match &result {
7057 Value::Null => None,
7058 Value::Object(proto) => Some(proto.clone()),
7059 _ => {
7060 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7061 }
7062 };
7063 if !self.object_is_extensible(&target)? {
7064 let actual = self.object_prototype_of(&target)?;
7065 if !same_proto(proto.as_ref(), actual.as_ref()) {
7066 return Err(self.type_error(
7067 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7068 ));
7069 }
7070 }
7071 Ok(Some(proto))
7072 }
7073
7074 /// `[[SetPrototypeOf]]` on a proxy.
7075 fn proxy_set_prototype_of(
7076 &mut self,
7077 object: &Gc<JsObject>,
7078 proto: Option<Gc<JsObject>>,
7079 ) -> JsResult<Option<bool>> {
7080 let Some((target, handler)) = self.proxy_parts(object)? else {
7081 return Ok(None);
7082 };
7083 let proto_value = match &proto {
7084 Some(proto) => Value::Object(proto.clone()),
7085 None => Value::Null,
7086 };
7087 let Some(result) = self.proxy_trap(
7088 &handler,
7089 "setPrototypeOf",
7090 vec![Value::Object(target.clone()), proto_value],
7091 )?
7092 else {
7093 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7094 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7095 // its stored prototype overwritten behind its back.
7096 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7097 };
7098 if result.to_boolean()
7099 && !self.object_is_extensible(&target)?
7100 && !same_proto(
7101 Some(&proto).and_then(|p| p.clone()).as_ref(),
7102 self.object_prototype_of(&target)?.as_ref(),
7103 )
7104 {
7105 return Err(self.type_error(
7106 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7107 ));
7108 }
7109 Ok(Some(result.to_boolean()))
7110 }
7111
7112 /// `[[IsExtensible]]` on a proxy.
7113 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7114 let Some((target, handler)) = self.proxy_parts(object)? else {
7115 return Ok(None);
7116 };
7117 let Some(result) = self.proxy_trap(
7118 &handler,
7119 "isExtensible",
7120 vec![Value::Object(target.clone())],
7121 )?
7122 else {
7123 return Ok(Some(self.object_is_extensible(&target)?));
7124 };
7125 // The answer is not the proxy's to invent: it must agree with the target, or a
7126 // script could learn `false` while the target keeps accepting new properties.
7127 if result.to_boolean() != self.object_is_extensible(&target)? {
7128 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7129 }
7130 Ok(Some(result.to_boolean()))
7131 }
7132
7133 /// `[[PreventExtensions]]` on a proxy.
7134 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7135 let Some((target, handler)) = self.proxy_parts(object)? else {
7136 return Ok(None);
7137 };
7138 let Some(result) = self.proxy_trap(
7139 &handler,
7140 "preventExtensions",
7141 vec![Value::Object(target.clone())],
7142 )?
7143 else {
7144 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7145 // its answer can be `false`.
7146 return Ok(Some(self.object_prevent_extensions(&target)?));
7147 };
7148 if result.to_boolean() && self.object_is_extensible(&target)? {
7149 return Err(self.type_error(
7150 "proxy 'preventExtensions' reported success but the target is still extensible",
7151 ));
7152 }
7153 Ok(Some(result.to_boolean()))
7154 }
7155
7156 /// `[[Call]]` on a proxy, through the `apply` trap.
7157 fn proxy_apply(
7158 &mut self,
7159 object: &Gc<JsObject>,
7160 this: Value,
7161 args: Vec<Value>,
7162 ) -> JsResult<Option<Value>> {
7163 let Some((target, handler)) = self.proxy_parts(object)? else {
7164 return Ok(None);
7165 };
7166 // The trap gets the arguments as one array, which is the shape the spec passes
7167 // and the shape `apply` traps are written against (`args[0]` is the first one).
7168 let arguments = self.new_array(args.clone());
7169 let this_for_trap = this.clone();
7170 let Some(result) = self.proxy_trap(
7171 &handler,
7172 "apply",
7173 vec![
7174 Value::Object(target.clone()),
7175 this_for_trap,
7176 Value::Object(arguments),
7177 ],
7178 )?
7179 else {
7180 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7181 };
7182 Ok(Some(result))
7183 }
7184
7185 /// `[[Construct]]` on a proxy, through the `construct` trap.
7186 fn proxy_construct(
7187 &mut self,
7188 object: &Gc<JsObject>,
7189 args: Vec<Value>,
7190 new_target: &Value,
7191 ) -> JsResult<Option<Value>> {
7192 let Some((target, handler)) = self.proxy_parts(object)? else {
7193 return Ok(None);
7194 };
7195 if !target.is_callable() {
7196 return Err(self.type_error("proxy target is not a constructor"));
7197 }
7198 let arguments = self.new_array(args.clone());
7199 let Some(result) = self.proxy_trap(
7200 &handler,
7201 "construct",
7202 vec![
7203 Value::Object(target.clone()),
7204 Value::Object(arguments),
7205 new_target.clone(),
7206 ],
7207 )?
7208 else {
7209 return Ok(Some(self.construct(
7210 Value::Object(target),
7211 new_target.clone(),
7212 args,
7213 )?));
7214 };
7215 if !matches!(result, Value::Object(_)) {
7216 return Err(self.type_error("proxy 'construct' must return an object"));
7217 }
7218 Ok(Some(result))
7219 }
7220
7221 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7222 pub(crate) fn has_own_or_inherited(
7223 &mut self,
7224 object: &Gc<JsObject>,
7225 key: &PropertyKey,
7226 ) -> JsResult<bool> {
7227 // The object itself first: it may be a proxy, and then the answer is its trap's.
7228 if let Some(answer) = self.proxy_has(object, key)? {
7229 return Ok(answer);
7230 }
7231 // An integer-indexed exotic object answers a canonical numeric index from
7232 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7233 // prototype chain. That is observable twice: a view the buffer has been resized
7234 // away from has no indices, so `2 in view` is `false` even when
7235 // `Object.getPrototypeOf(view)[2]` exists (what
7236 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7237 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7238 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7239 // goes through here, which is why the same rule is repeated in `has_property_key`
7240 // rather than living only there.
7241 if object.typed_array_parts().is_some()
7242 && let Some(numeric) = canonical_numeric_index(key)
7243 {
7244 return Ok(typed_array_index_is_valid(object, numeric));
7245 }
7246 // A host class answers `in` for its own keys, which may live nowhere in a property
7247 // table — `"x" in point` is true because the class says so, not because a property
7248 // exists.
7249 if let Some(exotic) = object.exotic()
7250 && let Some(answer) = exotic.has_property(self, object, key)?
7251 {
7252 return Ok(answer);
7253 }
7254 // `has_own` rather than `own_property_key`: an array's elements and its derived
7255 // `length` are invisible to the property table, and `Array.prototype` is an array.
7256 // A host class's `get_own_property` counts too, because the reference's
7257 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7258 // lives — a class with only `get_own_property` answers `in` through it.
7259 if self.exotic_has_own(object, key)? {
7260 return Ok(true);
7261 }
7262 // A hole is *not* the end of the search: the chain may still have the key, which
7263 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7264 for ancestor in object.chain() {
7265 // A proxy further up the chain answers for itself.
7266 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7267 return Ok(answer);
7268 }
7269 // Same for a host class: a prototype may be one, and `in` reaches it.
7270 if let Some(exotic) = ancestor.exotic()
7271 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7272 {
7273 return Ok(answer);
7274 }
7275 if self.exotic_has_own(&ancestor, key)? {
7276 return Ok(true);
7277 }
7278 }
7279 Ok(false)
7280 }
7281
7282 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7283 /// trap included.
7284 ///
7285 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7286 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7287 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7288 if let Some(exotic) = object.exotic()
7289 && let Some(answer) = exotic.get_own_property(self, object, key)?
7290 {
7291 return Ok(answer.is_some());
7292 }
7293 Ok(has_own(object, key))
7294 }
7295
7296 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7297 ///
7298 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7299 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7300 /// `TypeError` instead of a property named `"1.5"`.
7301 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7302 let object = self.object_from(value)?;
7303 let length = self
7304 .get_property(&object, "length")?
7305 .map(|value| value.to_number())
7306 .unwrap_or(0.0);
7307 if !length.is_finite() || length < 0.0 {
7308 return Err(self.type_error("invalid array-like length"));
7309 }
7310 let length = length as usize;
7311 let mut items = Vec::with_capacity(length.min(1024));
7312 for index in 0..length {
7313 let item = self
7314 .get_property(&object, &index.to_string())?
7315 .unwrap_or(Value::Undefined);
7316 if keys_only && matches!(&item, Value::Symbol(_)) {
7317 items.push(item);
7318 continue;
7319 }
7320 if keys_only && !matches!(&item, Value::String(_)) {
7321 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7322 }
7323 items.push(item);
7324 }
7325 Ok(items)
7326 }
7327
7328 /// A `Property` from the descriptor object a trap returned.
7329 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7330 let object = self.object_from(value)?;
7331 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7332 interp.get_property(&object, name)
7333 };
7334 let getter = field(self, "get")?;
7335 let setter = field(self, "set")?;
7336 let accessor = getter.is_some() || setter.is_some();
7337 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7338 Ok(interp
7339 .get_property(&object, name)?
7340 .is_some_and(|value| value.to_boolean()))
7341 };
7342 let enumerable = boolean(self, "enumerable")?;
7343 let configurable = boolean(self, "configurable")?;
7344 if accessor {
7345 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7346 return Err(
7347 self.type_error("a descriptor cannot be both a data property and an accessor")
7348 );
7349 }
7350 Ok(Property {
7351 getter: getter.or(Some(Value::Undefined)),
7352 setter: setter.or(Some(Value::Undefined)),
7353 enumerable,
7354 configurable,
7355 writable: false,
7356 value: None,
7357 descriptor_fields: None,
7358 })
7359 } else {
7360 Ok(Property {
7361 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7362 writable: boolean(self, "writable")?,
7363 enumerable,
7364 configurable,
7365 getter: None,
7366 setter: None,
7367 descriptor_fields: None,
7368 })
7369 }
7370 }
7371
7372 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7373 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7374 let object = self.new_object(None);
7375 // A partial descriptor names only some fields, and the trap must see exactly those:
7376 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7377 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7378 // case, where every field is present.
7379 let fields = property.descriptor_fields;
7380 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7381 fields.is_none_or(|fields| field(&fields))
7382 };
7383 if property.is_accessor() {
7384 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7385 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7386 object.define_data("get", getter);
7387 object.define_data("set", setter);
7388 } else {
7389 if names(|fields| fields.value) {
7390 let value = property.value.clone().unwrap_or(Value::Undefined);
7391 object.define_data("value", value);
7392 }
7393 if names(|fields| fields.writable) {
7394 object.define_data("writable", Value::Bool(property.writable));
7395 }
7396 }
7397 if names(|fields| fields.enumerable) {
7398 object.define_data("enumerable", Value::Bool(property.enumerable));
7399 }
7400 if names(|fields| fields.configurable) {
7401 object.define_data("configurable", Value::Bool(property.configurable));
7402 }
7403 Value::Object(object)
7404 }
7405
7406 // -- calling ------------------------------------------------------------
7407
7408 /// Call `callee` with `this` and `args`.
7409 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7410 let Value::Object(function) = &callee else {
7411 // `typeof x === "function"` is not enough to make `x()` legal: only a
7412 // callable object is. `null` and `undefined` need no special wording
7413 // here — their `ToString` already reads the way the reference's does.
7414 let what = format!("{} is not a function", callee.to_js_string());
7415 return Err(Signal::Throw(self.make_error("TypeError", &what)));
7416 };
7417 // A proxy of a function is called through its `apply` trap. It has no
7418 // `ObjectKind::Function` of its own, so this has to come before the dispatch
7419 // below, and a proxy of a non-function has nothing to forward to.
7420 if function.proxy_state().is_some() {
7421 return match self.proxy_apply(function, this, args)? {
7422 Some(result) => Ok(result),
7423 None => Err(Signal::Throw(
7424 self.make_error("TypeError", "proxy target is not callable"),
7425 )),
7426 };
7427 }
7428 let callable = function.with(|data| match &data.kind {
7429 ObjectKind::Function(callable) => match callable {
7430 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7431 // The `Rc` is cloned out so the borrow of this object's data is released
7432 // before the closure runs: the closure may touch the same object.
7433 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7434 Callable::Bound {
7435 target,
7436 this,
7437 args: leading,
7438 } => Some(NativeCall::Bound {
7439 target: target.clone(),
7440 this: this.clone(),
7441 leading: leading.clone(),
7442 }),
7443 Callable::Bytecode { code, env } => {
7444 Some(NativeCall::Bytecode(code.clone(), env.clone()))
7445 }
7446 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7447 Callable::PromiseResolve(promise) => {
7448 Some(NativeCall::PromiseResolve(promise.clone()))
7449 }
7450 Callable::PromiseReject(promise) => {
7451 Some(NativeCall::PromiseReject(promise.clone()))
7452 }
7453 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7454 state: state.clone(),
7455 }),
7456 Callable::ThenShim {
7457 handler,
7458 resolve,
7459 reject,
7460 fulfilled,
7461 } => Some(NativeCall::ThenShim {
7462 handler: handler.clone(),
7463 resolve: resolve.clone(),
7464 reject: reject.clone(),
7465 fulfilled: *fulfilled,
7466 }),
7467 Callable::AwaitResume {
7468 coroutine,
7469 promise,
7470 kind,
7471 } => Some(NativeCall::AwaitResume {
7472 coroutine: coroutine.clone(),
7473 promise: promise.clone(),
7474 kind: *kind,
7475 }),
7476 Callable::CombinatorSettle {
7477 state,
7478 index,
7479 fulfilled,
7480 } => Some(NativeCall::CombinatorSettle {
7481 state: state.clone(),
7482 index: *index,
7483 fulfilled: *fulfilled,
7484 }),
7485 Callable::FinallyShim {
7486 callback,
7487 fulfilled,
7488 constructor,
7489 } => Some(NativeCall::FinallyShim {
7490 callback: callback.clone(),
7491 fulfilled: *fulfilled,
7492 constructor: constructor.clone(),
7493 }),
7494 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7495 Callable::CompletedReturn {
7496 generator,
7497 promise,
7498 rejected,
7499 } => Some(NativeCall::CompletedReturn {
7500 generator: generator.clone(),
7501 promise: promise.clone(),
7502 rejected: *rejected,
7503 }),
7504 Callable::YieldResult {
7505 generator,
7506 promise,
7507 done,
7508 } => Some(NativeCall::YieldResult {
7509 generator: generator.clone(),
7510 promise: promise.clone(),
7511 done: *done,
7512 }),
7513 Callable::DisposeStep {
7514 remaining,
7515 promise,
7516 error,
7517 rejected,
7518 } => Some(NativeCall::DisposeStep {
7519 remaining: remaining.clone(),
7520 promise: promise.clone(),
7521 error: error.clone(),
7522 rejected: *rejected,
7523 }),
7524 Callable::GeneratorResume {
7525 generator,
7526 promise,
7527 kind,
7528 } => Some(NativeCall::GeneratorResume {
7529 generator: generator.clone(),
7530 promise: promise.clone(),
7531 kind: *kind,
7532 }),
7533 Callable::SettlePromise {
7534 promise,
7535 value,
7536 rejected,
7537 } => Some(NativeCall::SettlePromise {
7538 promise: promise.clone(),
7539 value: value.clone(),
7540 rejected: *rejected,
7541 }),
7542 },
7543 _ => None,
7544 });
7545 match callable {
7546 Some(NativeCall::Host(func)) => {
7547 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7548 // function by name rather than stopping at the caller.
7549 let frame_less = function
7550 .own_property("_frame_less")
7551 .and_then(|property| property.value)
7552 .is_some_and(|value| value.to_boolean());
7553 let outer = if frame_less {
7554 None
7555 } else {
7556 self.native_frames
7557 .push((function.clone(), self.frames.len()));
7558 Some(self.current_native.replace(function.clone()))
7559 };
7560 let result = {
7561 let mut body = func.borrow_mut();
7562 body(self, this, &args)
7563 };
7564 if !frame_less {
7565 self.native_frames.pop();
7566 self.current_native = outer.flatten();
7567 }
7568 result
7569 }
7570 Some(NativeCall::Native(func)) => {
7571 // A function marked `_frame_less` is one the reference implements
7572 // without a call frame — `eval` is the only one so far.
7573 let frame_less = function
7574 .own_property("_frame_less")
7575 .and_then(|property| property.value)
7576 .is_some_and(|value| value.to_boolean());
7577 let outer = if frame_less {
7578 None
7579 } else {
7580 self.native_frames
7581 .push((function.clone(), self.frames.len()));
7582 Some(self.current_native.replace(function.clone()))
7583 };
7584 let result = func(self, this, &args);
7585 if !frame_less {
7586 self.native_frames.pop();
7587 self.current_native = outer.flatten();
7588 }
7589 result
7590 }
7591 Some(NativeCall::Revoker(slots)) => {
7592 // Idempotent: revoking twice answers `undefined` again rather than
7593 // complaining, which is what the spec says and what a `finally` block
7594 // relies on.
7595 let mut state = slots.borrow_mut();
7596 state.target = None;
7597 state.handler = None;
7598 Ok(Value::Undefined)
7599 }
7600 Some(NativeCall::PromiseResolve(promise)) => {
7601 // One-shot: a second call is silently ignored, which
7602 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
7603 let value = args.first().cloned().unwrap_or(Value::Undefined);
7604 self.resolve_promise_with(&promise, value)?;
7605 Ok(Value::Undefined)
7606 }
7607 Some(NativeCall::PromiseReject(promise)) => {
7608 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7609 self.reject_promise(&promise, reason);
7610 Ok(Value::Undefined)
7611 }
7612 Some(NativeCall::ThenShim {
7613 handler,
7614 resolve,
7615 reject,
7616 fulfilled,
7617 }) => {
7618 // `PerformPromiseThen` with a capability: run the handler, then settle
7619 // through the capability's own pair. A throw from the handler is the
7620 // rejection, and a throw from the capability's `resolve` is not caught —
7621 // exactly the spec's `?`.
7622 let value = args.first().cloned().unwrap_or(Value::Undefined);
7623 match handler {
7624 Some(handler) => {
7625 match self.call_value(handler, Value::Undefined, vec![value]) {
7626 Ok(result) => {
7627 self.call_value(resolve, Value::Undefined, vec![result])?;
7628 }
7629 Err(Signal::Throw(reason)) => {
7630 self.call_value(reject, Value::Undefined, vec![reason])?;
7631 }
7632 Err(signal) => return Err(signal),
7633 }
7634 }
7635 None => {
7636 let handler = if fulfilled { resolve } else { reject };
7637 self.call_value(handler, Value::Undefined, vec![value])?;
7638 }
7639 }
7640 Ok(Value::Undefined)
7641 }
7642 Some(NativeCall::CapabilityExecutor { state }) => {
7643 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7644 // slot holds a value yet. The test is on the *values*, not on a call count —
7645 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7646 // called-twice`'s first case does exactly that), while a second call after a
7647 // real pair is the `TypeError`.
7648 let defined = |name: &str| {
7649 state
7650 .own_property(name)
7651 .and_then(|property| property.value)
7652 .is_some_and(|value| !matches!(value, Value::Undefined))
7653 };
7654 if defined("resolve") || defined("reject") {
7655 return Err(self.type_error("promise capability executor called twice"));
7656 }
7657 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7658 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7659 state.define_data("resolve", resolve);
7660 state.define_data("reject", reject);
7661 Ok(Value::Undefined)
7662 }
7663 Some(NativeCall::CombinatorSettle {
7664 state,
7665 index,
7666 fulfilled,
7667 }) => {
7668 let value = args.first().cloned().unwrap_or(Value::Undefined);
7669 self.settle_combinator(&state, index, fulfilled, value)?;
7670 Ok(Value::Undefined)
7671 }
7672 Some(NativeCall::AwaitResume {
7673 coroutine,
7674 promise,
7675 kind,
7676 }) => {
7677 // Resume *inline*, in the reaction that delivered the value. Deferring it
7678 // by another job inserts a tick between every `await` and its
7679 // continuation, which reorders `await` against unrelated `then` chains —
7680 // `f().then(g)` then runs before `f`'s own next statement.
7681 self.drive_async(
7682 &coroutine,
7683 &promise,
7684 kind,
7685 args.first().cloned().unwrap_or(Value::Undefined),
7686 )
7687 .map(|()| Value::Undefined)
7688 }
7689 Some(NativeCall::FinallyShim {
7690 callback,
7691 fulfilled,
7692 constructor,
7693 }) => {
7694 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
7695 // that settles with the *original* outcome once the callback's result has
7696 // settled. The callback's own value is discarded — that is the whole
7697 // difference between `finally` and `then`.
7698 let original = args.first().cloned().unwrap_or(Value::Undefined);
7699 let result = match &callback {
7700 Some(callback) => {
7701 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7702 }
7703 None => Value::Undefined,
7704 };
7705 // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
7706 // already a promise of this constructor is reused rather than rewrapped.
7707 let resolved = self.promise_resolve_for(&constructor, result)?;
7708 let Value::Object(resolved) = resolved else {
7709 return Ok(original);
7710 };
7711 // The wait is a chained promise rather than a bare return, so a callback
7712 // that returns a slow promise really does delay the continuation.
7713 let waiting = self.new_promise();
7714 let pass = JsObject::function(
7715 self.heap,
7716 Some(self.realm.function_proto.clone()),
7717 Callable::SettlePromise {
7718 promise: waiting.clone(),
7719 value: original,
7720 rejected: !fulfilled,
7721 },
7722 );
7723 let pass = Value::Object(pass);
7724 // Whichever way the callback's promise settles, the original outcome wins.
7725 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
7726 Ok(Value::Object(waiting))
7727 }
7728 Some(NativeCall::DisposeStep {
7729 remaining,
7730 promise,
7731 error,
7732 rejected,
7733 }) => {
7734 let error = if rejected {
7735 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7736 self.merge_dispose_error(reason, error)
7737 } else {
7738 error
7739 };
7740 self.dispose_step(&remaining, &promise, error)?;
7741 Ok(Value::Undefined)
7742 }
7743 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7744 Some(NativeCall::CompletedReturn {
7745 generator,
7746 promise,
7747 rejected,
7748 }) => {
7749 let value = args.first().cloned().unwrap_or(Value::Undefined);
7750 let outcome = if rejected {
7751 AsyncOutcome::Error(value)
7752 } else {
7753 AsyncOutcome::Value(self.iterator_result(value, true)?)
7754 };
7755 self.settle_async_request(&generator, &promise, outcome)?;
7756 Ok(Value::Undefined)
7757 }
7758 Some(NativeCall::YieldResult {
7759 generator,
7760 promise,
7761 done,
7762 }) => {
7763 let value = args.first().cloned().unwrap_or(Value::Undefined);
7764 let result = self.iterator_result(value, done)?;
7765 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7766 Ok(Value::Undefined)
7767 }
7768 Some(NativeCall::GeneratorResume {
7769 generator,
7770 promise,
7771 kind,
7772 }) => {
7773 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7774 // tick and reorders the generator against other chains.
7775 self.step_async_generator(
7776 &generator,
7777 &promise,
7778 kind,
7779 args.first().cloned().unwrap_or(Value::Undefined),
7780 )
7781 .map(|()| Value::Undefined)
7782 }
7783 Some(NativeCall::SettlePromise {
7784 promise,
7785 value,
7786 rejected,
7787 }) => {
7788 if rejected {
7789 self.reject_promise(&promise, value);
7790 } else {
7791 self.fulfill_promise(&promise, value);
7792 }
7793 Ok(Value::Undefined)
7794 }
7795 Some(NativeCall::Bound {
7796 target,
7797 this: bound_this,
7798 leading,
7799 }) => {
7800 let mut all = leading;
7801 all.extend(args);
7802 self.call_value(target, bound_this, all)
7803 }
7804 Some(NativeCall::Bytecode(code, env)) => {
7805 if code.code.kind.is_generator() {
7806 return self.new_generator(callee, this, args);
7807 }
7808 if code.code.kind.is_async() {
7809 // Same coroutine machinery as a generator; the difference is only in
7810 // what the completion does — see `new_async_function`.
7811 return self.new_async_function(callee, this, args);
7812 }
7813 self.execute(code, env, this, args, callee)
7814 }
7815 None => Err(Signal::Throw(
7816 self.make_error("TypeError", "not a function"),
7817 )),
7818 }
7819 }
7820
7821 /// Give a freshly built function its own `prototype` object.
7822 ///
7823 /// Every function that can be used with `new` carries one, and its
7824 /// `constructor` points back at the function — a reference cycle, which is
7825 /// exactly what the collector's cycle pass exists to reclaim.
7826 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
7827 self.install_function_prototype_with(function, None);
7828 }
7829
7830 /// [`Interp::install_function_prototype`] with an explicit parent for the new
7831 /// `prototype` object.
7832 ///
7833 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
7834 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
7835 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
7836 /// `None` means `%Object.prototype%`.
7837 fn install_function_prototype_with(
7838 &mut self,
7839 function: &Gc<JsObject>,
7840 parent: Option<Gc<JsObject>>,
7841 ) {
7842 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
7843 let prototype = self.new_object(Some(parent));
7844 let constructor = Value::Object(function.clone());
7845 prototype.define(
7846 "constructor",
7847 Property::with_attributes(constructor, true, false),
7848 );
7849 let value = Value::Object(prototype);
7850 function.define("prototype", Property::prototype_of(value, true));
7851 }
7852
7853 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
7854 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
7855 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
7856 ///
7857 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
7858 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
7859 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
7860 /// is `[]` there.
7861 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
7862 let prototype = self.new_object(Some(parent));
7863 let value = Value::Object(prototype);
7864 function.define("prototype", Property::prototype_of(value, true));
7865 }
7866
7867 /// The `[[Prototype]]` a newly created generator object gets:
7868 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
7869 ///
7870 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
7871 /// function's `prototype` is writable, so a script can replace it with anything, and
7872 /// only an *object* is consulted.
7873 fn generator_instance_proto(
7874 &mut self,
7875 function: &Gc<JsObject>,
7876 default: Gc<JsObject>,
7877 ) -> JsResult<Gc<JsObject>> {
7878 match self.get_property(function, "prototype")? {
7879 Some(Value::Object(prototype)) => Ok(prototype),
7880 _ => Ok(default),
7881 }
7882 }
7883
7884 /// A getter or setter that reads or writes the reference cell behind a mapped
7885 /// `arguments` index.
7886 ///
7887 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
7888 /// count — which is what the collector treats as "a reference from outside the
7889 /// heap". The closure therefore keeps the cell alive for exactly as long as the
7890 /// accessor is reachable, which is the same lifetime the arguments object has.
7891 ///
7892 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
7893 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
7894 /// parameter value and the arguments object reaches the closure, never the other
7895 /// way round. Nothing the collector has to see is hidden.
7896 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
7897 let name = if is_setter { "set" } else { "get" };
7898 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
7899 if is_setter {
7900 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
7901 Ok(Value::Undefined)
7902 } else {
7903 Ok(cell.get())
7904 }
7905 };
7906 self.new_host_function(name, 1, Box::new(func))
7907 }
7908
7909 /// The object `special_object` builds.
7910 ///
7911 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
7912 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
7913 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
7914 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
7915 /// write through `arguments` does not reach the parameter.
7916 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
7917 match magic {
7918 0 | 1 => {
7919 let args = self.frame().passed().to_vec();
7920 let proto = self.realm.object_proto.clone();
7921 let object = self.new_object(Some(proto));
7922 // The marker `Object.prototype.toString` needs: an arguments object is an
7923 // ordinary object apart from reporting `[object Arguments]`, and that has
7924 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
7925 // show up ahead of them in a key listing anyway — it is non-enumerable.
7926 self.internal_set(&object, "_class", self.string("Arguments"));
7927 // `length` is writable and configurable but neither enumerable nor a
7928 // plain data property: `Object.keys(arguments)` lists the indices only,
7929 // which is how `{...arguments}` copies them without the length.
7930 object.define(
7931 "length",
7932 Property::with_attributes(Value::Int(args.len() as i32), true, false),
7933 );
7934 // `magic == 1` is sloppy mode, where each index is *mapped* to the
7935 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
7936 // change `a`, and assigning `a` has to change `arguments[0]`.
7937 //
7938 // The shared storage is the parameter's reference cell. The compiler
7939 // gives every parameter of such a function one (see
7940 // `provide_body_arguments`), and the cell outlives the frame, so this
7941 // keeps working after the arguments object escapes.
7942 //
7943 // The index becomes an accessor rather than a data property. A mapped
7944 // index reports as a plain writable/enumerable data property through
7945 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
7946 // the getter/setter pair is only the plumbing underneath.
7947 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
7948 let frame = self.frame();
7949 frame
7950 .code
7951 .arg_cell
7952 .iter()
7953 .map(|cell| {
7954 (*cell >= 0)
7955 .then(|| frame.cells.get(*cell as usize).cloned())
7956 .flatten()
7957 })
7958 .collect()
7959 } else {
7960 Vec::new()
7961 };
7962 // Tell the object which indices are mapped, so
7963 // `Object.getOwnPropertyDescriptor` can report them as the data
7964 // properties the spec describes instead of the accessors that
7965 // implement the aliasing.
7966 if magic == 1 {
7967 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
7968 for cell in &mapped_cells {
7969 table.push(cell.clone());
7970 }
7971 object.set_mapped_arguments(table);
7972 }
7973 for (index, value) in args.into_iter().enumerate() {
7974 match mapped_cells.get(index).cloned().flatten() {
7975 Some(cell) => {
7976 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
7977 let setter = self.new_mapped_arguments_accessor(cell, true);
7978 object.define(
7979 &index.to_string(),
7980 Property::accessor_with(
7981 Some(Value::Object(getter)),
7982 Some(Value::Object(setter)),
7983 true,
7984 ),
7985 );
7986 }
7987 None => object.define_data(&index.to_string(), value),
7988 }
7989 }
7990 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
7991 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
7992 // non-enumerable and non-configurable. It is not a nicety — it is the only
7993 // documented way to reach `%ThrowTypeError%`:
7994 //
7995 // Object.getOwnPropertyDescriptor(function(){"use strict";
7996 // return arguments;}(), "callee").get
7997 //
7998 // and the whole `ThrowTypeError/` directory is written against that
7999 // expression. Without it 13 cases failed with `cannot read property 'get'
8000 // of undefined`, which reads like a test harness bug rather than a missing
8001 // accessor.
8002 //
8003 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8004 // writable data property holding the function being called, and
8005 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8006 // `hasOwnProperty("callee")` hold there.
8007 if magic == 1 {
8008 let callee = self.frame().callee.clone();
8009 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8010 object.define("callee", Property::with_attributes(callee, true, false));
8011 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8012 && object.own_property("callee").is_none()
8013 {
8014 object.define(
8015 "callee",
8016 Property {
8017 getter: Some(Value::Object(thrower.clone())),
8018 setter: Some(Value::Object(thrower)),
8019 enumerable: false,
8020 configurable: false,
8021 ..Property::default()
8022 },
8023 );
8024 }
8025 // An arguments object is iterable: `[...arguments]` and
8026 // `for (const a of arguments)` both work, through the *array* iterator
8027 // because the object is array-like. Without this the whole spread form
8028 // reported "not iterable".
8029 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8030 let values = self
8031 .realm
8032 .array_proto
8033 .own_property("values")
8034 .and_then(|property| property.value);
8035 if let Some(values) = values {
8036 object.define_key(
8037 &iterator_key,
8038 Property::with_attributes(values, true, false),
8039 );
8040 }
8041 Ok(Value::Object(object))
8042 }
8043 // `this.active_func`: the constructor `super()` resolves against.
8044 //
8045 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8046 // own, so it inherits this from the function it was written in along with `this`
8047 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8048 // the constructor and is called back later (`iter.return = () => super()`) has
8049 // the constructor nowhere on the stack. The compiler therefore reads it out of
8050 // a closure variable of the enclosing function, exactly as the reference does
8051 // with its `this_active_func` local.
8052 2 => Ok(self
8053 .current_callee()
8054 .map_or(Value::Undefined, Value::Object)),
8055 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8056 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8057 // its own either, so the lookup walks out to the nearest non-arrow frame for
8058 // the same reason as `this.active_func` above — without that, `super()` inside
8059 // an arrow passed `undefined` as the new target and the parent constructor was
8060 // then rejected for being invoked without `new`.
8061 3 => Ok(self
8062 .eval_new_target
8063 .clone()
8064 .unwrap_or_else(|| self.frame().new_target.clone())),
8065 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8066 // An arrow has none of its own, so the lookup walks out to the enclosing
8067 // method — which is why `super` works inside an arrow inside a method.
8068 4 => Ok(self
8069 .frames
8070 .iter()
8071 .rev()
8072 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8073 .map_or(Value::Undefined, Value::Object)),
8074 // `import.meta`: the innermost module body's meta object. Outside a module
8075 // the compiler never emits this, so an empty fallback is unreachable rather
8076 // than permissive.
8077 6 => {
8078 let name = self.module_stack.last().cloned();
8079 let meta = name
8080 .and_then(|name| self.modules.get(&name).cloned())
8081 .and_then(|module| module.with(|r| r.import_meta.clone()));
8082 Ok(meta.map_or(Value::Undefined, Value::Object))
8083 }
8084 other => Err(Signal::Throw(self.make_error(
8085 "InternalError",
8086 &format!("special_object {other} is not implemented yet"),
8087 ))),
8088 }
8089 }
8090
8091 /// `[[HomeObject]]` of the innermost function that has one, if any.
8092 ///
8093 /// An arrow has none, so the search walks out to the enclosing method — the same
8094 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8095 /// inside a method.
8096 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8097 self.frames
8098 .iter()
8099 .rev()
8100 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8101 }
8102
8103 /// The dispose method a `using` declaration should snapshot, or an error.
8104 ///
8105 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8106 /// is what makes a resource that only knows the synchronous protocol usable in both
8107 /// forms.
8108 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8109 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8110 if value.is_nullish() {
8111 return Ok(Value::Undefined);
8112 }
8113 let Some(object) = value.as_object() else {
8114 return Err(self.type_error("not an object"));
8115 };
8116 let mut method = if await_form {
8117 let found = self.get_property_key(
8118 object,
8119 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8120 )?;
8121 match found {
8122 Some(found) if !found.is_nullish() => Some(found),
8123 _ => self
8124 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8125 }
8126 } else {
8127 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8128 };
8129 let Some(found) = method.take() else {
8130 return Err(self.type_error("value is not disposable"));
8131 };
8132 if found.is_nullish() {
8133 return Err(self.type_error("value is not disposable"));
8134 }
8135 let callable = found.as_object().is_some_and(|object| object.is_callable());
8136 if !callable {
8137 return Err(self.type_error("dispose method is not a function"));
8138 }
8139 Ok(found)
8140 }
8141
8142 /// Call one resource's disposer, folding a failure into `error_state`.
8143 ///
8144 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8145 /// because a captured `using` binding lives in its reference cell and the local slot is
8146 /// stale — a closure over the resource is legal and must not change what is disposed.
8147 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8148 let value = self.get_loc(slot);
8149 let method = self.get_loc(slot + 1);
8150 // A resource that was never initialised — its declaration threw — or that is
8151 // `null`/`undefined` has nothing to dispose.
8152 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8153 return Ok(error_state);
8154 }
8155 if matches!(method, Value::Undefined | Value::Uninitialized) {
8156 return Ok(error_state);
8157 }
8158 match self.call_value(method, value, Vec::new()) {
8159 Ok(_) => Ok(error_state),
8160 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8161 Err(other) => Err(other),
8162 }
8163 }
8164
8165 /// Combine a disposal failure with whatever was already going wrong.
8166 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8167 if matches!(error_state, Value::Uninitialized) {
8168 return new_error;
8169 }
8170 self.new_suppressed_error(new_error, error_state)
8171 }
8172
8173 /// A `SuppressedError` instance built straight from its prototype.
8174 ///
8175 /// Not through the constructor: a script that rewrites
8176 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8177 /// error wrapping.
8178 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8179 let proto = self
8180 .realm
8181 .suppressed_error_proto
8182 .clone()
8183 .unwrap_or_else(|| self.realm.error_proto.clone());
8184 let object = self.new_object(Some(proto));
8185 object.define("error", Property::with_attributes(error, true, true));
8186 object.define(
8187 "suppressed",
8188 Property::with_attributes(suppressed, true, true),
8189 );
8190 object.define(
8191 "message",
8192 Property::with_attributes(self.string("SuppressedError"), true, true),
8193 );
8194 self.internal_set(&object, "_class", self.string("Error"));
8195 self.add_stack(&object);
8196 Value::Object(object)
8197 }
8198
8199 /// Call `callee`, or push its frame and let the main loop run it.
8200 ///
8201 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8202 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8203 /// continues, so `function f(){ return f() }` costs heap and stops at
8204 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8205 /// is entered directly, and natives do not re-enter JavaScript in this
8206 /// milestone.
8207 ///
8208 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8209 /// because the returning frame will.
8210 /// The elements of an array-like value, as a call argument list.
8211 ///
8212 /// `apply` accepts any array-like, not only a real array: the reference reads
8213 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8214 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8215 let Some(object) = value.as_object().cloned() else {
8216 if value.is_nullish() {
8217 // `f.apply(this, null)` passes no arguments at all.
8218 return Ok(Vec::new());
8219 }
8220 return Err(self.type_error("createListFromArrayLike called on non-object"));
8221 };
8222 let length = match self.get_property(&object, "length")? {
8223 Some(length) => length.to_number(),
8224 None => 0.0,
8225 };
8226 if !length.is_finite() || length <= 0.0 {
8227 return Ok(Vec::new());
8228 }
8229 let length = (length as usize).min(1_000_000);
8230 let mut args = Vec::with_capacity(length);
8231 for index in 0..length {
8232 let element = self.get_property(&object, &index.to_string())?;
8233 args.push(element.unwrap_or(Value::Undefined));
8234 }
8235 Ok(args)
8236 }
8237
8238 /// Turn a call to a generator function into a generator object.
8239 ///
8240 /// The frame is built exactly as an ordinary call would build it, then detached and
8241 /// stored in the generator before any body instruction runs — which is what makes
8242 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8243 /// is `initial_yield`, the first instruction of every suspending body.
8244 pub fn new_generator(
8245 &mut self,
8246 function: Value,
8247 this: Value,
8248 args: Vec<Value>,
8249 ) -> JsResult<Value> {
8250 let Some(object) = function.as_object().cloned() else {
8251 return Err(self.type_error("not a generator function"));
8252 };
8253 let Some((code, env)) = bytecode_of(&object) else {
8254 return Err(self.type_error("not a generator function"));
8255 };
8256 let is_async = code.code.kind.is_async();
8257 self.push_frame(code, env, this, args, function)?;
8258 let frame = self.frames.pop().expect("push_frame just pushed it");
8259 // A fresh generator is *suspended at start*: the body has not run, so a
8260 // `return`/`throw` on it finishes without executing anything.
8261 let mut state = GeneratorState {
8262 frame: Some(frame),
8263 phase: GeneratorPhase::SuspendedStart,
8264 parked_on_await: false,
8265 parked_on_yield_star: false,
8266 requests: std::collections::VecDeque::new(),
8267 async_busy: false,
8268 is_async,
8269 };
8270 // Run to the first suspension. For a generator that is `initial_yield`, so no
8271 // body code runs; for a malformed body it would be the first `yield`.
8272 // An `async function*` answers an async generator: same coroutine, but its
8273 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8274 let default_proto = if is_async {
8275 self.realm
8276 .async_generator_proto
8277 .clone()
8278 .unwrap_or_else(|| self.realm.generator_proto.clone())
8279 } else {
8280 self.realm.generator_proto.clone()
8281 };
8282 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8283 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8284 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8285 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8286 let proto = self.generator_instance_proto(&object, default_proto)?;
8287 let generator = self.new_object(Some(proto));
8288 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8289 Ok(_) => {}
8290 Err(error) => return Err(error),
8291 }
8292 generator.with_mut(|data| {
8293 data.kind = ObjectKind::Generator(Box::new(state));
8294 });
8295 Ok(Value::Object(generator))
8296 }
8297
8298 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8299 ///
8300 /// Returns the `{value, done}` object itself rather than the pair, because a
8301 /// `yield*` suspension already has one — the inner iterator's own result — and the
8302 /// protocol says to hand that straight through rather than nest it.
8303 /// Advance a generator and report *why* it parked.
8304 ///
8305 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8306 /// "hand this value to the caller" — but an async generator does: an `await` has to
8307 /// settle before it can answer, while a `yield` is the answer.
8308 fn resume_generator_detailed(
8309 &mut self,
8310 generator: &Gc<JsObject>,
8311 kind: ResumeKind,
8312 value: Value,
8313 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8314 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8315 ObjectKind::Generator(state) => {
8316 let is_async = state.is_async;
8317 Some(std::mem::replace(
8318 state.as_mut(),
8319 GeneratorState {
8320 frame: None,
8321 phase: GeneratorPhase::Executing,
8322 parked_on_await: false,
8323 parked_on_yield_star: false,
8324 requests: std::collections::VecDeque::new(),
8325 // **Busy while the body runs**, so a `next()` called *from inside*
8326 // the body queues instead of being served. §27.6.3.7
8327 // `AsyncGeneratorResumeNext` returns immediately for the state
8328 // "executing", and the request is served once the body suspends;
8329 // with `false` here the re-entrant call found an empty frame and
8330 // rejected (`request-queue-order-state-executing`).
8331 async_busy: is_async,
8332 is_async,
8333 },
8334 ))
8335 }
8336 _ => None,
8337 }) else {
8338 return Err(self.type_error("not a generator"));
8339 };
8340 let result = self.step_generator(&mut state, kind, value);
8341 // Requests queued *while* the body ran live on the placeholder, because the real
8342 // state is out of the object for the duration. They have to be folded back in
8343 // before the placeholder is overwritten, or the promise they carry never settles.
8344 let queued = generator.with_mut(|data| match &mut data.kind {
8345 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8346 _ => std::collections::VecDeque::new(),
8347 });
8348 state.requests.extend(queued);
8349 generator.with_mut(|data| {
8350 data.kind = ObjectKind::Generator(Box::new(state));
8351 });
8352 result
8353 }
8354
8355 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8356 ///
8357 /// Returns the `{value, done}` object itself rather than the pair, because a
8358 /// `yield*` suspension already has one — the inner iterator's own result — and the
8359 /// protocol says to hand that straight through rather than nest it.
8360 pub fn resume_generator(
8361 &mut self,
8362 generator: &Gc<JsObject>,
8363 kind: ResumeKind,
8364 value: Value,
8365 ) -> JsResult<Value> {
8366 let (value, done, ready, _reason) =
8367 self.resume_generator_detailed(generator, kind, value)?;
8368 if ready {
8369 return Ok(value);
8370 }
8371 self.iterator_result(value, done)
8372 }
8373
8374 /// `next`/`return`/`throw` on an async generator, which answer a promise.
8375 ///
8376 /// The body is the same coroutine a sync generator runs; what changes is that an
8377 /// `await` inside it has to settle before the method can answer, so the step is
8378 /// driven off the job queue rather than returning inline.
8379 pub fn resume_async_generator(
8380 &mut self,
8381 generator: &Gc<JsObject>,
8382 kind: ResumeKind,
8383 value: Value,
8384 ) -> JsResult<Value> {
8385 let promise = self.new_promise();
8386 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8387 // that order, and the second value must reach the *second* `yield`.
8388 let idle = generator.with_mut(|data| match &mut data.kind {
8389 ObjectKind::Generator(state) => {
8390 state.requests.push_back(AsyncRequest {
8391 kind,
8392 value,
8393 promise: promise.clone(),
8394 });
8395 !state.async_busy
8396 }
8397 _ => false,
8398 });
8399 if idle {
8400 self.next_async_request(generator)?;
8401 }
8402 Ok(Value::Object(promise))
8403 }
8404
8405 /// Serve the front queued request, if the generator is free to run one.
8406 ///
8407 /// A finished generator answers from the queue without running anything:
8408 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8409 /// first, and `throw(e)` rejects.
8410 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8411 enum Front {
8412 Idle,
8413 Run(ResumeKind, Value, Gc<JsObject>),
8414 Finished(ResumeKind, Value, Gc<JsObject>),
8415 }
8416 let front = generator.with_mut(|data| match &mut data.kind {
8417 ObjectKind::Generator(state) => {
8418 let Some(request) = state.requests.front() else {
8419 return Front::Idle;
8420 };
8421 // Busy means a request is still in flight — awaiting inside the body, not
8422 // finished. Serving another now would interleave two requests.
8423 if state.async_busy && state.phase != GeneratorPhase::Completed {
8424 return Front::Idle;
8425 }
8426 let kind = request.kind;
8427 let value = request.value.clone();
8428 let promise = request.promise.clone();
8429 state.async_busy = true;
8430 if state.phase == GeneratorPhase::Completed {
8431 Front::Finished(kind, value, promise)
8432 } else {
8433 Front::Run(kind, value, promise)
8434 }
8435 }
8436 _ => Front::Idle,
8437 });
8438 match front {
8439 Front::Idle => Ok(()),
8440 Front::Run(kind, value, promise) => {
8441 self.step_async_generator(generator, &promise, kind, value)
8442 }
8443 Front::Finished(kind, value, promise) => match kind {
8444 ResumeKind::Throw => {
8445 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
8446 }
8447 ResumeKind::Next | ResumeKind::Start => {
8448 let result = self.iterator_result(Value::Undefined, true)?;
8449 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
8450 }
8451 ResumeKind::Return => {
8452 // `js_async_generator_completed_return`: the value is awaited before it
8453 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
8454 // finished generator answers `1`, not a promise.
8455 let resolved = match self.promise_resolve_intrinsic(value) {
8456 Ok(resolved) => resolved,
8457 Err(Signal::Throw(reason)) => {
8458 return self.settle_async_request(
8459 generator,
8460 &promise,
8461 AsyncOutcome::Error(reason),
8462 );
8463 }
8464 Err(other) => return Err(other),
8465 };
8466 let done = JsObject::function(
8467 self.heap,
8468 Some(self.realm.function_proto.clone()),
8469 Callable::CompletedReturn {
8470 generator: generator.clone(),
8471 promise: promise.clone(),
8472 rejected: false,
8473 },
8474 );
8475 let failed = JsObject::function(
8476 self.heap,
8477 Some(self.realm.function_proto.clone()),
8478 Callable::CompletedReturn {
8479 generator: generator.clone(),
8480 promise: promise.clone(),
8481 rejected: true,
8482 },
8483 );
8484 let Value::Object(resolved) = resolved else {
8485 return self.settle_async_request(
8486 generator,
8487 &promise,
8488 AsyncOutcome::Error(Value::Undefined),
8489 );
8490 };
8491 self.perform_then(
8492 &resolved,
8493 Some(Value::Object(done)),
8494 Some(Value::Object(failed)),
8495 )?;
8496 Ok(())
8497 }
8498 },
8499 }
8500 }
8501
8502 /// Settle the front request and start the next one.
8503 ///
8504 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
8505 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
8506 /// generator would strand every later request.
8507 fn settle_async_request(
8508 &mut self,
8509 generator: &Gc<JsObject>,
8510 promise: &Gc<JsObject>,
8511 outcome: AsyncOutcome,
8512 ) -> JsResult<()> {
8513 let settled = generator.with_mut(|data| match &mut data.kind {
8514 ObjectKind::Generator(state) => {
8515 let front = state.requests.front();
8516 debug_assert!(
8517 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
8518 "a request settled outside its turn"
8519 );
8520 state.requests.pop_front();
8521 state.async_busy = false;
8522 true
8523 }
8524 _ => false,
8525 });
8526 if settled {
8527 match outcome {
8528 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
8529 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
8530 }
8531 }
8532 self.next_async_request(generator)
8533 }
8534
8535 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
8536 ///
8537 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
8538 /// disposer runs **synchronously** — the reference starts it before returning, which
8539 /// a test can observe by logging after the call — and the rest follow once their
8540 /// predecessor settles.
8541 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
8542 let promise = self.new_promise();
8543 let mut pairs = Vec::with_capacity(resources.len());
8544 for (value, method) in resources {
8545 let pair = self.new_array(vec![value, method]);
8546 pairs.push(Value::Object(pair));
8547 }
8548 let remaining = self.new_array(pairs);
8549 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
8550 Ok(Value::Object(promise))
8551 }
8552
8553 /// One link of the `disposeAsync` chain.
8554 ///
8555 /// Loops while the disposers finish synchronously, and parks on the first thenable it
8556 /// meets — pushing itself back in as the continuation, with the accumulated error
8557 /// carried along so a later failure can still be folded into the `SuppressedError`.
8558 fn dispose_step(
8559 &mut self,
8560 remaining: &Gc<JsObject>,
8561 promise: &Gc<JsObject>,
8562 mut error: Value,
8563 ) -> JsResult<()> {
8564 loop {
8565 let length = remaining.array_length().unwrap_or(0);
8566 if length == 0 {
8567 if matches!(error, Value::Uninitialized) {
8568 self.fulfill_promise(promise, Value::Undefined);
8569 } else {
8570 self.reject_promise(promise, error);
8571 }
8572 return Ok(());
8573 }
8574 let Some(Value::Object(pair)) = remaining
8575 .array_get(length - 1)
8576 .filter(|v| !matches!(v, Value::Hole))
8577 else {
8578 remaining.array_truncate(self.heap, length - 1);
8579 continue;
8580 };
8581 remaining.array_truncate(self.heap, length - 1);
8582 let value = pair.array_get(0).unwrap_or(Value::Undefined);
8583 let Some(Value::Object(method)) = pair.array_get(1) else {
8584 continue;
8585 };
8586 if !method.is_callable() {
8587 continue;
8588 }
8589 match self.call_value(Value::Object(method), value, Vec::new()) {
8590 Ok(result) => {
8591 if !self.is_thenable(&result)? {
8592 // Finished synchronously; the next disposer is the next iteration.
8593 continue;
8594 }
8595 let awaited = match self.promise_resolve_value(result) {
8596 Ok(awaited) => awaited,
8597 Err(Signal::Throw(reason)) => {
8598 self.reject_promise(promise, reason);
8599 return Ok(());
8600 }
8601 Err(other) => return Err(other),
8602 };
8603 let Value::Object(awaited) = awaited else {
8604 continue;
8605 };
8606 let ok = JsObject::function(
8607 self.heap,
8608 Some(self.realm.function_proto.clone()),
8609 Callable::DisposeStep {
8610 remaining: remaining.clone(),
8611 promise: promise.clone(),
8612 error: error.clone(),
8613 rejected: false,
8614 },
8615 );
8616 let failed = JsObject::function(
8617 self.heap,
8618 Some(self.realm.function_proto.clone()),
8619 Callable::DisposeStep {
8620 remaining: remaining.clone(),
8621 promise: promise.clone(),
8622 error,
8623 rejected: true,
8624 },
8625 );
8626 self.perform_then(
8627 &awaited,
8628 Some(Value::Object(ok)),
8629 Some(Value::Object(failed)),
8630 )?;
8631 return Ok(());
8632 }
8633 Err(Signal::Throw(thrown)) => {
8634 error = self.merge_dispose_error(thrown, error);
8635 }
8636 Err(other) => return Err(other),
8637 }
8638 }
8639 }
8640
8641 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8642 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8643 let Value::Object(object) = value else {
8644 return Ok(false);
8645 };
8646 Ok(matches!(
8647 self.get_property(object, "then")?,
8648 Some(Value::Object(then)) if then.is_callable()
8649 ))
8650 }
8651
8652 /// One step of an async generator, settling `promise` with an `{value, done}` result.
8653 fn step_async_generator(
8654 &mut self,
8655 generator: &Gc<JsObject>,
8656 promise: &Gc<JsObject>,
8657 kind: ResumeKind,
8658 value: Value,
8659 ) -> JsResult<()> {
8660 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
8661 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
8662 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
8663 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
8664 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
8665 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
8666 // out of the same read, one as a rejection and one as a rethrow.
8667 //
8668 // Narrow on purpose: only a value that is *already a promise* is inspected, so
8669 // nothing changes for `return 1` and the extra read is a plain data-property
8670 // lookup on the intrinsic case.
8671 if kind == ResumeKind::Return
8672 && let Value::Object(object) = &value
8673 && self.promise_state(object).is_some()
8674 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
8675 {
8676 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
8677 }
8678 let stepped = self.resume_generator_detailed(generator, kind, value);
8679 let (value, done, ready, reason) = match stepped {
8680 Ok(stepped) => stepped,
8681 Err(Signal::Throw(reason)) => {
8682 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8683 }
8684 Err(other) => return Err(other),
8685 };
8686 // Only an `await` has to wait before the method can answer.
8687 if !done && reason == Some(SuspendKind::Await) {
8688 let awaited = match self.promise_resolve_value(value) {
8689 Ok(awaited) => awaited,
8690 Err(Signal::Throw(reason)) => {
8691 return self.settle_async_request(
8692 generator,
8693 promise,
8694 AsyncOutcome::Error(reason),
8695 );
8696 }
8697 Err(other) => return Err(other),
8698 };
8699 let Value::Object(awaited) = awaited else {
8700 return Ok(());
8701 };
8702 let resumed = JsObject::function(
8703 self.heap,
8704 Some(self.realm.function_proto.clone()),
8705 Callable::GeneratorResume {
8706 generator: generator.clone(),
8707 promise: promise.clone(),
8708 kind: ResumeKind::Next,
8709 },
8710 );
8711 let raised = JsObject::function(
8712 self.heap,
8713 Some(self.realm.function_proto.clone()),
8714 Callable::GeneratorResume {
8715 generator: generator.clone(),
8716 promise: promise.clone(),
8717 kind: ResumeKind::Throw,
8718 },
8719 );
8720 self.perform_then(
8721 &awaited,
8722 Some(Value::Object(resumed)),
8723 Some(Value::Object(raised)),
8724 )?;
8725 return Ok(());
8726 }
8727 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
8728 // completes it — both arrive as the settled value rather than as the promise
8729 // object. A plain value skips the round trip, which is also what keeps `yield 1`
8730 // from costing an extra tick.
8731 let awaits_value = self.is_thenable(&value)?;
8732 if awaits_value {
8733 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
8734 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
8735 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
8736 // no `PromiseResolve` appears, so that path keeps the shortcut.
8737 let awaited = match if done {
8738 self.promise_resolve_intrinsic(value)
8739 } else {
8740 self.promise_resolve_value(value)
8741 } {
8742 Ok(awaited) => awaited,
8743 Err(Signal::Throw(reason)) => {
8744 return self.settle_async_request(
8745 generator,
8746 promise,
8747 AsyncOutcome::Error(reason),
8748 );
8749 }
8750 Err(other) => return Err(other),
8751 };
8752 let Value::Object(awaited) = awaited else {
8753 return Ok(());
8754 };
8755 // A rejected yield throws *at the yield* inside the body, so the rejection
8756 // resumes the generator rather than the method's promise.
8757 let answer = JsObject::function(
8758 self.heap,
8759 Some(self.realm.function_proto.clone()),
8760 Callable::YieldResult {
8761 generator: generator.clone(),
8762 promise: promise.clone(),
8763 done,
8764 },
8765 );
8766 let raise = JsObject::function(
8767 self.heap,
8768 Some(self.realm.function_proto.clone()),
8769 Callable::GeneratorResume {
8770 generator: generator.clone(),
8771 promise: promise.clone(),
8772 kind: ResumeKind::Throw,
8773 },
8774 );
8775 self.perform_then(
8776 &awaited,
8777 Some(Value::Object(answer)),
8778 Some(Value::Object(raise)),
8779 )?;
8780 return Ok(());
8781 }
8782 let result = if ready {
8783 // `yield*` handed back the inner iterator's own result object.
8784 value
8785 } else {
8786 self.iterator_result(value, done)?
8787 };
8788 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
8789 }
8790
8791 /// The `{value, done}` object an iterator method answers with.
8792 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
8793 let result = self.new_object(Some(self.realm.object_proto.clone()));
8794 result.define_data("value", value);
8795 result.define_data("done", Value::Bool(done));
8796 Ok(Value::Object(result))
8797 }
8798
8799 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
8800 fn step_generator(
8801 &mut self,
8802 state: &mut GeneratorState,
8803 kind: ResumeKind,
8804 value: Value,
8805 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8806 match state.phase {
8807 GeneratorPhase::Executing => {
8808 return Err(self.type_error("cannot invoke a running generator"));
8809 }
8810 GeneratorPhase::Completed => {
8811 // A finished generator answers every resumption without running.
8812 return Ok(match kind {
8813 ResumeKind::Throw => return Err(Signal::Throw(value)),
8814 ResumeKind::Return => (value, true, false, None),
8815 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
8816 });
8817 }
8818 GeneratorPhase::SuspendedStart => {
8819 if kind != ResumeKind::Next && kind != ResumeKind::Start {
8820 // The body never started, so there is nothing to unwind or return
8821 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
8822 state.frame = None;
8823 state.phase = GeneratorPhase::Completed;
8824 return Ok(match kind {
8825 ResumeKind::Throw => return Err(Signal::Throw(value)),
8826 _ => (value, true, false, None),
8827 });
8828 }
8829 }
8830 GeneratorPhase::SuspendedYield => {}
8831 }
8832
8833 let Some(mut frame) = state.frame.take() else {
8834 return Ok((Value::Undefined, true, false, None));
8835 };
8836 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
8837 // number that says which method resumed it; the emitted `if_false` branches on
8838 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
8839 let mut raised = None;
8840 match kind {
8841 ResumeKind::Next | ResumeKind::Start => {
8842 if state.phase == GeneratorPhase::SuspendedYield {
8843 frame.stack.push(value);
8844 // An `await` resumes with its value alone; only a `yield` gets the
8845 // magic number that says which of `next`/`return` resumed it.
8846 if !state.parked_on_await {
8847 frame.stack.push(Value::Int(RESUME_NEXT));
8848 }
8849 }
8850 }
8851 ResumeKind::Return => {
8852 // A `return` on a not-yet-started generator is handled above, so this is
8853 // always a real resumption.
8854 frame.stack.push(value);
8855 frame.stack.push(Value::Int(RESUME_RETURN));
8856 }
8857 ResumeKind::Throw => {
8858 // At a `yield*` the exception is *data* for the delegation: the compiled
8859 // code resumes with the value and magic `2` and calls the inner iterator's
8860 // `throw`. Everywhere else it is raised at the suspension point, so the
8861 // body's own handler sees it.
8862 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
8863 frame.stack.push(value);
8864 frame.stack.push(Value::Int(RESUME_THROW));
8865 } else {
8866 raised = Some(value);
8867 }
8868 }
8869 }
8870 state.phase = GeneratorPhase::Executing;
8871
8872 let depth = self.frames.len();
8873 self.frames.push(frame);
8874 // A `throw` unwinds from where the frame parked, exactly as if the exception had
8875 // happened at the `yield`.
8876 if let Some(exception) = raised {
8877 if self.catch_here(exception.clone()).is_none() {
8878 self.pop_frame();
8879 state.phase = GeneratorPhase::Completed;
8880 return Err(Signal::Throw(exception));
8881 }
8882 }
8883
8884 // Only the generator's *own* frame ends the generator. The body may call ordinary
8885 // functions, and those push frames of their own: a `Step::Return` from one of them
8886 // is a nested call finishing, not the generator completing. Miscounting that is
8887 // silent — the generator reports the callee's value as its own result and marks
8888 // itself done — so the depth comparison is load-bearing, not defensive.
8889 let own_frame = depth + 1;
8890 loop {
8891 match self.step() {
8892 Ok(Step::Continue) => {}
8893 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
8894 let mut frame = self.frames.pop().expect("a frame is live");
8895 // `yield` left the value on the stack; `initial_yield` left nothing.
8896 let yielded = if reason == SuspendKind::Initial {
8897 Value::Undefined
8898 } else {
8899 frame.stack.pop().unwrap_or(Value::Undefined)
8900 };
8901 state.frame = Some(frame);
8902 state.parked_on_await = reason == SuspendKind::Await;
8903 state.parked_on_yield_star =
8904 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
8905 state.phase = if reason == SuspendKind::Initial {
8906 GeneratorPhase::SuspendedStart
8907 } else {
8908 GeneratorPhase::SuspendedYield
8909 };
8910 // `yield*` hands the inner iterator's own result object straight
8911 // back, so the caller sees one `{value, done}` rather than a nested
8912 // one — which is why the third field says "already a result".
8913 return Ok((
8914 yielded,
8915 false,
8916 reason == SuspendKind::YieldStar,
8917 Some(reason),
8918 ));
8919 }
8920 Ok(Step::Suspend(_)) => {
8921 // A `yield` in a frame other than the generator's would mean a
8922 // generator body entered as an ordinary call, which
8923 // `call_or_push` prevents.
8924 self.unwind_to(depth);
8925 state.phase = GeneratorPhase::Completed;
8926 return Err(Signal::Throw(self.make_error(
8927 "InternalError",
8928 "a generator body ran as an ordinary call",
8929 )));
8930 }
8931 Ok(Step::Return(value)) => {
8932 self.pop_frame();
8933 if self.frames.len() > depth {
8934 // A nested call finished: hand the value back to its caller and
8935 // keep running the generator body.
8936 self.frames
8937 .last_mut()
8938 .expect("a caller is live")
8939 .stack
8940 .push(value);
8941 continue;
8942 }
8943 state.phase = GeneratorPhase::Completed;
8944 // The reference closes the generator's closure variables here; ours
8945 // live in cells the frame owned, which the drop below releases.
8946 return Ok((value, true, false, None));
8947 }
8948 Err(Signal::Throw(exception)) => {
8949 // The frame that threw gets the first chance to catch, exactly as in
8950 // the ordinary call loop; a frame above the generator's is popped and
8951 // the exception carries on down.
8952 let exception = exception;
8953 loop {
8954 if self.frames.len() <= depth {
8955 // The generator's own frame is gone, so nothing here caught it.
8956 state.phase = GeneratorPhase::Completed;
8957 return Err(Signal::Throw(exception));
8958 }
8959 if self.catch_here(exception.clone()).is_some() {
8960 break;
8961 }
8962 self.pop_frame();
8963 }
8964 }
8965 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
8966 }
8967 }
8968 }
8969
8970 /// Pop frames until `depth` are left, keeping their buffers.
8971 fn unwind_to(&mut self, depth: usize) {
8972 while self.frames.len() > depth {
8973 self.pop_frame();
8974 }
8975 }
8976 fn call_or_push(
8977 &mut self,
8978 callee: Value,
8979 this: Value,
8980 args: Vec<Value>,
8981 ) -> JsResult<Option<Value>> {
8982 if let Value::Object(function) = &callee
8983 && let Some((code, env)) = bytecode_of(function)
8984 {
8985 // Calling a generator function does not run anything: it captures the
8986 // arguments in a frame and hands back the generator object.
8987 if code.code.kind.is_generator() {
8988 return self.new_generator(callee, this, args).map(Some);
8989 }
8990 // An async function answers a promise and runs its body as a coroutine, so it
8991 // takes the same path as a plain call into it.
8992 if code.code.kind.is_async() {
8993 return self.new_async_function(callee, this, args).map(Some);
8994 }
8995 self.push_frame(code, env, this, args, callee)?;
8996 return Ok(None);
8997 }
8998 self.call_value(callee, this, args).map(Some)
8999 }
9000
9001 /// `new callee(args)`.
9002 ///
9003 /// A constructor differs from a plain call in three ways: it gets a fresh object
9004 /// as `this` whose prototype is the constructor's `prototype` property, its
9005 /// return value is *replaced* by that object unless it returns an object itself,
9006 /// and a native constructor is expected to initialise the object it is given
9007 /// rather than build one.
9008 pub fn construct(
9009 &mut self,
9010 callee: Value,
9011 new_target: Value,
9012 args: Vec<Value>,
9013 ) -> JsResult<Value> {
9014 // `new` on a bound function constructs its *target*, prepending the arguments
9015 // the bind fixed and ignoring the bound `this` — a bound function is a
9016 // constructor only when its target is one, and `new` always makes a fresh
9017 // object of the target's prototype rather than reusing the bound receiver.
9018 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9019 // ran the body with `this === null` and threw on `this.x = a`.
9020 let mut callee = callee;
9021 let mut new_target = new_target;
9022 let mut args = args;
9023 loop {
9024 let Some(object) = callee.as_object().cloned() else {
9025 return Err(Signal::Throw(
9026 self.make_error("TypeError", "not a constructor"),
9027 ));
9028 };
9029 // A proxy of a function constructs through its `construct` trap, and the
9030 // trap's answer is the result directly — no fresh object is made here.
9031 if object.proxy_state().is_some() {
9032 return match self.proxy_construct(&object, args, &new_target)? {
9033 Some(result) => Ok(result),
9034 None => Err(Signal::Throw(
9035 self.make_error("TypeError", "proxy target is not a constructor"),
9036 )),
9037 };
9038 }
9039 // A generator function has no `[[Construct]]`, and the reference names it in
9040 // the message: `new (function* G(){})()` reports "G is not a constructor".
9041 if object.with(|data| match &data.kind {
9042 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9043 code.code.kind.is_generator()
9044 }
9045 _ => false,
9046 }) {
9047 let name = object
9048 .own_property("name")
9049 .and_then(|property| property.value)
9050 .map(|value| value.to_js_string())
9051 .unwrap_or_default();
9052 return Err(Signal::Throw(
9053 self.make_error("TypeError", &format!("{name} is not a constructor")),
9054 ));
9055 }
9056 let bound = object.with(|data| match &data.kind {
9057 ObjectKind::Function(Callable::Bound {
9058 target,
9059 args: leading,
9060 ..
9061 }) => Some((target.clone(), leading.clone())),
9062 _ => None,
9063 });
9064 let Some((target, leading)) = bound else {
9065 // Not a bound function, so this object is the callee. §7.2.4
9066 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9067 // refusals above cover only the built-ins the reference also refuses by
9068 // name. Everything else — a method, an arrow, an async function — has no
9069 // `[[Construct]]` either, and answering "yes" here made
9070 // `new (Array.prototype.map)` build an object instead of throwing.
9071 if !object.is_constructor() {
9072 let name = object
9073 .own_property("name")
9074 .and_then(|property| property.value)
9075 .map(|value| value.to_js_string())
9076 .unwrap_or_default();
9077 return Err(Signal::Throw(
9078 self.make_error("TypeError", &format!("{name} is not a constructor")),
9079 ));
9080 }
9081 break;
9082 };
9083 let mut all = leading;
9084 all.extend(args);
9085 args = all;
9086 // A bound function that is its own `new.target` stands in for its target:
9087 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9088 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9089 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9090 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9091 _ => false,
9092 };
9093 if same_wrapper {
9094 new_target = target.clone();
9095 }
9096 callee = target;
9097 }
9098 let Value::Object(function) = &callee else {
9099 unreachable!("the loop above only breaks on an object");
9100 };
9101 // The fresh object's prototype comes from `new.target`, not from the callee: a
9102 // derived constructor reaches here through `super()`, and the instance must be a
9103 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9104 // an object inheriting `D.prototype` rather than `C.prototype`.
9105 let prototype_source = match new_target.as_object() {
9106 Some(target) => target.clone(),
9107 None => function.clone(),
9108 };
9109 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9110 // has validated its arguments. Pre-building one here would read
9111 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9112 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9113 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9114 let is_native = function.native_creates_own_instance();
9115 let this = if is_native {
9116 Value::Undefined
9117 } else {
9118 let prototype = self.get_property(&prototype_source, "prototype")?;
9119 let prototype = match prototype {
9120 Some(Value::Object(proto)) => Some(proto),
9121 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9122 // object, the answer is the realm's *intrinsic* prototype for this
9123 // constructor, not `%Object.prototype%`.
9124 _ => {
9125 let fallback = self.get_property(function, "prototype")?;
9126 match fallback {
9127 Some(Value::Object(proto)) => Some(proto),
9128 _ => Some(self.realm.object_proto.clone()),
9129 }
9130 }
9131 };
9132 Value::Object(self.new_object(prototype))
9133 };
9134 // `new.target` inside the body is the constructor that was written, so a bound
9135 // function's target sees itself rather than the bound wrapper.
9136 //
9137 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9138 // `?`, so assigning `None` after the call would be skipped and the failed
9139 // `new.target` would stay visible to every later native call. The symptom was a
9140 // native constructor refusing a plain call — `var s = Symbol(); new
9141 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9142 // "FinalizationRegistry is not a constructor".
9143 let outer_new_target = self.pending_new_target.replace(new_target);
9144 let result = self.call_value(callee, this.clone(), args);
9145 self.pending_new_target = outer_new_target;
9146 let result = result?;
9147 // A constructor that returns an object overrides `this`; any other return
9148 // value (including `undefined`) is ignored.
9149 Ok(match result {
9150 Value::Object(_) => result,
9151 _ => this,
9152 })
9153 }
9154
9155 /// `new.target` for the call currently being made.
9156 ///
9157 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9158 /// it as `this`), but a *host* constructor that builds its own instance is handed
9159 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9160 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9161 /// it here.
9162 ///
9163 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9164 /// receives for a plain call.
9165 pub fn current_new_target(&self) -> Value {
9166 self.pending_new_target.clone().unwrap_or(Value::Undefined)
9167 }
9168
9169 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9170 ///
9171 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9172 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9173 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9174 let constructor = self.realm.errors.get("AggregateError").cloned();
9175 let Some(constructor) = constructor else {
9176 return self.make_error("AggregateError", message);
9177 };
9178 let list = self.new_array(errors);
9179 match self.construct(
9180 Value::Object(constructor.clone()),
9181 Value::Object(constructor),
9182 vec![Value::Object(list), self.string(message)],
9183 ) {
9184 Ok(value) => value,
9185 // A user could have replaced `AggregateError` with something that throws; the
9186 // engine still owes the caller a rejection, so it falls back rather than
9187 // turning `Promise.any`'s rejection into a throw.
9188 Err(_) => self.make_error("AggregateError", message),
9189 }
9190 }
9191
9192 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9193 ///
9194 /// The error classes themselves arrive with the builtins milestone; what
9195 /// matters here is that the thrown value stringifies the way a script printing
9196 /// the caught value expects.
9197 ///
9198 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9199 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9200 /// rely on when they print a caught value.
9201 pub fn make_error(&self, name: &str, message: &str) -> Value {
9202 let proto = self
9203 .realm
9204 .errors
9205 .get(name)
9206 .map(|constructor| self.prototype_of(constructor))
9207 .unwrap_or_else(|| self.realm.error_proto.clone());
9208 let error = self.new_object(Some(proto));
9209 // `name` and `message` are own properties of the instance, which is what
9210 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9211 // `Error`.
9212 error.define(
9213 "name",
9214 Property::with_attributes(self.string(name), true, false),
9215 );
9216 error.define(
9217 "message",
9218 Property::with_attributes(self.string(message), true, false),
9219 );
9220 // The internal class, which is what tells a printer this is an error rather than a
9221 // plain object with `name` and `message` properties. The constructor path sets it
9222 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9223 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9224 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9225 // a `RangeError` still prints as `RangeError`.
9226 self.internal_set(&error, "_class", self.string("Error"));
9227 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9228 // answered `false` from `Error.isError` while a constructed one answered `true`,
9229 // because only the constructor set the slot. The reference answers `true` for both
9230 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9231 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9232 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9233 // engine-thrown error lost its blank line.
9234 self.internal_set(&error, "_error_data", Value::Bool(true));
9235 // The trace is captured where the error is *made*, which is where the reference
9236 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9237 // way out, so a caught engine error already has its stack even if the handler
9238 // never rethrows it.
9239 self.add_stack(&error);
9240 Value::Object(error)
9241 }
9242
9243 /// Give an error object its `stack` property, from the current frame stack.
9244 ///
9245 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9246 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9247 /// `stack` a script set, is not rewritten.
9248 pub fn add_stack(&self, object: &Gc<JsObject>) {
9249 self.add_stack_skipping(object, 0);
9250 }
9251
9252 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9253 ///
9254 /// An `Error` constructor passes 1: the reference builds those traces with
9255 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9256 /// constructor itself, while a `RangeError` raised inside `toISOString` does
9257 /// report `at toISOString (native)`.
9258 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9259 if object.has_own("stack") {
9260 return;
9261 }
9262 // The trace is *captured* here but not installed as a property: `stack` is an
9263 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9264 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9265 // is kept in a hidden slot and the getter materialises it on first read.
9266 //
9267 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9268 // shows it — this is the same discipline `_error_data` and `_class` follow.
9269 let trace = self.stack_trace_skipping(skip);
9270 let text = self.string(trace);
9271 self.internal_set(object, "_stack_trace", text);
9272 }
9273
9274 /// The function object currently being called, if any.
9275 ///
9276 /// A native function is a bare `fn` pointer, so it cannot capture which class
9277 /// it belongs to; it reads that from the callee instead. This is also what a
9278 /// stack trace would use.
9279 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9280 match &self.frames.last()?.callee {
9281 Value::Object(object) => Some(object.clone()),
9282 _ => None,
9283 }
9284 }
9285
9286 /// The `prototype` property of a constructor, falling back to
9287 /// `Object.prototype` for anything that is not shaped like one.
9288 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9289 constructor
9290 .own_property("prototype")
9291 .and_then(|property| property.value)
9292 .and_then(|value| value.as_object().cloned())
9293 .unwrap_or_else(|| self.realm.object_proto.clone())
9294 }
9295
9296 /// Throw a `TypeError` carrying `message`.
9297 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9298 Signal::Throw(self.make_error("TypeError", message.as_ref()))
9299 }
9300
9301 /// Throw a `RangeError` carrying `message`.
9302 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9303 Signal::Throw(self.make_error("RangeError", message.as_ref()))
9304 }
9305
9306 /// The `ReferenceError` a read of an uninitialised binding raises.
9307 /// The name of the binding `slot` refers to, for an error message.
9308 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9309 match kind {
9310 VarSlot::Loc => self
9311 .frame()
9312 .code
9313 .code
9314 .vars
9315 .get(slot)
9316 .map(|v| v.name.clone()),
9317 VarSlot::Closure => self
9318 .frame()
9319 .code
9320 .code
9321 .closure_vars
9322 .get(slot)
9323 .map(|c| c.name.clone()),
9324 }
9325 .unwrap_or_default()
9326 }
9327
9328 /// Whether `slot` names a `const` binding, which rejects every store after its
9329 /// initialiser.
9330 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9331 match kind {
9332 VarSlot::Loc => self
9333 .frame()
9334 .code
9335 .code
9336 .vars
9337 .get(slot)
9338 .is_some_and(|v| v.is_const),
9339 VarSlot::Closure => self
9340 .frame()
9341 .code
9342 .code
9343 .closure_vars
9344 .get(slot)
9345 .is_some_and(|c| c.is_const),
9346 }
9347 }
9348
9349 /// The `TypeError` a store to a `const` binding raises.
9350 ///
9351 /// `const` is enforced here rather than at compile time because the binding can be
9352 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9353 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9354 /// both halves of what "checked store" means: the dead zone is over, and the
9355 /// binding is writable.
9356 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9357 let name = self.binding_name(slot, kind);
9358 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
9359 }
9360
9361 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
9362 let name = match kind {
9363 VarSlot::Loc => self
9364 .frame()
9365 .code
9366 .code
9367 .vars
9368 .get(slot)
9369 .map(|v| v.name.clone()),
9370 VarSlot::Closure => self
9371 .frame()
9372 .code
9373 .code
9374 .closure_vars
9375 .get(slot)
9376 .map(|c| c.name.clone()),
9377 }
9378 .unwrap_or_default();
9379 Signal::Throw(self.make_error(
9380 "ReferenceError",
9381 &format!("cannot access '{name}' before initialization"),
9382 ))
9383 }
9384
9385 fn throw_reference(&self, name: &str) -> Signal {
9386 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
9387 }
9388
9389 // -- the instruction loop -----------------------------------------------
9390
9391 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
9392 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
9393 // measured at 16% of a tight arithmetic loop's total time.
9394 #[inline(always)]
9395 fn step(&mut self) -> JsResult<Step> {
9396 // The instruction is already decoded (see [`crate::insn`]), so this is an index
9397 // and a `Copy` read rather than a table lookup plus a width switch. Only the
9398 // borrow lives across the boundary; nothing is cloned.
9399 // **One** borrow of the frame: fetch the record, then advance in the same scope.
9400 // The obvious version borrowed it three times (`last` to read, `last_mut` to
9401 // write, and once more inside the handler), and each is a bounds check plus an
9402 // `Option` unwrap — on the one path every instruction takes.
9403 let Some((insn, next)) = ({
9404 let frame = self
9405 .frames
9406 .last_mut()
9407 .expect("step() is only called with a live frame");
9408 // Past the last instruction is a normal return: the compiler ends a function
9409 // with `return`, and a jump to the end of a block lands here.
9410 let insn = frame.insns().get(frame.pc).copied();
9411 match insn {
9412 None => None,
9413 Some(insn) => {
9414 // A fused record stands for the next few instructions, so the next
9415 // `pc` is its width ahead — the instructions it replaces are never
9416 // dispatched. `at` is the byte offset a stack trace reports; it stays
9417 // an offset because the line table is keyed by bytes.
9418 frame.at = insn.offset as usize;
9419 frame.pc += insn.width();
9420 Some((insn, frame.pc))
9421 }
9422 }
9423 }) else {
9424 return Ok(Step::Return(Value::Undefined));
9425 };
9426 self.check_memory()?;
9427 self.check_interrupt()?;
9428 if insn.fused == crate::insn::Fused::None {
9429 self.execute_instruction(insn.op, insn.a, insn.b, next)
9430 } else {
9431 self.execute_fused(insn)
9432 }
9433 }
9434
9435 /// Run a fused instruction: several bytecode instructions in one dispatch.
9436 ///
9437 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
9438 /// it cannot throw and cannot allocate — and anything else falls back to the real
9439 /// instructions, in their real order, so an exception leaves the operand stack
9440 /// exactly as it would have been.
9441 #[inline]
9442 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
9443 use crate::insn::Fused;
9444 let slot = insn.a as usize;
9445 match insn.fused {
9446 // `x = k`: `push k; put_loc x`.
9447 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
9448 // `x += k`: `get_loc x; push k; add; put_loc x`.
9449 Fused::AddImmLoc => {
9450 let delta = insn.b as i32;
9451 match self.get_loc(slot) {
9452 Value::Int(left) => {
9453 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
9454 // that built two `Value`s, called a function, and matched on them
9455 // again to reach this same `checked_add`. It is the innermost
9456 // operation of every accumulator in every program.
9457 let answer = match left.checked_add(delta) {
9458 Some(sum) => Value::Int(sum),
9459 None => Value::Float(left as f64 + delta as f64),
9460 };
9461 self.put_loc(slot, answer);
9462 }
9463 other => {
9464 self.push(other);
9465 self.push(Value::Int(delta));
9466 self.binary_add()?;
9467 let value = self.pop();
9468 self.put_loc(slot, value);
9469 }
9470 }
9471 }
9472 // `x += "literal"` and `x += y`: the two shapes that can append in place.
9473 Fused::AddAtomLoc => {
9474 let text = self.atom_wtf8(insn.b as usize);
9475 let right = self.string_wtf8(text);
9476 self.add_into_loc(slot, right)?;
9477 }
9478 Fused::AddLocLoc => {
9479 let source = (insn.a & 0xFFFF) as usize;
9480 let target = (insn.a >> 16) as usize;
9481 let right = self.get_loc(source);
9482 self.add_into_loc(target, right)?;
9483 }
9484 Fused::AddArgLoc => {
9485 let source = (insn.a & 0xFFFF) as usize;
9486 let target = (insn.a >> 16) as usize;
9487 let right = self.get_arg(source);
9488 self.add_into_loc(target, right)?;
9489 }
9490 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
9491 Fused::PostIncLoc => match self.get_loc(slot) {
9492 Value::Int(left) => {
9493 let answer = match left.checked_add(1) {
9494 Some(sum) => Value::Int(sum),
9495 None => Value::Float(left as f64 + 1.0),
9496 };
9497 self.put_loc(slot, answer);
9498 }
9499 other => {
9500 self.push(other);
9501 let raw = self.pop();
9502 let (old, updated) = self.advance_numeric(raw, true)?;
9503 self.push(old);
9504 self.push(updated);
9505 let value = self.pop();
9506 self.put_loc(slot, value);
9507 self.pop();
9508 }
9509 },
9510 // `if (!(x < arg)) goto target`: a loop header.
9511 //
9512 // The comparison is computed rather than replayed on the operand stack. That
9513 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
9514 // that throws: the effects happen in the same order, and a handler truncates
9515 // the stack down to its marker, so the intermediate values are unobservable.
9516 Fused::LtLocArgJump => {
9517 let loc = (insn.a >> 16) as usize;
9518 let arg = (insn.a & 0xFFFF) as usize;
9519 let left = self.get_loc(loc);
9520 let right = self.get_arg(arg);
9521 let taken = match (&left, &right) {
9522 (Value::Int(left), Value::Int(right)) => !(left < right),
9523 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9524 };
9525 if taken {
9526 self.frame_mut().pc = insn.b as usize;
9527 }
9528 }
9529 // `i < k` in a loop header, where `k` is an integer literal.
9530 Fused::LtLocImmJump => {
9531 let left = self.get_loc(insn.a as usize);
9532 let right = Value::Int(insn.imm as i32);
9533 let taken = match &left {
9534 Value::Int(left) => !(*left < insn.imm as i32),
9535 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9536 };
9537 if taken {
9538 self.frame_mut().pc = insn.b as usize;
9539 }
9540 }
9541 Fused::None => unreachable!("only called for a fused record"),
9542 }
9543 Ok(Step::Continue)
9544 }
9545
9546 /// Run records that cannot call script, cannot throw and cannot change frames.
9547 ///
9548 /// Returns `Some(value)` when the function ran off the end of its instructions (a
9549 /// normal return), and `None` when it stopped in front of an instruction the slow path
9550 /// has to handle — `pc` is written back either way, so `step` resumes at the right
9551 /// place.
9552 ///
9553 /// **The invariant is the whole point.** Every arm here is restricted to work that
9554 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
9555 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
9556 /// that the memory limit has to see. An opcode whose operands turn out to need any of
9557 /// that **stops the loop** instead of trying, so the slow path gets the instruction
9558 /// untouched and with its operands still on the stack. That is why the fallback is a
9559 /// `break` and not a duplicated slow arm: a second implementation of the same
9560 /// semantics is how a wrong answer gets in with no test noticing.
9561 ///
9562 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
9563 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
9564 fn run_fast(&mut self) -> JsResult<Option<Value>> {
9565 use crate::insn::Fused;
9566 // The outer loop exists only so a `Call` can come back through here: once a
9567 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
9568 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
9569 // frame. Re-entering re-reads both from whichever frame is now on top. Every
9570 // other exit from the inner loop returns, so this costs one loop per call.
9571 'outer: loop {
9572 // One reference-count bump per *slow* instruction (a call, an allocation, a
9573 // property access), never one per instruction — that distinction is worth
9574 // two orders of magnitude and was measured as such.
9575 let (code, mut pc) = {
9576 let frame = self.frame();
9577 (frame.code.clone(), frame.pc)
9578 };
9579 let insns = &code.insns;
9580 loop {
9581 let Some(insn) = insns.get(pc).copied() else {
9582 self.frame_mut().pc = pc;
9583 return Ok(Some(Value::Undefined));
9584 };
9585 match insn.fused {
9586 // `x = k`
9587 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
9588 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
9589 // object — stops the loop so `binary_add` can decide.
9590 Fused::AddImmLoc => {
9591 let slot = insn.a as usize;
9592 let delta = insn.b as i32;
9593 let Value::Int(left) = self.get_loc(slot) else {
9594 return Ok(self.stop(pc));
9595 };
9596 let sum = match left.checked_add(delta) {
9597 Some(sum) => Value::Int(sum),
9598 None => Value::Float(left as f64 + delta as f64),
9599 };
9600 self.put_loc(slot, sum);
9601 }
9602 // `x += "literal"` / `x += y`: the operand is a string, so the append
9603 // either allocates one or grows one. Both are the slow path's business;
9604 // the fusion's job is only to make the *slot* the sole owner, which is what
9605 // `execute_fused` needs and what `get_loc` alone destroys.
9606 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
9607 return Ok(self.stop(pc));
9608 }
9609 // `x++` on an integer, old value dropped.
9610 Fused::PostIncLoc => {
9611 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
9612 // value is read in place and overwritten in place, so the reference
9613 // count it held is released by the same assignment that stores the
9614 // new one. `get_loc` plus `put_loc` did two borrows, two table
9615 // lookups and a clone, and this arm is the whole body of a counting
9616 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
9617 let slot = insn.a as usize;
9618 let frame = self.frames.last_mut().expect("a frame is live");
9619 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
9620 let target = if cell < 0 {
9621 frame.locals.get_mut(slot)
9622 } else {
9623 None
9624 };
9625 let Some(target) = target else {
9626 return Ok(self.stop(pc));
9627 };
9628 let Value::Int(left) = *target else {
9629 return Ok(self.stop(pc));
9630 };
9631 *target = match left.checked_add(1) {
9632 Some(sum) => Value::Int(sum),
9633 None => Value::Float(left as f64 + 1.0),
9634 };
9635 }
9636 // A loop header, `if (!(x < arg)) goto target`, with both sides already
9637 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
9638 // bound stayed small integers.
9639 Fused::LtLocArgJump => {
9640 let loc = (insn.a >> 16) as usize;
9641 let arg = (insn.a & 0xFFFF) as usize;
9642 // One borrow for both slots: this arm *is* the whole loop of a
9643 // `for (i = 0; i < n; i++)` with an argument bound, so a second
9644 // `frames.last()` here is paid on every iteration. Measured 7.5% on
9645 // `dispatch:empty-loop`.
9646 let (left, right) = {
9647 let frame = self.frame();
9648 (frame.read_loc(loc), frame.read_arg(arg))
9649 };
9650 // Heavily measured: the bound is very often a `Float` even when the
9651 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
9652 // `JSON.parse` or a division is one — so requiring both sides to be
9653 // `Int` sent every iteration of those loops down the slow path. The
9654 // comparison below is the same one `relational` makes for two numbers.
9655 if !is_number(&left) || !is_number(&right) {
9656 return Ok(self.stop(pc));
9657 }
9658 // `if_false` branches on the comparison being false, which is **not**
9659 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
9660 // `>=` is also false and would keep it running forever. Clippy wants the
9661 // negation folded; that would be a wrong answer.
9662 let ordered = left.to_number() < right.to_number();
9663 let take_branch = !ordered;
9664 if take_branch {
9665 pc = insn.b as usize;
9666 continue;
9667 }
9668 }
9669 // The same header with a literal bound: `if (!(x < k)) goto target`.
9670 // The bound is an immediate, so only the counter needs a type test.
9671 #[allow(clippy::neg_cmp_op_on_partial_ord)]
9672 Fused::LtLocImmJump => {
9673 let left = self.get_loc(insn.a as usize);
9674 if !is_number(&left) {
9675 return Ok(self.stop(pc));
9676 }
9677 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9678 if take_branch {
9679 pc = insn.b as usize;
9680 continue;
9681 }
9682 }
9683 Fused::None => match insn.op {
9684 // -- branches ---------------------------------------------------
9685 // A jump is an assignment now, because the target is an instruction
9686 // index. No arithmetic, no resolution table.
9687 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9688 let target = insn.a as usize;
9689 // A **back-edge** is a loop, and it is the only place an
9690 // instruction-level checkpoint can stop one: `for(;;){}` compiles
9691 // to a jump to itself and never leaves this loop, so the
9692 // per-instruction checks in `step` never run. That is exactly the
9693 // hole this arm closes — a host's `JS_SetInterruptHandler` did
9694 // nothing to a `for(;;){}` until it did, which is what
9695 // `tests/c/embed.c` is for.
9696 //
9697 // Polling here rather than on every instruction in this loop is
9698 // also the reference's choice (`OP_goto` calls
9699 // `js_poll_interrupts`), and it costs one compare per branch
9700 // instead of one decrement per instruction.
9701 if target <= pc {
9702 self.frame_mut().pc = target;
9703 self.check_memory()?;
9704 self.check_interrupt()?;
9705 }
9706 pc = target;
9707 continue;
9708 }
9709 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
9710 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
9711 let taken = self.pop().to_boolean();
9712 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
9713 if taken == want {
9714 pc = insn.a as usize;
9715 continue;
9716 }
9717 }
9718 // -- slot access -------------------------------------------------
9719 // A load's slot is already an operand (see `insn::implicit_operand`);
9720 // a captured one goes through its cell, which runs no script.
9721 Opcode::GetLoc
9722 | Opcode::GetLoc8
9723 | Opcode::GetLoc0
9724 | Opcode::GetLoc1
9725 | Opcode::GetLoc2
9726 | Opcode::GetLoc3 => {
9727 let value = self.get_loc(insn.a as usize);
9728 self.push(value);
9729 }
9730 Opcode::PutLoc
9731 | Opcode::PutLoc8
9732 | Opcode::PutLoc0
9733 | Opcode::PutLoc1
9734 | Opcode::PutLoc2
9735 | Opcode::PutLoc3 => {
9736 let value = self.pop();
9737 self.put_loc(insn.a as usize, value);
9738 }
9739 Opcode::GetArg
9740 | Opcode::GetArg0
9741 | Opcode::GetArg1
9742 | Opcode::GetArg2
9743 | Opcode::GetArg3 => {
9744 let value = self.get_arg(insn.a as usize);
9745 self.push(value);
9746 }
9747 Opcode::PutArg
9748 | Opcode::PutArg0
9749 | Opcode::PutArg1
9750 | Opcode::PutArg2
9751 | Opcode::PutArg3 => {
9752 let value = self.pop();
9753 self.put_arg(insn.a as usize, value);
9754 }
9755 // `a[i]` with an integer index on a dense array: see `fast_array_get`
9756 // for why a non-hole own element is exactly the slow path's answer.
9757 // The two operands are *peeked*, so a miss leaves the stack as the
9758 // slow path expects to find it.
9759 Opcode::GetArrayEl => {
9760 // One lookup, not two. The guard used `if …is_some()` and the arm
9761 // then called it again to get the value — two `peek`s, two
9762 // `array_get`s and two `Value` clones for one element.
9763 // `fast_array_get` was 13.1% of `array:indexed`, and the same
9764 // double call was the first version of the `get_field` fast path.
9765 let Some(value) = self.fast_array_get() else {
9766 return Ok(self.stop(pc));
9767 };
9768 // `a[i]` consumes both operands and leaves the element in their
9769 // place: one `truncate` and one write, no `pop`/`push` pair.
9770 let frame = self.frame_mut();
9771 frame.stack.truncate(frame.stack.len() - 2);
9772 frame.stack.push(value);
9773 }
9774 // `a[i] = v` on a dense array with an integer index: see
9775 // `fast_array_set` for why the whole store is one step.
9776 Opcode::PutArrayEl if self.fast_array_set() => {}
9777 // `o.x` resolved from the inline cache without leaving the loop.
9778 //
9779 // The cache is keyed by `(receiver identity, atom, site)` and a
9780 // monomorphic read re-validates the same chain every iteration, so
9781 // each one used to cost a `stop(pc)` — a write of `pc` into the
9782 // frame, a return out of this loop, a re-dispatch through `step` and
9783 // a re-entry. `property:monomorphic` spent 18% in
9784 // `read_field_cached` and 21% in `push`, both across that boundary.
9785 //
9786 // The site is `pc + width`, which is exactly the `next` the slow arm
9787 // passes — the two must agree or every fast lookup misses and
9788 // re-records the same entry forever.
9789 //
9790 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
9791 // slow arm finds the receiver where it expects it.
9792 // `name` resolved from the global-variable cache inside the loop.
9793 //
9794 // Same shape as `get_field` above and for the same reason: `get_var`
9795 // was not in the fast loop, so reading a global — which `fib` does
9796 // once per recursive call, for its own name — cost a `stop(pc)`, a
9797 // return out of the loop, a `step` re-dispatch and a re-entry, before
9798 // `get_global` even started its `scopes_are_plain` checks.
9799 //
9800 // Everything here is exactly `get_global`'s first branch: not lexical,
9801 // no `eval` scope, cache hit. Anything else leaves the stack untouched
9802 // and lets the slow arm decide.
9803 Opcode::GetVar => {
9804 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
9805 return Ok(self.stop(pc));
9806 };
9807 self.push(value);
9808 }
9809 Opcode::GetField | Opcode::GetField2 => {
9810 let Some(value) =
9811 self.fast_field_get(insn.a as usize, pc + insn.width())
9812 else {
9813 return Ok(self.stop(pc));
9814 };
9815 if insn.op == Opcode::GetField2 {
9816 // `get_field2` keeps the receiver for the `call_method` that
9817 // follows.
9818 self.push(value);
9819 } else {
9820 // `get_field` replaces the receiver, so this is one store over
9821 // the top slot rather than a `pop` and a `push`: the length
9822 // never changes, so neither `Vec` arm has a capacity check or a
9823 // drop to run beyond the one the overwrite itself does.
9824 let frame = self.frame_mut();
9825 match frame.stack.last_mut() {
9826 Some(slot) => *slot = value,
9827 None => return Ok(self.stop(pc)),
9828 }
9829 }
9830 }
9831 // -- constants ---------------------------------------------------
9832 Opcode::PushMinus1
9833 | Opcode::Push0
9834 | Opcode::Push1
9835 | Opcode::Push2
9836 | Opcode::Push3
9837 | Opcode::Push4
9838 | Opcode::Push5
9839 | Opcode::Push6
9840 | Opcode::Push7
9841 | Opcode::PushI8
9842 | Opcode::PushI16
9843 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
9844 // -- stack shuffling ---------------------------------------------
9845 Opcode::Drop => {
9846 self.pop();
9847 }
9848 // -- arithmetic on two integers ----------------------------------
9849 //
9850 // The operands are *looked at* before they are popped, so a non-integer
9851 // pair leaves the stack exactly as the slow path expects to find it.
9852 Opcode::Add if self.numeric_pair() => {
9853 let right = self.pop();
9854 let left = self.pop();
9855 // Exactly [`add_numbers`], which is what the slow arm reaches.
9856 let answer = match (&left, &right) {
9857 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9858 Some(sum) => Value::Int(sum),
9859 None => Value::Float(*a as f64 + *b as f64),
9860 },
9861 _ => Value::Float(left.to_number() + right.to_number()),
9862 };
9863 self.push(answer);
9864 }
9865 Opcode::Sub
9866 | Opcode::And
9867 | Opcode::Or
9868 | Opcode::Xor
9869 | Opcode::Shl
9870 | Opcode::Sar
9871 | Opcode::Shr
9872 if self.numeric_pair() =>
9873 {
9874 let right = self.pop();
9875 let left = self.pop();
9876 let answer =
9877 arithmetic(insn.op, left, right).expect("numbers cannot throw");
9878 self.push(answer);
9879 }
9880 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
9881 if self.numeric_pair() =>
9882 {
9883 let right = self.pop();
9884 let left = self.pop();
9885 let answer = self
9886 .relational(insn.op, left, right)
9887 .expect("numbers cannot throw");
9888 self.push(answer);
9889 }
9890 // -- calls -------------------------------------------------------
9891 //
9892 // A plain call: `callee(arg0, …, argN) -> result`.
9893 //
9894 // This arm exists because of one measurement. `call:recursion` had
9895 // **20.4% of its profile in `execute_instruction`** — the *slow*
9896 // executor — and `fib`'s recursive call is the only thing in that
9897 // function which is not a fast arm. Every call therefore left this
9898 // loop via `stop()`, went through `step()`'s dispatch and
9899 // `execute_instruction`'s match over every opcode, and came back here
9900 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
9901 //
9902 // Two things make it safe to do here rather than only in the slow path:
9903 //
9904 // * the caller's `pc` is stored *before* the call, which is what
9905 // `step` does too — so when the callee returns, the caller resumes
9906 // after the call and not at it;
9907 // * `check_memory` runs, because `step` calls it once per instruction
9908 // and a call allocates a frame, its locals and its cells. Skipping
9909 // the checkpoint here would let a `--memory-limit` script overshoot
9910 // by one call per instruction.
9911 Opcode::Call
9912 | Opcode::Call0
9913 | Opcode::Call1
9914 | Opcode::Call2
9915 | Opcode::Call3 => {
9916 let argc = self.argc_operand(insn.op, insn.a);
9917 let next = pc + insn.width();
9918 {
9919 let frame = self
9920 .frames
9921 .last_mut()
9922 .expect("run_fast() is only called with a live frame");
9923 // `at` is what a stack trace reports for this frame, so a throw
9924 // inside the callee has to see the call site and not whatever
9925 // the last `stop()` left there.
9926 frame.at = insn.offset as usize;
9927 frame.pc = next;
9928 }
9929 self.check_memory()?;
9930 self.check_interrupt()?;
9931 let args = self.pop_n(argc);
9932 let callee = self.pop();
9933 // A plain call has no receiver; the callee decides what to do with
9934 // `undefined` (a sloppy function substitutes the global object).
9935 if let Some(result) =
9936 self.call_or_push(callee, Value::Undefined, args)?
9937 {
9938 // Native, host, generator, async, bound — no frame was pushed,
9939 // so this loop is still describing the right function. `pc`
9940 // is advanced by the loop tail like every other arm; only the
9941 // frame's copy had to be written here, and it already was.
9942 self.push(result);
9943 } else {
9944 // A bytecode callee: its frame is on top now, and `insns` and
9945 // `pc` both belong to the caller. Start over on the new frame.
9946 continue 'outer;
9947 }
9948 }
9949 // -- return ------------------------------------------------------
9950 Opcode::Return => {
9951 let value = self.pop();
9952 self.frame_mut().pc = pc + insn.width();
9953 return Ok(Some(value));
9954 }
9955 Opcode::ReturnUndef => {
9956 self.frame_mut().pc = pc + insn.width();
9957 return Ok(Some(Value::Undefined));
9958 }
9959 // Everything else needs the slow path.
9960 _ => return Ok(self.stop(pc)),
9961 },
9962 }
9963 pc += insn.width();
9964 }
9965 }
9966 }
9967
9968 /// Whether the top two operand-stack values are both numbers.
9969 ///
9970 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
9971 /// cannot run script, so the arm may not throw and may not change frames.
9972 fn numeric_pair(&self) -> bool {
9973 is_number(&self.peek(0)) && is_number(&self.peek(1))
9974 }
9975
9976 /// `a[i]` for a dense array and an integer index, without the string round trip.
9977 ///
9978 /// The slow path answers this by turning `i` into a string (`propkey` →
9979 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
9980 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
9981 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
9982 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
9983 /// without even the cheap `Int` formatting.
9984 ///
9985 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
9986 /// unambiguously the one the slow path would give:
9987 ///
9988 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
9989 /// `2^32-1` is the length, not an index),
9990 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
9991 /// typed array or an ordinary object, all of which have their own rules),
9992 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
9993 /// starts walking the prototype chain, and `a[i]` on a hole must find
9994 /// `Array.prototype[i]` if it exists rather than `undefined`.
9995 ///
9996 /// The last condition is the one that makes this safe rather than merely fast: an own
9997 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
9998 /// `get_var` answered from the global-variable cache, or `None`.
9999 ///
10000 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10001 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10002 /// records nothing — the slow arm is about to walk the chain and record it.
10003 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10004 let frame = self.frame();
10005 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10006 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10007 // `GlobalRef` forwarded through a nested function has its flags cleared.
10008 if self.realm.globals.contains_key(name) {
10009 return None;
10010 }
10011 if !self.scopes_are_plain() {
10012 return None;
10013 }
10014 let object = &self.realm.global;
10015 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10016 let cached = self.global_cache[site].as_ref()?;
10017 if !object.upgrades_to(&cached.object) {
10018 return None;
10019 }
10020 object.data_property_at(cached.index, name)
10021 }
10022
10023 /// `o.x` answered entirely from the inline cache, or `None`.
10024 ///
10025 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10026 /// about to do exactly that and recording it twice would rebuild the chain for every
10027 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10028 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10029 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10030 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10031 // an object receiver is a reference-count bump that the answer never needs.
10032 let frame = self.frame();
10033 let object = frame.stack.last()?;
10034 let Value::Object(target) = object else {
10035 return None;
10036 };
10037 // A proxy traps the lookup, so no cache entry ever describes it.
10038 if target.proxy_state().is_some() {
10039 return None;
10040 }
10041 let key = frame.code.atom_keys.get(atom)?;
10042 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10043 if cached.key != *key {
10044 return None;
10045 }
10046 Self::cached_hit(target, cached)
10047 }
10048
10049 fn fast_array_get(&self) -> Option<Value> {
10050 let Value::Int(index) = self.peek(0) else {
10051 return None;
10052 };
10053 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10054 // set for an `i32`.
10055 if index < 0 {
10056 return None;
10057 }
10058 let Value::Object(object) = self.peek(1) else {
10059 return None;
10060 };
10061 match object.array_get(index as usize) {
10062 Some(value) if !matches!(value, Value::Hole) => Some(value),
10063 _ => None,
10064 }
10065 }
10066
10067 /// `a[i] = v` on a dense array with an integer index, as one store.
10068 ///
10069 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10070 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10071 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10072 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10073 /// reference at the time it was measured (14.7x).
10074 ///
10075 /// Every condition here is one the slow path would also have to satisfy before
10076 /// storing into the element vector:
10077 ///
10078 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10079 /// accepts as an index;
10080 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10081 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10082 /// one inside a recorded descriptor, reports `false` and the caller stops.
10083 ///
10084 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10085 /// writes the own element too once `array_set` says it did.
10086 fn fast_array_set(&mut self) -> bool {
10087 // Every test runs *before* anything is popped: a refusal has to leave the stack
10088 // exactly as the slow path expects to find it. Popping first and reporting the
10089 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10090 // then ran the slow path with nothing to write.
10091 let Value::Int(index) = self.peek(1) else {
10092 return false;
10093 };
10094 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10095 if index < 0 {
10096 return false;
10097 }
10098 // Only a real array: a typed array's elements live in its buffer, a string-like
10099 // object has no element vector, and `array_set` on either does nothing.
10100 let Value::Object(object) = self.peek(2) else {
10101 return false;
10102 };
10103 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10104 return false;
10105 }
10106 // A non-extensible array reports `false` here, but the *slow* path has to decide
10107 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10108 // that with the key and the stack still intact.
10109 if !object.is_extensible() {
10110 return false;
10111 }
10112 // Inside the logical length, so the store cannot change `length`. Combined with
10113 // extensibility above, the only growth left for `array_set` is filling a hole in
10114 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10115 // shape this fast path exists for. A store past the length would grow the array,
10116 // and whether that is allowed is the slow path's question.
10117 if index as usize >= object.array_length().unwrap_or(0) {
10118 return false;
10119 }
10120 // Only an *own element* can take the inline store. A hole is not an own property,
10121 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10122 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10123 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10124 // the one case this path used to swallow.
10125 //
10126 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10127 // `array:push` appends past the length, which this path already refused.
10128 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10129 {
10130 return false;
10131 }
10132 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10133 // to report a failure after the operands are gone.
10134 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10135 return false;
10136 }
10137 let value = self.pop();
10138 self.pop();
10139 self.pop();
10140 object.array_store(self.heap, index as usize, value)
10141 }
10142
10143 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10144 fn stop(&mut self, pc: usize) -> Option<Value> {
10145 self.frame_mut().pc = pc;
10146 None
10147 }
10148
10149 fn push(&mut self, value: Value) {
10150 self.frame_mut().stack.push(value);
10151 }
10152
10153 fn pop(&mut self) -> Value {
10154 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10155 }
10156
10157 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10158 let frame = self.frame_mut();
10159 let start = frame.stack.len().saturating_sub(count);
10160 frame.stack.split_off(start)
10161 }
10162
10163 fn peek(&self, back: usize) -> Value {
10164 let frame = self.frame();
10165 frame
10166 .stack
10167 .get(frame.stack.len().wrapping_sub(1 + back))
10168 .cloned()
10169 .unwrap_or(Value::Undefined)
10170 }
10171
10172 #[allow(clippy::too_many_lines)]
10173 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10174 use Opcode::*;
10175 match op {
10176 // -- constants and stack shuffling -----------------------------
10177 Nop => {}
10178 PushMinus1 => self.push(Value::Int(-1)),
10179 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10180 let value = match op {
10181 Push0 => 0,
10182 Push1 => 1,
10183 Push2 => 2,
10184 Push3 => 3,
10185 Push4 => 4,
10186 Push5 => 5,
10187 Push6 => 6,
10188 _ => 7,
10189 };
10190 self.push(Value::Int(value));
10191 }
10192 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10193 PushBigintI32 => {
10194 // The immediate form of a `BigInt` literal; the reference has the same
10195 // split between this and a constant-pool entry.
10196 let value = crate::bigint::BigInt::from_i64(a as i64);
10197 self.push(self.bigint(value));
10198 }
10199 PushTrue => self.push(Value::Bool(true)),
10200 PushFalse => self.push(Value::Bool(false)),
10201 PushEmptyString => self.push(self.string("")),
10202 Undefined => self.push(Value::Undefined),
10203 Null => self.push(Value::Null),
10204 Object => {
10205 let proto = self.realm.object_proto.clone();
10206 self.push(Value::Object(self.new_object(Some(proto))));
10207 }
10208 PushThis => {
10209 let this = self.frame().this.clone();
10210 self.push(this);
10211 }
10212 PushConst | PushConst8 => {
10213 let value = self.constant(a as usize)?;
10214 self.push(value);
10215 }
10216 PushAtomValue => {
10217 let text = self.atom_wtf8(a as usize);
10218 self.push(self.string_wtf8(text));
10219 }
10220 Dup => {
10221 let value = self.peek(0);
10222 self.push(value);
10223 }
10224 Dup2 => {
10225 // `a b -> a b a b`
10226 let b = self.peek(0);
10227 let a = self.peek(1);
10228 self.push(a);
10229 self.push(b);
10230 }
10231 Dup3 => {
10232 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10233 // prototype and key while reading the current value through them.
10234 let c = self.peek(0);
10235 let b = self.peek(1);
10236 let a = self.peek(2);
10237 self.push(a);
10238 self.push(b);
10239 self.push(c);
10240 }
10241 Swap => {
10242 // `a b -> b a`
10243 let bottom = self.pop();
10244 let top = self.pop();
10245 self.push(bottom);
10246 self.push(top);
10247 }
10248 Perm3 => {
10249 // `a b c -> b a c`, the reference's reordering for a spread method
10250 // call: `obj func array` becomes the `func this array` that `apply`
10251 // takes.
10252 let c = self.pop();
10253 let b = self.pop();
10254 let a = self.pop();
10255 self.push(b);
10256 self.push(a);
10257 self.push(c);
10258 }
10259 Dup1 => {
10260 let value = self.peek(1);
10261 self.push(value);
10262 }
10263 Drop => {
10264 self.pop();
10265 }
10266 Nip => {
10267 // `a b -> b`
10268 let top = self.pop();
10269 self.pop();
10270 self.push(top);
10271 }
10272 Perm4 => {
10273 // `obj prop a b -> a obj prop b`, the reference's reordering for a
10274 // postfix update of a computed element: it puts the *old* value
10275 // underneath the receiver and key so `put_array_el` can consume them
10276 // and leave the old value as the expression's result.
10277 let d = self.pop();
10278 let c = self.pop();
10279 let b = self.pop();
10280 let a = self.pop();
10281 self.push(c);
10282 self.push(a);
10283 self.push(b);
10284 self.push(d);
10285 }
10286 Insert2 => {
10287 // `obj a -> a obj a`
10288 let value = self.pop();
10289 let object = self.pop();
10290 self.push(value.clone());
10291 self.push(object);
10292 self.push(value);
10293 }
10294 Insert3 => {
10295 // `obj prop a -> a obj prop a`
10296 let value = self.pop();
10297 let key = self.pop();
10298 let object = self.pop();
10299 self.push(value.clone());
10300 self.push(object);
10301 self.push(key);
10302 self.push(value);
10303 }
10304 Insert4 => {
10305 // `this obj prop a -> a this obj prop a`
10306 //
10307 // `put_super_value` consumes all four and yields nothing, so the copy
10308 // underneath is what leaves the assignment an expression value.
10309 let value = self.pop();
10310 let key = self.pop();
10311 let object = self.pop();
10312 let receiver = self.pop();
10313 self.push(value.clone());
10314 self.push(receiver);
10315 self.push(object);
10316 self.push(key);
10317 self.push(value);
10318 }
10319 Swap2 => {
10320 // `a b c d -> c d a b`
10321 let d = self.pop();
10322 let c = self.pop();
10323 let b = self.pop();
10324 let a = self.pop();
10325 self.push(c);
10326 self.push(d);
10327 self.push(a);
10328 self.push(b);
10329 }
10330 Rot3l => {
10331 // `x a b -> a b x`
10332 let b = self.pop();
10333 let a = self.pop();
10334 let x = self.pop();
10335 self.push(a);
10336 self.push(b);
10337 self.push(x);
10338 }
10339 Rot3r => {
10340 // `a b c -> c a b`
10341 let c = self.pop();
10342 let b = self.pop();
10343 let a_value = self.pop();
10344 self.push(c);
10345 self.push(a_value);
10346 self.push(b);
10347 }
10348
10349 Rest => {
10350 // `...rest` in a parameter list: the arguments from index `a` on, as a
10351 // real array. It takes nothing off the stack — the arguments are in the
10352 // frame, not on it.
10353 let frame = self.frame();
10354 let from = a as usize;
10355 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10356 let array = self.new_array(collected);
10357 self.push(Value::Object(array));
10358 }
10359
10360 // -- slots ------------------------------------------------------
10361 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
10362 let slot = self.slot_operand(op, a);
10363 let value = self.get_loc(slot);
10364 self.push(value);
10365 }
10366 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
10367 let slot = self.slot_operand(op, a);
10368 let value = self.pop();
10369 self.put_loc(slot, value);
10370 }
10371 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
10372 let slot = self.slot_operand(op, a);
10373 let value = self.pop();
10374 self.put_loc(slot, value.clone());
10375 self.push(value);
10376 }
10377 // The `_check` forms are the temporal dead zone: they throw when the
10378 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
10379 // *reads*, so only the two writes may pop — mishandling that quietly
10380 // consumes the value the caller pushed just before.
10381 GetLocCheck => {
10382 let slot = self.slot_operand(op, a);
10383 let value = self.get_loc(slot);
10384 if matches!(value, Value::Uninitialized) {
10385 return Err(self.dead_zone(slot, VarSlot::Loc));
10386 }
10387 self.push(value);
10388 }
10389 PutLocCheck | SetLocCheck => {
10390 let slot = self.slot_operand(op, a);
10391 let value = self.pop();
10392 if matches!(value, Value::Uninitialized) {
10393 return Err(self.dead_zone(slot, VarSlot::Loc));
10394 }
10395 // The initialiser goes through `put_loc`, not this, so any store that
10396 // reaches here is a later assignment — which a `const` refuses.
10397 if self.is_read_only(slot, VarSlot::Loc) {
10398 return Err(self.read_only(slot, VarSlot::Loc));
10399 }
10400 if op == SetLocCheck {
10401 self.put_loc(slot, value.clone());
10402 self.push(value);
10403 } else {
10404 self.put_loc(slot, value);
10405 }
10406 }
10407 PutLocCheckInit => {
10408 // The one store that *initialises* a lexical slot: `this` in a derived
10409 // constructor, which only exists after `super()` has run. A second
10410 // initialisation is the error the reference reports as
10411 // "'this' can be initialized only once".
10412 let slot = self.slot_operand(op, a);
10413 let value = self.pop();
10414 if !matches!(self.get_loc(slot), Value::Uninitialized) {
10415 return Err(Signal::Throw(self.make_error(
10416 "ReferenceError",
10417 "'this' can be initialized only once",
10418 )));
10419 }
10420 self.put_loc(slot, value);
10421 }
10422 CheckCtor => {
10423 // A class constructor may only run under `new`, which is what makes
10424 // `class A {}; A()` a TypeError.
10425 if matches!(self.frame().new_target, Value::Undefined) {
10426 return Err(Signal::Throw(self.make_error(
10427 "TypeError",
10428 "class constructors must be invoked with 'new'",
10429 )));
10430 }
10431 }
10432 InitCtor => {
10433 // The body a derived class gets when it declares no constructor:
10434 // forward every argument to the parent constructor, keeping `new.target`.
10435 if matches!(self.frame().new_target, Value::Undefined) {
10436 return Err(Signal::Throw(self.make_error(
10437 "TypeError",
10438 "class constructors must be invoked with 'new'",
10439 )));
10440 }
10441 let Some(callee) = self.current_callee() else {
10442 return Err(Signal::Throw(
10443 self.make_error("TypeError", "no constructor to inherit from"),
10444 ));
10445 };
10446 let parent = callee.proto().map_or(Value::Null, Value::Object);
10447 let new_target = self.frame().new_target.clone();
10448 let args = self.frame().passed().to_vec();
10449 let result = self.construct(parent, new_target, args)?;
10450 self.push(result);
10451 }
10452 SetLocUninitialized => {
10453 let slot = self.slot_operand(op, a);
10454 self.put_loc(slot, Value::Uninitialized);
10455 }
10456 CloseLoc => {
10457 // "Close" a binding: give it a *fresh* cell holding the current
10458 // value. Closures created before this point keep the old cell and the
10459 // ones created after see the new one, which is what makes every
10460 // iteration of `for (let i ...)` capture its own `i`, and what freezes
10461 // a block-scoped binding when the block ends.
10462 //
10463 // Clearing the slot instead (which this used to do) broke both: a
10464 // closure over a captured block variable read `undefined`, and a loop
10465 // terminated after one iteration.
10466 let slot = self.slot_operand(op, a);
10467 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
10468 if index >= 0 {
10469 let current = self.frame().cells[index as usize].get();
10470 let fresh = self.new_cell(current);
10471 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
10472 *cell = fresh;
10473 }
10474 }
10475 }
10476 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
10477 let slot = self.slot_operand(op, a);
10478 let value = self.get_arg(slot);
10479 self.push(value);
10480 }
10481 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
10482 let slot = self.slot_operand(op, a);
10483 let value = self.pop();
10484 self.put_arg(slot, value);
10485 }
10486 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
10487 let slot = self.slot_operand(op, a);
10488 let value = self.pop();
10489 self.put_arg(slot, value.clone());
10490 self.push(value);
10491 }
10492
10493 // -- closure variables ------------------------------------------
10494 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
10495 let slot = self.slot_operand(op, a);
10496 // A name a direct `eval` created shadows the binding the compiler chose.
10497 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
10498 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
10499 // and only a runtime lookup can know that.
10500 if let Some(cell) = self.eval_created_local(slot) {
10501 self.push(cell.get());
10502 return self.step();
10503 }
10504 let value = self.cell_value(slot)?;
10505 self.push(value);
10506 }
10507 GetVarRefCheck => {
10508 let slot = self.slot_operand(op, a);
10509 let value = self.cell_value(slot)?;
10510 if matches!(value, Value::Uninitialized) {
10511 return Err(self.dead_zone(slot, VarSlot::Closure));
10512 }
10513 self.push(value);
10514 }
10515 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
10516 let slot = self.slot_operand(op, a);
10517 let value = self.pop();
10518 if let Some(cell) = self.eval_created_local(slot) {
10519 cell.set(value);
10520 return self.step();
10521 }
10522 // Same rule as `PutLocCheck`: a checked store to a captured binding
10523 // refuses a `const` once its initialiser has run.
10524 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
10525 return Err(self.read_only(slot, VarSlot::Closure));
10526 }
10527 self.set_cell(slot, value)?;
10528 }
10529 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
10530 let slot = self.slot_operand(op, a);
10531 let value = self.pop();
10532 if let Some(cell) = self.eval_created_local(slot) {
10533 cell.set(value.clone());
10534 self.push(value);
10535 return self.step();
10536 }
10537 self.set_cell(slot, value.clone())?;
10538 self.push(value);
10539 }
10540
10541 // -- globals ----------------------------------------------------
10542 GetVar => {
10543 let value = self.get_global(a as usize)?;
10544 self.push(value);
10545 }
10546 GetVarUndef => {
10547 let value = self
10548 .get_global(a as usize)
10549 .or_else(|_| Ok(Value::Undefined))?;
10550 self.push(value);
10551 }
10552 DeleteVar => {
10553 // `delete name` for a name that is not a declared binding. A lexical
10554 // global lives in the reference table and cannot be deleted; anything
10555 // reachable only as a property of the global object is *implicit* —
10556 // `x = 1` with no declaration — and goes away if it is configurable,
10557 // which is what `delete` on an implicit global answers.
10558 let name = self.atom_text(a as usize);
10559 let global = self.realm.global.clone();
10560 let deleted = if self.realm.globals.contains_key(&name) {
10561 false
10562 } else if global.own_property(&name).is_some() {
10563 self.delete_property(&global, &name)?
10564 } else {
10565 true
10566 };
10567 self.push(Value::Bool(deleted));
10568 }
10569 PutVar => {
10570 let value = self.pop();
10571 self.put_global(a as usize, value)?;
10572 }
10573 PutVarInit => {
10574 let slot = a as usize;
10575 let value = self.pop();
10576 self.init_global(slot, value)?;
10577 }
10578
10579 // -- arithmetic -------------------------------------------------
10580 Add => self.binary_add()?,
10581 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
10582 let raw_right = self.pop();
10583 let raw_left = self.pop();
10584 // BigInt arithmetic is a separate path, and not only for the type of the
10585 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
10586 // rather than a silent conversion.
10587 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
10588 let left = self.primitive_of(raw_left)?;
10589 let right = self.primitive_of(raw_right)?;
10590 let value = self.bigint_arithmetic(op, left, right)?;
10591 self.push(value);
10592 } else {
10593 let right = self.numeric(raw_right)?;
10594 let left = self.numeric(raw_left)?;
10595 self.push(arithmetic(op, left, right)?);
10596 }
10597 }
10598 Neg => {
10599 let raw = self.pop();
10600 match raw {
10601 // A bigint negates exactly, however wide it is.
10602 Value::BigInt(big) => {
10603 let negated = big.negate();
10604 self.push(self.bigint(negated));
10605 }
10606 other => {
10607 let value = self.numeric(other)?;
10608 self.push(negate(value));
10609 }
10610 }
10611 }
10612 Plus => {
10613 let value = self.pop();
10614 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
10615 // unary plus is defined to produce a *number*, which a bigint cannot
10616 // become without loss. It used to fall through to `NaN`.
10617 if matches!(value, Value::BigInt(_)) {
10618 return Err(self.type_error("cannot convert bigint to number"));
10619 }
10620 let numeric = self.numeric_of(value)?;
10621 self.push(numeric);
10622 }
10623 Inc => {
10624 let raw = self.pop();
10625 let (_, updated) = self.advance_numeric(raw, true)?;
10626 self.push(updated);
10627 }
10628 Dec => {
10629 let raw = self.pop();
10630 let (_, updated) = self.advance_numeric(raw, false)?;
10631 self.push(updated);
10632 }
10633 PostInc | PostDec => {
10634 // `x -> x x+1`: the *new* value ends up on top, so the store the
10635 // compiler emits right after (`put_var`) writes the incremented
10636 // one, while the old value stays underneath for the expression's
10637 // own result. Getting this backwards makes `i++` a no-op, which
10638 // turns `while (i < 3)` into an infinite loop.
10639 let raw = self.pop();
10640 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
10641 self.push(old);
10642 self.push(updated);
10643 }
10644 Not => {
10645 let raw = self.pop();
10646 match raw {
10647 // `~x` on a bigint is `-x - 1`, exact at any width.
10648 Value::BigInt(big) => {
10649 let inverted = big.bitnot();
10650 self.push(self.bigint(inverted));
10651 }
10652 other => {
10653 let value = self.numeric(other)?;
10654 self.push(Value::Int(!value.to_int32()));
10655 }
10656 }
10657 }
10658 Lnot => {
10659 let value = self.pop();
10660 self.push(Value::Bool(!value.to_boolean()));
10661 }
10662
10663 // -- comparison -------------------------------------------------
10664 Lt | Lte | Gt | Gte => {
10665 let right = self.pop();
10666 let left = self.pop();
10667 let answer = self.relational(op, left, right)?;
10668 self.push(answer);
10669 }
10670 Eq | Neq => {
10671 let right = self.pop();
10672 let left = self.pop();
10673 let equal = self.abstract_equals(left, right)?;
10674 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
10675 }
10676 StrictEq => {
10677 let right = self.pop();
10678 let left = self.pop();
10679 self.push(Value::Bool(left.strict_equals(&right)));
10680 }
10681 StrictNeq => {
10682 let right = self.pop();
10683 let left = self.pop();
10684 self.push(Value::Bool(!left.strict_equals(&right)));
10685 }
10686 IsUndefined => {
10687 // `=== undefined`, which is what a destructuring default tests. It is
10688 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10689 let value = self.pop();
10690 self.push(Value::Bool(matches!(value, Value::Undefined)));
10691 }
10692 IsUndefinedOrNull => {
10693 let value = self.pop();
10694 self.push(Value::Bool(value.is_nullish()));
10695 }
10696 Typeof => {
10697 let value = self.pop();
10698 self.push(self.string(value.type_of()));
10699 }
10700 ToObject => {
10701 // A destructuring *object* pattern starts here, which is why
10702 // `var {} = null` throws. Only `undefined` and `null` are refused; a
10703 // primitive is boxed.
10704 let value = self.pop();
10705 let object = self.object_from(&value)?;
10706 self.push(Value::Object(object));
10707 }
10708 Instanceof => {
10709 let constructor = self.pop();
10710 let object = self.pop();
10711 let answer = self.instance_of(&object, &constructor)?;
10712 self.push(Value::Bool(answer));
10713 }
10714 In => {
10715 let object = self.pop();
10716 let key = self.pop();
10717 let answer = self.has_property(&key, &object)?;
10718 self.push(Value::Bool(answer));
10719 }
10720
10721 // -- control flow -----------------------------------------------
10722 Goto | Goto8 | Goto16 => {
10723 self.frame_mut().pc = a as usize;
10724 }
10725 IfTrue | IfTrue8 => {
10726 let value = self.pop();
10727 if value.to_boolean() {
10728 self.frame_mut().pc = a as usize;
10729 }
10730 }
10731 IfFalse | IfFalse8 => {
10732 let value = self.pop();
10733 if !value.to_boolean() {
10734 self.frame_mut().pc = a as usize;
10735 }
10736 }
10737 Catch => {
10738 // Pushes the handler target onto the value stack; `unwind` finds it.
10739 self.push(Value::CatchOffset(a));
10740 }
10741 Gosub => {
10742 self.push(Value::ReturnAddress(next as u32));
10743 self.frame_mut().pc = a as usize;
10744 }
10745 Ret => {
10746 let value = self.pop();
10747 match value {
10748 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
10749 _ => {
10750 return Err(Signal::Throw(
10751 self.make_error("InternalError", "invalid return address"),
10752 ));
10753 }
10754 }
10755 }
10756 NipCatch => {
10757 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
10758 // including the marker, keeping the top value.
10759 let top = self.pop();
10760 loop {
10761 match self.pop() {
10762 Value::CatchOffset(_) | Value::Undefined => break,
10763 _ => {}
10764 }
10765 if self.frame().stack.is_empty() {
10766 break;
10767 }
10768 }
10769 self.push(top);
10770 }
10771 Throw => {
10772 let value = self.pop();
10773 return Err(Signal::Throw(value));
10774 }
10775 ThrowError => {
10776 let name = self.atom_text(a as usize);
10777 let (class, message) = match b {
10778 0 => ("TypeError", format!("'{name}' is read-only")),
10779 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
10780 2 => ("ReferenceError", format!("'{name}' is not initialized")),
10781 // `delete super.x` is a syntax-level mistake the reference reports
10782 // with this wording, not a property-access failure.
10783 3 => (
10784 "ReferenceError",
10785 "unsupported reference to 'super'".to_string(),
10786 ),
10787 4 => (
10788 "TypeError",
10789 "iterator does not have a throw method".to_string(),
10790 ),
10791 5 => (
10792 "ReferenceError",
10793 "invalid assignment left-hand side".to_string(),
10794 ),
10795 _ => ("TypeError", format!("invalid operation on '{name}'")),
10796 };
10797 return Err(Signal::Throw(self.make_error(class, &message)));
10798 }
10799 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
10800 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
10801 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
10802 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
10803 Await => return Ok(Step::Suspend(SuspendKind::Await)),
10804 ReturnAsync => {
10805 // The reference's `return_async` returns `undefined` and lets the resume
10806 // machinery pick the real value off `sp[-1]`, which is how it tells a
10807 // completion from a suspension. Carrying the value explicitly says the
10808 // same thing without the implicit stack slot.
10809 let value = self.pop();
10810 return Ok(Step::Return(value));
10811 }
10812 Return => {
10813 let value = self.pop();
10814 return Ok(Step::Return(value));
10815 }
10816 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
10817
10818 // -- calls ------------------------------------------------------
10819 Call | Call0 | Call1 | Call2 | Call3 => {
10820 let argc = self.argc_operand(op, a);
10821 let args = self.pop_n(argc);
10822 let callee = self.pop();
10823 // A plain call has no receiver; the callee decides what to do with
10824 // `undefined` (a sloppy function substitutes the global object).
10825 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
10826 self.push(result);
10827 }
10828 }
10829 CallConstructor => {
10830 // `constructor this_obj args… -> object`. The duplicated
10831 // constructor is `new.target`; this milestone does not expose it,
10832 // so the extra copy is simply consumed here.
10833 let argc = a as usize;
10834 let args = self.pop_n(argc);
10835 let new_target = self.pop();
10836 let callee = self.pop();
10837 let result = self.construct(callee, new_target, args)?;
10838 self.push(result);
10839 }
10840 CallMethod => {
10841 let argc = a as usize;
10842 let args = self.pop_n(argc);
10843 let callee = self.pop();
10844 let this = self.pop();
10845 if let Some(result) = self.call_or_push(callee, this, args)? {
10846 self.push(result);
10847 }
10848 }
10849 Apply => {
10850 // `func this array -> result`, the spread-call form: the compiler
10851 // builds one array of arguments, and all that is left here is to
10852 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
10853 let array = self.pop();
10854 let this = self.pop();
10855 let callee = self.pop();
10856 let args = self.array_like_to_args(&array)?;
10857 if a & 1 != 0 {
10858 let result = self.construct(callee, this, args)?;
10859 self.push(result);
10860 } else if let Some(result) = self.call_or_push(callee, this, args)? {
10861 self.push(result);
10862 }
10863 }
10864 TailCall | TailCallMethod => {
10865 // `tail_call` is `call` whose result is returned immediately — the
10866 // reference jumps straight to `done` instead of storing the value and
10867 // running on. The callee still gets its own frame, so deep tail
10868 // recursion hits the stack limit exactly like plain recursion does;
10869 // marking this frame lets the return path unwind without needing
10870 // instructions after the call.
10871 let argc = if op == TailCallMethod {
10872 a as usize
10873 } else {
10874 self.argc_operand(op, a)
10875 };
10876 let args = self.pop_n(argc);
10877 let callee = self.pop();
10878 let this = if op == TailCallMethod {
10879 self.pop()
10880 } else {
10881 Value::Undefined
10882 };
10883 if let Value::Object(function) = &callee
10884 && let Some((code, env)) = bytecode_of(function)
10885 {
10886 // A generator or async body is not run here at all: calling it only
10887 // *creates* the generator/coroutine, so it must not inherit this
10888 // frame. Doing so made `function f(){ return g() }` push `g`'s body
10889 // onto `f`'s frame, and the first `yield`/`await` then reported
10890 // "a generator body ran as an ordinary call".
10891 if code.code.kind.is_generator() || code.code.kind.is_async() {
10892 let value = self.call_value(callee, this, args)?;
10893 return Ok(Step::Return(value));
10894 }
10895 self.frame_mut().tail = true;
10896 self.push_frame(code, env, this, args, callee)?;
10897 return Ok(Step::Continue);
10898 }
10899 // A native callee has no frame to reuse, so its value is simply
10900 // returned.
10901 let value = self.call_value(callee, this, args)?;
10902 return Ok(Step::Return(value));
10903 }
10904
10905 // -- objects ----------------------------------------------------
10906 SpecialObject => {
10907 let value = self.special_object(a)?;
10908 self.push(value);
10909 }
10910 PrivateSymbol => {
10911 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
10912 // symbol each time it is evaluated, which is why the compiler evaluates it
10913 // once (at class definition) and stores it in a class-scope binding.
10914 let name = self.atom_text(a as usize);
10915 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
10916 self.push(Value::Symbol(symbol));
10917 }
10918 GetPrivateField => {
10919 // `obj symbol -> value`. A missing private field is a TypeError, which is what
10920 // makes `#x` inaccessible on any object not built by this class.
10921 let symbol = self.pop();
10922 let object = self.pop();
10923 let value = self.read_private_field(&object, &symbol)?;
10924 self.push(value);
10925 }
10926 PutPrivateField => {
10927 // `obj value symbol ->`, and the store is a plain assignment to a property the
10928 // class already created, so there is no setter to consult.
10929 let symbol = self.pop();
10930 let value = self.pop();
10931 let object = self.pop();
10932 self.write_private_field(&object, &symbol, value)?;
10933 }
10934 DefinePrivateField => {
10935 // `obj symbol value -> obj`: a field initialiser creates the property, and
10936 // redefining one is a TypeError ("already exists").
10937 let value = self.pop();
10938 let symbol = self.pop();
10939 let object = self.pop();
10940 self.define_private_field(&object, &symbol, value)?;
10941 self.push(object);
10942 }
10943 PrivateIn => {
10944 // `obj key -> bool`: `#x in o`. The second operand decides which question is
10945 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
10946 // is a field, so this is an own-property test; a *function* is a method or
10947 // accessor, so this is a brand check.
10948 let key = self.pop();
10949 let object = self.pop();
10950 let Some(target) = object.as_object() else {
10951 return Err(Signal::Throw(
10952 self.make_error("TypeError", "invalid 'in' operand"),
10953 ));
10954 };
10955 let present = match &key {
10956 Value::Object(_) => self.check_brand(target, &key)?,
10957 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
10958 };
10959 self.push(Value::Bool(present));
10960 }
10961 AddBrand => {
10962 // `obj home ->`: create the class brand on `home` if it has none, then give
10963 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
10964 // class definition: only the prototype's copy of the symbol is wanted.
10965 let home = self.pop();
10966 let object = self.pop();
10967 self.add_brand(&object, &home)?;
10968 }
10969 CheckBrand => {
10970 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
10971 // Both stay, because the caller needs them — `nip` halves a read into its
10972 // value and `call_method` uses the pair as receiver and callee.
10973 let function = self.peek(0);
10974 let object = self.peek(1);
10975 let Some(target) = object.as_object() else {
10976 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10977 };
10978 if !self.check_brand(target, &function)? {
10979 return Err(Signal::Throw(
10980 self.make_error("TypeError", "invalid brand on object"),
10981 ));
10982 }
10983 }
10984 GetLength => {
10985 // `get_length` is the `.length` read; an array and a string answer
10986 // from their own length, anything else from the property.
10987 let target = self.pop();
10988 let value = match &target {
10989 Value::Object(object) => match object.array_length() {
10990 Some(length) => crate::object::length_value(length),
10991 None => self.read_field(&target, "length")?,
10992 },
10993 Value::String(text) => Value::Int(text.utf16_len() as i32),
10994 _ => self.read_field(&target, "length")?,
10995 };
10996 self.push(value);
10997 }
10998 GetField | GetField2 => {
10999 let object = self.pop();
11000 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11001 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11002 // just below is what lets the borrow outlive the `&mut self` the lookup
11003 // needs — one refcount bump instead of a key clone plus its drop, on the
11004 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11005 let code = self.frame().code.clone();
11006 let key = &code.atom_keys[a as usize];
11007 let value = self.read_field_cached(&object, key, next)?;
11008 if op == GetField2 {
11009 self.push(object);
11010 }
11011 self.push(value);
11012 }
11013 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11014 let key = self.pop();
11015 let object = self.pop();
11016 let key = self.propkey(&key)?;
11017 let value = self.read_field_key(&object, &key)?;
11018 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11019 self.push(object);
11020 }
11021 if op == GetArrayEl3 {
11022 // The key goes back in its *value* form, which the compiler stores
11023 // into the target of a destructuring assignment.
11024 self.push(match &key {
11025 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11026 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11027 });
11028 }
11029 self.push(value);
11030 }
11031 PutField => {
11032 let value = self.pop();
11033 let object = self.pop();
11034 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11035 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11036 // only reads. `this.value = …` is the write half of the hottest loop in
11037 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11038 let code = self.frame().code.clone();
11039 let key = &code.atom_keys[a as usize];
11040 self.write_field_key(&object, key, value)?;
11041 }
11042 PutArrayEl => {
11043 let value = self.pop();
11044 let key = self.pop();
11045 let object = self.pop();
11046 let key = self.propkey(&key)?;
11047 self.write_field_key(&object, &key, value)?;
11048 }
11049 DefineField => {
11050 let value = self.pop();
11051 let object = self.pop();
11052 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11053 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11054 // three U+FFFD — a property under a different name from the one
11055 // `o["\uD800"]` reads.
11056 let code = self.frame().code.clone();
11057 let key = code.atom_keys[a as usize].clone();
11058 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11059 // emits `set_name` — and only where `NamedEvaluation` applies, so
11060 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11061 // reaches a property definition got that case wrong, and the compiler is
11062 // the only place that can tell the two apart.
11063 if let Some(target) = object.as_object() {
11064 // Only an *array* stores into the element vector. A numeric key
11065 // on an ordinary object is an ordinary property, which is what
11066 // makes `{1: 'a'}` iterate as a key rather than disappear.
11067 let stored = target.is_array()
11068 && key.as_str().and_then(array_index).is_some_and(|index| {
11069 target.array_set(self.heap, index as usize, value.clone())
11070 });
11071 if !stored {
11072 target.define_data_key(&key, value);
11073 }
11074 }
11075 self.push(object);
11076 }
11077 DefineArrayEl => {
11078 // `obj key value -> obj key`. The *value* form of the key is what goes
11079 // back on the stack — the compiler stores it into the pattern's binding —
11080 // so the symbol is not stringified on the way through.
11081 let value = self.pop();
11082 let key_value = self.pop();
11083 let object = self.peek(0);
11084 let key = self.propkey(&key_value)?;
11085 self.write_field_key(&object, &key, value)?;
11086 self.push(key_value);
11087 }
11088 SetHomeObject => {
11089 // `obj func -> obj func`: records the object a method was defined on so
11090 // `super` inside it resolves against that object's prototype.
11091 let function = self.peek(0);
11092 let home = self.peek(1);
11093 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11094 function.set_home_object(Some(home.clone()));
11095 }
11096 }
11097 Regexp => {
11098 // `pattern flags -> regexp`. A literal compiles here rather than through the
11099 // constructor, which is both what the reference's dedicated opcode is for
11100 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11101 let flags = self.pop();
11102 let pattern = self.pop();
11103 let pattern = self.to_js_string(&pattern)?;
11104 let flags = self.to_js_string(&flags)?;
11105 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11106 self.push(Value::Object(object));
11107 }
11108 UsingDisposeInit => {
11109 // The error state a disposal accumulates into. Uninitialised means "no
11110 // failure yet"; anything else is the exception being propagated.
11111 self.push(Value::Uninitialized);
11112 }
11113 UsingCheck => {
11114 // `value -> value, method`: validate and snapshot the disposer now, so a
11115 // later change to `Symbol.dispose` cannot change what gets called, and so a
11116 // value that is not disposable fails before the body runs.
11117 let value = self.pop();
11118 let method = self.using_method_for(&value, a as u8 == 1)?;
11119 self.push(value);
11120 self.push(method);
11121 }
11122 UsingDispose => {
11123 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11124 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11125 // the pending error.
11126 let slot = self.slot_operand(op, a);
11127 let error_state = self.pop();
11128 let merged = self.using_dispose_once(slot, error_state)?;
11129 self.push(merged);
11130 }
11131 UsingDisposeMerge => {
11132 let new_error = self.pop();
11133 let error_state = self.pop();
11134 let merged = self.merge_dispose_error(new_error, error_state);
11135 self.push(merged);
11136 }
11137 UsingDisposeEnd => {
11138 // A disposal that failed replaces the block's normal completion, so the
11139 // error state becomes a real throw here rather than at the call site.
11140 let error_state = self.pop();
11141 if !matches!(error_state, Value::Uninitialized) {
11142 return Err(Signal::Throw(error_state));
11143 }
11144 }
11145 UsingDisposeAsync => {
11146 // `await using` needs a promise to await and this runtime has no
11147 // `Promise` builtin, so the disposer is called synchronously and its result
11148 // discarded. That is correct for a disposer that returns nothing and is
11149 // reported as a gap rather than silently skipped.
11150 let slot = self.slot_operand(op, a);
11151 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11152 self.push(error_state);
11153 }
11154 GetSuper => {
11155 // `obj -> obj's prototype`: the starting point of a `super` lookup.
11156 let object = self.pop();
11157 let proto = match &object {
11158 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11159 _ => Value::Null,
11160 };
11161 self.push(proto);
11162 }
11163 GetSuperValue => {
11164 // `receiver proto key -> value`, searching from `proto` but reporting to
11165 // `receiver`, which is what `super.g` must do for a getter to see `this`.
11166 //
11167 // Three values in, one out: the receiver is *consumed*, not left under the
11168 // result. Leaving it there was invisible for `super.x` in `return` or
11169 // statement position (the result is what gets popped) and corrupted the
11170 // frame everywhere else — `print(super.x)` left the class where the call
11171 // opcode looks for the receiver and called the class itself.
11172 let key = self.pop();
11173 let proto = self.pop();
11174 let receiver = self.pop();
11175 let value = self.super_read(&receiver, &proto, &key)?;
11176 self.push(value);
11177 }
11178 PutSuperValue => {
11179 // `receiver proto key value ->`: a store that starts at `proto` but
11180 // assigns to `receiver`.
11181 let value = self.pop();
11182 let key = self.pop();
11183 let proto = self.pop();
11184 let receiver = self.pop();
11185 self.super_write(&receiver, &proto, &key, value)?;
11186 }
11187 DefineClass => {
11188 // `parent ctor -> ctor proto`: the constructor becomes the class and a
11189 // fresh prototype object lands on top for the methods to go on.
11190 let name = self.atom_text(a as usize);
11191 let (ctor, proto) = self.define_class(&name, b)?;
11192 self.push(ctor);
11193 self.push(Value::Object(proto));
11194 }
11195 DefineClassComputed => {
11196 // `parent ctor key -> ctor proto key`: the computed name stays put so
11197 // `define_field`-style consumers can still read it.
11198 let key = self.pop();
11199 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11200 let (ctor, proto) = self.define_class(&name, b)?;
11201 self.push(ctor);
11202 self.push(Value::Object(proto));
11203 self.push(key);
11204 }
11205 DefineMethod => {
11206 let function = self.pop();
11207 let object = self.pop();
11208 // The exact key, like `define_field`: a quoted method key may hold an
11209 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11210 // that `o["\uD800"]` finds.
11211 let code = self.frame().code.clone();
11212 let key = code.atom_keys[a as usize].clone();
11213 // A method's `[[HomeObject]]` is the object it was defined on, which is
11214 // what `super` inside it resolves against.
11215 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11216 function.set_home_object(Some(object.clone()));
11217 }
11218 if let Some(text) = key.as_wtf8() {
11219 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11220 } else {
11221 self.set_function_name(
11222 &function,
11223 &key_with_accessor_prefix(&key.to_string(), b),
11224 );
11225 }
11226 if let Some(array) = object.as_object() {
11227 define_function_property(array, &key, function, b);
11228 }
11229 self.push(object);
11230 }
11231 DefineMethodComputed => {
11232 let function = self.pop();
11233 let key = self.pop();
11234 let object = self.pop();
11235 let key = self.propkey(&key)?;
11236 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11237 // the name: `super` inside a computed method resolves through it. Without
11238 // this, `class B extends A { [k]() { return super.m() } }` read the
11239 // home object as null and threw.
11240 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11241 function.set_home_object(Some(object.clone()));
11242 }
11243 match key.as_wtf8() {
11244 Some(text) => {
11245 let name = accessor_prefixed(text, a);
11246 self.set_function_name_wtf8(&function, &name);
11247 }
11248 None => self.set_function_name(
11249 &function,
11250 &key_with_accessor_prefix(&key.to_string(), a),
11251 ),
11252 }
11253 if let Some(array) = object.as_object() {
11254 define_function_property(array, &key, function, a);
11255 }
11256 self.push(object);
11257 }
11258 SetProto => {
11259 let proto = self.pop();
11260 let object = self.pop();
11261 if let Some(target) = object.as_object() {
11262 target.set_proto(proto.as_object().cloned());
11263 }
11264 self.push(object);
11265 }
11266 CopyDataProperties => {
11267 let exclusion = self.pop();
11268 let source = self.pop();
11269 let target = self.peek(0);
11270 self.copy_properties(&target, &source, &exclusion)?;
11271 self.push(source);
11272 self.push(exclusion);
11273 }
11274 ToPropkey => {
11275 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11276 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11277 // ordinary `"Symbol(b)"` property.
11278 let value = self.pop();
11279 let key = match self.propkey(&value)? {
11280 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11281 PropertyKey::String(text) => self.string_wtf8(text),
11282 };
11283 self.push(key);
11284 }
11285 SetName => {
11286 let function = self.peek(0);
11287 let name = self.atom_wtf8(a as usize);
11288 self.set_function_name_wtf8(&function, &name);
11289 }
11290 SetNameComputed => {
11291 let key = self.peek(1);
11292 let function = self.peek(0);
11293 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11294 self.set_function_name(&function, &name);
11295 }
11296
11297 // -- arrays -----------------------------------------------------
11298 ArrayFrom => {
11299 let count = a as usize;
11300 let elements = self.pop_n(count);
11301 let array = self.new_array(elements);
11302 self.push(Value::Object(array));
11303 }
11304 Append => {
11305 // `array index iterable -> array new_index`
11306 let iterable = self.pop();
11307 self.pop();
11308 let array = self.peek(0);
11309 let added = self.append_enumerate(&array, &iterable)?;
11310 self.push(Value::Int(added));
11311 }
11312
11313 // -- iteration --------------------------------------------------
11314 ForInStart => {
11315 let value = self.pop();
11316 let record = self.for_in_record(&value)?;
11317 self.push(Value::Object(record));
11318 }
11319 ForInNext => {
11320 // `record -> record key done`. The flag is *done*, not "found":
11321 // the compiler tests it with `if_false` to jump back into the body,
11322 // so reporting `true` while keys remain would end the loop at once.
11323 let record = self.peek(0);
11324 match self.for_in_advance(&record)? {
11325 Some(key) => {
11326 let text = self.string(key);
11327 self.push(text);
11328 self.push(Value::Bool(false));
11329 }
11330 None => {
11331 self.push(Value::Undefined);
11332 self.push(Value::Bool(true));
11333 }
11334 }
11335 }
11336 ForOfStart => {
11337 let value = self.pop();
11338 let iterator = self.get_iterator(&value)?;
11339 self.push(iterator.object);
11340 self.push(iterator.next);
11341 self.push(Value::CatchOffset(0));
11342 }
11343 ForOfNext => {
11344 // `iter next catch_offset -> iter next catch_offset value done`.
11345 //
11346 // The operand is how many values sit *above* the iterator triple: a
11347 // destructuring rest element keeps its target array and running index
11348 // there while draining the iterator, so the triple is not at the top.
11349 let extra = a as usize;
11350 let iterator_slot = 2 + extra;
11351 // An exhausted iterator is replaced by `undefined` (see below), so a
11352 // second step must not call `next` again — `Array.from` and a
11353 // destructuring pattern both keep stepping past the end.
11354 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
11355 (Value::Undefined, true)
11356 } else {
11357 let iterator = Iterator {
11358 object: self.peek(iterator_slot),
11359 next: self.peek(1 + extra),
11360 };
11361 self.iterator_step(&iterator)?
11362 };
11363 if done {
11364 // The result's `value` is meaningless once the iterator is done:
11365 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
11366 // rather than binding the generator's return value.
11367 let top = self.frame().stack.len() - 1 - iterator_slot;
11368 self.frame_mut().stack[top] = Value::Undefined;
11369 self.push(Value::Undefined);
11370 self.push(Value::Bool(true));
11371 } else {
11372 self.push(value);
11373 self.push(Value::Bool(false));
11374 }
11375 }
11376 IteratorNext => {
11377 // `iter next catch val -> iter next catch val'`: replace the argument with
11378 // the result of `next(val)`. The triple below stays put, which is why the
11379 // three instructions of the `yield*` loop all address the stack the same way.
11380 let value = self.pop();
11381 let object = self.peek(2);
11382 let next = self.peek(1);
11383 let result = self.call_value(next, object, vec![value])?;
11384 self.push(result);
11385 }
11386 IteratorCall => {
11387 // `iter next catch val -> iter next catch val' flag`.
11388 //
11389 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
11390 // The flag is `true` when the method was missing, which is how the
11391 // caller learns that the inner iterator cannot take part in the
11392 // unwinding.
11393 let value = self.pop();
11394 let object = self.peek(2);
11395 let key = if a & 1 != 0 { "throw" } else { "return" };
11396 let method = self.read_field(&object, key)?;
11397 if matches!(method, Value::Undefined | Value::Null) {
11398 self.push(value);
11399 self.push(Value::Bool(true));
11400 } else {
11401 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
11402 let result = self.call_value(method, object, argument)?;
11403 self.push(result);
11404 self.push(Value::Bool(false));
11405 }
11406 }
11407 IteratorCheckObject => {
11408 if !matches!(self.peek(0), Value::Object(_)) {
11409 return Err(Signal::Throw(
11410 self.make_error("TypeError", "iterator must return an object"),
11411 ));
11412 }
11413 }
11414 IteratorClose => {
11415 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
11416 // calling the iterator's `return` so it can release whatever it holds.
11417 //
11418 // The catch offset goes first, so an exception from `return` is not caught
11419 // by the loop being abandoned. This used to pop the three operands and call
11420 // nothing at all, which made `break` out of a `for of` invisible to an
11421 // iterator with a `return` method.
11422 self.pop();
11423 self.pop();
11424 let iterator = self.pop();
11425 if !matches!(iterator, Value::Undefined) {
11426 let method = self.read_field(&iterator, "return")?;
11427 if !matches!(method, Value::Undefined | Value::Null) {
11428 let result = self.call_value(method, iterator.clone(), Vec::new())?;
11429 // §7.4.6: a `return` that answers a non-object is a TypeError.
11430 if !matches!(result, Value::Object(_)) {
11431 return Err(Signal::Throw(
11432 self.make_error("TypeError", "iterator must return an object"),
11433 ));
11434 }
11435 }
11436 }
11437 }
11438 Import => {
11439 // `import(specifier)`: the options slot is on top and is not read yet.
11440 let _options = self.pop();
11441 let specifier = self.pop();
11442 let promise = self.dynamic_import(specifier)?;
11443 self.push(promise);
11444 }
11445 ForAwaitOfStart => {
11446 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
11447 // `Symbol.iterator` fallback.
11448 let value = self.pop();
11449 let iterator = self.get_async_iterator(&value)?;
11450 self.push(iterator.object);
11451 self.push(iterator.next);
11452 self.push(Value::CatchOffset(0));
11453 }
11454 ForAwaitOfNext => {
11455 // `for await` steps the iterator and leaves the *result* wrapped in a
11456 // promise, so the `await` the compiler emits right after this can suspend
11457 // on it. Unwrapping happens in `iterator_get_value_done`.
11458 let extra = a as usize;
11459 let iterator_slot = 2 + extra;
11460 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
11461 Value::Undefined
11462 } else {
11463 let iterator = Iterator {
11464 object: self.peek(iterator_slot),
11465 next: self.peek(1 + extra),
11466 };
11467 let next = iterator.next.clone();
11468 self.call_value(next, iterator.object, Vec::new())?
11469 };
11470 let promise = self.promise_resolve_value(result)?;
11471 self.push(promise);
11472 }
11473 IteratorGetValueDone => {
11474 // `result -> value done`. A missing result object means the iterator was
11475 // already exhausted, which the loop treats as `done`.
11476 let result = self.pop();
11477 let done = match &result {
11478 Value::Object(object) => self
11479 .get_property(object, "done")?
11480 .is_some_and(|value| value.to_boolean()),
11481 _ => true,
11482 };
11483 if done {
11484 // Clear the iterator object so the `iterator_close` the loop emits on
11485 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
11486 // on normal completion, and this is where a normal completion is
11487 // recognised — the same trick `for_of_next` uses, which also replaces
11488 // the slot with `undefined`.
11489 //
11490 // The layout is fixed because only `for await` emits this opcode:
11491 // `iter next catch [result]`, so the iterator is three below the top.
11492 let depth = self.frame().stack.len();
11493 if depth >= 3 {
11494 self.frame_mut().stack[depth - 3] = Value::Undefined;
11495 }
11496 self.push(Value::Undefined);
11497 self.push(Value::Bool(true));
11498 } else {
11499 let Value::Object(object) = &result else {
11500 self.push(Value::Undefined);
11501 self.push(Value::Bool(true));
11502 return Ok(Step::Continue);
11503 };
11504 let value = self
11505 .get_property(object, "value")?
11506 .unwrap_or(Value::Undefined);
11507 self.push(value);
11508 self.push(Value::Bool(false));
11509 }
11510 }
11511
11512 Delete => {
11513 // `delete obj[key]`, where the key was just pushed. Deleting an array
11514 // index leaves a *hole* rather than closing the gap, and a
11515 // non-configurable property answers `false` and stays.
11516 let key = self.pop();
11517 let target = self.pop();
11518 let key = self.propkey(&key)?;
11519 let text_label = key.as_str().unwrap_or("").to_string();
11520 let deleted = match &target {
11521 Value::Object(object) => {
11522 let object = object.clone();
11523 self.delete_property_key(&object, &key)?
11524 }
11525 // A string's `length` and its index properties are
11526 // non-configurable, so deleting one answers `false`.
11527 Value::String(text) => {
11528 !(text_label == "length"
11529 || array_index(&text_label)
11530 .is_some_and(|index| (index as usize) < text.utf16_len()))
11531 }
11532 // "delete null.a" is a TypeError, not a no-op: the operator needs an
11533 // object to delete from, and only a *boxable* primitive has one.
11534 Value::Undefined | Value::Null => {
11535 return Err(Signal::Throw(
11536 self.make_error("TypeError", "cannot convert to object"),
11537 ));
11538 }
11539 // Any other primitive has no own properties; deleting nothing
11540 // succeeds.
11541 _ => true,
11542 };
11543 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
11544 // `TypeError` rather than a `false` result. Sloppy mode silently reports
11545 // the refusal, which is why the same statement throws here but not there.
11546 if !deleted && self.current_strict() {
11547 return Err(Signal::Throw(
11548 self.make_error("TypeError", "cannot delete property"),
11549 ));
11550 }
11551 self.push(Value::Bool(deleted));
11552 }
11553
11554 // -- exceptions and bookkeeping ---------------------------------
11555 Fclosure | Fclosure8 => {
11556 let value = self.closure(a as usize)?;
11557 self.push(value);
11558 }
11559
11560 other => {
11561 let name = other.info().name;
11562 return Err(Signal::Throw(self.make_error(
11563 "InternalError",
11564 &format!("{name} is not implemented yet"),
11565 )));
11566 }
11567 }
11568 Ok(Step::Continue)
11569 }
11570
11571 // -- operand helpers ----------------------------------------------------
11572
11573 /// The slot index an operand names, taking short forms into account.
11574 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
11575 use Opcode::*;
11576 match op {
11577 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
11578 | SetVarRef0 => 0,
11579 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
11580 | SetVarRef1 => 1,
11581 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
11582 | SetVarRef2 => 2,
11583 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
11584 | SetVarRef3 => 3,
11585 _ => a as usize,
11586 }
11587 }
11588
11589 /// The argument count of a call, taking `call0`…`call3` into account.
11590 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
11591 use Opcode::*;
11592 match op {
11593 Call0 => 0,
11594 Call1 => 1,
11595 Call2 => 2,
11596 Call3 => 3,
11597 _ => a as usize,
11598 }
11599 }
11600
11601 /// The atom's name as a property key.
11602 ///
11603 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
11604 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
11605 /// `String::clone` was a heap allocation and a copy — per property access.
11606 /// The atom at `index`, as a property key.
11607 ///
11608 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
11609 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
11610 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
11611 /// 5.3% of `property:monomorphic`.
11612 /// The atom's text, exactly — including an unpaired surrogate.
11613 ///
11614 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
11615 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
11616 /// `atom_text` below is for the other kind of use, where the atom is a key in the
11617 /// engine's own tables.
11618 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
11619 self.frame()
11620 .code
11621 .code
11622 .atoms
11623 .get(index)
11624 .map(|atom| match atom {
11625 Atom::Str(text) => text.clone(),
11626 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
11627 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
11628 Atom::Null => crate::value::Wtf8::new(String::new()),
11629 })
11630 .unwrap_or_default()
11631 }
11632
11633 fn atom_text(&self, index: usize) -> String {
11634 self.frame()
11635 .code
11636 .code
11637 .atoms
11638 .get(index)
11639 .map(|atom| match atom {
11640 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
11641 // compare it to an identifier, and a surrogate-bearing name is reachable
11642 // through `atom_wtf8` where it matters.
11643 Atom::Str(text) => text.to_string_lossy().into_owned(),
11644 Atom::Index(value) => value.to_string(),
11645 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
11646 // `throw_error`, `delete super.x`) never read it.
11647 Atom::Null => String::new(),
11648 })
11649 .unwrap_or_default()
11650 }
11651
11652 fn constant(&mut self, index: usize) -> JsResult<Value> {
11653 let constant = self.frame().code.code.cpool.get(index).cloned();
11654 Ok(match &constant {
11655 Some(Constant::Number(number)) => Value::Float(*number),
11656 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
11657 Some(Constant::BigInt { digits, radix }) => {
11658 match crate::bigint::BigInt::from_radix(digits, *radix) {
11659 Some(big) => self.bigint(big),
11660 // A literal the parser accepted is always parseable; a failure here
11661 // would be a compiler bug, so it reads as an `InternalError`.
11662 None => {
11663 return Err(Signal::Throw(
11664 self.make_error("InternalError", "unparseable bigint literal"),
11665 ));
11666 }
11667 }
11668 }
11669 Some(Constant::Function(_)) => {
11670 return Err(Signal::Throw(
11671 self.make_error("InternalError", "a bare function constant"),
11672 ));
11673 }
11674 // A tagged template's call site: a frozen array of the cooked chunks with a
11675 // frozen `raw` array beside it, which is what `String.raw` reads back.
11676 Some(Constant::Template { cooked, raw }) => {
11677 let cooked_values: Vec<Value> = cooked
11678 .iter()
11679 .map(|chunk| match chunk {
11680 Some(text) => self.string_wtf8(text.clone()),
11681 None => Value::Undefined,
11682 })
11683 .collect();
11684 let raw_values: Vec<Value> =
11685 raw.iter().map(|text| self.string(text.clone())).collect();
11686 let raw_array = self.new_array(raw_values);
11687 raw_array.set_extensible(false);
11688 let template = self.new_array(cooked_values);
11689 template.define(
11690 "raw",
11691 Property::with_attributes(Value::Object(raw_array), false, false),
11692 );
11693 template.set_extensible(false);
11694 Value::Object(template)
11695 }
11696 _ => Value::Undefined,
11697 })
11698 }
11699
11700 /// The reference cell a closure-variable slot names.
11701 ///
11702 /// Two kinds of binding share this addressing: a genuine closure variable
11703 /// (captured from an enclosing function) lives in this frame's environment,
11704 /// while a *declared global* lives in the realm so that a script, a function
11705 /// declaration and their uses all see one binding. A plain `Global` — an
11706 /// undeclared name that may be satisfied by the global object — has no cell at
11707 /// all, which is how `typeof x` still works for a name that does not exist.
11708 /// The reference cell a closure-variable slot names.
11709 ///
11710 /// The environment is resolved once, when the closure is built, and this is
11711 /// just the lookup afterwards. A *declared global* is in there too, pointing at
11712 /// the realm's cell, so a script, a hoisted function declaration and their uses
11713 /// all share one binding. A plain `Global` — a name the script never declared —
11714 /// is read and written through `get_var`/`put_var` by name instead, which is
11715 /// what lets the global object satisfy it.
11716 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
11717 self.frame().env.cells.get(slot).cloned()
11718 }
11719
11720 /// Whether `slot` refers to a global binding through the reference table.
11721 ///
11722 /// A global's cell in the closure environment only exists so the slot has
11723 /// something to point at; the binding itself lives on the global object (a `var`)
11724 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
11725 /// be routed, not performed on the placeholder.
11726 fn is_global_slot(&self, slot: usize) -> bool {
11727 self.frame()
11728 .code
11729 .code
11730 .closure_vars
11731 .get(slot)
11732 .is_some_and(|c| {
11733 // A module's declarations and imports are *not* globals: their cells are
11734 // the module environment's, filled by the host, so the placeholder routing
11735 // must not apply to them.
11736 matches!(
11737 c.closure_type,
11738 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
11739 )
11740 })
11741 }
11742
11743 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
11744 if self.is_global_slot(slot) {
11745 return self.get_global(slot);
11746 }
11747 Ok(self
11748 .var_ref_cell(slot)
11749 .map(|cell| cell.get())
11750 .unwrap_or(Value::Undefined))
11751 }
11752
11753 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
11754 // A function declaration is hoisted by storing into a global reference before
11755 // the body runs, so this path is also what puts it on the global object.
11756 if self.is_global_slot(slot) {
11757 return self.put_global(slot, value);
11758 }
11759 if let Some(cell) = self.var_ref_cell(slot) {
11760 cell.set(value);
11761 }
11762 Ok(())
11763 }
11764
11765 // -- closures -----------------------------------------------------------
11766
11767 /// Build the closure for the function constant `index`.
11768 ///
11769 /// Every entry in the child's closure table names where its binding lives in
11770 /// *this* frame: a local or argument slot that was marked captured, or a cell
11771 /// this frame is itself holding. That is how a variable three functions deep
11772 /// stays one binding.
11773 fn closure(&mut self, index: usize) -> JsResult<Value> {
11774 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
11775 else {
11776 return Err(Signal::Throw(
11777 self.make_error("InternalError", "fclosure of a non-function"),
11778 ));
11779 };
11780 let mut cells = Vec::with_capacity(function.closure_vars.len());
11781 for closure_var in &function.closure_vars {
11782 let cell = match closure_var.closure_type {
11783 ClosureType::Arg => {
11784 let slot = closure_var.var_idx as usize;
11785 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
11786 }
11787 ClosureType::Local => {
11788 let slot = closure_var.var_idx as usize;
11789 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
11790 }
11791 ClosureType::Ref | ClosureType::GlobalRef => {
11792 // A `Ref` names a cell in this frame's own closure table; a
11793 // `GlobalRef` also starts there, then resolves by name below.
11794 let slot = closure_var.var_idx as usize;
11795 if let Some(cell) = self.frame().env.cells.get(slot) {
11796 cells.push(cell.clone());
11797 continue;
11798 }
11799 -1
11800 }
11801 _ => -1,
11802 };
11803 if cell >= 0 {
11804 let cell = self.frame().cells[cell as usize].clone();
11805 cells.push(cell);
11806 continue;
11807 }
11808 // A global: the cell is created on demand and shared through the realm,
11809 // so every function sees one binding.
11810 let name = closure_var.name.clone();
11811 let cell = match self.realm.globals.get(&name) {
11812 Some(cell) => cell.clone(),
11813 None => {
11814 let cell = self.new_cell(Value::Undefined);
11815 self.realm.globals.insert(name.clone(), cell.clone());
11816 cell
11817 }
11818 };
11819 cells.push(cell);
11820 }
11821 let name = function.name.clone();
11822 // `.length` is the arity before any default or rest parameter, not the number
11823 // of slots a pattern parameter needs.
11824 let length = function.defined_args;
11825 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
11826 // function and an arrow function do not. A *method* also does not, but that is not
11827 // known here — the method is marked when the `[[HomeObject]]` is attached (see
11828 // `set_home_object`), which is the moment it becomes a method.
11829 let function_kind = function.kind;
11830 let constructible =
11831 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
11832 let code = Gc::new(self.heap, CompiledCode::new(*function));
11833 // A closure built inside an `eval` inherits the eval's view of the enclosing
11834 // bindings, so it can still read them once the eval has returned.
11835 let eval_scope = self
11836 .active_eval_scope
11837 .clone()
11838 .or_else(|| self.frame().env.eval_scope.clone());
11839 // A closure sees the variables a direct `eval` declared in the frame it was
11840 // created in — the ones declared before *and after* it, so the same object is
11841 // shared; only the phase bounds which of them are visible.
11842 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
11843 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
11844 let env = Gc::new(
11845 self.heap,
11846 ClosureEnv {
11847 cells,
11848 eval_scope,
11849 local_vars,
11850 local_phase,
11851 },
11852 );
11853 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
11854 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
11855 // the only thing that carries `Symbol.toStringTag`, so without it
11856 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
11857 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
11858 let proto = match function_kind {
11859 js_compile::bytecode::FunctionKind::AsyncGenerator => self
11860 .realm
11861 .async_generator_function_proto
11862 .clone()
11863 .or_else(|| self.realm.function_proto.clone().into()),
11864 js_compile::bytecode::FunctionKind::Generator => self
11865 .realm
11866 .generator_function_proto
11867 .clone()
11868 .or_else(|| self.realm.function_proto.clone().into()),
11869 js_compile::bytecode::FunctionKind::Async => self
11870 .realm
11871 .async_function_proto
11872 .clone()
11873 .or_else(|| self.realm.function_proto.clone().into()),
11874 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
11875 };
11876 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
11877 object.set_constructible(constructible);
11878 object.define(
11879 "length",
11880 Property::name_or_length(Value::Int(length as i32)),
11881 );
11882 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
11883 // that checks the own-property descriptor fails if the property is missing.
11884 object.define("name", Property::name_or_length(self.string(name)));
11885 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
11886 // when `[[Construct]]` is created, so an async function and an arrow function have
11887 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
11888 // function) an own `prototype` property, which `builtin.js` checks for absence.
11889 //
11890 // A **generator** function is the exception that is not constructible: it still
11891 // gets a `prototype` field, because that object is what a generator *instance*
11892 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
11893 // made `function* g(){}; g.prototype` `undefined` and every generator share
11894 // `%GeneratorPrototype%` as its direct prototype.
11895 if constructible {
11896 self.install_function_prototype(&object);
11897 } else if matches!(
11898 function_kind,
11899 js_compile::bytecode::FunctionKind::Generator
11900 | js_compile::bytecode::FunctionKind::AsyncGenerator
11901 ) {
11902 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
11903 self.realm.generator_proto.clone()
11904 } else {
11905 self.realm
11906 .async_generator_proto
11907 .clone()
11908 .unwrap_or_else(|| self.realm.generator_proto.clone())
11909 };
11910 self.install_generator_prototype(&object, parent);
11911 }
11912 Ok(Value::Object(object))
11913 }
11914
11915 // -- conversions used by the operators ----------------------------------
11916
11917 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
11918 // `+x` is `ToNumber`, which for a string parses it and for an object runs
11919 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
11920 // string, which then behaves differently in every later comparison.
11921 match value {
11922 Value::Int(_) | Value::Float(_) => Ok(value),
11923 other => Ok(Value::Float(self.to_js_number(&other)?)),
11924 }
11925 }
11926
11927 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
11928 ///
11929 /// Returns the *converted* old value and the new one, because the two callers need
11930 /// different halves: `++x` yields the new value, while `x++` yields the old one and
11931 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
11932 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
11933 /// boolean.
11934 ///
11935 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
11936 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
11937 /// a bigint algorithm then ran exactly once.
11938 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
11939 if let Value::BigInt(big) = &value {
11940 let one = crate::bigint::BigInt::from_i64(1);
11941 let next = if up { big.add(&one) } else { big.sub(&one) };
11942 return Ok((value, self.bigint(next)));
11943 }
11944 let old = self.numeric(value)?;
11945 let new = if up {
11946 increment(old.clone())
11947 } else {
11948 decrement(old.clone())
11949 };
11950 Ok((old, new))
11951 }
11952
11953 fn numeric(&mut self, value: Value) -> JsResult<Value> {
11954 // `ToNumber` on an object runs `ToPrimitive` first, which is how
11955 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
11956 // heard at all. Reading the object's own tag instead (`other.to_number()`)
11957 // turned the whole operand into `NaN` and swallowed the exception.
11958 match value {
11959 Value::Int(_) | Value::Float(_) => Ok(value),
11960 other => Ok(Value::Float(self.to_js_number(&other)?)),
11961 }
11962 }
11963
11964 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
11965 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
11966 match value {
11967 Value::BigInt(big) => Ok((**big).clone()),
11968 // The reference words this the same way for every operator, so a failing
11969 // script reads identically; the operator itself adds nothing a caller can use.
11970 _ => Err(Signal::Throw(
11971 self.make_error("TypeError", "cannot convert bigint to number"),
11972 )),
11973 }
11974 }
11975
11976 /// Arithmetic where at least one operand is a `BigInt`.
11977 ///
11978 /// The two numeric types never mix, so a bigint paired with anything else is an error
11979 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
11980 /// that the relational operators handle it separately.
11981 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11982 use Opcode::*;
11983 let a = self.bigint_operand(&left)?;
11984 let b = self.bigint_operand(&right)?;
11985 let result = match op {
11986 Add => a.add(&b),
11987 Sub => a.sub(&b),
11988 Mul => a.mul(&b),
11989 Div | Mod => {
11990 let Some((quotient, remainder)) = a.div_rem(&b) else {
11991 return Err(Signal::Throw(
11992 self.make_error("RangeError", "division by zero"),
11993 ));
11994 };
11995 if op == Div { quotient } else { remainder }
11996 }
11997 Pow => {
11998 let Some(value) = a.pow(&b) else {
11999 return Err(Signal::Throw(self.make_error(
12000 "RangeError",
12001 "BigInt exponent must be non-negative and not absurdly large",
12002 )));
12003 };
12004 value
12005 }
12006 And => a.bitand(&b),
12007 Or => a.bitor(&b),
12008 Xor => a.bitxor(&b),
12009 Shl | Sar => {
12010 // A shift count is a `BigInt` here, and both directions are exact; a
12011 // negative count would be the other direction, which the spec forbids.
12012 let Some(count) = b.to_i64() else {
12013 return Err(Signal::Throw(
12014 self.make_error("RangeError", "BigInt shift count is too large"),
12015 ));
12016 };
12017 if count < 0 {
12018 return Err(Signal::Throw(self.make_error(
12019 "RangeError",
12020 "BigInt shift count must be non-negative",
12021 )));
12022 }
12023 if op == Shl {
12024 a.shl(count as u64)
12025 } else {
12026 a.shr(count as u64)
12027 }
12028 }
12029 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12030 _ => {
12031 return Err(Signal::Throw(self.make_error(
12032 "TypeError",
12033 "BigInts have no unsigned right shift, use >> instead",
12034 )));
12035 }
12036 };
12037 Ok(self.bigint(result))
12038 }
12039
12040 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12041 ///
12042 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12043 /// is on the mathematical values, and nothing is rounded first.
12044 /// `<`, `<=`, `>`, `>=`.
12045 ///
12046 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12047 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12048 /// It is a `?`-returning function for exactly that reason: an object operand can run
12049 /// script, and script can throw. The old version compared `to_number` of the raw
12050 /// values, which answered `false` for every object instead of calling `valueOf` —
12051 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12052 /// never ran.
12053 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12054 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12055 // call, nothing that can throw.
12056 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12057 let ordering = Some(left.cmp(right));
12058 return Ok(ordering_answer(op, ordering));
12059 }
12060 // Anything that can run script has to be converted first, in this order.
12061 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12062 {
12063 (
12064 self.to_primitive(left, Hint::Number)?,
12065 self.to_primitive(right, Hint::Number)?,
12066 )
12067 } else {
12068 (left, right)
12069 };
12070 let ordering = match (&left, &right) {
12071 // The loop condition `i < n` is integer against integer, and it runs once
12072 // per iteration of every loop in every program. Without this arm it took the
12073 // `to_number` path twice, which is a `match` plus a conversion each.
12074 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12075 (Value::String(a), Value::String(b)) => {
12076 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12077 }
12078 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12079 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12080 // is true even though `2.5` has no bigint form.
12081 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12082 let b = other.to_number();
12083 if b.is_nan() {
12084 None
12085 } else {
12086 compare_bigint_and_f64(a, b)
12087 }
12088 }
12089 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12090 let a = other.to_number();
12091 if a.is_nan() {
12092 None
12093 } else {
12094 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12095 }
12096 }
12097 _ => left.to_number().partial_cmp(&right.to_number()),
12098 };
12099 Ok(ordering_answer(op, ordering))
12100 }
12101
12102 fn binary_add(&mut self) -> JsResult<()> {
12103 let right = self.pop();
12104 let left = self.pop();
12105 // Two integers add without any of the machinery below: no `ToPrimitive` (an
12106 // `Int` is already primitive), no string check, no bigint check, no allocation.
12107 // `x += 1` in a loop is the single most common instruction sequence in real
12108 // script, and it used to walk every one of those checks before reaching the
12109 // same `checked_add`.
12110 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12111 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12112 return Ok(());
12113 }
12114 let left = self.primitive_of(left)?;
12115 let right = self.primitive_of(right)?;
12116 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12117 // that check comes before the bigint one: `"" + 1n` is a string, not a
12118 // mixed-type error.
12119 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12120 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12121 // `TypeError`, the one place a symbol and a string do not mix.
12122 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12123 // between a copy and a rope from their lengths, and a rope is what turns
12124 // `text += "abc"` in a loop from quadratic into linear.
12125 if let (Value::String(left), Value::String(right)) = (&left, &right) {
12126 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12127 // reports as `InternalError: string too long`.
12128 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12129 return Err(Signal::Throw(
12130 self.make_error("InternalError", "string too long"),
12131 ));
12132 };
12133 self.push(Value::String(Gc::new(self.heap, joined)));
12134 return Ok(());
12135 }
12136 // At least one operand was not a string, so `ToString` it. This rejects a
12137 // symbol, which is the one place a symbol and a string do not mix.
12138 let left = self.checked_to_wtf8(&left)?;
12139 let right = self.checked_to_wtf8(&right)?;
12140 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12141 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12142 let text = left.concat(&right);
12143 self.push(self.string_wtf8(text));
12144 return Ok(());
12145 }
12146 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12147 // not a conversion.
12148 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12149 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12150 self.push(value);
12151 return Ok(());
12152 }
12153 let left = self.numeric(left)?;
12154 let right = self.numeric(right)?;
12155 self.push(add_numbers(left, right));
12156 Ok(())
12157 }
12158
12159 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12160 self.to_primitive(value, Hint::Default)
12161 }
12162
12163 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12164 ///
12165 /// The order depends on the hint: the "number" order tries `valueOf` first and
12166 /// `toString` second, the "string" order the other way round, and the default
12167 /// hint uses the number order. A result that is still an object is a `TypeError`,
12168 /// because no built-in `valueOf`/`toString` returns one.
12169 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12170 let Value::Object(object) = &value else {
12171 return Ok(value);
12172 };
12173 // A Date overrides the default hint to mean "string", which is what
12174 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12175 // this, `"" + new Date()` would print the milliseconds, not the date.
12176 let hint = if hint == Hint::Default && is_date_object(self, object) {
12177 Hint::String
12178 } else {
12179 hint
12180 };
12181 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12182 // handed the hint as a string. This is the hook a Date uses for its default hint
12183 // and a script uses to take over conversion entirely.
12184 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12185 // `GetMethod`, not "is it a callable object": the property has to be read and then
12186 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12187 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12188 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12189 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12190 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12191 // callable.
12192 match self.get_property_key(object, &key)? {
12193 None | Some(Value::Undefined) | Some(Value::Null) => {}
12194 Some(Value::Object(function)) if function.is_callable() => {
12195 let hint = match hint {
12196 Hint::String => "string",
12197 Hint::Number => "number",
12198 Hint::Default => "default",
12199 };
12200 let hint = self.string(hint);
12201 let result = self.call_value(
12202 Value::Object(function),
12203 Value::Object(object.clone()),
12204 vec![hint],
12205 )?;
12206 if !matches!(result, Value::Object(_)) {
12207 return Ok(result);
12208 }
12209 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12210 }
12211 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12212 }
12213 let order: [&str; 2] = match hint {
12214 Hint::String => ["toString", "valueOf"],
12215 Hint::Number | Hint::Default => ["valueOf", "toString"],
12216 };
12217 let receiver = object.clone();
12218 for method in order {
12219 if let Some(function) = self.get_property(&receiver, method)?
12220 && matches!(&function, Value::Object(object) if object.is_callable())
12221 {
12222 let result =
12223 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12224 if !matches!(result, Value::Object(_)) {
12225 return Ok(result);
12226 }
12227 }
12228 }
12229 Err(self.type_error("cannot convert object to primitive value"))
12230 }
12231
12232 /// `ToString` with the object case going through `ToPrimitive`.
12233 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12234 if matches!(value, Value::Object(_)) {
12235 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12236 return Ok(primitive.to_js_string());
12237 }
12238 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12239 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12240 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12241 // check here broke `String(Symbol())` and 45 cases that print a symbol.
12242 Ok(value.to_js_string())
12243 }
12244
12245 /// `ToString(value)`, with §7.1.19's symbol refusal.
12246 ///
12247 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12248 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12249 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12250 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12251 if matches!(value, Value::Symbol(_)) {
12252 return Err(self.type_error("cannot convert a Symbol to a string"));
12253 }
12254 if matches!(value, Value::Object(_)) {
12255 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12256 if matches!(primitive, Value::Symbol(_)) {
12257 return Err(self.type_error("cannot convert a Symbol to a string"));
12258 }
12259 return Ok(primitive.to_js_string());
12260 }
12261 Ok(value.to_js_string())
12262 }
12263
12264 /// `ToString` that keeps the string's code units instead of flattening them.
12265 ///
12266 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12267 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12268 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12269 if matches!(value, Value::Symbol(_)) {
12270 return Err(Signal::Throw(
12271 self.make_error("TypeError", "cannot convert symbol to string"),
12272 ));
12273 }
12274 // An object runs `ToPrimitive` first, which may itself produce a symbol.
12275 let value = self.to_primitive(value.clone(), Hint::String)?;
12276 match value {
12277 Value::Symbol(_) => Err(Signal::Throw(
12278 self.make_error("TypeError", "cannot convert symbol to string"),
12279 )),
12280 Value::String(text) => Ok(text.wtf8().clone()),
12281 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12282 }
12283 }
12284
12285 /// `ToNumber` with the object case going through `ToPrimitive`.
12286 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12287 let value = if matches!(value, Value::Object(_)) {
12288 self.to_primitive(value.clone(), Hint::Number)?
12289 } else {
12290 value.clone()
12291 };
12292 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12293 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12294 // `NaN` to stay total, and the operators check for the bigint themselves — but
12295 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12296 // refuse, and answering `NaN` made them silently wrong instead.
12297 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12298 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12299 match value {
12300 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12301 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12302 other => Ok(other.to_number()),
12303 }
12304 }
12305
12306 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12307 /// [`ElementType::write`].
12308 ///
12309 /// This is separated from the write because both conversions are observable script —
12310 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12311 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12312 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12313 /// setters, and a plain `a[i] = v`.
12314 pub(crate) fn element_value(
12315 &mut self,
12316 element: crate::builtins::typedarray::ElementType,
12317 value: Value,
12318 ) -> JsResult<Value> {
12319 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12320 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12321 let primitive = match &value {
12322 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12323 _ => value,
12324 };
12325 if element.is_bigint() {
12326 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12327 Ok(Value::BigInt(Gc::new(self.heap, big)))
12328 } else {
12329 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12330 Ok(Value::Float(self.to_js_number(&primitive)?))
12331 }
12332 }
12333
12334 /// `ToPropertyKey`: what a computed member access uses as its key.
12335 ///
12336 /// A symbol is returned as itself, never stringified — that is what keeps
12337 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
12338 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
12339 match value {
12340 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
12341 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
12342 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
12343 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
12344 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12345 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
12346 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
12347 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
12348 other.to_js_string(),
12349 ))),
12350 },
12351 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
12352 }
12353 }
12354
12355 /// `ToPropertyKey` for the callers that can only use a string key.
12356 ///
12357 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
12358 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
12359 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
12360 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
12361 /// program continues with a value nobody asked for.
12362 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12363 use crate::value::Wtf8;
12364 Ok(match value {
12365 // A string key keeps its code units. Going through a lossy `String` would make
12366 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
12367 Value::String(text) => text.wtf8().clone(),
12368 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
12369 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
12370 // falling back to its `ToString` would print `[object Object]`.
12371 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12372 Value::String(text) => text.wtf8().clone(),
12373 other => Wtf8::new(other.to_js_string()),
12374 },
12375 other => Wtf8::new(other.to_js_string()),
12376 })
12377 }
12378
12379 // -- object operations used by instructions -----------------------------
12380
12381 /// Read `object[key]`, returning `undefined` when the property is missing.
12382 ///
12383 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
12384 /// primitive (looking through its prototype) as well as an object — which is what
12385 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
12386 /// argument needs too.
12387 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
12388 self.read_field_key(object, &PropertyKey::from(key))
12389 }
12390
12391 /// [`Interp::read_field`] with a key that may be a symbol.
12392 ///
12393 /// A symbol key never reaches the string shortcuts: a string's `length` and its
12394 /// indices are string properties, and a symbol named `length` is a different
12395 /// property that a string primitive cannot have.
12396 /// [`Interp::read_field_key`], with an inline cache in front of it.
12397 ///
12398 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
12399 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
12400 /// without this the engine walked the chain and compared ~40 property names on each
12401 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
12402 ///
12403 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
12404 /// missing property. Those answers depend on running code or on state the guard below
12405 /// does not cover, and a wrong answer here is far more expensive than a lookup.
12406 ///
12407 /// A hit is re-validated against the *whole* walked chain, not just the level that
12408 /// answered: the receiver and every prototype down to that level must still be the same
12409 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
12410 /// property-table *lengths* — which is what catches a property appearing on an
12411 /// intermediate prototype and shadowing the cached one.
12412 pub fn read_field_cached(
12413 &mut self,
12414 object: &Value,
12415 key: &PropertyKey,
12416 slot: usize,
12417 ) -> JsResult<Value> {
12418 let index = Self::field_cache_slot(object, key, slot);
12419 let Value::Object(target) = object else {
12420 return self.read_field_key(object, key);
12421 };
12422 if target.proxy_state().is_some() {
12423 return self.read_field_key(object, key);
12424 }
12425 if let Some(cached) = &self.field_cache[index]
12426 && cached.key == *key
12427 && let Some(value) = Self::cached_hit(target, cached)
12428 {
12429 return Ok(value);
12430 }
12431 let value = self.read_field_key(object, key)?;
12432 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
12433 Ok(value)
12434 }
12435
12436 /// Whether a cache entry still describes this lookup, and if so the value.
12437 ///
12438 /// The guard is the whole point of the entry: identity plus property-table length for
12439 /// every level walked. Re-checked per level rather than once at the receiving end,
12440 /// because a shadowing property can appear anywhere along the chain.
12441 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
12442 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
12443 // starts with: a clone is a reference-count bump and a drop, and for
12444 // `property:monomorphic` every single hit takes only this arm.
12445 let (weak, len) = cached.chain[0].as_ref()?;
12446 if !target.upgrades_to(weak) {
12447 return None;
12448 }
12449 if cached.level == 0 {
12450 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
12451 return target.cached_property_at(cached.index, &cached.key, *len);
12452 }
12453 if target.props_len() != *len {
12454 return None;
12455 }
12456 let mut level = 1;
12457 let mut current = target.proto()?;
12458 loop {
12459 let (weak, len) = cached.chain[level].as_ref()?;
12460 if !current.upgrades_to(weak) || current.props_len() != *len {
12461 return None;
12462 }
12463 if level == cached.level as usize {
12464 // The level that answered: the value is only reusable while the key is
12465 // still there and still a plain data property.
12466 return current.cached_data_property(cached.index, &cached.key);
12467 }
12468 current = current.proto()?;
12469 level += 1;
12470 }
12471 }
12472
12473 /// Build a cache entry for a lookup that just went through the slow path.
12474 ///
12475 /// Records the chain only when the answer came from a plain data property at a level
12476 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
12477 /// costs the next lookup the walk it would have cost anyway.
12478 fn record_field_lookup(
12479 target: &Gc<JsObject>,
12480 key: &PropertyKey,
12481 _value: Value,
12482 ) -> Option<FieldCache> {
12483 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
12484 [None, None, None];
12485 let mut current = target.clone();
12486 for level in 0..MAX_CACHED_CHAIN {
12487 chain[level] = Some((current.downgrade(), current.props_len()));
12488 if let Some((found, _)) = current.own_property_index(key) {
12489 // `own_property_index` declines an accessor and a hole, which is exactly
12490 // the set that must not be cached.
12491 return Some(FieldCache {
12492 key: key.clone(),
12493 index: found,
12494 level: level as u8,
12495 chain,
12496 });
12497 }
12498 current = current.proto()?;
12499 }
12500 None
12501 }
12502
12503 /// Which cache slot a lookup uses.
12504 ///
12505 /// Mixes the object's address, the name and the site, so that two properties of one
12506 /// object, and one property of two objects, land in different slots — which is what lets
12507 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
12508 /// other iteration.
12509 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
12510 let mut hash = match object {
12511 Value::Object(object) => object.address(),
12512 _ => 0,
12513 };
12514 hash = hash
12515 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
12516 .rotate_left(17)
12517 .wrapping_add(key.hash_code());
12518 hash = hash.wrapping_add(site.wrapping_mul(31));
12519 // The table is a power of two, so the low bits are the slot.
12520 hash & (FIELD_CACHE_SLOTS - 1)
12521 }
12522
12523 /// Read `key` from `object`, without the inline cache.
12524 ///
12525 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
12526 /// prototype chain, while the cached form answers an own data property from memory.
12527 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
12528 let text = key.as_str().unwrap_or("");
12529 let Value::Object(object) = object else {
12530 // Reading a property of `undefined`/`null` is the classic TypeError.
12531 if object.is_nullish() {
12532 return Err(Signal::Throw(self.make_error(
12533 "TypeError",
12534 &format!("cannot read property '{key}' of {}", object.to_js_string()),
12535 )));
12536 }
12537 // A string has `length` and index access without being boxed.
12538 if let Value::String(value) = object {
12539 if text == "length" {
12540 return Ok(Value::Int(value.utf16_len() as i32));
12541 }
12542 if let Some(index) = array_index(text) {
12543 return Ok(match value.wtf8().unit_at(index as usize) {
12544 Some(unit) => self.string_wtf8(unit),
12545 None => Value::Undefined,
12546 });
12547 }
12548 }
12549 // A property of a primitive is looked up on its prototype: this is what
12550 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
12551 let prototype = match object {
12552 Value::String(_) => self.realm.string_proto.clone(),
12553 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12554 Value::Bool(_) => self.realm.boolean_proto.clone(),
12555 // A symbol's methods live on `Symbol.prototype`, reached the same way —
12556 // `sym.description` reads through the prototype, not off the symbol.
12557 Value::Symbol(_) => self.realm.symbol_proto.clone(),
12558 // …and a bigint's on `BigInt.prototype`, which is how
12559 // `(255n).toString(16)` reaches its method.
12560 Value::BigInt(_) => self.realm.bigint_proto.clone(),
12561 _ => None,
12562 };
12563 if let Some(prototype) = prototype
12564 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
12565 {
12566 return Ok(value);
12567 }
12568 return Ok(Value::Undefined);
12569 };
12570 Ok(self
12571 .get_property_key(object, key)?
12572 .unwrap_or(Value::Undefined))
12573 }
12574
12575 /// The `#name` a private symbol stands for, for error messages.
12576 ///
12577 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
12578 /// was made from.
12579 fn private_name(symbol: &Value) -> Option<String> {
12580 match symbol {
12581 Value::Symbol(symbol) if symbol.is_private() => Some(
12582 symbol
12583 .description()
12584 .map(|text| text.to_string())
12585 .unwrap_or_default(),
12586 ),
12587 _ => None,
12588 }
12589 }
12590
12591 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
12592 ///
12593 /// Every private-field opcode takes the symbol the class stored in its own scope; a
12594 /// non-symbol here would be a compiler bug, and the reference guards it with
12595 /// `JS_ThrowTypeErrorNotASymbol`.
12596 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
12597 match symbol {
12598 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
12599 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
12600 }
12601 }
12602
12603 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
12604 ///
12605 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
12606 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
12607 /// would hit if the parser did not reject it first.
12608 fn define_private_field(
12609 &mut self,
12610 object: &Value,
12611 symbol: &Value,
12612 value: Value,
12613 ) -> JsResult<()> {
12614 let key = self.private_key(symbol)?;
12615 let Some(target) = object.as_object() else {
12616 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12617 };
12618 if !target.is_extensible() {
12619 return Err(Signal::Throw(
12620 self.make_error("TypeError", "object is not extensible"),
12621 ));
12622 }
12623 if target.own_property_key(&key).is_some() {
12624 let name = Self::private_name(symbol).unwrap_or_default();
12625 return Err(Signal::Throw(self.make_error(
12626 "TypeError",
12627 &format!("private class field '{name}' already exists"),
12628 )));
12629 }
12630 target.define_data_key(&key, value);
12631 Ok(())
12632 }
12633
12634 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
12635 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
12636 let key = self.private_key(symbol)?;
12637 let Some(target) = object.as_object() else {
12638 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12639 };
12640 match target.own_property_key(&key) {
12641 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
12642 None => {
12643 let name = Self::private_name(symbol).unwrap_or_default();
12644 Err(Signal::Throw(self.make_error(
12645 "TypeError",
12646 &format!("private class field '{name}' does not exist"),
12647 )))
12648 }
12649 }
12650 }
12651
12652 /// `JS_SetPrivateField`: the store half of the same rule.
12653 fn write_private_field(
12654 &mut self,
12655 object: &Value,
12656 symbol: &Value,
12657 value: Value,
12658 ) -> JsResult<()> {
12659 let key = self.private_key(symbol)?;
12660 let Some(target) = object.as_object() else {
12661 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12662 };
12663 if target.write_value_key(&key, value) {
12664 return Ok(());
12665 }
12666 let name = Self::private_name(symbol).unwrap_or_default();
12667 Err(Signal::Throw(self.make_error(
12668 "TypeError",
12669 &format!("private class field '{name}' does not exist"),
12670 )))
12671 }
12672
12673 /// The `in` half: does `object` have this private field?
12674 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
12675 ///
12676 /// The symbol is created once per class — the first `add_brand` on a given home object
12677 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
12678 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
12679 /// emit for the *instance* brand passes null because all it wants is the symbol.
12680 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
12681 let Some(home_object) = home.as_object() else {
12682 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12683 };
12684 let symbol = match home_object.private_brand() {
12685 Some(symbol) => symbol,
12686 None => {
12687 let symbol = Gc::new(
12688 self.heap,
12689 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
12690 );
12691 home_object.set_private_brand(symbol.clone());
12692 symbol
12693 }
12694 };
12695 let Some(target) = object.as_object() else {
12696 // Not an object: nothing to brand. The reference does the same, and `undefined`
12697 // here would otherwise turn a field initialiser into a TypeError.
12698 return Ok(());
12699 };
12700 if !target.is_extensible() {
12701 return Err(Signal::Throw(
12702 self.make_error("TypeError", "object is not extensible"),
12703 ));
12704 }
12705 if target.carries_brand(&symbol) {
12706 return Err(Signal::Throw(
12707 self.make_error("TypeError", "private method is already present"),
12708 ));
12709 }
12710 target.add_brand(symbol);
12711 Ok(())
12712 }
12713
12714 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
12715 ///
12716 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
12717 /// decides whether to throw.
12718 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
12719 let Some(function) = function.as_object() else {
12720 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12721 };
12722 let Some(home) = function.home_object() else {
12723 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12724 };
12725 let Some(brand) = home.private_brand() else {
12726 return Err(Signal::Throw(
12727 self.make_error("TypeError", "expecting <brand> private field"),
12728 ));
12729 };
12730 Ok(object.carries_brand(&brand))
12731 }
12732
12733 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
12734 let Value::Object(object) = object else {
12735 return Err(Signal::Throw(self.make_error(
12736 "TypeError",
12737 &format!("cannot set property '{key}' of {}", object.to_js_string()),
12738 )));
12739 };
12740 // The write half of the property inline cache, in effect: an own, writable,
12741 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
12742 // decide — no prototype walk (an own property shadows the chain before a setter
12743 // there could matter), no extensibility check (the object already has the key),
12744 // and no `[[DefineOwnProperty]]`.
12745 //
12746 // `this.value = …` inside a method is the whole write side of
12747 // `property:method-call`, and it was reaching `set_property_with_key` with its
12748 // proxy test, its typed-array test, its array-index test and finally a linear
12749 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
12750 //
12751 // Every disqualifier is checked here: a proxy traps the set, an array index and
12752 // `length` live outside the property table, and a typed array's element is stored
12753 // through its view's element type.
12754 if object.proxy_state().is_none()
12755 && !object.is_array()
12756 && object.typed_array_element_type().is_none()
12757 && object.write_value_key(key, value.clone())
12758 {
12759 return Ok(());
12760 }
12761 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
12762 let on_failure = if self.frame().code.code.strict {
12763 DeleteFailure::Throw
12764 } else {
12765 DeleteFailure::Ignore
12766 };
12767 self.set_property_with_key(object, key, value, on_failure)
12768 }
12769
12770 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
12771 ///
12772 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
12773 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
12774 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
12775 /// `Number.parseInt(sym)` — so those callers use this instead.
12776 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
12777 if matches!(value, Value::Symbol(_)) {
12778 return Err(Signal::Throw(
12779 self.make_error("TypeError", "cannot convert symbol to string"),
12780 ));
12781 }
12782 // An object runs `ToPrimitive` first, which may itself produce a symbol —
12783 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
12784 let value = self.to_primitive(value.clone(), Hint::String)?;
12785 if matches!(value, Value::Symbol(_)) {
12786 return Err(Signal::Throw(
12787 self.make_error("TypeError", "cannot convert symbol to string"),
12788 ));
12789 }
12790 Ok(value.to_js_string())
12791 }
12792
12793 /// `ToPropertyKey` for a builtin that takes a key argument.
12794 ///
12795 /// Fallible: a key whose `toString` throws has to propagate that error, both for
12796 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
12797 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
12798 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
12799 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
12800 self.propkey(value)
12801 }
12802
12803 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
12804 ///
12805 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
12806 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
12807 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
12808 /// `RangeError` — and why this cannot be a plain `ToNumber`.
12809 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
12810 let number = match value {
12811 Value::Int(number) => *number as f64,
12812 Value::Float(number) => *number,
12813 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
12814 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
12815 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
12816 // reference answers 0.
12817 Value::Null | Value::Bool(_) => value.to_number(),
12818 _ => {
12819 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
12820 match primitive {
12821 Value::Int(number) => number as f64,
12822 Value::Float(number) => number,
12823 other => {
12824 // `ToString` then `ToNumber`, so a string length goes through the
12825 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
12826 // `Value::to_number` on the string already implements exactly that.
12827 let text = self.to_js_string(&other)?;
12828 crate::value::string_to_number(&text)
12829 }
12830 }
12831 }
12832 };
12833 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
12834 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
12835 // is a `RangeError`, not `0`.
12836 if !number.is_finite()
12837 || number.fract() != 0.0
12838 || !(0.0..=u32::MAX as f64).contains(&number)
12839 {
12840 return Err(self.range_error("invalid array length"));
12841 }
12842 Ok(number as u32)
12843 }
12844
12845 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
12846 /// `Object.getOwnPropertySymbols` put in their result array.
12847 pub fn key_value(&self, key: &PropertyKey) -> Value {
12848 match key {
12849 PropertyKey::String(text) => self.string_wtf8(text.clone()),
12850 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12851 }
12852 }
12853
12854 /// Fill in a String exotic object: `_value`, `length` and the index properties.
12855 ///
12856 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
12857 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
12858 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
12859 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
12860 /// the two paths had drifted; this is the one both now use.
12861 ///
12862 /// The indices are *code units*, so an astral character occupies two of them — the
12863 /// same rule `s.length` and `s[i]` follow.
12864 /// Give an already-created object the internal slot that makes it a wrapper of
12865 /// `value`, so the primitive's prototype methods work on it.
12866 ///
12867 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
12868 /// which are wrappers of their own type holding the empty value.
12869 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
12870 self.internal_set(object, "_value", value);
12871 }
12872
12873 pub(crate) fn init_string_wrapper(
12874 &mut self,
12875 object: &Gc<JsObject>,
12876 text: &Gc<crate::value::JsString>,
12877 ) {
12878 object.define(
12879 "length",
12880 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
12881 );
12882 for index in 0..text.utf16_len() {
12883 if let Some(unit) = text.wtf8().unit_at(index) {
12884 object.define(
12885 &index.to_string(),
12886 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
12887 Property::with_attributes(self.string_wtf8(unit), false, true),
12888 );
12889 }
12890 }
12891 object.define_key(
12892 &self.internal_slot("_value"),
12893 Property::with_attributes(Value::String(text.clone()), false, false),
12894 );
12895 }
12896
12897 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
12898 ///
12899 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
12900 /// throws. The wrapper carries its primitive in `_value` — the same slot
12901 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
12902 /// on a boxed value no constructor ever built.
12903 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12904 let (prototype, primitive) = match value {
12905 Value::Object(object) => return Ok(object.clone()),
12906 Value::String(text) => {
12907 let object = self.new_object(self.realm.string_proto.clone());
12908 self.init_string_wrapper(&object, text);
12909 return Ok(object);
12910 }
12911 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
12912 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
12913 // A symbol and a bigint box into wrappers whose methods live on
12914 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
12915 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
12916 // branch below instead produced an object with *no* prototype, so those
12917 // methods were unreachable on a box.
12918 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
12919 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
12920 Value::Undefined | Value::Null => {
12921 return Err(Signal::Throw(self.make_error(
12922 "TypeError",
12923 &format!("cannot convert {} to object", value.to_js_string()),
12924 )));
12925 }
12926 _ => (None, value.clone()),
12927 };
12928 let object = self.new_object(prototype);
12929 self.internal_set(&object, "_value", primitive);
12930 Ok(object)
12931 }
12932
12933 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
12934 ///
12935 /// Split out for a reader that has to create the object *before* it knows what it wraps:
12936 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
12937 /// written before its primitive, so the placeholder has to exist first and be filled in
12938 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
12939 /// than a second in the deserialiser.
12940 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
12941 let prototype = match value {
12942 Value::String(_) => self.realm.string_proto.clone(),
12943 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12944 Value::Bool(_) => self.realm.boolean_proto.clone(),
12945 Value::Symbol(_) => self.realm.symbol_proto.clone(),
12946 Value::BigInt(_) => self.realm.bigint_proto.clone(),
12947 _ => {
12948 return Err(Signal::Throw(self.make_error(
12949 "TypeError",
12950 &format!("cannot box {}", value.to_js_string()),
12951 )));
12952 }
12953 };
12954 object.set_proto(prototype);
12955 if let Value::String(text) = value {
12956 self.init_string_wrapper(object, text);
12957 return Ok(());
12958 }
12959 self.internal_set(object, "_value", value.clone());
12960 Ok(())
12961 }
12962
12963 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
12964 ///
12965 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
12966 /// through the `Symbol` function object, so the registry is reachable as a method rather
12967 /// than only from `builtins::symbol`.
12968 pub fn symbol_for(&mut self, key: &str) -> Value {
12969 if let Some(existing) = self.realm.symbol_registry.get(key) {
12970 return existing.clone();
12971 }
12972 let symbol = crate::builtins::symbol::symbol_value(
12973 self,
12974 crate::value::JsSymbol::registered(key.to_string()),
12975 );
12976 self.realm
12977 .symbol_registry
12978 .insert(key.to_string(), symbol.clone());
12979 symbol
12980 }
12981
12982 /// `a == b`, the coercing comparison.
12983 ///
12984 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
12985 /// which is what makes `[] == ""` true: `[]` becomes `""` via
12986 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
12987 /// because the conversion is allowed to call script code, so the two primitive
12988 /// operands are handed back to it.
12989 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
12990 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
12991 return Ok(left.loose_equals(&right));
12992 }
12993 // `null == undefined` holds even though neither is an object.
12994 if matches!(left, Value::Undefined | Value::Null)
12995 && matches!(right, Value::Undefined | Value::Null)
12996 {
12997 return Ok(true);
12998 }
12999 if matches!(left, Value::Undefined | Value::Null)
13000 || matches!(right, Value::Undefined | Value::Null)
13001 {
13002 return Ok(false);
13003 }
13004 // Two objects compare by identity. Only an object *against a primitive* is
13005 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13006 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13007 return Ok(a.ptr_eq(b));
13008 }
13009 let left = self.to_primitive(left, Hint::Default)?;
13010 let right = self.to_primitive(right, Hint::Default)?;
13011 Ok(left.loose_equals(&right))
13012 }
13013
13014 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13015 let Value::Object(object) = object else {
13016 return Err(Signal::Throw(
13017 self.make_error("TypeError", "cannot use 'in' on a non-object"),
13018 ));
13019 };
13020 let key = self.propkey(key)?;
13021 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13022 // trap. One implementation, so an array's derived `length` and its inherited holes
13023 // cannot be right in one caller and wrong in another.
13024 self.has_own_or_inherited(object, &key)
13025 }
13026
13027 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13028 ///
13029 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13030 /// whole reason the operator is a hook rather than a prototype walk.
13031 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13032 if let Value::Object(function) = constructor {
13033 let key = self.realm.well_known_key(WellKnown::HasInstance);
13034 let method = self.get_property_key(function, &key)?;
13035 if let Some(method) = method
13036 && !matches!(method, Value::Undefined)
13037 {
13038 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13039 return Ok(answer.to_boolean());
13040 }
13041 }
13042 self.instance_of(object, constructor)
13043 }
13044
13045 /// `OrdinaryHasInstance`: the prototype walk on its own.
13046 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13047 self.instance_of(object, constructor)
13048 }
13049
13050 /// `IsArray`: an array, or a proxy whose target is one.
13051 ///
13052 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13053 /// makes `Array.isArray(new Proxy([], {}))` true.
13054 pub fn is_array_value(&self, value: &Value) -> bool {
13055 match value {
13056 Value::Object(object) => {
13057 if let Some(state) = object.proxy_state() {
13058 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13059 }
13060 object.is_array()
13061 }
13062 _ => false,
13063 }
13064 }
13065
13066 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13067 ///
13068 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13069 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13070 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13071 /// see [`Interp::enqueue_job_function`].
13072 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13073 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13074 // the handler is reported rather than lost — the same reason a `then` reaction needs a
13075 // promise to settle.
13076 let promise = self.new_promise();
13077 self.fulfill_promise(&promise, Value::Undefined);
13078 self.jobs.push_back(Job::Reaction {
13079 handler: Some(function),
13080 argument: Value::Undefined,
13081 rejected: false,
13082 promise,
13083 });
13084 Ok(())
13085 }
13086
13087 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13088 ///
13089 /// Four of its steps were missing or wrong, and each one is a test262 case in
13090 /// `Function/prototype/Symbol.hasInstance/`:
13091 ///
13092 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13093 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13094 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
13095 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13096 /// `prototype` of its own, so without this step the walk below gives `false`;
13097 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13098 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13099 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13100 let Value::Object(function) = constructor else {
13101 return Ok(false);
13102 };
13103 if !function.is_callable() {
13104 return Ok(false);
13105 }
13106 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13107 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13108 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13109 if let Some((target, this)) = function.bound_target_and_this() {
13110 let object = if this.as_object().is_some() {
13111 this
13112 } else {
13113 object.clone()
13114 };
13115 return self.instance_of(&object, &target);
13116 }
13117 let Value::Object(target) = object else {
13118 return Ok(false);
13119 };
13120 let prototype = self.get_property(function, "prototype")?;
13121 let Some(Value::Object(prototype)) = prototype else {
13122 return Err(Signal::Throw(self.make_error(
13123 "TypeError",
13124 "function has non-object prototype in instanceof check",
13125 )));
13126 };
13127 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13128 // which is also what makes `proxyOfInstance instanceof C` work.
13129 let mut current = Some(target.clone());
13130 while let Some(object) = current {
13131 if object.ptr_eq(&prototype) {
13132 return Ok(true);
13133 }
13134 current = self.object_prototype_of(&object)?;
13135 }
13136 Ok(false)
13137 }
13138
13139 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13140 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13141 if let Some(proto) = self.proxy_get_prototype_of(object)? {
13142 return Ok(proto);
13143 }
13144 if let Some(exotic) = object.exotic()
13145 && let Some(proto) = exotic.get_prototype(self, object)?
13146 {
13147 return Ok(proto);
13148 }
13149 Ok(object.proto())
13150 }
13151
13152 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13153 pub fn object_set_prototype_of(
13154 &mut self,
13155 object: &Gc<JsObject>,
13156 proto: Option<Gc<JsObject>>,
13157 ) -> JsResult<bool> {
13158 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13159 return Ok(answer);
13160 }
13161 if let Some(exotic) = object.exotic()
13162 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13163 {
13164 return Ok(answer);
13165 }
13166 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13167 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13168 // inheriting from itself, which every later prototype walk then had to defend
13169 // against — and `Reflect.setPrototypeOf` reported success for an operation the
13170 // language says is impossible.
13171 if let Some(proto) = &proto {
13172 let mut current = Some(proto.clone());
13173 let mut guard = 0;
13174 while let Some(node) = current {
13175 if node.ptr_eq(object) {
13176 return Err(Signal::Throw(
13177 self.make_error("TypeError", "circular prototype chain"),
13178 ));
13179 }
13180 guard += 1;
13181 if guard > 1000 {
13182 break;
13183 }
13184 current = node.proto();
13185 }
13186 }
13187 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13188 // re-setting it to the *same* one is a no-op `true`. Missing this made
13189 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13190 // actually reparent the object — and it is what
13191 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13192 // forwarding path has nothing else left to refuse it.
13193 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13194 return Ok(false);
13195 }
13196 object.set_proto(proto);
13197 Ok(true)
13198 }
13199
13200 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13201 ///
13202 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13203 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13204 /// already one.
13205 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13206 // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
13207 // (§10.4.5.2 step 1.b) — the prototype chain is *not* consulted for a canonical
13208 // numeric index. That is observable twice over: a view that has been resized out
13209 // of bounds has no indices, so `2 in view` must then be `false` even when
13210 // `Object.getPrototypeOf(view)[2]` exists, and a key like `"-1"` or `"1.5"` is
13211 // canonical-numeric-but-invalid, so `in` answers `false` where an ordinary
13212 // lookup would have found `TypedArray.prototype["1.5"]`. A proxy is excluded
13213 // because it has no `[[ViewedArrayBuffer]]` slot of its own.
13214 if object.typed_array_parts().is_some()
13215 && object.proxy_state().is_none()
13216 && let Some(numeric) = canonical_numeric_index(key)
13217 {
13218 return Ok(typed_array_index_is_valid(object, numeric));
13219 }
13220 let mut current = Some(object.clone());
13221 // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
13222 let mut guard = 0;
13223 while let Some(node) = current {
13224 guard += 1;
13225 if guard > 1000 {
13226 return Ok(false);
13227 }
13228 let own = self.object_get_own_property(&node, key)?;
13229 if own.is_some() {
13230 return Ok(true);
13231 }
13232 current = self.object_prototype_of(&node)?;
13233 }
13234 Ok(false)
13235 }
13236
13237 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13238 ///
13239 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13240 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13241 /// boolean as well, and it needs the receiver to be the one the caller named.
13242 pub fn set_property_with_key_receiver(
13243 &mut self,
13244 object: &Gc<JsObject>,
13245 key: &PropertyKey,
13246 value: Value,
13247 receiver: Option<&Value>,
13248 on_failure: DeleteFailure,
13249 ) -> JsResult<bool> {
13250 let receiver = receiver
13251 .cloned()
13252 .unwrap_or_else(|| Value::Object(object.clone()));
13253 if object.proxy_state().is_some() {
13254 return match self.proxy_set(object, key, value, &receiver)? {
13255 Some(accepted) => Ok(accepted),
13256 None => Ok(true),
13257 };
13258 }
13259 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13260 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13261 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13262 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13263 //
13264 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13265 //
13266 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13267 // * an *invalid* index with a different receiver answers `true` and does nothing,
13268 // not even converting `V` (`valueOfCalls` stays 0);
13269 // * a valid index with a different receiver falls through to
13270 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13271 // value lands on the **receiver**, unconverted, and can be refused by a
13272 // non-extensible receiver, an accessor, or a read-only index there.
13273 //
13274 // The last one used to write into the view itself, which left `target[0]` changed
13275 // and `receiver[0]` untouched — backwards.
13276 if object.typed_array_element_type().is_some()
13277 && let Some(numeric) = canonical_numeric_index(key)
13278 {
13279 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13280 if same {
13281 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13282 return Ok(true);
13283 }
13284 if !typed_array_index_is_valid(object, numeric) {
13285 return Ok(true);
13286 }
13287 let Some(receiver) = receiver.as_object().cloned() else {
13288 return Ok(false);
13289 };
13290 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13291 if existing.is_accessor() || !existing.writable {
13292 return Ok(false);
13293 }
13294 let property = Property {
13295 value: Some(value),
13296 ..existing
13297 };
13298 return self.object_define_own_property(&receiver, key, property);
13299 }
13300 return self.object_define_own_property(&receiver, key, Property::data(value));
13301 }
13302 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13303 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13304 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13305 // `Reflect.set` to *report* the refusal instead of raising.
13306 //
13307 // A receiver that is not the object turns the whole operation into
13308 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13309 // `[[Set]]` rather than a lookup — that is what makes
13310 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13311 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13312 // writes to `object`, so it cannot express that and is only used when the two are
13313 // the same.
13314 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13315 if !same {
13316 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
13317 }
13318 // Same receiver: the plain path below writes into `object`, which is right, but it
13319 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
13320 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
13321 if let Some(existing) = self.object_get_own_property(object, key)? {
13322 if existing.is_accessor() {
13323 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
13324 Some(setter) => {
13325 self.call_value(setter, receiver, vec![value])?;
13326 Ok(true)
13327 }
13328 None => Ok(false),
13329 };
13330 }
13331 if !existing.writable {
13332 return Ok(false);
13333 }
13334 }
13335 // Otherwise it is an ordinary create-or-write into `object` itself.
13336 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13337 Ok(true)
13338 }
13339
13340 /// `[[IsExtensible]]`, with the proxy trap when there is one.
13341 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13342 if let Some(answer) = self.proxy_is_extensible(object)? {
13343 return Ok(answer);
13344 }
13345 if let Some(exotic) = object.exotic()
13346 && let Some(answer) = exotic.is_extensible(self, object)?
13347 {
13348 return Ok(answer);
13349 }
13350 Ok(object.is_extensible())
13351 }
13352
13353 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
13354 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13355 if let Some(answer) = self.proxy_prevent_extensions(object)? {
13356 return Ok(answer);
13357 }
13358 if let Some(exotic) = object.exotic()
13359 && let Some(answer) = exotic.prevent_extensions(self, object)?
13360 {
13361 return Ok(answer);
13362 }
13363 object.set_extensible(false);
13364 Ok(true)
13365 }
13366
13367 fn copy_properties(
13368 &mut self,
13369 target: &Value,
13370 source: &Value,
13371 exclusion: &Value,
13372 ) -> JsResult<()> {
13373 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
13374 // does contribute: its index properties are own, enumerable and writable, which
13375 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
13376 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
13377 // is a no-op.
13378 let Some(target) = target.as_object() else {
13379 return Ok(());
13380 };
13381 let source_object = match source {
13382 Value::Object(object) => object.clone(),
13383 Value::String(text) => {
13384 // Untaken keys are the string's indices, which are code units.
13385 for index in 0..text.utf16_len() {
13386 if let Some(unit) = text.wtf8().unit_at(index) {
13387 target.define_data(&index.to_string(), self.string_wtf8(unit));
13388 }
13389 }
13390 return Ok(());
13391 }
13392 _ => return Ok(()),
13393 };
13394 // An object *rest* element passes the keys already taken by the literal part as
13395 // an array of strings; a spread passes `null`, which excludes nothing. Only the
13396 // string keys of the exclusion array are meaningful, so an array is read by its
13397 // elements rather than by its own property names.
13398 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
13399 if let Value::Object(list) = exclusion
13400 && let Some(length) = list.array_length()
13401 {
13402 for index in 0..length {
13403 if let Some(value) = list.array_get(index) {
13404 excluded.push(self.propkey_of(&value)?);
13405 }
13406 }
13407 }
13408 let source = &source_object;
13409 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
13410 // Reading the property table directly made every spread of a proxy empty.
13411 let keys = self.object_own_property_keys(source)?;
13412 for as_key in keys {
13413 if as_key.is_symbol() {
13414 // A spread copies string-keyed properties only.
13415 continue;
13416 }
13417 if excluded.contains(&crate::value::Wtf8::new(
13418 as_key.as_str().unwrap_or_default(),
13419 )) {
13420 continue;
13421 }
13422 let enumerable = self
13423 .object_get_own_property(source, &as_key)?
13424 .is_some_and(|property| property.enumerable);
13425 if !enumerable {
13426 continue;
13427 }
13428 let value = self
13429 .get_property_key(source, &as_key)?
13430 .unwrap_or(Value::Undefined);
13431 target.define_data_key(&as_key, value);
13432 }
13433 Ok(())
13434 }
13435
13436 // -- iteration ---------------------------------------------------------
13437
13438 /// One object's own keys in enumeration order: array indices ascending, then the
13439 /// rest in insertion order.
13440 ///
13441 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
13442 /// whether the key is enumerable, which the caller resolves per key because an
13443 /// array's elements are not in the same store as its named properties.
13444 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
13445 // An index can arrive twice, once from the array's element store and once from
13446 // its property map, so the numeric keys go through a map that keeps the
13447 // enumerable answer if either source gave one.
13448 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
13449 for (key, enumerable) in &own {
13450 if let Some(index) = key.as_str().and_then(array_index) {
13451 let entry = numeric.entry(index).or_insert(false);
13452 *entry = *entry || *enumerable;
13453 }
13454 }
13455 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
13456 .into_iter()
13457 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
13458 .collect();
13459 ordered.extend(
13460 own.into_iter()
13461 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
13462 );
13463 ordered
13464 }
13465
13466 /// Build the key list a `for-in` loop walks.
13467 ///
13468 /// The order is the specification's: own properties before inherited ones, and
13469 /// within one object the integer-like keys in ascending numeric order ahead of the
13470 /// string keys in insertion order. A shadowed key only appears once, and a key that
13471 /// is a non-enumerable own property anywhere nearer is skipped entirely.
13472 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13473 let record = self.new_object(None);
13474 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
13475 // A proxy supplies its own key list, and — the reason this is not just another
13476 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
13477 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
13478 // descriptor there.
13479 if let Value::Object(object) = value
13480 && object.proxy_state().is_some()
13481 {
13482 let own = self
13483 .proxy_own_keys(object)?
13484 .unwrap_or_else(|| object.own_property_keys());
13485 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
13486 let mut numeric: Vec<u32> = Vec::new();
13487 let mut rest: Vec<PropertyKey> = Vec::new();
13488 for key in own {
13489 match key.as_str().and_then(array_index) {
13490 Some(index) => numeric.push(index),
13491 None => rest.push(key),
13492 }
13493 }
13494 numeric.sort_unstable();
13495 ordered.extend(
13496 numeric
13497 .into_iter()
13498 .map(|index| PropertyKey::from(index.to_string())),
13499 );
13500 ordered.extend(rest);
13501 for (index, key) in ordered.into_iter().enumerate() {
13502 record.define_data(&index.to_string(), self.key_value(&key));
13503 }
13504 record.define_data("__index", Value::Int(0));
13505 // The mark that makes `for_in_advance` re-ask the proxy per key.
13506 record.define_data("__proxy", Value::Object(object.clone()));
13507 return Ok(record);
13508 }
13509 if let Value::Object(object) = value {
13510 let mut chain = vec![object.clone()];
13511 chain.extend(object.chain());
13512 // Every own string key the walk has seen, enumerable or not. A
13513 // non-enumerable own property still hides a same-named enumerable one
13514 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
13515 // keeps `x` out of the loop even when the prototype has one.
13516 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
13517 for object in chain {
13518 let mut own: Vec<(crate::value::Wtf8, bool)> = object
13519 .own_property_keys()
13520 .iter()
13521 .filter_map(|key| key.as_wtf8().cloned())
13522 .map(|key| {
13523 let enumerable = object
13524 .own_property(&key.to_string_lossy())
13525 .map(|property| property.enumerable)
13526 .unwrap_or(false);
13527 (key, enumerable)
13528 })
13529 .collect();
13530 if let Some(length) = object.array_length() {
13531 own.retain(|(key, _)| key.as_str() != Some("length"));
13532 for index in 0..length {
13533 if object.array_get(index).is_some() {
13534 own.push((crate::value::Wtf8::new(index.to_string()), true));
13535 }
13536 }
13537 }
13538 // Integer-like keys come first in ascending order, then the rest in
13539 // insertion order — and the ordering is *per object*, not for the chain
13540 // as a whole: one pass over every collected key lifted a prototype's
13541 // `"4"` above the target's own `x`/`y`, which is not the order
13542 // `for…in` reports.
13543 for (key, enumerable) in Self::order_own_keys(own) {
13544 if visited.contains(&key) {
13545 continue;
13546 }
13547 visited.push(key.clone());
13548 if enumerable {
13549 keys.push(key);
13550 }
13551 }
13552 }
13553 }
13554 for (index, key) in keys.into_iter().enumerate() {
13555 record.define_data(&index.to_string(), self.string_wtf8(key));
13556 }
13557 record.define_data("__index", Value::Int(0));
13558 Ok(record)
13559 }
13560
13561 /// The next key of a `for…in` record, `None` when the loop is done.
13562 ///
13563 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
13564 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
13565 /// the loop reaches it, so a handler that stops reporting a key partway through drops
13566 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
13567 /// key the handler had already withdrawn.
13568 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
13569 let Value::Object(record) = record else {
13570 return Ok(None);
13571 };
13572 let proxy = record
13573 .own_property("__proxy")
13574 .and_then(|property| property.value);
13575 loop {
13576 let index = record
13577 .own_property("__index")
13578 .and_then(|property| property.value)
13579 .map(|value| value.to_int32())
13580 .unwrap_or(0);
13581 let Some(candidate) = record
13582 .own_property(&index.to_string())
13583 .and_then(|property| property.value)
13584 else {
13585 return Ok(None);
13586 };
13587 record.define_data("__index", Value::Int(index + 1));
13588 let text = candidate.to_js_string();
13589 let Some(Value::Object(proxy)) = &proxy else {
13590 return Ok(Some(text));
13591 };
13592 // The candidate is already a key string here, so the lookup does not need a
13593 // second `ToPropertyKey` conversion.
13594 let key = PropertyKey::from(text.as_str());
13595 let live = match self.proxy_get_own_property(proxy, &key)? {
13596 Some(descriptor) => descriptor,
13597 // Not a proxy after all, or it lost its state: fall back to the target.
13598 None => proxy.own_property_key(&key),
13599 };
13600 if live.is_some_and(|property| property.enumerable) {
13601 return Ok(Some(text));
13602 }
13603 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
13604 // next one.
13605 }
13606 }
13607
13608 /// The iterator for `for-of`: the object and its `next` method.
13609 ///
13610 /// An object that already carries a `next` method is used as it is — that is what
13611 /// `arr.values()` returns — and only arrays and strings get the built-in
13612 /// sequence iterator.
13613 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
13614 ///
13615 /// Callers that must choose between the iterable and the array-like protocol — the
13616 /// typed-array constructor is the main one — need to ask *before* committing to one.
13617 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
13618 let key = self.realm.well_known_key(WellKnown::Iterator);
13619 let method = self.read_field_key(value, &key)?;
13620 if matches!(method, Value::Undefined | Value::Null) {
13621 return Ok(false);
13622 }
13623 if !matches!(&method, Value::Object(object) if object.is_callable()) {
13624 return Err(Signal::Throw(
13625 self.make_error("TypeError", "Symbol.iterator is not callable"),
13626 ));
13627 }
13628 Ok(true)
13629 }
13630
13631 /// Collect everything an iterable yields.
13632 ///
13633 /// The cap is a guard against a generator that never ends: an unbounded collect would
13634 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
13635 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
13636 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
13637 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
13638 const MAX_ITEMS: usize = 1 << 24;
13639 let iterator = self.get_iterator(value)?;
13640 let mut out = Vec::new();
13641 loop {
13642 let (element, done) = self.iterator_step(&iterator)?;
13643 if done {
13644 return Ok(out);
13645 }
13646 out.push(element);
13647 if out.len() > MAX_ITEMS {
13648 // Close before refusing: the walk is being abandoned, so the iterator's
13649 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
13650 // unrun and a locked resource unreleased.
13651 self.close_iterator_after_throw(&iterator)?;
13652 return Err(self.range_error("iterable is too long to collect"));
13653 }
13654 }
13655 }
13656
13657 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
13658 ///
13659 /// A native constructor calls this once it has validated its arguments, which is the
13660 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
13661 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
13662 /// never reached. The prototype comes from `new.target` when it is an object, and from
13663 /// `default_proto` otherwise.
13664 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13665 let proto = self.ctor_prototype(default_proto)?;
13666 Ok(self.new_object(Some(proto)))
13667 }
13668
13669 /// An **array** whose prototype comes from `new.target`.
13670 ///
13671 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
13672 /// instance from `new.target.prototype`, and building a plain array instead made every
13673 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
13674 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
13675 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
13676 Ok(JsObject::array(self.heap, Some(proto), 0))
13677 }
13678
13679 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
13680 ///
13681 /// The `Option` form is for the constructors that build their instance in a helper which
13682 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
13683 /// from `await`'s internal promise, and only the first has a `new.target`.
13684 fn ctor_prototype_opt(
13685 &mut self,
13686 default_proto: Option<Gc<JsObject>>,
13687 ) -> JsResult<Option<Gc<JsObject>>> {
13688 let Some(target) = self.pending_new_target.clone() else {
13689 return Ok(default_proto);
13690 };
13691 let Some(target) = target.as_object().cloned() else {
13692 return Ok(default_proto);
13693 };
13694 match self.get_property(&target, "prototype")? {
13695 Some(Value::Object(proto)) => Ok(Some(proto)),
13696 _ => Ok(default_proto),
13697 }
13698 }
13699
13700 /// `new.target.prototype`, or `default_proto` when this is a plain call.
13701 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13702 let Some(target) = self.pending_new_target.clone() else {
13703 return Ok(default_proto);
13704 };
13705 let Some(target) = target.as_object().cloned() else {
13706 return Ok(default_proto);
13707 };
13708 match self.get_property(&target, "prototype")? {
13709 Some(Value::Object(proto)) => Ok(proto),
13710 _ => Ok(default_proto),
13711 }
13712 }
13713
13714 /// `CreateDataPropertyOrThrow(O, key, value)`.
13715 ///
13716 /// A *definition*, not an assignment. The difference is visible the moment the target
13717 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
13718 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
13719 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
13720 /// refused (`configurable: false`).
13721 ///
13722 /// The fast path exists because this is called once per element by `map`, `filter`,
13723 /// `slice` and friends: a plain array with no custom element descriptors and a writable
13724 /// `length` can store straight into its element vector.
13725 pub fn create_data_property_or_throw(
13726 &mut self,
13727 object: &Gc<JsObject>,
13728 index: usize,
13729 value: Value,
13730 ) -> JsResult<()> {
13731 if object.is_array()
13732 && object.elements_writable()
13733 && !object.has_element_descriptors()
13734 && object.is_extensible()
13735 && object.array_set(self.heap, index, value.clone())
13736 {
13737 return Ok(());
13738 }
13739 let key = PropertyKey::from(index.to_string());
13740 let property = Property {
13741 value: Some(value),
13742 writable: true,
13743 enumerable: true,
13744 configurable: true,
13745 ..Property::default()
13746 };
13747 // `CreateDataProperty` always asks for the default attributes, so it can only ever
13748 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
13749 // the rest. Checking here rather than inside `object_define_own_property` is
13750 // deliberate: that function receives a fully-populated `Property` and cannot tell
13751 // an omitted attribute from an explicit `false`, so the generic check it would need
13752 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
13753 // writable property (that cost eight `Object/defineProperty` tests).
13754 if let Some(existing) = self.object_get_own_property(object, &key)?
13755 && !existing.configurable
13756 {
13757 return Err(self.type_error("cannot create the property"));
13758 }
13759 if self.object_define_own_property(object, &key, property)? {
13760 return Ok(());
13761 }
13762 Err(self.type_error("cannot create the property"))
13763 }
13764
13765 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
13766 ///
13767 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
13768 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
13769 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
13770 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
13771 /// run user code and both can throw.
13772 pub fn species_constructor(
13773 &mut self,
13774 object: &Gc<JsObject>,
13775 default: Value,
13776 ) -> JsResult<Value> {
13777 let Some(constructor) = self.get_property(object, "constructor")? else {
13778 return Ok(default);
13779 };
13780 let constructor = match constructor {
13781 Value::Undefined => return Ok(default),
13782 Value::Object(constructor) => constructor,
13783 _ => return Err(self.type_error("constructor is not an object")),
13784 };
13785 let key = self.realm.well_known_key(WellKnown::Species);
13786 let species = self.get_property_key(&constructor, &key)?;
13787 match species {
13788 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
13789 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
13790 Some(_) => Err(self.type_error("species is not a constructor")),
13791 }
13792 }
13793
13794 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
13795 ///
13796 /// The result is an array of `length` holes whose prototype comes from
13797 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
13798 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
13799 /// is why the `IsArray` check is the first step and not an optimisation.
13800 pub fn array_species_create(
13801 &mut self,
13802 original: &Value,
13803 length: usize,
13804 ) -> JsResult<Gc<JsObject>> {
13805 let Some(object) = original.as_object().cloned() else {
13806 return Ok(self.new_array_of_length(length));
13807 };
13808 if !object.is_array() {
13809 return Ok(self.new_array_of_length(length));
13810 }
13811 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
13812 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
13813 let Some(constructor) = self.get_property(&object, "constructor")? else {
13814 return Ok(self.new_array_of_length(length));
13815 };
13816 let species = match constructor {
13817 Value::Undefined => return Ok(self.new_array_of_length(length)),
13818 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
13819 return Ok(self.new_array_of_length(length));
13820 }
13821 Value::Object(constructor) => {
13822 let key = self.realm.well_known_key(WellKnown::Species);
13823 match self.get_property_key(&constructor, &key)? {
13824 None | Some(Value::Undefined) | Some(Value::Null) => {
13825 return Ok(self.new_array_of_length(length));
13826 }
13827 Some(species) => species,
13828 }
13829 }
13830 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
13831 // is a `TypeError`, not "the default". Treating it as the default made
13832 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
13833 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
13834 // `concat/create-ctor-non-object` are the same rule three times.
13835 _ => return Err(self.type_error("constructor is not an object")),
13836 };
13837 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
13838 // that is merely callable is the `create-species-non-ctor` case.
13839 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
13840 return Err(self.type_error("species is not a constructor"));
13841 }
13842 let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
13843 let Some(created) = created.as_object().cloned() else {
13844 return Err(self.type_error("species constructor did not answer an object"));
13845 };
13846 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
13847 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
13848 // object, and `create-species-with-non-writable-property` asserts exactly that.
13849 // The length is set for the array case; the generic case is the caller's
13850 // `Set(A, "length", …)`.
13851 if created.is_array() {
13852 created.array_set_length(self.heap, length);
13853 }
13854 Ok(created)
13855 }
13856
13857 /// Whether `object` is this realm's `%Array%`.
13858 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
13859 self.realm
13860 .array_constructor
13861 .as_ref()
13862 .is_some_and(|array| array.ptr_eq(object))
13863 }
13864
13865 /// A fresh `length`-hole array with the intrinsic prototype.
13866 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
13867 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
13868 array.array_set_length(self.heap, length);
13869 array
13870 }
13871
13872 /// Whether this call is a construction, i.e. `new.target` is defined.
13873 ///
13874 /// A native constructor receives `this = undefined` (it builds its own instance), so it
13875 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
13876 /// The native function currently executing, if any.
13877 pub fn current_native(&self) -> Option<Gc<JsObject>> {
13878 self.current_native.clone()
13879 }
13880
13881 /// Whether this call is a construction, i.e. `new.target` is defined.
13882 pub fn is_constructing(&self) -> bool {
13883 self.pending_new_target.is_some()
13884 }
13885
13886 /// The `TypeError` a constructor too primitive to have a wrapper raises.
13887 ///
13888 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
13889 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
13890 /// happens inside the native function, which is why the trace carries an
13891 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
13892 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
13893 /// constructor`, and an unnamed one reports the leading space of `" is not a
13894 /// constructor"` because the reference formats the empty name as it is.
13895 ///
13896 /// It is also the answer for a `new.target` that cannot be named at all — not a
13897 /// function, or a throwing `name` getter — where the reference falls back to the bare
13898 /// `not a constructor`.
13899 pub fn not_a_constructor_error(&mut self) -> Signal {
13900 let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
13901 self.not_a_constructor_error_for(target)
13902 }
13903
13904 /// The same `TypeError` for an explicit target, for the callers that check
13905 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
13906 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
13907 let target = match target {
13908 Value::Object(target) if target.is_callable() => target,
13909 _ => return self.type_error("not a constructor"),
13910 };
13911 let name = match self.get_property(&target, "name") {
13912 Ok(Some(value)) => value.to_js_string(),
13913 _ => return self.type_error("not a constructor"),
13914 };
13915 self.type_error(format!("{name} is not a constructor"))
13916 }
13917
13918 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
13919 ///
13920 /// True whenever `new.target` is not the callee itself, or when it has no usable
13921 /// `prototype` — the cases where reading the property is observable at all.
13922 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
13923 match &self.pending_new_target {
13924 Some(Value::Object(target)) => !target.ptr_eq(callee),
13925 Some(_) => true,
13926 None => false,
13927 }
13928 }
13929
13930 /// The symbol key for one of the engine's own hidden slots.
13931 ///
13932 /// Cached on the realm, so every object of a kind shares one key and a slot can be
13933 /// read back by name.
13934 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
13935 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
13936 return PropertyKey::Symbol(symbol.clone());
13937 }
13938 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
13939 self.realm
13940 .internal_slots
13941 .borrow_mut()
13942 .insert(name, Value::Symbol(symbol.clone()));
13943 PropertyKey::Symbol(symbol)
13944 }
13945
13946 /// Read a hidden slot, or `None` when the object has none of that name.
13947 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
13948 let slots = self.realm.internal_slots.borrow();
13949 let Value::Symbol(symbol) = slots.get(name)? else {
13950 return None;
13951 };
13952 object
13953 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
13954 .and_then(|property| property.value)
13955 }
13956
13957 /// Define a hidden slot.
13958 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
13959 let key = self.internal_slot(name);
13960 object.define_key(&key, Property::with_attributes(value, false, false));
13961 }
13962
13963 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
13964 ///
13965 /// The method is looked up on the value (through its prototype), called with no
13966 /// arguments, and its result becomes the iterator. A generator gets here through
13967 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
13968 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
13969 ///
13970 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
13971 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
13972 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
13973 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
13974 /// does, and a user-defined iterable works without a special case.
13975 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
13976 /// `Symbol.iterator`.
13977 ///
13978 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
13979 /// iterable is legal there, and each value it produces is simply already settled by
13980 /// the time the `await` around it runs.
13981 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
13982 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
13983 let method = self.read_field_key(value, &async_key)?;
13984 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
13985 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
13986 // is *present but not callable* is a TypeError — it does not mean "try the other
13987 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
13988 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
13989 // guard is there to catch.
13990 let absent = matches!(method, Value::Undefined | Value::Null);
13991 if !absent {
13992 let Value::Object(object) = &method else {
13993 return Err(Signal::Throw(
13994 self.make_error("TypeError", "value is not iterable"),
13995 ));
13996 };
13997 if !object.is_callable() {
13998 return Err(Signal::Throw(
13999 self.make_error("TypeError", "value is not iterable"),
14000 ));
14001 }
14002 }
14003 if absent {
14004 return self.get_iterator(value);
14005 }
14006 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14007 if !matches!(iterator, Value::Object(_)) {
14008 return Err(Signal::Throw(
14009 self.make_error("TypeError", "iterator is not an object"),
14010 ));
14011 }
14012 let next = self.read_field(&iterator, "next")?;
14013 Ok(Iterator {
14014 object: iterator,
14015 next,
14016 })
14017 }
14018
14019 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14020 /// read — `@@iterator` is **not** consulted.
14021 ///
14022 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14023 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14024 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14025 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14026 /// refused it with "[object Object] is not iterable".
14027 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14028 if !matches!(value, Value::Object(_)) {
14029 return Err(self.type_error("iterator is not an object"));
14030 }
14031 let next = self.read_field(&value, "next")?;
14032 Ok(Iterator {
14033 object: value,
14034 next,
14035 })
14036 }
14037
14038 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14039 let key = self.realm.well_known_key(WellKnown::Iterator);
14040 let method = self.read_field_key(value, &key)?;
14041 let Value::Object(function) = &method else {
14042 return Err(Signal::Throw(self.make_error(
14043 "TypeError",
14044 &format!("{} is not iterable", value.to_js_string()),
14045 )));
14046 };
14047 if !function.is_callable() {
14048 return Err(Signal::Throw(self.make_error(
14049 "TypeError",
14050 &format!("{} is not iterable", value.to_js_string()),
14051 )));
14052 }
14053 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14054 // The spec requires an object here; a primitive iterator has no `next` to call
14055 // and would fail one step later with a confusing message.
14056 if !matches!(iterator, Value::Object(_)) {
14057 return Err(Signal::Throw(
14058 self.make_error("TypeError", "iterator is not an object"),
14059 ));
14060 }
14061 let next = self.read_field(&iterator, "next")?;
14062 Ok(Iterator {
14063 object: iterator,
14064 next,
14065 })
14066 }
14067
14068 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
14069 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
14070 /// exception from `return` propagates normally instead of being swallowed. That is the
14071 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
14072 /// because confusing them is exactly the bug both exist to avoid.
14073 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
14074 let method = self.read_field(&iterator.object, "return")?;
14075 if matches!(method, Value::Undefined | Value::Null) {
14076 return Ok(());
14077 }
14078 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14079 return Err(self.type_error("iterator return is not a function"));
14080 }
14081 self.call_value(method, iterator.object.clone(), Vec::new())?;
14082 Ok(())
14083 }
14084
14085 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
14086 /// cannot replace it.
14087 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
14088 let method = self.read_field(&iterator.object, "return")?;
14089 if matches!(method, Value::Undefined | Value::Null) {
14090 return Ok(());
14091 }
14092 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14093 return Err(self.type_error("iterator return is not a function"));
14094 }
14095 self.call_value(method, iterator.object.clone(), Vec::new())?;
14096 Ok(())
14097 }
14098
14099 /// One step of an internal iterator: the value and whether it is exhausted.
14100 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
14101 // A real iterator (`next` is a function) answers with a result object.
14102 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
14103 let result =
14104 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
14105 let Some(result) = result.as_object().cloned() else {
14106 return Err(self.type_error("iterator result is not an object"));
14107 };
14108 let done = self
14109 .get_property(&result, "done")?
14110 .is_some_and(|value| value.to_boolean());
14111 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
14112 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
14113 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
14114 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
14115 // made an unrelated `value` getter observable after the loop was over.
14116 if done {
14117 return Ok((Value::Undefined, true));
14118 }
14119 let value = self
14120 .get_property(&result, "value")?
14121 .unwrap_or(Value::Undefined);
14122 return Ok((value, false));
14123 }
14124 // An iterator whose `next` is not callable is treated as exhausted, which is
14125 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
14126 // that are not iterable at all.
14127 Ok((Value::Undefined, true))
14128 }
14129
14130 /// `[...iterable]`: append everything the iterator yields, and answer the next
14131 /// index.
14132 ///
14133 /// This goes through the same iterator machinery `for-of` uses rather than copying
14134 /// an array's elements, because a spread source is any iterable: a string spreads
14135 /// into its characters and an array iterator spreads into its results. Handling
14136 /// only arrays made `[..."ab"]` come out empty with no error at all.
14137 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
14138 let Some(target) = array.as_object().cloned() else {
14139 return Ok(0);
14140 };
14141 let start = target.array_length().unwrap_or(0);
14142 let mut added = 0;
14143 let iterator = self.get_iterator(iterable)?;
14144 loop {
14145 let (value, done) = self.iterator_step(&iterator)?;
14146 if done {
14147 break;
14148 }
14149 target.array_set(self.heap, start + added, value);
14150 added += 1;
14151 }
14152 Ok((start + added) as i32)
14153 }
14154
14155 /// How an uncaught exception is reported.
14156 ///
14157 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
14158 /// with `ToString` — `js_std_dump_error` is three lines that end in
14159 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
14160 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
14161 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
14162 ///
14163 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
14164 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
14165 /// `toString`"; it does call it, but only for objects of a class it does not know how
14166 /// to walk, and never for errors, arrays or plain objects.
14167 ///
14168 /// A printer that fails must not take the reporter down with it, so that case falls
14169 /// back to the `ToString` rendering.
14170 pub fn describe_exception(&mut self, value: &Value) -> String {
14171 match crate::print::sprint(self, value) {
14172 Ok(text) => text,
14173 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
14174 }
14175 }
14176
14177 /// The file name of whatever is running, innermost frame first.
14178 ///
14179 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
14180 /// innermost frame's file name, without distinguishing a module body from a plain
14181 /// script. `import()` uses it as the base for a relative specifier, which is why
14182 /// `import('./x.js')` inside a script resolves next to the script and not next to the
14183 /// process's working directory.
14184 pub fn script_or_module_name(&self) -> Option<String> {
14185 self.script_or_module_name_at(0)
14186 }
14187
14188 /// [`Interp::script_or_module_name`] `level` frames further out.
14189 ///
14190 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
14191 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
14192 /// frame without a file name is skipped rather than counted, because a native call
14193 /// pushes no frame of its own and so cannot be a level.
14194 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
14195 self.frames
14196 .iter()
14197 .rev()
14198 .filter_map(|frame| frame.code.code.filename.clone())
14199 .nth(level)
14200 }
14201
14202 /// The current call stack, formatted the way `qjs` prints `error.stack`.
14203 ///
14204 /// One ` at name (file:line:col)` line per active frame, innermost first. The
14205 /// position is the one recorded for the instruction each frame is stopped on, which
14206 /// is why the compiler builds a pc-to-position table per function: without it a
14207 /// trace could only name the function, not the line inside it.
14208 ///
14209 /// A frame whose code has no positions prints just `(file)`, matching the
14210 /// reference's output for stripped bytecode.
14211 pub fn stack_trace(&self) -> String {
14212 self.stack_trace_skipping(0)
14213 }
14214
14215 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
14216 fn stack_trace_skipping(&self, skip: usize) -> String {
14217 // One ordered list, innermost first, so `skip` counts the same thing whether the
14218 // frames it leaves out are native or bytecode. Indices rather than references: a
14219 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
14220 let depth = self.frames.len();
14221 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
14222 // A native entered while `at` bytecode frames were live was called *from* the
14223 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
14224 // entered at the current depth are therefore innermost of all.
14225 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
14226 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
14227 if *at == wanted {
14228 order.push((true, index));
14229 }
14230 }
14231 };
14232 push_natives(&mut order, depth);
14233 for index in (0..depth).rev() {
14234 order.push((false, index));
14235 push_natives(&mut order, index);
14236 }
14237 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
14238 // barrier. Natives entered at exactly the barrier depth are the eval entry point
14239 // itself (`evalScript (native)`), and the reference leaves those out too.
14240 if let Some(barrier) = self.trace_barriers.last().copied() {
14241 order.retain(|(is_native, index)| match is_native {
14242 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
14243 false => *index >= barrier,
14244 });
14245 }
14246
14247 let mut out = String::new();
14248 for (is_native, index) in order.into_iter().skip(skip) {
14249 match is_native {
14250 true => {
14251 out.push_str(" at ");
14252 let (native, _) = &self.native_frames[index];
14253 let name = native
14254 .own_property("name")
14255 .and_then(|property| property.value)
14256 .map(|value| value.to_js_string())
14257 .unwrap_or_default();
14258 out.push_str(&name);
14259 out.push_str(" (native)\n");
14260 }
14261 false => {
14262 let frame = &self.frames[index];
14263 let code = &frame.code.code;
14264 let file = code.filename.as_deref().unwrap_or("<input>");
14265 // The name comes from the function *object*, not from the compiled code:
14266 // an anonymous function expression is named by the property it is stored
14267 // in (`{valueOf: function(){}}`), which only the object knows.
14268 let bound_name = match &frame.callee {
14269 Value::Object(object) => {
14270 object
14271 .own_property("name")
14272 .and_then(|property| match property.value {
14273 Some(Value::String(text)) if !text.wtf8().is_empty() => {
14274 Some(text.to_string_lossy().into_owned())
14275 }
14276 _ => None,
14277 })
14278 }
14279 _ => None,
14280 };
14281 // No callee object means the body was entered by the host, so the
14282 // name has to come from the compiled code. Two cases differ:
14283 //
14284 // * an *unnamed* function of any kind — the reference reads the
14285 // `name` property, finds it empty, and prints `<anonymous>`;
14286 // * a *module* body, which has no `name` property at all: the
14287 // reference builds that function object with `js_closure2` and
14288 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
14289 // so a trace reaching it also prints `<anonymous>` — while a
14290 // *script* body prints `<eval>`, its `name`.
14291 let unnamed = code.name.is_empty() || code.module.is_some();
14292 out.push_str(" at ");
14293 match bound_name.as_deref() {
14294 Some(name) => out.push_str(name),
14295 None if unnamed => out.push_str("<anonymous>"),
14296 None => out.push_str(&code.name),
14297 }
14298 match code.position_at(frame.at as u32) {
14299 Some((line, column)) => {
14300 out.push_str(&format!(" ({file}:{line}:{column})\n"));
14301 }
14302 None => out.push_str(&format!(" ({file})\n")),
14303 }
14304 }
14305 }
14306 }
14307 out
14308 }
14309
14310 /// Give an anonymous function the name of the property it is stored in.
14311 ///
14312 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
14313 /// enumerable and not configurable, and a function that already has a real name
14314 /// keeps it.
14315 ///
14316 /// "Already named" means a *non-empty* name: every function object is created with
14317 /// a `name` of `""` so the property exists on all of them, and treating that empty
14318 /// string as a name left every anonymous function nameless — which is how a stack
14319 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
14320 /// `SetFunctionName`, for a name that came from source text.
14321 fn set_function_name(&mut self, function: &Value, name: &str) {
14322 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
14323 }
14324
14325 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
14326 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
14327 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
14328 let Value::Object(object) = function else {
14329 return;
14330 };
14331 // `SetFunctionName` applies to *functions* and classes only, and only when they are
14332 // anonymous. Without the callability guard, `{value: someObject}` renamed
14333 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
14334 // on the right-hand side of a property. That is how a `zipKeyed` result object
14335 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
14336 // has no `NamedEvaluation` at all.
14337 if !object.is_callable() {
14338 return;
14339 }
14340 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
14341 && !existing.wtf8().is_empty()
14342 {
14343 return;
14344 }
14345 let text = self.string_wtf8(name.clone());
14346 object.define("name", Property::name_or_length(text));
14347 }
14348
14349 // -- global declarations -----------------------------------------------
14350
14351 /// Declare a global binding, creating its reference cell.
14352 /// Declare a `var` or function global, whose home is the global object.
14353 ///
14354 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
14355 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
14356 /// such as `print`, or a redeclaration — is left alone.
14357 pub fn declare_var_global(&mut self, name: &str) {
14358 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
14359 // global object is exactly the leak `typeof my_var === "undefined"` after
14360 // `eval("var my_var=2")` rules out.
14361 if let Some(scope) = self.eval_scope.as_mut() {
14362 scope.entry(name.to_string()).or_insert(Value::Undefined);
14363 return;
14364 }
14365 // A sloppy direct eval declares into its *caller's* variable environment. Doing
14366 // this on the global object instead made `eval("var c = 1")` inside a parameter
14367 // list overwrite a global `c`, and made two calls to the same function share one
14368 // binding.
14369 if let Some(cell) = self.declare_eval_local(name) {
14370 cell.set(Value::Undefined);
14371 return;
14372 }
14373 let global = self.realm.global.clone();
14374 if global.own_property(name).is_some() {
14375 return;
14376 }
14377 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
14378 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
14379 // whole point of that trick and what lets `Object.defineProperty` reshape it
14380 // afterwards. `eval_scope` is `Some` while an eval is running.
14381 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
14382 global.define(
14383 name,
14384 Property {
14385 value: Some(Value::Undefined),
14386 writable: true,
14387 enumerable: true,
14388 configurable: from_eval,
14389 ..Property::default()
14390 },
14391 );
14392 }
14393
14394 /// Declare a *lexical* global binding, which starts in its dead zone.
14395 ///
14396 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
14397 /// global object and is created when its initialiser runs.
14398 pub fn declare_global(&mut self, name: &str, is_const: bool) {
14399 if is_const {
14400 self.realm.lexical_consts.insert(name.to_string());
14401 }
14402 if !self.realm.globals.contains_key(name) {
14403 // `Uninitialized` rather than `Undefined`: the binding exists but is not
14404 // readable until its initialiser runs, and that is what `let x` before
14405 // `x = 1` has to observe.
14406 let cell = self.new_cell(Value::Uninitialized);
14407 self.realm.globals.insert(name.to_string(), cell);
14408 self.realm.declared.push(name.to_string());
14409 }
14410 }
14411}
14412
14413/// The bytecode and environment of a function object, if it is a bytecode function.
14414///
14415/// Extracted before a call so no borrow of the object is held across it.
14416fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
14417 function.with(|data| match &data.kind {
14418 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
14419 _ => None,
14420 })
14421}
14422
14423/// A native call target, extracted before the call so no borrow is held.
14424enum NativeCall {
14425 Native(NativeFn),
14426 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
14427 /// not hold that object's `RefCell` borrow.
14428 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
14429 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
14430 Bound {
14431 target: Value,
14432 this: Value,
14433 leading: Vec<Value>,
14434 },
14435 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
14436 Revoker(crate::object::ProxyRef),
14437 /// A promise's `resolve`.
14438 PromiseResolve(Gc<JsObject>),
14439 /// A promise's `reject`.
14440 PromiseReject(Gc<JsObject>),
14441 /// The executor `NewPromiseCapability(C)` hands a user constructor.
14442 CapabilityExecutor {
14443 state: Gc<JsObject>,
14444 },
14445 /// One leg of a `then` that settles through a user capability.
14446 ThenShim {
14447 handler: Option<Value>,
14448 resolve: Value,
14449 reject: Value,
14450 fulfilled: bool,
14451 },
14452 /// One continuation of an `await`.
14453 AwaitResume {
14454 coroutine: Gc<JsObject>,
14455 promise: Gc<JsObject>,
14456 kind: ResumeKind,
14457 },
14458 /// One element of a `Promise` combinator settling.
14459 CombinatorSettle {
14460 state: Gc<JsObject>,
14461 index: usize,
14462 fulfilled: bool,
14463 },
14464 /// One of `Promise.prototype.finally`'s two shims.
14465 FinallyShim {
14466 callback: Option<Value>,
14467 fulfilled: bool,
14468 constructor: Value,
14469 },
14470 /// Settle a promise with a fixed outcome.
14471 SettlePromise {
14472 promise: Gc<JsObject>,
14473 value: Value,
14474 rejected: bool,
14475 },
14476 /// Continue an async generator after its `await` settled.
14477 GeneratorResume {
14478 generator: Gc<JsObject>,
14479 promise: Gc<JsObject>,
14480 kind: ResumeKind,
14481 },
14482 /// Read a module namespace's binding out of its cell.
14483 ModuleBinding(Gc<Cell>),
14484 /// Finish a completed async generator's `return(v)` once `v` has settled.
14485 CompletedReturn {
14486 generator: Gc<JsObject>,
14487 promise: Gc<JsObject>,
14488 rejected: bool,
14489 },
14490 /// Answer a pending async-generator method with `{value, done}`.
14491 YieldResult {
14492 generator: Gc<JsObject>,
14493 promise: Gc<JsObject>,
14494 done: bool,
14495 },
14496 /// One step of `AsyncDisposableStack.disposeAsync`.
14497 DisposeStep {
14498 remaining: Gc<JsObject>,
14499 promise: Gc<JsObject>,
14500 error: Value,
14501 rejected: bool,
14502 },
14503}
14504
14505/// What a store does when the object refuses the write.
14506#[derive(Clone, Copy, PartialEq, Eq)]
14507pub enum DeleteFailure {
14508 /// Raise a `TypeError`, which is what strict mode and every built-in does.
14509 Throw,
14510 /// Ignore the write, which is what a sloppy-mode assignment does.
14511 Ignore,
14512}
14513
14514/// Whether `object` is a `Date` instance, by the class tag it carries.
14515///
14516/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
14517/// builtins module depending on the interpreter's conversion order.
14518fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
14519 interp
14520 .internal_get(object, "_class")
14521 .is_some_and(|value| value.to_js_string() == "Date")
14522}
14523
14524/// Which type `ToPrimitive` prefers when it converts an object.
14525#[derive(Clone, Copy, PartialEq, Eq)]
14526pub enum Hint {
14527 /// The default hint, which behaves like [`Hint::Number`].
14528 Default,
14529 /// `Number(obj)` and the arithmetic operators.
14530 Number,
14531 /// `String(obj)` and `ToPropertyKey`.
14532 String,
14533}
14534
14535/// Which table a binding slot indexes, for the messages that name it.
14536#[derive(Clone, Copy)]
14537enum VarSlot {
14538 Loc,
14539 Closure,
14540}
14541
14542/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
14543fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
14544 Ok(this)
14545}
14546
14547/// An internal iterator: the sequence plus a cursor.
14548pub(crate) struct Iterator {
14549 pub(crate) object: Value,
14550 pub(crate) next: Value,
14551}
14552
14553/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
14554/// and plain `a` for a method.
14555///
14556/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
14557/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
14558/// reads `at get a (file:1:2)`.
14559/// The same prefixing, for a name that may hold an unpaired surrogate.
14560fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
14561 let prefix = match flags & 3 {
14562 1 => "get ",
14563 2 => "set ",
14564 _ => return key.clone(),
14565 };
14566 let mut units: Vec<u16> = prefix.encode_utf16().collect();
14567 units.extend_from_slice(&key.to_units());
14568 crate::value::Wtf8::from_units(&units)
14569}
14570
14571fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
14572 match flags & 3 {
14573 1 => format!("get {key}"),
14574 2 => format!("set {key}"),
14575 _ => key.to_string(),
14576 }
14577}
14578
14579/// Define a method or accessor property, per the `define_method` flag byte.
14580///
14581/// The low two bits pick value/getter/setter and bit 2 marks the property
14582/// enumerable.
14583///
14584/// A getter and a setter arrive as two separate `define_method` instructions, and the
14585/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
14586/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
14587/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
14588/// `JS_DefineProperty`, which leaves the other half alone.
14589fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
14590 let enumerable = flags & 4 != 0;
14591 let kind = flags & 3;
14592 let existing = object.own_property_key(key);
14593 let property = match kind {
14594 1 => Property {
14595 getter: Some(function),
14596 // The setter half, if this literal already defined one.
14597 setter: existing
14598 .filter(Property::is_accessor)
14599 .and_then(|p| p.setter),
14600 enumerable,
14601 configurable: true,
14602 ..Property::default()
14603 },
14604 2 => Property {
14605 getter: existing
14606 .filter(Property::is_accessor)
14607 .and_then(|p| p.getter),
14608 setter: Some(function),
14609 enumerable,
14610 configurable: true,
14611 ..Property::default()
14612 },
14613 _ => Property {
14614 value: Some(function),
14615 writable: true,
14616 enumerable,
14617 configurable: true,
14618 ..Property::default()
14619 },
14620 };
14621 object.define_key(key, property);
14622}
14623
14624// ---------------------------------------------------------------------------
14625// Operand decoding
14626// ---------------------------------------------------------------------------
14627
14628/// How `print` renders a value: the reference's `JS_PrintValue`.
14629///
14630/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
14631/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
14632/// The format is reproduced closely because the test suite compares output text:
14633///
14634/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
14635/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
14636/// * a cycle prints `[circular N]` with `N` the stack index of the object;
14637/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
14638/// end print as `<N empty item(s)>`;
14639/// * a string is quoted inside a container but raw at the top level, which is why
14640/// `print("x")` and `print(["x"])` differ.
14641pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
14642 // A string argument is printed raw: `js_print` converts it with `ToString`
14643 // instead of dumping it, and the quoting only appears inside a container.
14644 if let Value::String(text) = value {
14645 return text.to_string_lossy().into_owned();
14646 }
14647 let mut printer = Printer {
14648 interp,
14649 out: String::new(),
14650 stack: Vec::new(),
14651 };
14652 printer.value(value, 0);
14653 printer.out
14654}
14655
14656/// The internal class name an object carries, when it has one.
14657fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
14658 interp
14659 .internal_get(object, "_class")
14660 .map(|value| value.to_js_string())
14661}
14662
14663/// A string property, looked up the way `GetProperty` does: own first, then the
14664/// prototype chain. Needed because the print formatter holds the interpreter
14665/// immutably and so cannot run getters.
14666fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
14667 let mut current = Some(object.clone());
14668 // Bounded, because a prototype cycle would otherwise loop forever.
14669 for _ in 0..100 {
14670 let node = current?;
14671 if let Some(property) = node.own_property(name)
14672 && let Some(value) = property.value
14673 {
14674 return Some(value.to_js_string());
14675 }
14676 current = node.with(|data| data.proto.clone());
14677 }
14678 None
14679}
14680
14681/// The `JS_PrintValue` state: output, and the objects currently being printed.
14682struct Printer<'a, 'rt> {
14683 /// Kept for the class-name lookups that typed arrays and `Date` will need.
14684 #[allow(dead_code)]
14685 interp: &'a Interp<'rt>,
14686 out: String,
14687 stack: Vec<Gc<JsObject>>,
14688}
14689
14690impl Printer<'_, '_> {
14691 /// Depth past which a container is summarised by its class name.
14692 const MAX_DEPTH: usize = 2;
14693
14694 fn value(&mut self, value: &Value, level: usize) {
14695 match value {
14696 Value::Undefined
14697 | Value::Uninitialized
14698 | Value::Hole
14699 | Value::CatchOffset(_)
14700 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
14701 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
14702 // The printer writes a bigint the way the language spells one, so a dump is
14703 // unambiguous about which kind of number it is showing.
14704 Value::BigInt(big) => {
14705 self.out.push_str(&big.to_decimal_string());
14706 self.out.push('n');
14707 }
14708 Value::Null => self.out.push_str("null"),
14709 Value::Bool(true) => self.out.push_str("true"),
14710 Value::Bool(false) => self.out.push_str("false"),
14711 Value::Int(number) => self.out.push_str(&number.to_string()),
14712 Value::Float(number) => {
14713 self.out
14714 .push_str(&crate::value::number_to_string_for_print(*number));
14715 }
14716 Value::String(text) => self.print_string(&text.to_string_lossy()),
14717 Value::Object(object) => self.object(object, level),
14718 }
14719 }
14720
14721 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
14722 // A cycle is reported rather than followed; the index is where the object
14723 // already sits in the print stack, which is what the reference shows.
14724 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
14725 self.out.push_str(&format!("[circular {index}]"));
14726 return;
14727 }
14728 if object.is_callable() {
14729 let name = object
14730 .own_property("name")
14731 .and_then(|property| property.value)
14732 .map(|value| value.to_js_string())
14733 .unwrap_or_default();
14734 if name.is_empty() {
14735 self.out.push_str("[Function (anonymous)]");
14736 } else {
14737 self.out.push_str(&format!("[Function {name}]"));
14738 }
14739 return;
14740 }
14741 if level >= Self::MAX_DEPTH {
14742 let class = if object.is_array() { "Array" } else { "Object" };
14743 self.out.push_str(&format!("[{class}]"));
14744 return;
14745 }
14746 // `Date` and `Error` print as themselves rather than as bags of properties:
14747 // the ISO string, and `Name: message` followed by the trace.
14748 if let Some(class) = class_of(self.interp, object) {
14749 if class == "Date" {
14750 self.date(object);
14751 return;
14752 }
14753 if class == "Error" {
14754 self.error(object);
14755 return;
14756 }
14757 }
14758 self.stack.push(object.clone());
14759 if object.is_array() {
14760 self.array(object, level);
14761 } else {
14762 self.plain_object(object, level);
14763 }
14764 self.stack.pop();
14765 }
14766
14767 /// A Date prints as its ISO string; an invalid one falls through to the plain
14768 /// object form, the way the reference falls back when `toISOString` throws.
14769 fn date(&mut self, object: &Gc<JsObject>) {
14770 let value = self
14771 .interp
14772 .internal_get(object, "_date_value")
14773 .map(|value| value.to_number());
14774 match value.and_then(crate::builtins::date::iso_string) {
14775 Some(text) => self.out.push_str(&text),
14776 None => self.plain_object(object, 0),
14777 }
14778 }
14779
14780 /// `Name: message`, then the trace with its trailing newline removed.
14781 fn error(&mut self, object: &Gc<JsObject>) {
14782 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
14783 self.out.push_str(&name);
14784 if let Some(message) = inherited(object, "message")
14785 && !message.is_empty()
14786 {
14787 self.out.push_str(": ");
14788 self.out.push_str(&message);
14789 }
14790 if let Some(stack) = inherited(object, "stack") {
14791 self.out.push('\n');
14792 self.out.push_str(stack.trim_end_matches('\n'));
14793 }
14794 }
14795
14796 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
14797 let elements = object.array_elements().unwrap_or_default();
14798 self.out.push_str("[ ");
14799 // An interior hole means the array is "sparse": the reference prints those
14800 // as `index: value` pairs and says nothing about the holes themselves, while
14801 // a hole run at the end becomes a single `<N empty items>` note.
14802 let last_present = elements
14803 .iter()
14804 .rposition(|value| !matches!(value, Value::Hole));
14805 let has_interior_hole = match last_present {
14806 Some(last) => elements[..last]
14807 .iter()
14808 .any(|value| matches!(value, Value::Hole)),
14809 None => false,
14810 };
14811 let mut first = true;
14812 if has_interior_hole {
14813 let mut index = 0;
14814 while index < elements.len() {
14815 let value = &elements[index];
14816 if matches!(value, Value::Hole) {
14817 index += 1;
14818 continue;
14819 }
14820 if !first {
14821 self.out.push_str(", ");
14822 }
14823 first = false;
14824 self.out.push_str(&format!("{index}: "));
14825 self.value(value, level + 1);
14826 index += 1;
14827 }
14828 } else {
14829 for (index, value) in elements.iter().enumerate() {
14830 if matches!(value, Value::Hole) {
14831 continue;
14832 }
14833 if !first {
14834 self.out.push_str(", ");
14835 }
14836 first = false;
14837 let _ = index;
14838 self.value(value, level + 1);
14839 }
14840 if let Some(last) = last_present {
14841 let trailing = elements.len() - last - 1;
14842 if trailing > 0 {
14843 if !first {
14844 self.out.push_str(", ");
14845 }
14846 self.out.push_str(&format!(
14847 "<{trailing} empty item{}>",
14848 if trailing > 1 { "s" } else { "" }
14849 ));
14850 }
14851 } else if !elements.is_empty() {
14852 let count = elements.len();
14853 self.out.push_str(&format!(
14854 "<{count} empty item{}>",
14855 if count > 1 { "s" } else { "" }
14856 ));
14857 }
14858 }
14859 self.out.push_str(" ]");
14860 }
14861
14862 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
14863 self.out.push_str("{ ");
14864 let mut first = true;
14865 for key in object.own_keys() {
14866 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
14867 continue;
14868 };
14869 if !property.enumerable {
14870 continue;
14871 }
14872 if !first {
14873 self.out.push_str(", ");
14874 }
14875 first = false;
14876 self.out
14877 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
14878 &key.to_string_lossy(),
14879 )));
14880 self.out.push_str(": ");
14881 // An accessor has no value to dump; the reference names the half that
14882 // exists instead of calling it.
14883 if property.is_accessor() {
14884 let text = match (property.getter.is_some(), property.setter.is_some()) {
14885 (true, true) => "[Getter/Setter]",
14886 (false, true) => "[Setter]",
14887 _ => "[Getter]",
14888 };
14889 self.out.push_str(text);
14890 } else {
14891 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
14892 }
14893 }
14894 self.out.push_str(" }");
14895 }
14896
14897 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
14898 fn print_string(&mut self, text: &str) {
14899 self.out.push('"');
14900 for character in text.chars() {
14901 match character {
14902 '"' => self.out.push_str("\\\""),
14903 '\\' => self.out.push_str("\\\\"),
14904 '\n' => self.out.push_str("\\n"),
14905 '\r' => self.out.push_str("\\r"),
14906 '\t' => self.out.push_str("\\t"),
14907 c if (c as u32) < 0x20 => {
14908 self.out.push_str(&format!("\\u{:04x}", c as u32));
14909 }
14910 c => self.out.push(c),
14911 }
14912 }
14913 self.out.push('"');
14914 }
14915}
14916
14917/// How `print` renders a value.
14918///
14919/// `ToString`, except that negative zero keeps its sign — the reference's host
14920/// printer does that while `String(-0)` is `"0"`.
14921pub fn display(value: &Value) -> String {
14922 match value {
14923 Value::Float(number) => crate::value::number_to_string_for_print(*number),
14924 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
14925 "undefined".to_string()
14926 }
14927 other => other.to_js_string(),
14928 }
14929}
14930
14931// ---------------------------------------------------------------------------
14932// Numeric operators
14933// ---------------------------------------------------------------------------
14934
14935/// `a + b` keeping the `Int` representation when it fits.
14936fn add_numbers(left: Value, right: Value) -> Value {
14937 match (&left, &right) {
14938 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
14939 Some(sum) => Value::Int(sum),
14940 None => Value::Float(*a as f64 + *b as f64),
14941 },
14942 _ => Value::Float(left.to_number() + right.to_number()),
14943 }
14944}
14945
14946/// The arithmetic operators other than `+`, which needs string concatenation.
14947fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14948 use Opcode::*;
14949 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
14950 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
14951 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
14952 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
14953 return Ok(match op {
14954 And => Value::Int(x & y),
14955 Or => Value::Int(x | y),
14956 Xor => Value::Int(x ^ y),
14957 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
14958 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
14959 Shr => match (*x as u32) >> ((*y as u32) & 31) {
14960 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
14961 shifted => Value::Float(shifted as f64),
14962 },
14963 Sub => match x.checked_sub(*y) {
14964 Some(value) => Value::Int(value),
14965 None => Value::Float(*x as f64 - *y as f64),
14966 },
14967 _ => return arithmetic_slow(op, left, right),
14968 });
14969 }
14970 arithmetic_slow(op, left, right)
14971}
14972
14973/// [`arithmetic`] for everything the integer fast path above does not take.
14974fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14975 use Opcode::*;
14976 let (a, b) = (left.to_number(), right.to_number());
14977 Ok(match op {
14978 Sub => match (&left, &right) {
14979 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
14980 Some(value) => Value::Int(value),
14981 None => Value::Float(a - b),
14982 },
14983 _ => Value::Float(a - b),
14984 },
14985 Mul => Value::Float(a * b),
14986 Div => Value::Float(a / b),
14987 Mod => Value::Float(js_mod(a, b)),
14988 Pow => Value::Float(a.powf(b)),
14989 And => Value::Int(left.to_int32() & right.to_int32()),
14990 Or => Value::Int(left.to_int32() | right.to_int32()),
14991 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
14992 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
14993 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
14994 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
14995 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
14996 // fits the small-integer representation stays an `Int`; the rest become a
14997 // float, which is how the reference keeps `n >>> 0` non-negative.
14998 Shr => {
14999 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15000 match i32::try_from(shifted) {
15001 Ok(value) => Value::Int(value),
15002 Err(_) => Value::Float(shifted as f64),
15003 }
15004 }
15005 _ => Value::Float(a),
15006 })
15007}
15008
15009/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
15010///
15011/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
15012/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
15013/// slow path where the rules live.
15014fn is_number(value: &Value) -> bool {
15015 matches!(value, Value::Int(_) | Value::Float(_))
15016}
15017
15018/// The `Value::Bool` a comparison operator answers for `ordering`.
15019///
15020/// `None` is the unordered case — a `NaN` on either side — and every operator answers
15021/// false for it, including `<=` and `>=`.
15022fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
15023 use Opcode::*;
15024 let answer = match (op, ordering) {
15025 (_, None) => false,
15026 (Lt, Some(ordering)) => ordering.is_lt(),
15027 (Lte, Some(ordering)) => ordering.is_le(),
15028 (Gt, Some(ordering)) => ordering.is_gt(),
15029 (Gte, Some(ordering)) => ordering.is_ge(),
15030 _ => false,
15031 };
15032 Value::Bool(answer)
15033}
15034
15035/// `%`, which follows the sign of the dividend rather than Rust's.
15036fn js_mod(left: f64, right: f64) -> f64 {
15037 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
15038 return f64::NAN;
15039 }
15040 if right.is_infinite() {
15041 return left;
15042 }
15043 let remainder = left % right;
15044 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
15045 // the spec makes the sign match the dividend.
15046 if remainder == 0.0 {
15047 0.0f64.copysign(left)
15048 } else {
15049 remainder
15050 }
15051}
15052
15053fn negate(value: Value) -> Value {
15054 match value {
15055 Value::Int(0) => Value::Float(-0.0),
15056 Value::Int(i) => Value::Int(-i),
15057 other => Value::Float(-other.to_number()),
15058 }
15059}
15060
15061fn increment(value: Value) -> Value {
15062 match value {
15063 Value::Int(i) => match i.checked_add(1) {
15064 Some(next) => Value::Int(next),
15065 None => Value::Float(i as f64 + 1.0),
15066 },
15067 other => Value::Float(other.to_number() + 1.0),
15068 }
15069}
15070
15071fn decrement(value: Value) -> Value {
15072 match value {
15073 Value::Int(i) => match i.checked_sub(1) {
15074 Some(next) => Value::Int(next),
15075 None => Value::Float(i as f64 - 1.0),
15076 },
15077 other => Value::Float(other.to_number() - 1.0),
15078 }
15079}
15080
15081/// Compare a `BigInt` with an `f64` on their mathematical values.
15082///
15083/// Neither side is rounded to the other's precision: the number is split into its integer
15084/// part (compared as an exact bigint) and its fraction, which is what decides the answer
15085/// when the integer parts are equal. An infinite value is larger than every bigint.
15086fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
15087 use std::cmp::Ordering;
15088 if number.is_nan() {
15089 return None;
15090 }
15091 if number.is_infinite() {
15092 return Some(if number > 0.0 {
15093 Ordering::Less
15094 } else {
15095 Ordering::Greater
15096 });
15097 }
15098 let truncated = number.trunc();
15099 // A number wider than `i128` still has an exact integer part, but no bigint form we can
15100 // build cheaply; the sign of the difference is all that is needed, so compare against
15101 // the bigint's own magnitude instead.
15102 if truncated.abs() >= 1.7e38 {
15103 let big_as_f64 = big.to_f64();
15104 return big_as_f64.partial_cmp(&number);
15105 }
15106 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
15107 match big.cmp(&integer) {
15108 Ordering::Equal => {
15109 // Same integer part: the fraction decides, and a negative number's fraction is
15110 // below the integer (`-1.5` truncates to `-1`).
15111 if number > truncated {
15112 Some(Ordering::Less)
15113 } else if number < truncated {
15114 Some(Ordering::Greater)
15115 } else {
15116 Some(Ordering::Equal)
15117 }
15118 }
15119 other => Some(other),
15120 }
15121}
15122
15123/// `CanonicalNumericIndexString(argument)` (§7.1.21).
15124///
15125/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
15126/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
15127/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
15128/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
15129/// rather than treating it as `0`.
15130fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
15131 let PropertyKey::String(text) = key else {
15132 // A symbol is never an index.
15133 return None;
15134 };
15135 let text = text.to_string_lossy();
15136 if text == "-0" {
15137 return Some(-0.0);
15138 }
15139 let number: f64 = text.parse().ok()?;
15140 // The round-trip test *is* the definition: only the canonical spelling qualifies.
15141 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
15142 // `"0.10"` does not.
15143 let rendered = Value::Float(number).to_js_string();
15144 (rendered == text).then_some(number)
15145}
15146
15147/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
15148///
15149/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
15150/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
15151/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
15152/// numeric and invalid, which is why they stop the prototype chain instead of falling
15153/// through it.
15154///
15155/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
15156/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
15157/// `in`, `delete` and `defineProperty` separately to make sure it does not.
15158fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
15159 numeric.is_finite()
15160 && numeric.fract() == 0.0
15161 && !(numeric == 0.0 && numeric.is_sign_negative())
15162 && numeric >= 0.0
15163 && object
15164 .typed_array_length()
15165 .is_some_and(|length| (numeric as usize) < length)
15166}