quickjs/interp.rs
1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25 Callable, ClassDef, ClassId, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars,
26 NativeFn, ObjectKind, Opaque, Property, PropertyKey, array_index, has_own, lookup_key,
27 lookup_key_above, same_proto,
28};
29use crate::value::{Cell, Value, number_to_string};
30
31/// Why execution stopped.
32#[derive(Debug, Clone)]
33pub enum Signal {
34 /// A JavaScript exception carrying the thrown value.
35 Throw(Value),
36 /// The runtime ran out of memory.
37 OutOfMemory,
38}
39
40/// What an execution step produced.
41pub type JsResult<T> = std::result::Result<T, Signal>;
42
43/// The result of one instruction.
44enum Step {
45 /// Keep executing the current frame.
46 Continue,
47 /// The current frame returned this value.
48 Return(Value),
49 /// The frame parked at a suspension point, with the yielded value on its stack.
50 ///
51 /// Only a generator or an async function can produce this, and only its own frame —
52 /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
53 /// detached and handed to the generator object, which is what lets it resume later
54 /// with its locals and operand stack intact.
55 Suspend(SuspendKind),
56}
57
58/// Why a frame parked, which decides how the resumption is delivered.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum SuspendKind {
61 /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
62 /// without passing a value, because there is no `yield` expression to receive one.
63 Initial,
64 /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
65 Yield,
66 /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
67 /// `{value, done}` object from the inner iterator and is handed straight back.
68 YieldStar,
69 /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
70 /// what was yielded is the plain value and still has to be awaited and wrapped —
71 /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
72 /// made it pass a bare value through as if it were an iterator result, so
73 /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
74 AsyncYieldStar,
75 /// `await expr`: the value is a promise the async machinery has to settle first.
76 Await,
77}
78
79/// Everything one JavaScript realm owns.
80///
81/// A realm is the set of objects a script can reach without naming them: the global
82/// object, the prototype chain roots, and the global binding cells.
83pub struct Realm {
84 /// The global object.
85 pub global: Gc<JsObject>,
86 /// `Object.prototype`.
87 pub object_proto: Gc<JsObject>,
88 /// `Function.prototype`, which is itself callable.
89 pub function_proto: Gc<JsObject>,
90 /// `Array.prototype`.
91 pub array_proto: Gc<JsObject>,
92 /// The **intrinsic** `%Object.prototype.toString%`.
93 ///
94 /// Not a lookup on `Object.prototype`: `Array.prototype.toString` names the intrinsic
95 /// directly, so `delete Object.prototype.toString` does not change its fallback
96 /// (`Array/prototype/toString/non-callable-join-string-tag` deletes it and then calls
97 /// `Array.prototype.toString` on a dozen receivers).
98 pub object_proto_to_string: Option<Gc<JsObject>>,
99 /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
100 pub array_constructor: Option<Gc<JsObject>>,
101 /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
102 pub promise_constructor: Option<Gc<JsObject>>,
103 /// Reference cells for globals declared by the script.
104 ///
105 /// A declared global is read with `get_var` (by name) but written with
106 /// `put_var_ref` (through the cell), so the cell is what makes a function
107 /// declaration and its uses agree on one binding.
108 pub globals: BTreeMap<String, Gc<Cell>>,
109 /// Names of the globals that came from a *declaration*, which are
110 /// non-configurable properties of the global object.
111 pub declared: Vec<String>,
112 /// Names among the lexical globals that are `const`.
113 ///
114 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
115 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
116 /// path does not carry, so a store through it would look like a plain `let`. The
117 /// realm records it once, at declaration, and answers for every reader.
118 pub lexical_consts: BTreeSet<String>,
119 /// The error constructors by class name, so a runtime error can throw a real
120 /// `TypeError` instance rather than a look-alike object.
121 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
122 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
123 pub string_proto: Option<Gc<JsObject>>,
124 /// `Number.prototype`.
125 pub number_proto: Option<Gc<JsObject>>,
126 /// `Boolean.prototype`.
127 pub boolean_proto: Option<Gc<JsObject>>,
128 /// `BigInt.prototype`.
129 pub bigint_proto: Option<Gc<JsObject>>,
130 /// `Error.prototype`, the prototype of every error instance.
131 pub error_proto: Gc<JsObject>,
132 /// `Date.prototype`, so the constructor can build an instance in the
133 /// function-call form (`Date()` returns a string) without going through `new`.
134 pub date_proto: Gc<JsObject>,
135 /// `%ThrowTypeError%`, the single frozen thrower behind every restricted property.
136 ///
137 /// §10.2.4 makes it *one* object per realm, and the identity is observable: test262's
138 /// whole `ThrowTypeError/` directory finds it through
139 /// `Object.getOwnPropertyDescriptor(function(){"use strict"; return arguments;}(),
140 /// "callee").get` and then asserts on its `length`, `name`, prototype and frozenness.
141 /// Creating a fresh one per property would make
142 /// `getOwnPropertyDescriptor(Function.prototype, "caller").get ===
143 /// getOwnPropertyDescriptor(Function.prototype, "arguments").get` false.
144 pub throw_type_error: Option<Gc<JsObject>>,
145 /// `%GeneratorPrototype%`, the prototype of every generator object.
146 pub generator_proto: Gc<JsObject>,
147 /// `Promise.prototype`, the prototype of every promise.
148 pub promise_proto: Option<Gc<JsObject>>,
149 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
150 pub async_generator_proto: Option<Gc<JsObject>>,
151 /// `%AsyncIteratorPrototype%`, the prototype of `%AsyncGeneratorPrototype%`.
152 ///
153 /// It carries exactly two methods — `@@asyncIterator` and `@@asyncDispose` — and is the
154 /// object test262 reaches through
155 /// `Object.getPrototypeOf(Object.getPrototypeOf(generator.prototype))`.
156 pub async_iterator_proto: Option<Gc<JsObject>>,
157 /// `Symbol.prototype`.
158 pub symbol_proto: Option<Gc<JsObject>>,
159 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
160 /// `_date_value`.
161 ///
162 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
163 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
164 /// language does not have and `new Error()` listed `_class` beside `message` and
165 /// `stack` — and a caller that copies every own property (which
166 /// `Object.create(null, props)` effectively does) tried to write an internal name and
167 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
168 /// and `JSON.stringify`, while remaining an ordinary traced property.
169 ///
170 /// `RefCell` because interning is memoisation rather than observable state: filling the
171 /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
172 /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
173 /// built while reporting a failure must not require an exclusive borrow.
174 pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
175
176 /// The `Symbol.for` registry: `key -> symbol`.
177 ///
178 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
179 /// symbol every time within one script while a fresh realm starts empty.
180 pub symbol_registry: BTreeMap<String, Value>,
181 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
182 pub regexp_proto: Option<Gc<JsObject>>,
183 /// The `RegExp` constructor.
184 pub regexp_ctor: Option<Gc<JsObject>>,
185 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
186 ///
187 /// The prototype rather than the constructor on purpose: a script that replaces
188 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
189 /// error wrapping, which the `using` test suite checks explicitly.
190 pub suppressed_error_proto: Option<Gc<JsObject>>,
191 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
192 pub disposable_stack_proto: Option<Gc<JsObject>>,
193 /// `Map.prototype`.
194 pub map_proto: Option<Gc<JsObject>>,
195 /// `Set.prototype`.
196 pub set_proto: Option<Gc<JsObject>>,
197 /// Every live `FinalizationRegistry`, held weakly.
198 ///
199 /// The cleanup callback has to run from a *safe point* — a place where script is not
200 /// already executing and no engine borrow is held — and the collector cannot enumerate
201 /// heap objects by type. Registering each registry here gives the drain a list to walk.
202 ///
203 /// The handles are weak on purpose: a registry the script dropped must be collectable,
204 /// and it must not be resurrected merely because the drain knew about it. Entries whose
205 /// target has expired are swept out as the drain walks, so the vector does not grow
206 /// without bound in a program that creates many short-lived registries.
207 pub finalization_registries: Vec<WeakGc<JsObject>>,
208 /// `ArrayBuffer.prototype`.
209 pub array_buffer_proto: Option<Gc<JsObject>>,
210 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
211 pub typed_array_proto: Option<Gc<JsObject>>,
212 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
213 ///
214 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
215 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
216 /// `"Object"` and `r instanceof Int32Array` is false.
217 pub typed_array_protos: Vec<Gc<JsObject>>,
218 /// `DataView.prototype`.
219 pub data_view_proto: Option<Gc<JsObject>>,
220 /// The `AsyncDisposableStack` prototype.
221 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
222 /// `CreateAsyncFromSyncIterator`, as a script function.
223 ///
224 /// `GetIterator(obj, async)` has to wrap the synchronous iterator it falls back to, and
225 /// the wrapper's state machine is written in JavaScript (see
226 /// [`crate::builtins::async_from_sync`]). Holding the factory here is what lets the Rust
227 /// side call it without a global name a script could shadow.
228 pub async_from_sync: Option<Value>,
229 /// `Iterator.prototype`.
230 pub iterator_proto: Option<Gc<JsObject>>,
231 /// The `Iterator` constructor itself.
232 ///
233 /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
234 /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
235 /// place it can live is the realm.
236 pub iterator_ctor: Option<Gc<JsObject>>,
237 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
238 ///
239 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
240 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
241 /// `[object Iterator Helper]`).
242 pub iterator_helper_proto: Option<Gc<JsObject>>,
243 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
244 /// that was not already an `Iterator`.
245 ///
246 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
247 /// untouched and does *not* override `@@toStringTag`, so
248 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
249 pub iterator_wrap_proto: Option<Gc<JsObject>>,
250 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
251 pub generator_function_proto: Option<Gc<JsObject>>,
252 /// `%AsyncFunction.prototype%`.
253 pub async_function_proto: Option<Gc<JsObject>>,
254 /// `%AsyncGeneratorFunction.prototype%`.
255 pub async_generator_function_proto: Option<Gc<JsObject>>,
256 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
257 ///
258 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
259 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
260 /// prototype per iterator made every array iterator's prototype distinct.
261 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
262 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
263 ///
264 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
265 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
266 /// both faster and impossible to break from a script.
267 well_known_symbols: WellKnownSymbols,
268 /// The classes the host registered, and the prototype each one hands its instances.
269 pub host_classes: HostClasses,
270 /// `[[TemplateMap]]` — §13.2.8.1 `GetTemplateObject`'s registry, keyed by call site.
271 ///
272 /// The spec keys it by *parse node*, which the runtime does not have; a compiled code
273 /// object plus the index of the `push_const` that names the template is the same
274 /// thing, because that pair is exactly one source location. It also gives the answer
275 /// the tests demand for `eval`: each `eval` call compiles a fresh code object, so two
276 /// calls of `eval("tag`${a}`")` see different objects while two iterations of a loop
277 /// *inside* one eval see the same one (`cache-eval-inner-function`).
278 template_map: std::collections::HashMap<u32, js_gc::WeakGc<JsObject>>,
279}
280
281/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
282///
283/// One per realm, because a class id is only meaningful within the runtime that handed it
284/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
285/// a host class cannot collide.
286pub struct HostClasses {
287 /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
288 /// `JS_GetOpaque(val, 0)` has to match nothing.
289 next_id: u32,
290 /// What each registered class does.
291 defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
292 /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
293 ///
294 /// A strong reference, so the prototype a host installed outlives every script
295 /// reference to it — which is what `JS_SetClassProto` promises.
296 protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
297}
298
299impl HostClasses {
300 fn new() -> HostClasses {
301 HostClasses {
302 next_id: 1,
303 defs: std::collections::BTreeMap::new(),
304 protos: std::collections::BTreeMap::new(),
305 }
306 }
307
308 /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
309 pub fn register(&mut self, def: ClassDef) -> ClassId {
310 let id = ClassId::from_raw(self.next_id);
311 self.next_id += 1;
312 self.defs.insert(id, std::rc::Rc::new(def));
313 id
314 }
315
316 /// Register `def` under an id the caller already has (`JS_NewClass`).
317 ///
318 /// The C API splits "get an id" from "register a class" because a module may be
319 /// initialised lazily; registering twice under one id replaces the definition, and an
320 /// object created under the old one keeps the old behaviour, since it carries its own
321 /// reference.
322 pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
323 if !id.is_valid() {
324 return false;
325 }
326 // Keep the counter past any id handed out explicitly, so a later `register` cannot
327 // reuse one.
328 self.next_id = self.next_id.max(id.get() + 1);
329 self.defs.insert(id, std::rc::Rc::new(def));
330 true
331 }
332
333 /// What `id` was registered with.
334 pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
335 self.defs.get(&id).cloned()
336 }
337
338 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
339 pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
340 self.protos.insert(id, proto);
341 }
342
343 /// The prototype installed for `id`, if the host installed one.
344 pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
345 self.protos.get(&id).cloned()
346 }
347
348 /// How many classes the host registered.
349 pub fn len(&self) -> usize {
350 self.defs.len()
351 }
352
353 /// Whether no class has been registered.
354 pub fn is_empty(&self) -> bool {
355 self.defs.is_empty()
356 }
357}
358
359impl Default for HostClasses {
360 fn default() -> HostClasses {
361 HostClasses::new()
362 }
363}
364
365/// One binding of the frame that called `eval`, so the eval'd code can read and
366/// write it by name.
367struct EvalBinding {
368 /// The name it was declared with.
369 name: String,
370 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
371 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
372 /// a function that declares `a` must find that `a`.
373 frame: usize,
374 /// Which table of that frame it lives in.
375 slot: EvalSlot,
376 /// The slot index within that table.
377 index: usize,
378}
379
380/// Which table of a frame an [`EvalBinding`] indexes.
381#[derive(Clone, Copy)]
382enum EvalSlot {
383 Arg,
384 Local,
385}
386
387/// One activation record.
388struct Frame {
389 /// The bytecode being run.
390 code: Gc<CompiledCode>,
391 /// The cells this closure captured.
392 env: Gc<ClosureEnv>,
393 /// The `this` binding.
394 this: Value,
395 /// Argument slots, sized to the declared parameter count.
396 args: Vec<Value>,
397 /// How many values the caller actually passed, which is what `arguments.length`
398 /// reports and what `...rest` slices from.
399 passed_count: usize,
400 /// The passed values, **only when they do not fit in [`Self::args`]**.
401 ///
402 /// `args` is sized to the declared parameters, so a call that passes no more than
403 /// that already holds every passed value in its first `passed_count` slots — copying
404 /// them here as well was two writes and a buffer per call, on the hottest path in
405 /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
406 /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
407 /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
408 /// its own copy.
409 ///
410 /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
411 /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
412 /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
413 /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
414 /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
415 /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
416 #[allow(clippy::box_collection)]
417 passed_overflow: Option<Box<Vec<Value>>>,
418 /// Local slots.
419 locals: Vec<Value>,
420 /// Reference cells for this frame's own captured bindings.
421 cells: Vec<Gc<Cell>>,
422 /// The operand stack.
423 stack: Vec<Value>,
424 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
425 local_vars: Option<Gc<LocalVars>>,
426
427 /// Index of the next instruction, not a byte offset.
428 ///
429 /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
430 /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
431 /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
432 /// `Frame`, and `frames.push` copies the whole struct on every call.
433 pc: usize,
434 /// Byte offset of the instruction being executed, which is what a stack trace
435 /// reports. `pc` has already moved past it by the time an instruction runs.
436 ///
437 /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
438 at: usize,
439 /// The callee, so a native builtin can tell which constructor it is.
440 callee: Value,
441 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
442 new_target: Value,
443 /// What this frame costs against [`Interp::stack_limit`], in bytes.
444 ///
445 /// Cached rather than recomputed because it is charged on every call and a call is the
446 /// hottest thing in the interpreter.
447 cost: usize,
448 /// [`Interp::stack_used`] before this frame was pushed.
449 ///
450 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
451 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
452 /// leave the counter wrong. There are eight places that drop frames; one subtraction
453 /// forgotten in any of them would leak budget until the depth limit moved.
454 stack_base: usize,
455 /// Whether this frame's body ended in a `tail_call`.
456 ///
457 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
458 /// with its own frame just like `call` does and only skips storing the result
459 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
460 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
461 /// pushed as usual, and this marker makes its return value the *caller's* return
462 /// value without running the instructions after the call.
463 tail: bool,
464}
465
466impl Frame {
467 /// Read a local slot, taking the frame as `self`.
468 ///
469 /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
470 /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
471 /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
472 /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
473 /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
474 #[inline]
475 fn read_loc(&self, slot: usize) -> Value {
476 let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
477 if cell == -1 {
478 return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
479 }
480 match self.cells.get(cell as usize) {
481 Some(cell) => cell.get(),
482 None => Value::Undefined,
483 }
484 }
485
486 /// [`Self::read_loc`] for an argument slot.
487 #[inline]
488 fn read_arg(&self, slot: usize) -> Value {
489 let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
490 if cell == -1 {
491 return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
492 }
493 match self.cells.get(cell as usize) {
494 Some(cell) => cell.get(),
495 None => Value::Undefined,
496 }
497 }
498
499 /// The values the caller actually passed, which is what `arguments` exposes.
500 ///
501 /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
502 fn passed(&self) -> &[Value] {
503 match &self.passed_overflow {
504 Some(values) => values,
505 None => &self.args[..self.passed_count],
506 }
507 }
508
509 /// The decoded instructions of the function this frame runs.
510 ///
511 /// A method rather than `frame.code.insns` at the call site so that the borrow is
512 /// obviously of the frame — the dispatch loop holds one across a `get`.
513 fn insns(&self) -> &[crate::insn::Insn] {
514 &self.code.insns
515 }
516}
517
518impl js_gc::Trace for Frame {
519 fn trace(&self, tracer: &mut js_gc::Tracer) {
520 self.code.trace(tracer);
521 self.env.trace(tracer);
522 self.this.trace(tracer);
523 for value in &self.args {
524 value.trace(tracer);
525 }
526 for value in self.passed() {
527 value.trace(tracer);
528 }
529 for value in &self.locals {
530 value.trace(tracer);
531 }
532 for cell in &self.cells {
533 cell.trace(tracer);
534 }
535 if let Some(local_vars) = &self.local_vars {
536 tracer.visit(local_vars);
537 }
538 for value in &self.stack {
539 value.trace(tracer);
540 }
541 self.callee.trace(tracer);
542 self.new_target.trace(tracer);
543 }
544}
545
546/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
547/// emitted `if_false` treats as "keep going".
548/// How many finished frames' value buffers are kept for reuse.
549const RECYCLE_SLOTS: usize = 8;
550
551/// The largest buffer worth keeping. See [`Interp::free_values`].
552const RECYCLE_MAX_CAPACITY: usize = 4096;
553
554const RESUME_NEXT: i32 = 0;
555/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
556/// generator fall into its `return_async`.
557const RESUME_RETURN: i32 = 1;
558/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
559/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
560/// must forward the exception into the inner iterator rather than finish.
561const RESUME_THROW: i32 = 2;
562
563/// One microtask.
564///
565/// The queue holds *data* rather than closures because its contents are GC values: a
566/// closure would be invisible to the collector, and a pending reaction is exactly the
567/// kind of thing that must keep its handlers and its promise alive.
568pub enum Job {
569 /// A `then` reaction about to run.
570 Reaction {
571 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
572 handler: Option<Value>,
573 /// The value or reason to call it with.
574 argument: Value,
575 /// Whether the source promise rejected, which decides the pass-through kind.
576 rejected: bool,
577 /// The promise the answer settles.
578 promise: Gc<JsObject>,
579 },
580 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
581 Thenable {
582 /// The `then` that was found on the value.
583 then: Value,
584 /// The thenable itself, which becomes `then`'s `this`.
585 value: Value,
586 /// The promise being resolved.
587 promise: Gc<JsObject>,
588 },
589 /// A pending `import(specifier)`.
590 Import {
591 /// The specifier, already converted to a string.
592 specifier: String,
593 /// The module that asked, which the specifier resolves against.
594 referrer: String,
595 /// The promise `import()` handed back.
596 promise: Gc<JsObject>,
597 },
598 /// An async generator resuming after the value it awaited settled.
599 GeneratorResume {
600 /// The async generator to continue.
601 generator: Gc<JsObject>,
602 /// The promise the pending method returned.
603 promise: Gc<JsObject>,
604 /// Whether this delivers the value or raises the reason.
605 kind: ResumeKind,
606 /// The settled value, or the rejection reason.
607 value: Value,
608 },
609 /// An async function resuming after the value it awaited settled.
610 Resume {
611 /// The body, parked in a coroutine.
612 coroutine: Gc<JsObject>,
613 /// The promise the async function handed its caller.
614 promise: Gc<JsObject>,
615 /// Whether this resumption delivers a value or raises one.
616 kind: ResumeKind,
617 /// The settled value, or the rejection reason.
618 value: Value,
619 },
620}
621
622/// One macro-task: work the event loop owes the script but has not run yet.
623///
624/// The microtask queue ([`Job`]) is different: those run before the host regains control.
625/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
626/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
627/// logic: the engine decides *what* is due, the host decides *how to wait*.
628///
629/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
630/// reference counting even though nothing else references it — the same rule the `HostFn`
631/// documentation states from the other side (a host closure must not hold a `Gc`, so the
632/// `Gc` lives here instead).
633pub enum Task {
634 /// A `setTimeout` that is due at `due_at`.
635 ///
636 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
637 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
638 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
639 /// would give this engine a timer the reference cannot produce, with nothing to
640 /// compare it against.
641 Timer {
642 /// The id `setTimeout` returned, for `clearTimeout`.
643 id: i32,
644 /// What to call when it fires.
645 callback: Value,
646 /// When it becomes runnable, as a monotonic instant.
647 due_at: std::time::Instant,
648 },
649}
650
651/// A descriptor the host has to poll, and which directions have a handler.
652///
653/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
654/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
655/// blocks on it, and the host reports back through [`Interp::fire_fd`].
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
657pub struct FdInterest {
658 /// The descriptor to watch.
659 pub fd: i32,
660 /// Whether `os.setReadHandler` registered a callback.
661 pub read: bool,
662 /// Whether `os.setWriteHandler` registered a callback.
663 pub write: bool,
664}
665
666/// The callbacks registered for one descriptor, per direction.
667#[derive(Default)]
668pub(crate) struct FdHandlers {
669 /// `os.setReadHandler`'s callback.
670 pub read: Option<Value>,
671 /// `os.setWriteHandler`'s callback.
672 pub write: Option<Value>,
673}
674
675/// The file name `eval` reports, which the reference does not inherit from the caller.
676///
677/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
678/// reference and the names show up in stack traces.
679/// The description of the private symbol a class brand is made from.
680///
681/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
682/// place no script can reach, since no expression can name a private symbol.
683const BRAND_DESCRIPTION: &str = "brand";
684
685/// One validated property lookup.
686///
687/// Covers both own-property hits and prototype hits. The second kind was deliberately left
688/// uncached at first ("a prototype hit depends on more than the object and the name"), and
689/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
690/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
691/// names on every iteration (measured: 100 ns per call over an empty loop).
692pub struct FieldCache {
693 /// The name, so two different properties of one object do not collide.
694 key: PropertyKey,
695 /// Where the value was found, relative to the chain below.
696 index: usize,
697 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
698 level: u8,
699 /// The receiver and every prototype down to (and including) the level that answered,
700 /// each with the length of its property table at the time.
701 ///
702 /// That length is the whole guard, and it is sufficient for the ways the answer can
703 /// change without a lookup: adding or deleting any property moves it, and a
704 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
705 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
706 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
707 /// the one that was cached.
708 ///
709 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
710 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
711 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
712}
713
714/// How many links of a prototype chain a [`FieldCache`] remembers.
715///
716/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
717/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
718/// at three.
719const MAX_CACHED_CHAIN: usize = 3;
720
721/// A remembered global-variable lookup.
722///
723/// A `var` global is an ordinary property of the global object, so reading one walks the
724/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
725/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
726/// fixed by the bytecode, and the slot in the object's table only changes if the global
727/// object is mutated, which the index-and-name check below catches.
728pub struct GlobalCache {
729 /// The global object the lookup was resolved on, weakly.
730 object: js_gc::WeakGc<JsObject>,
731 /// Index of the data property in the global object's table.
732 index: usize,
733}
734
735/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
736const GLOBAL_CACHE_SLOTS: usize = 1024;
737
738/// How many property lookups are remembered.
739///
740/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
741/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
742/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
743/// lookup itself. Making it bigger stops helping: the working set of a real program's
744/// property sites is bounded by its code size.
745const FIELD_CACHE_SLOTS: usize = 4096;
746
747/// How much the heap may grow past the last `out of memory` before saying it again.
748///
749/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
750/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
751/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
752/// because it looks like it works. The reference gets this for free: it fails inside
753/// `js_malloc`, and its printing path happens not to allocate.
754///
755/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
756/// allocating is stopped within a rounding error of the limit) and far above what a
757/// handler needs.
758const OOM_HYSTERESIS: usize = 64 * 1024;
759
760/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
761pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
762
763/// How many instructions run between polls of [`Interp::interrupt`].
764///
765/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
766/// order of magnitude on both implementations — which is what lets a C driver compare its
767/// output byte for byte (see `scripts/m15-capi.sh --embed`).
768pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
769
770/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
771///
772/// Chosen so that the byte budget is what actually decides for every ordinary
773/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
774/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
775/// millions of frames.
776pub const MAX_FRAMES: usize = 200_000;
777
778const EVAL_FILE: &str = "<input>";
779
780/// The file name `std.evalScript` reports.
781const EVAL_SCRIPT_FILE: &str = "<evalScript>";
782
783/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
784///
785/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
786/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
787fn clamp_delay(delay_ms: f64) -> std::time::Duration {
788 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
789 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
790 // non-positive delay mean "due now".
791 if delay_ms.is_nan() || delay_ms <= 0.0 {
792 return std::time::Duration::ZERO;
793 }
794 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
795}
796
797impl js_gc::Trace for Task {
798 fn trace(&self, tracer: &mut js_gc::Tracer) {
799 let Task::Timer { callback, .. } = self;
800 callback.trace(tracer);
801 }
802}
803
804/// What one turn of the event loop did, so the caller cannot spin by accident.
805///
806/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
807/// core until the timer is due. Naming the three cases makes the wait explicit.
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809pub enum Turn {
810 /// Something ran. Call again immediately — there may be more ready work.
811 Ran,
812 /// Nothing is runnable, but descriptors are registered: the host must poll
813 /// [`Interp::pending_fds`] for at most this long, then report readiness with
814 /// [`Interp::fire_fd`].
815 ///
816 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
817 /// the failure this project treats as worst — a handler that silently never fires —
818 /// so the two cannot be confused by accident.
819 Poll(std::time::Duration),
820 /// Nothing is runnable yet, but something is pending. Block at most this long, then
821 /// call again.
822 Wait(std::time::Duration),
823 /// Nothing is pending at all: the loop is done.
824 Done,
825}
826
827impl js_gc::Trace for Job {
828 fn trace(&self, tracer: &mut js_gc::Tracer) {
829 match self {
830 Job::Reaction {
831 handler,
832 argument,
833 promise,
834 ..
835 } => {
836 if let Some(handler) = handler {
837 handler.trace(tracer);
838 }
839 argument.trace(tracer);
840 tracer.visit(promise);
841 }
842 Job::Thenable {
843 then,
844 value,
845 promise,
846 } => {
847 then.trace(tracer);
848 value.trace(tracer);
849 tracer.visit(promise);
850 }
851 Job::Resume {
852 coroutine,
853 promise,
854 value,
855 ..
856 } => {
857 tracer.visit(coroutine);
858 tracer.visit(promise);
859 value.trace(tracer);
860 }
861 Job::Import { promise, .. } => tracer.visit(promise),
862 Job::GeneratorResume {
863 generator,
864 promise,
865 value,
866 ..
867 } => {
868 tracer.visit(generator);
869 tracer.visit(promise);
870 value.trace(tracer);
871 }
872 }
873 }
874}
875
876/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
877#[derive(Debug, Clone, Copy, PartialEq, Eq)]
878pub enum ResumeKind {
879 /// The generator was just created and is being run to its first suspension.
880 Start,
881 /// `next(v)`.
882 Next,
883 /// `return(v)`.
884 Return,
885 /// `throw(e)`.
886 Throw,
887}
888
889/// A generator object's saved execution.
890///
891/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
892/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
893/// separately allocated buffers.
894pub struct GeneratorState {
895 /// The detached frame, or `None` once the generator has finished or while it runs.
896 frame: Option<Frame>,
897 /// How far it got.
898 phase: GeneratorPhase,
899 /// Whether the last suspension was an `await` rather than a `yield`.
900 ///
901 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
902 /// value and a magic number, because the emitted code branches on which method
903 /// resumed it, while an `await` simply continues with its value. Getting this wrong
904 /// leaves an extra value on the operand stack that the next instruction then
905 /// consumes — a wrong answer rather than a crash.
906 parked_on_await: bool,
907 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
908 ///
909 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
910 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
911 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
912 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
913 /// delegating. Tracking it as part of the phase, the way the reference splits
914 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
915 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
916 /// exception and never reached `xs.throw`.
917 parked_on_yield_star: bool,
918 /// Pending `next`/`return`/`throw` calls, oldest first.
919 ///
920 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
921 /// called back to back must answer in that order, with the second call's value
922 /// arriving at the *second* `yield`. Running each call straight into the body — which
923 /// is what this engine did before — delivered the last queued value to whichever
924 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
925 /// `a === b ===` the final argument.
926 ///
927 /// The front entry is the one being served; it stays there (with `async_busy` set)
928 /// until its promise settles, because an `await` inside the body is a suspension of
929 /// the *driver*, not the end of the request.
930 requests: std::collections::VecDeque<AsyncRequest>,
931 /// Whether the front request is in flight.
932 async_busy: bool,
933 /// Whether this came from an `async function*`.
934 ///
935 /// A sync generator and an async one share `ObjectKind::Generator`, so without this
936 /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
937 /// `AsyncGeneratorValidate` has to tell them apart
938 /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
939 pub is_async: bool,
940}
941
942/// How one async-generator request ended.
943enum AsyncOutcome {
944 /// The method answered this `{value, done}`.
945 Value(Value),
946 /// The body threw.
947 Error(Value),
948}
949
950/// One queued `next`/`return`/`throw` on an async generator: the reference's
951/// `JSAsyncGeneratorRequest`.
952pub struct AsyncRequest {
953 /// Which method was called.
954 kind: ResumeKind,
955 /// Its argument.
956 value: Value,
957 /// The promise the method answered.
958 promise: Gc<JsObject>,
959}
960
961/// Which of §27.5.3.3's states a generator is in.
962#[derive(Debug, Clone, Copy, PartialEq, Eq)]
963enum GeneratorPhase {
964 /// Created, `initial_yield` reached, body not entered.
965 SuspendedStart,
966 /// Parked at a `yield`.
967 SuspendedYield,
968 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
969 Executing,
970 /// Finished; the frame is gone.
971 Completed,
972}
973
974impl js_gc::Trace for GeneratorState {
975 fn trace(&self, tracer: &mut js_gc::Tracer) {
976 if let Some(frame) = &self.frame {
977 frame.trace(tracer);
978 }
979 for request in &self.requests {
980 request.value.trace(tracer);
981 tracer.visit(&request.promise);
982 }
983 }
984}
985
986/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
987/// them in.
988///
989/// Each is a field rather than a map entry because the runtime reads them on hot paths
990/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
991/// failure — reaching a default here means the builtin did not install, and every
992/// accessor panics rather than silently answering `undefined`.
993///
994/// [`builtins::symbol`]: crate::builtins::symbol
995#[derive(Default)]
996pub struct WellKnownSymbols {
997 /// The symbol values, positionally. Empty until `Symbol` installs.
998 symbols: Vec<Value>,
999}
1000
1001/// Which well-known symbol a caller wants.
1002///
1003/// A typed accessor beats passing a name around: a typo is a compile error rather than
1004/// an `undefined` key that quietly matches nothing.
1005#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1006pub enum WellKnown {
1007 /// `Symbol.toPrimitive`.
1008 ToPrimitive,
1009 /// `Symbol.iterator`.
1010 Iterator,
1011 /// `Symbol.match`.
1012 Match,
1013 /// `Symbol.matchAll`.
1014 MatchAll,
1015 /// `Symbol.replace`.
1016 Replace,
1017 /// `Symbol.search`.
1018 Search,
1019 /// `Symbol.split`.
1020 Split,
1021 /// `Symbol.toStringTag`.
1022 ToStringTag,
1023 /// `Symbol.isConcatSpreadable`.
1024 IsConcatSpreadable,
1025 /// `Symbol.hasInstance`.
1026 HasInstance,
1027 /// `Symbol.species`.
1028 Species,
1029 /// `Symbol.unscopables`.
1030 Unscopables,
1031 /// `Symbol.asyncIterator`.
1032 AsyncIterator,
1033 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1034 Disposable,
1035 /// `Symbol.asyncDispose` — the awaited form.
1036 AsyncDisposable,
1037}
1038
1039impl WellKnown {
1040 /// The index `Symbol`'s installer creates this symbol at.
1041 fn index(self) -> usize {
1042 match self {
1043 WellKnown::ToPrimitive => 0,
1044 WellKnown::Iterator => 1,
1045 WellKnown::Match => 2,
1046 WellKnown::MatchAll => 3,
1047 WellKnown::Replace => 4,
1048 WellKnown::Search => 5,
1049 WellKnown::Split => 6,
1050 WellKnown::ToStringTag => 7,
1051 WellKnown::IsConcatSpreadable => 8,
1052 WellKnown::HasInstance => 9,
1053 WellKnown::Species => 10,
1054 WellKnown::Unscopables => 11,
1055 WellKnown::AsyncIterator => 12,
1056 WellKnown::Disposable => 13,
1057 WellKnown::AsyncDisposable => 14,
1058 }
1059 }
1060}
1061
1062impl Realm {
1063 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1064 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1065 self.well_known_symbols.symbols = symbols;
1066 }
1067
1068 /// A well-known symbol.
1069 pub fn well_known(&self, which: WellKnown) -> Value {
1070 self.well_known_symbols
1071 .symbols
1072 .get(which.index())
1073 .cloned()
1074 .unwrap_or(Value::Undefined)
1075 }
1076
1077 /// The well-known symbol as a property key.
1078 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1079 match self.well_known(which) {
1080 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1081 // Unreachable once `Symbol` has installed; an empty string key matches
1082 // nothing, which degrades to "the object has no such method".
1083 _ => PropertyKey::from(String::new()),
1084 }
1085 }
1086}
1087
1088/// The interpreter: a realm plus a frame stack.
1089pub struct Interp<'a> {
1090 /// The heap everything is allocated on.
1091 pub heap: &'a Heap,
1092 /// The realm.
1093 pub realm: Realm,
1094 /// Active frames, outermost first.
1095 frames: Vec<Frame>,
1096 /// Value buffers from frames that have finished, reused by the next call.
1097 ///
1098 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1099 /// the locals and the operand stack — and free all four on return. `call:recursion`
1100 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1101 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1102 ///
1103 /// Bounded in both directions: a few buffers per kind, and none larger than
1104 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1105 /// and keeping its buffer would pin that memory for the rest of the run.
1106 free_values: Vec<Vec<Value>>,
1107 /// A strict-mode `eval`'s own variable scope, while its script runs.
1108 ///
1109 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1110 /// become a global. Name lookups still fall through to the realm, which is why
1111 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1112 eval_scope: Option<BTreeMap<String, Value>>,
1113 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1114 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1115 eval_depth: usize,
1116 /// The calling frame's own bindings, which the running `eval` can read and write.
1117 ///
1118 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1119 /// come from the frame, and a write is applied back to the frame (or to the cell
1120 /// the frame captured) when the eval finishes. That is what makes
1121 /// `f("a = 3")` visible to the caller as `a === 3`.
1122 eval_bindings: Vec<EvalBinding>,
1123 /// The calling frame's `arguments`, while an `eval` runs.
1124 ///
1125 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1126 /// own yet still has to see the caller's `arguments`.
1127 eval_arguments: Option<Value>,
1128 /// The `with` objects live at the moment the running `eval` started, innermost first.
1129 ///
1130 /// `None` outside an eval, which is what keeps a finished block's object from
1131 /// shadowing ordinary bytecode reads.
1132 eval_with: Option<Vec<Gc<JsObject>>>,
1133 /// The bindings the running direct `eval` makes visible, as name → cell.
1134 ///
1135 /// Set for the duration of an eval and then restored, but every closure created
1136 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1137 /// `eval("f = () => i")` work after the eval has returned.
1138 active_eval_scope: Option<Gc<EvalScope>>,
1139 /// The frame that called the direct `eval` currently running, if any.
1140 ///
1141 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1142 /// on the global object, which is what keeps
1143 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1144 /// gives each call its own `x`.
1145 eval_caller: Option<Option<usize>>,
1146 /// The caller's `new.target`, while an `eval` runs.
1147 ///
1148 /// The eval'd code is a script with no constructor of its own, so it inherits the
1149 /// one the enclosing function was called with.
1150 eval_new_target: Option<Value>,
1151 /// `new.target` for the frame about to be pushed.
1152 ///
1153 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1154 /// value reaches the frame without threading a parameter through every call site.
1155 ///
1156 /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1157 /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1158 /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1159 /// value was parked for the outer call and never consumed.
1160 pending_new_target: Option<Value>,
1161 /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1162 ///
1163 /// `undefined` outside a `new` call.
1164 active_new_target: Value,
1165 /// Names of the native functions currently executing, outermost first.
1166 ///
1167 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1168 /// trace still names it with `(native)` instead of a position, so the names are
1169 /// tracked separately and stitched into [`Interp::stack_trace`].
1170 ///
1171 /// The third field is how many bytecode frames were live when the native was entered,
1172 /// which is what places it *among* them rather than before all of them. Native
1173 /// functions used to be emitted up front on the grounds that they never re-enter
1174 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1175 /// The natives currently running, innermost last: the function object and the
1176 /// depth it was entered at.
1177 ///
1178 /// The *name* is deliberately not stored. It used to be, read with
1179 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1180 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1181 /// benchmark. A stack trace is built rarely; it can read the name then.
1182 native_frames: Vec<(Gc<JsObject>, usize)>,
1183 /// The native function currently executing, for the ones that have to know *which*
1184 /// function they are — a typed-array constructor reads its element type off itself.
1185 ///
1186 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1187 /// reports whatever the enclosing bytecode frame was called with.
1188 current_native: Option<Gc<JsObject>>,
1189 /// Text written by `print` and friends, in order.
1190 ///
1191 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1192 /// once at the end, which is also when upstream's line buffering becomes
1193 /// visible for the cases compared here.
1194 pub output: String,
1195 /// Where `print` also writes, as it goes. `output` keeps the full log for
1196 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1197 ///
1198 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1199 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1200 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1201 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1202 /// would show a script's output all at once when it finished.
1203 pub output_sink: Option<Box<dyn std::io::Write>>,
1204 /// Where recent property reads found their value.
1205 ///
1206 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1207 /// table remembering *which object* and *which entry of its property table* answered a
1208 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1209 /// can move; the property can become an accessor), which is what makes a stale entry a
1210 /// miss rather than a wrong answer.
1211 ///
1212 /// The object is held weakly: a cache that held it strongly would keep up to
1213 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1214 /// program cannot see and cannot work around.
1215 pub field_cache: Vec<Option<FieldCache>>,
1216 /// Global lookups, by binding slot. See [`GlobalCache`].
1217 global_cache: Vec<Option<GlobalCache>>,
1218 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1219 /// under its limit. See [`Interp::check_memory`].
1220 pub oom_reported_at: usize,
1221 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1222 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1223 ///
1224 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1225 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1226 /// host that wants to stop a runaway script must not have to wait for it to return.
1227 ///
1228 /// Two things this cannot do, both of them differences a host can observe:
1229 ///
1230 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1231 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1232 /// needs a signal that the `catch` machinery does not see, which is a change to
1233 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1234 /// a host that stops the script itself.
1235 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1236 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1237 /// both, so the difference is when the counter hits zero, not whether it will.
1238 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1239 /// Instructions until the next [`Interp::interrupt`] poll.
1240 pub interrupt_counter: u32,
1241 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1242 ///
1243 /// A separate field from [`Interp::uncatchable`] because the two live for different
1244 /// spans. This one is the host's standing request; it survives the start of an
1245 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1246 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1247 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1248 /// cleared it before the script it was set for had a chance to throw.
1249 pub uncatchable_next: bool,
1250 /// Whether the exception now unwinding may be caught by a `catch`.
1251 ///
1252 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1253 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1254 /// a host stopping a runaway loop is not fought by the loop.
1255 ///
1256 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1257 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1258 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1259 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1260 pub uncatchable: bool,
1261 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1262 ///
1263 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1264 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1265 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1266 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1267 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1268 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1269 ///
1270 /// The numbers come out close for the same reason a C frame and a heap frame of this
1271 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1272 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1273 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1274 /// `crates/quickjs-cli/tests/limits.rs`.
1275 pub stack_limit: usize,
1276 /// The most frames that may be live at once, whatever the byte budget says.
1277 ///
1278 /// A second bound for a reason the reference does not have: our frames cost less than
1279 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1280 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1281 /// `--stack-size 1G` from being a memory bomb.
1282 pub max_frames: usize,
1283 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1284 ///
1285 /// Script execution does not return until this has drained, which is what makes
1286 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1287 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1288 /// not a `for`.
1289 pub(crate) jobs: std::collections::VecDeque<Job>,
1290 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1291 ///
1292 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1293 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1294 pub(crate) tasks: Vec<Task>,
1295 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1296 /// barrier'd evaluation started.
1297 ///
1298 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1299 /// lets a REPL report an error from the line it just evaluated without also reporting
1300 /// its own readline loop.
1301 trace_barriers: Vec<usize>,
1302 /// `os.signal` handlers, keyed by signal number.
1303 ///
1304 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1305 /// a handler cannot be freed while it is still registered.
1306 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1307 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1308 ///
1309 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1310 /// that is only reachable from a host closure could be freed while still registered.
1311 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1312 /// The next timer id.
1313 ///
1314 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1315 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1316 next_timer_id: i32,
1317 /// Errors thrown by timer callbacks, already rendered.
1318 ///
1319 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1320 /// that throws has no promise behind it. Both are reported by the host at the end of
1321 /// the loop, but only one is fixed up by a later `.catch`.
1322 timer_errors: Vec<String>,
1323 /// The module registry, keyed by canonical name.
1324 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1325 /// How the host turns a specifier into bytes.
1326 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1327 /// The module the host was asked to run, for `import.meta.main`.
1328 pub main_module_name: Option<String>,
1329 /// The name to register the *entry* module under, when the host supplies one.
1330 ///
1331 /// The entry's bytes come from a path on disk; this is the name the module graph should
1332 /// know it by. They differ for a host that evaluates a file it did not write — a test
1333 /// runner that prepends a harness, a bundler, a REPL — and getting it wrong is visible:
1334 /// a module importing *itself* resolves the specifier against the real path, finds no
1335 /// record under that name, and loads a second copy with its own bindings.
1336 pub entry_module_name: Option<String>,
1337 /// Module bodies currently running, innermost last.
1338 ///
1339 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1340 /// this is the only place that knows which module that is.
1341 pub module_stack: Vec<String>,
1342 /// Rejections that no handler has claimed, with the promise they belong to.
1343 ///
1344 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1345 /// reason alone cannot say whether somebody eventually listened.
1346 unhandled: Vec<(Gc<JsObject>, Value)>,
1347}
1348
1349impl<'a> Interp<'a> {
1350 /// Build an interpreter over `heap`, with a fresh realm.
1351 pub fn new(heap: &'a Heap) -> Interp<'a> {
1352 let object_proto = JsObject::ordinary(heap, None);
1353 let function_proto = JsObject::function(
1354 heap,
1355 Some(object_proto.clone()),
1356 Callable::Native {
1357 func: |_, _, _| Ok(Value::Undefined),
1358 own_instance: false,
1359 },
1360 );
1361 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1362 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1363 let mut interp = Interp {
1364 heap,
1365 realm: Realm {
1366 global,
1367 object_proto,
1368 function_proto,
1369 array_proto,
1370 array_constructor: None,
1371 promise_constructor: None,
1372 object_proto_to_string: None,
1373 globals: BTreeMap::new(),
1374 declared: Vec::new(),
1375 lexical_consts: BTreeSet::new(),
1376 errors: BTreeMap::new(),
1377 string_proto: None,
1378 number_proto: None,
1379 boolean_proto: None,
1380 bigint_proto: None,
1381 error_proto: JsObject::ordinary(heap, None),
1382 date_proto: JsObject::ordinary(heap, None),
1383 throw_type_error: None,
1384 generator_proto: JsObject::ordinary(heap, None),
1385 promise_proto: None,
1386 async_generator_proto: None,
1387 async_iterator_proto: None,
1388 symbol_proto: None,
1389 symbol_registry: BTreeMap::new(),
1390 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1391 regexp_proto: None,
1392 regexp_ctor: None,
1393 suppressed_error_proto: None,
1394 disposable_stack_proto: None,
1395 map_proto: None,
1396 set_proto: None,
1397 finalization_registries: Vec::new(),
1398 array_buffer_proto: None,
1399 typed_array_proto: None,
1400 typed_array_protos: Vec::new(),
1401 data_view_proto: None,
1402 async_disposable_stack_proto: None,
1403 async_from_sync: None,
1404 iterator_proto: None,
1405 iterator_ctor: None,
1406 iterator_helper_proto: None,
1407 iterator_wrap_proto: None,
1408 generator_function_proto: None,
1409 async_function_proto: None,
1410 async_generator_function_proto: None,
1411 iterator_protos: std::collections::BTreeMap::new(),
1412 well_known_symbols: WellKnownSymbols::default(),
1413 host_classes: HostClasses::new(),
1414 template_map: std::collections::HashMap::new(),
1415 },
1416 frames: Vec::new(),
1417 free_values: Vec::new(),
1418 global_cache: {
1419 let mut cache = Vec::new();
1420 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1421 cache
1422 },
1423 eval_scope: None,
1424 eval_depth: 0,
1425 eval_bindings: Vec::new(),
1426 eval_arguments: None,
1427 eval_with: None,
1428 active_eval_scope: None,
1429 eval_caller: None,
1430 pending_new_target: None,
1431 active_new_target: Value::Undefined,
1432 eval_new_target: None,
1433 native_frames: Vec::new(),
1434 current_native: None,
1435 output: String::new(),
1436 output_sink: None,
1437 field_cache: {
1438 let mut cache = Vec::new();
1439 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1440 cache
1441 },
1442 oom_reported_at: 0,
1443 interrupt: None,
1444 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1445 uncatchable_next: false,
1446 uncatchable: false,
1447 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1448 // absent.
1449 stack_limit: DEFAULT_STACK_SIZE,
1450 max_frames: MAX_FRAMES,
1451 jobs: std::collections::VecDeque::new(),
1452 tasks: Vec::new(),
1453 trace_barriers: Vec::new(),
1454 signal_handlers: std::collections::BTreeMap::new(),
1455 fd_handlers: std::collections::BTreeMap::new(),
1456 next_timer_id: 1,
1457 timer_errors: Vec::new(),
1458 modules: std::collections::BTreeMap::new(),
1459 module_loader: None,
1460 main_module_name: None,
1461 entry_module_name: None,
1462 module_stack: Vec::new(),
1463 unhandled: Vec::new(),
1464 };
1465 crate::builtins::install(&mut interp);
1466 interp
1467 }
1468
1469 // -- allocation helpers -------------------------------------------------
1470
1471 /// A new string value.
1472 /// A `BigInt` value from a computed big integer.
1473 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1474 Value::BigInt(Gc::new(self.heap, value))
1475 }
1476
1477 /// A string value from bytes that are already WTF-8, which is how a string with an
1478 /// unpaired surrogate reaches a `Value`.
1479 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1480 Value::string_wtf8(self.heap, text)
1481 }
1482
1483 /// A new string value, from text that is valid UTF-8.
1484 pub fn string(&self, text: impl Into<String>) -> Value {
1485 Value::string(self.heap, text)
1486 }
1487
1488 /// A new ordinary object with the given prototype.
1489 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1490 JsObject::ordinary(self.heap, proto)
1491 }
1492
1493 // -- host classes -------------------------------------------------------
1494
1495 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1496 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1497 self.realm.host_classes.register(def)
1498 }
1499
1500 /// Register `def` under an id the host already holds (`JS_NewClass`).
1501 ///
1502 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1503 /// `JS_NewClass`.
1504 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1505 self.realm.host_classes.define(id, def)
1506 }
1507
1508 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1509 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1510 self.realm.host_classes.set_proto(id, proto);
1511 }
1512
1513 /// The prototype installed for `id`, if any.
1514 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1515 self.realm.host_classes.proto(id)
1516 }
1517
1518 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1519 ///
1520 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1521 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1522 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1523 /// host installed none.
1524 ///
1525 /// Answers `None` for an id that was never registered: the C API would return an
1526 /// exception, and silently making an ordinary object instead would move the failure to
1527 /// the first `JS_GetOpaque` that no longer matches.
1528 pub fn new_host_object(
1529 &mut self,
1530 proto: Option<Gc<JsObject>>,
1531 class_id: ClassId,
1532 ) -> Option<Gc<JsObject>> {
1533 let class = self.realm.host_classes.def(class_id)?;
1534 let proto = proto
1535 .or_else(|| self.realm.host_classes.proto(class_id))
1536 .or_else(|| Some(self.realm.object_proto.clone()));
1537 Some(JsObject::host_object(self.heap, proto, class_id, class))
1538 }
1539
1540 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1541 ///
1542 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1543 /// object, it is an object of another class, or the class never got a payload. A host
1544 /// that has to tell them apart uses [`JsObject::host_class_id`].
1545 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1546 let object = value.as_object()?;
1547 if object.host_class_id()? != class_id {
1548 return None;
1549 }
1550 object.host_opaque()
1551 }
1552
1553 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1554 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1555 match value.as_object() {
1556 Some(object) => object.set_host_opaque(opaque),
1557 None => false,
1558 }
1559 }
1560
1561 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1562 ///
1563 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1564 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1565 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1566 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1567 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1568 /// said `[object Object]` instead of `[object Array Iterator]`.
1569 ///
1570 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1571 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1572 /// its own.
1573 pub fn new_iterator_prototype(
1574 &mut self,
1575 tag: &str,
1576 next: crate::object::NativeFn,
1577 ) -> Gc<JsObject> {
1578 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1579 return existing.clone();
1580 }
1581 let parent = self.realm.iterator_proto.clone();
1582 let proto = self.new_object(parent);
1583 let next = self.new_native("next", 0, next);
1584 proto.define(
1585 "next",
1586 Property::with_attributes(Value::Object(next), true, false),
1587 );
1588 let key = self.realm.well_known_key(WellKnown::Iterator);
1589 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1590 proto.define_key(
1591 &key,
1592 Property::with_attributes(Value::Object(identity), true, false),
1593 );
1594 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1595 let tag_value = self.string(tag);
1596 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1597 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1598 // checks it.
1599 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1600 self.realm
1601 .iterator_protos
1602 .insert(tag.to_string(), proto.clone());
1603 proto
1604 }
1605
1606 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1607 ///
1608 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1609 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1610 /// produced. That is why the two branches are not merged.
1611 pub fn object_own_property_keys(
1612 &mut self,
1613 object: &Gc<JsObject>,
1614 ) -> JsResult<Vec<PropertyKey>> {
1615 if let Some(keys) = self.proxy_own_keys(object)? {
1616 return Ok(keys);
1617 }
1618 // Integer-like keys ascending, then the string keys in insertion order, then the
1619 // symbols — the order every schema that walks an object expects.
1620 let entries = object.property_entries();
1621 let mut numeric: Vec<u32> = Vec::new();
1622 // An integer-indexed exotic object reports its indices as own keys even though they
1623 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1624 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1625 // order). The length is asked per call, so a resizable buffer's view reports the
1626 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1627 if object.typed_array_parts().is_some() {
1628 for index in 0..object.typed_array_length().unwrap_or(0) {
1629 // `u32::try_from` cannot fail for a real length, but the length is a
1630 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1631 // as an array index and one element beyond is not.
1632 match u32::try_from(index) {
1633 Ok(index) => numeric.push(index),
1634 Err(_) => break,
1635 }
1636 }
1637 }
1638 let mut strings: Vec<PropertyKey> = Vec::new();
1639 let mut symbols: Vec<PropertyKey> = Vec::new();
1640 for (key, _) in entries {
1641 match &key {
1642 // A class-private name is never reported by any enumeration: that is the
1643 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1644 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1645 // symbol skip, `Object.assign`) therefore cannot see it.
1646 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1647 PropertyKey::Symbol(_) => symbols.push(key),
1648 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1649 Some(index) => {
1650 if !numeric.contains(&index) {
1651 numeric.push(index);
1652 }
1653 }
1654 None => strings.push(key),
1655 },
1656 }
1657 }
1658 // An array's `length` is an own property from the moment the array exists, so it
1659 // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1660 // as `["length", "a"]`, not `["a", "length"]`
1661 // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1662 // than stored in the property table, which is why it has to be placed here.
1663 if object.is_array() && object.proxy_state().is_none() {
1664 // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1665 // the property table, at whatever position the *define* happened, but the key
1666 // lists it as the array's oldest string property because that is what it is.
1667 if let Some(position) = strings
1668 .iter()
1669 .position(|key| key.as_str() == Some("length"))
1670 {
1671 strings.remove(position);
1672 }
1673 strings.insert(0, PropertyKey::from("length"));
1674 }
1675 numeric.sort_unstable();
1676 let mut keys: Vec<PropertyKey> = numeric
1677 .into_iter()
1678 .map(|index| PropertyKey::from(index.to_string()))
1679 .collect();
1680 keys.extend(strings);
1681 keys.extend(symbols);
1682 Ok(keys)
1683 }
1684
1685 /// The state behind a promise object, or `None` when `object` is not one.
1686 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1687 object.with(|data| match &data.kind {
1688 ObjectKind::Promise(state) => Some(state.clone()),
1689 _ => None,
1690 })
1691 }
1692
1693 /// A new pending promise.
1694 pub fn new_promise(&mut self) -> Gc<JsObject> {
1695 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1696 // the one place every promise is built, and a subclass that builds its instances
1697 // somewhere else would be invisible to `instanceof`.
1698 let default = self.realm.promise_proto.clone();
1699 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1700 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1701 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1702 // `prototype` getter therefore still gets a working promise; the alternative is a
1703 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1704 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1705 Self::make_promise_object(self.heap, proto)
1706 }
1707
1708 /// A promise object with an explicit prototype, and nothing else.
1709 ///
1710 /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1711 /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1712 /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1713 /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1714 pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1715 let promise = JsObject::ordinary(heap, proto);
1716 promise.with_mut(|data| {
1717 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1718 crate::object::PromiseState::default(),
1719 )));
1720 });
1721 promise
1722 }
1723
1724 /// Fulfil `promise`, unless it has already settled.
1725 ///
1726 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1727 /// after `reject`, changes nothing.
1728 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1729 let Some(state) = self.promise_state(promise) else {
1730 return;
1731 };
1732 let reactions = {
1733 let mut state = state.borrow_mut();
1734 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1735 return;
1736 }
1737 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1738 std::mem::take(&mut state.reactions)
1739 };
1740 self.queue_reactions(reactions, value, false);
1741 }
1742
1743 /// Reject `promise`, unless it has already settled.
1744 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1745 let Some(state) = self.promise_state(promise) else {
1746 return;
1747 };
1748 let reactions = {
1749 let mut state = state.borrow_mut();
1750 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1751 return;
1752 }
1753 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1754 std::mem::take(&mut state.reactions)
1755 };
1756 // Remember it only when nothing is listening *now*; a `then` registered later
1757 // prunes the entry in `perform_then`.
1758 if reactions.is_empty() {
1759 self.unhandled.push((promise.clone(), reason.clone()));
1760 }
1761 self.queue_reactions(reactions, reason, true);
1762 }
1763
1764 /// Queue one job per reaction.
1765 ///
1766 /// This is what makes `then` asynchronous even on an already-settled promise:
1767 /// `p.then(f); g()` calls `g` first.
1768 fn queue_reactions(
1769 &mut self,
1770 reactions: Vec<crate::object::PromiseReaction>,
1771 argument: Value,
1772 rejected: bool,
1773 ) {
1774 for reaction in reactions {
1775 let handler = if rejected {
1776 reaction.on_rejected.clone()
1777 } else {
1778 reaction.on_fulfilled.clone()
1779 };
1780 self.jobs.push_back(Job::Reaction {
1781 handler,
1782 argument: argument.clone(),
1783 rejected,
1784 promise: reaction.promise,
1785 });
1786 }
1787 }
1788
1789 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1790 /// resolve/reject pair.
1791 ///
1792 /// The pair are callable objects rather than Rust closures, because the script gets
1793 /// them and may stash them for later.
1794 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1795 let promise = self.new_promise();
1796 // Both handlers are built-ins with an empty name and length 1, in
1797 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1798 // off `Object.getOwnPropertyNames`.
1799 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1800 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1801 (promise, Value::Object(resolve), Value::Object(reject))
1802 }
1803
1804 /// §27.2.1.5 `NewPromiseCapability(C)`.
1805 ///
1806 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1807 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1808 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1809 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1810 /// silently ignored argument.
1811 ///
1812 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1813 /// the engine's own executor is exactly what `new_promise_capability` builds.
1814 pub fn new_promise_capability_for(
1815 &mut self,
1816 constructor: &Value,
1817 ) -> JsResult<(Value, Value, Value)> {
1818 let Some(object) = constructor.as_object().cloned() else {
1819 return Err(self.type_error("promise constructor is not a constructor"));
1820 };
1821 if !object.is_constructor() {
1822 return Err(self.type_error("promise constructor is not a constructor"));
1823 }
1824 if self
1825 .realm
1826 .promise_constructor
1827 .as_ref()
1828 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1829 {
1830 let (promise, resolve, reject) = self.new_promise_capability();
1831 return Ok((Value::Object(promise), resolve, reject));
1832 }
1833 let state = self.new_object(Some(self.realm.object_proto.clone()));
1834 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1835 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1836 // which only a *custom* constructor can observe, and none of the combinator tests
1837 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1838 let executor = self.builtin_function(
1839 "",
1840 2,
1841 Callable::CapabilityExecutor {
1842 state: state.clone(),
1843 },
1844 );
1845 let promise = self.construct(
1846 Value::Object(object.clone()),
1847 Value::Object(object),
1848 vec![Value::Object(executor)],
1849 )?;
1850 // The pair is read *after* the constructor returns, so a constructor that never
1851 // called its executor, or called it with non-callables, is the spec's step 11
1852 // `TypeError` — not something the engine can paper over.
1853 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1854 return Err(self.type_error("promise executor never ran"));
1855 };
1856 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1857 return Err(self.type_error("promise executor never ran"));
1858 };
1859 for handler in [&resolve, &reject] {
1860 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1861 return Err(self.type_error("promise capability handler is not callable"));
1862 }
1863 }
1864 Ok((promise, resolve, reject))
1865 }
1866
1867 /// §27.2.3.1 `PromiseResolve(C, x)`.
1868 ///
1869 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1870 /// an `x` that is already a promise of exactly this constructor is handed back
1871 /// unchanged, and anything else gets a fresh capability from `C`.
1872 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1873 if let Value::Object(object) = &value
1874 && self.promise_state(object).is_some()
1875 {
1876 // `x.constructor === C` means "already the right kind", so no capability is
1877 // built — which is observable through a `resolve` that counts its calls.
1878 let x_constructor = self.get_property(object, "constructor")?;
1879 let same = match (
1880 x_constructor.as_ref().and_then(Value::as_object),
1881 constructor.as_object(),
1882 ) {
1883 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1884 _ => false,
1885 };
1886 if same {
1887 return Ok(value);
1888 }
1889 }
1890 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1891 // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1892 // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1893 // the intrinsic one swallows its own self-resolution error.
1894 self.call_value(resolve, Value::Undefined, vec![value])?;
1895 Ok(promise)
1896 }
1897
1898 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1899 /// promise, as `{ value: completion }`.
1900 ///
1901 /// The three cases are the reference's, and they differ on purpose:
1902 ///
1903 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1904 /// exception before any promise exists;
1905 /// * a **runtime** error rejects the returned promise;
1906 /// * success resolves it with `{ value }`, where the value is the script's completion
1907 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1908 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1909 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1910 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1911 ///
1912 /// # What this does not do
1913 ///
1914 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1915 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1916 /// the parser and the suspension machinery to accept a suspended top-level script, and
1917 /// is not implemented — such source is a syntax error here. Everything else about the
1918 /// flag is reproduced.
1919 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1920 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1921 // too, and the reference truncates that one at the same place as a runtime failure.
1922 if barrier {
1923 let depth = self.frames.len();
1924 self.trace_barriers.push(depth);
1925 }
1926 // Compiled before the promise exists, so a parse failure propagates as a throw
1927 // instead of being folded into a rejection.
1928 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1929 Ok(compiled) => compiled,
1930 Err(error) => {
1931 if barrier {
1932 self.trace_barriers.pop();
1933 }
1934 return Err(error);
1935 }
1936 };
1937 // An async body answers its own promise, and that promise is what the reference
1938 // hands back — the same object, not a wrapper around it. Its resolution value is
1939 // the `{value}` object the compiled epilogue built.
1940 if compiled.kind.is_async() {
1941 let strict = compiled.strict;
1942 let promise = self.run_eval_script(compiled, strict)?;
1943 if barrier {
1944 self.trace_barriers.pop();
1945 }
1946 return Ok(promise);
1947 }
1948 let (promise, resolve, reject) = self.new_promise_capability();
1949 let strict = compiled.strict;
1950 match self.run_eval_script(compiled, strict) {
1951 Ok(value) => {
1952 // `{ value }` is a plain object, so resolving with it adopts nothing even
1953 // when the completion value is itself a promise.
1954 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1955 self.set_property(&wrapped, "value", value)?;
1956 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1957 }
1958 Err(Signal::Throw(error)) => {
1959 self.call_value(reject, Value::Undefined, vec![error])?;
1960 }
1961 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1962 }
1963 if barrier {
1964 self.trace_barriers.pop();
1965 }
1966 Ok(Value::Object(promise))
1967 }
1968
1969 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1970 ///
1971 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1972 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1973 /// timer table, where the collector already scans it.
1974 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1975 let (promise, resolve, _reject) = self.new_promise_capability();
1976 let resolve = self.new_host_function(
1977 "resolve",
1978 1,
1979 Box::new(
1980 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1981 let value = args.first().cloned().unwrap_or(Value::Undefined);
1982 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1983 },
1984 ),
1985 );
1986 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1987 // timer table is part of what the collector walks.
1988 self.schedule_timer(Value::Object(resolve), delay_ms);
1989 Ok(Value::Object(promise))
1990 }
1991
1992 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1993 /// new promise resolved with it.
1994 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1995 if let Value::Object(object) = &value
1996 && self.promise_state(object).is_some()
1997 {
1998 return Ok(value);
1999 }
2000 let promise = self.new_promise();
2001 self.resolve_promise_with(&promise, value)?;
2002 Ok(Value::Object(promise))
2003 }
2004
2005 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
2006 ///
2007 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
2008 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
2009 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
2010 /// therefore observable — which is exactly what
2011 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
2012 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
2013 /// shortcut.
2014 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
2015 if let Value::Object(object) = &value
2016 && self.promise_state(object).is_some()
2017 {
2018 let constructor = self.get_property(object, "constructor")?;
2019 let same = match (&constructor, &self.realm.promise_constructor) {
2020 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2021 _ => false,
2022 };
2023 if same {
2024 return Ok(value);
2025 }
2026 }
2027 let promise = self.new_promise();
2028 self.resolve_promise_with(&promise, value)?;
2029 Ok(Value::Object(promise))
2030 }
2031
2032 /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2033 ///
2034 /// The pair of resolving functions a promise hands to its executor shares this record, so
2035 /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2036 /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2037 pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2038 let Some(state) = self.promise_state(promise) else {
2039 return true;
2040 };
2041 let mut state = state.borrow_mut();
2042 if state.resolved {
2043 return false;
2044 }
2045 state.resolved = true;
2046 true
2047 }
2048
2049 /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2050 fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2051 let Some(state) = self.promise_state(promise) else {
2052 return;
2053 };
2054 state.borrow_mut().resolved = false;
2055 }
2056
2057 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2058 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2059 // Resolving a promise with itself is a `TypeError`. The check exists because the
2060 // alternative is a chain of self-reactions that never settles.
2061 if let Value::Object(object) = &value
2062 && object.ptr_eq(promise)
2063 {
2064 // The spec rejects *and* throws, so both the promise and the caller see it.
2065 let thrown = self.type_error("cannot resolve a promise with itself");
2066 let Signal::Throw(error) = thrown.clone() else {
2067 unreachable!("type_error always throws")
2068 };
2069 self.reject_promise(promise, error);
2070 return Err(thrown);
2071 }
2072 // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2073 // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2074 // whoever resolved it — a poisoned `then` getter is the case every
2075 // `*-poisoned-then` test is written against.
2076 let then = match &value {
2077 Value::Object(object) => match self.get_property(object, "then") {
2078 Ok(then) => then,
2079 Err(signal) => {
2080 if let Signal::Throw(reason) = signal {
2081 self.reject_promise(promise, reason);
2082 return Ok(());
2083 }
2084 return Err(signal);
2085 }
2086 },
2087 _ => None,
2088 };
2089 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2090 if !callable_then {
2091 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2092 self.fulfill_promise(promise, value);
2093 return Ok(());
2094 }
2095 // Adopting a thenable is asynchronous — `then` is called from a job, never from
2096 // inside `resolve`, so a script cannot make a promise settle synchronously.
2097 self.jobs.push_back(Job::Thenable {
2098 then: then.expect("checked callable"),
2099 value,
2100 promise: promise.clone(),
2101 });
2102 Ok(())
2103 }
2104
2105 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2106 ///
2107 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2108 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2109 ///
2110 /// The property read is **not** short-circuitable even for a real promise: the spec says
2111 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2112 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2113 /// the combinator's loop infinite — the test's iterator never sets `done`.
2114 pub fn invoke_then(
2115 &mut self,
2116 thenable: Value,
2117 on_fulfilled: Value,
2118 on_rejected: Value,
2119 ) -> JsResult<()> {
2120 let then = match &thenable {
2121 Value::Object(object) => self.get_property(object, "then")?,
2122 primitive => {
2123 let boxed = self.object_from(primitive)?;
2124 self.get_property(&boxed, "then")?
2125 }
2126 };
2127 let Some(then) = then else {
2128 return Err(self.type_error("thenable has no then method"));
2129 };
2130 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2131 return Err(self.type_error("then is not a function"));
2132 }
2133 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2134 Ok(())
2135 }
2136
2137 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2138 ///
2139 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2140 /// promise.
2141 pub fn perform_then(
2142 &mut self,
2143 promise: &Gc<JsObject>,
2144 on_fulfilled: Option<Value>,
2145 on_rejected: Option<Value>,
2146 ) -> JsResult<Value> {
2147 let Some(state) = self.promise_state(promise) else {
2148 return Err(self.type_error("not a promise"));
2149 };
2150 // Whether a rejection handler is being attached decides whether a recorded
2151 // rejection stops being unhandled, so it is read before the values are moved.
2152 let has_rejection_handler = on_rejected.is_some();
2153 let derived = self.new_promise();
2154 let reaction = crate::object::PromiseReaction {
2155 on_fulfilled,
2156 on_rejected,
2157 promise: derived.clone(),
2158 };
2159 let settled = {
2160 let mut state = state.borrow_mut();
2161 // A rejection somebody reacts to is no longer unhandled.
2162 state.handled = true;
2163 match &state.status {
2164 crate::object::PromiseStatus::Pending => {
2165 state.reactions.push(reaction.clone());
2166 None
2167 }
2168 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2169 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2170 }
2171 };
2172 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2173 // later, means somebody is listening after all.
2174 if has_rejection_handler {
2175 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2176 }
2177 if let Some((argument, rejected)) = settled {
2178 let handler = if rejected {
2179 reaction.on_rejected
2180 } else {
2181 reaction.on_fulfilled
2182 };
2183 self.jobs.push_back(Job::Reaction {
2184 handler,
2185 argument,
2186 rejected,
2187 promise: reaction.promise,
2188 });
2189 }
2190 Ok(Value::Object(derived))
2191 }
2192
2193 /// The rejections nobody listened to, formatted the way the reference reports them.
2194 ///
2195 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2196 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2197 /// unhandled at the point the queue drains, because a `then` may still be attached
2198 /// before the host acts on it.
2199 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2200 let entries = std::mem::take(&mut self.unhandled);
2201 // Somebody may have attached a handler after the rejection was recorded, so the
2202 // promise is the authority rather than the list.
2203 let still_unhandled: Vec<Value> = entries
2204 .into_iter()
2205 .filter_map(|(promise, reason)| {
2206 let handled = self
2207 .promise_state(&promise)
2208 .map(|state| state.borrow().handled)
2209 .unwrap_or(true);
2210 (!handled).then_some(reason)
2211 })
2212 .collect();
2213 still_unhandled
2214 .into_iter()
2215 .map(|reason| {
2216 let text = self.describe_exception(&reason);
2217 let stack = match &reason {
2218 Value::Object(object) => self
2219 .get_property(object, "stack")
2220 .ok()
2221 .flatten()
2222 .map(|value| value.to_js_string())
2223 // `stack` carries a trailing newline of its own, which would leave
2224 // a blank line between two reported rejections.
2225 .map(|text| text.trim_end().to_string())
2226 .unwrap_or_default(),
2227 _ => String::new(),
2228 };
2229 if stack.is_empty() {
2230 format!("Possibly unhandled promise rejection: {text}")
2231 } else {
2232 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2233 }
2234 })
2235 .collect()
2236 }
2237
2238 /// Run the microtask queue to exhaustion.
2239 ///
2240 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2241 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2242 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2243 ///
2244 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2245 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2246 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2247 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2248 crate::builtins::json::parse_text(self, text, true)
2249 }
2250
2251 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2252 ///
2253 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2254 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2255 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2256 ///
2257 /// The callback is called with **no arguments**. The reference stores only the function
2258 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2259 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2260 /// extra arguments arrive as `undefined`.
2261 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2262 let id = self.next_timer_id;
2263 // Wrap rather than grow: the id reaches the script as an `Int32`.
2264 self.next_timer_id = if self.next_timer_id == i32::MAX {
2265 1
2266 } else {
2267 self.next_timer_id + 1
2268 };
2269 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2270 self.tasks.push(Task::Timer {
2271 id,
2272 callback,
2273 due_at,
2274 });
2275 id
2276 }
2277
2278 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2279 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2280 pub fn cancel_timer(&mut self, id: i32) -> bool {
2281 let before = self.tasks.len();
2282 self.tasks.retain(|task| match task {
2283 Task::Timer { id: task_id, .. } => *task_id != id,
2284 });
2285 self.tasks.len() != before
2286 }
2287
2288 /// How long until the earliest pending timer, or `None` when none is pending.
2289 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2290 let now = std::time::Instant::now();
2291 self.tasks
2292 .iter()
2293 .map(|task| match task {
2294 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2295 })
2296 .min()
2297 }
2298
2299 /// Run one turn of the event loop.
2300 ///
2301 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2302 /// run at most one due timer, then drain again. The blocking belongs to the caller
2303 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2304 /// is how it asks.
2305 ///
2306 /// One timer per turn rather than all of them: a timer callback may schedule another
2307 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2308 /// starve the microtask queue.
2309 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2310 self.drain_jobs()?;
2311 let now = std::time::Instant::now();
2312 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2313 // followed by `setTimeout(g, 1)` must run `g` first.
2314 let due = self
2315 .tasks
2316 .iter()
2317 .enumerate()
2318 .filter(|(_, task)| match task {
2319 Task::Timer { due_at, .. } => *due_at <= now,
2320 })
2321 .min_by_key(|(_, task)| match task {
2322 Task::Timer { due_at, .. } => *due_at,
2323 })
2324 .map(|(index, _)| index);
2325 let Some(index) = due else {
2326 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2327 // descriptor is registered but no timer is closer, so a script that never
2328 // touches the descriptor still gets control back. Without a cap a handler on a
2329 // descriptor that is never ready would block for as long as the host allows.
2330 let timeout = self
2331 .next_timeout()
2332 .unwrap_or(std::time::Duration::from_secs(10))
2333 .min(std::time::Duration::from_secs(10));
2334 if !self.fd_handlers.is_empty() {
2335 // Blocking on a timer while descriptors are registered would starve them,
2336 // and blocking on the descriptors while a timer is due would delay it; the
2337 // host polls with the earlier of the two deadlines, which this timeout is.
2338 return Ok(Turn::Poll(timeout));
2339 }
2340 return Ok(match self.next_timeout() {
2341 Some(wait) => Turn::Wait(wait),
2342 None => Turn::Done,
2343 });
2344 };
2345 let Task::Timer { callback, .. } = self.tasks.remove(index);
2346 let this = Value::Undefined;
2347 // A throwing timer callback must not stop the loop: the reference reports it and
2348 // keeps going, because the alternative is that one bad timer silently stops every
2349 // later one.
2350 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2351 match self.call_value(callback, this, Vec::new()) {
2352 Ok(_) => {}
2353 Err(Signal::Throw(value)) => {
2354 let text = self.describe_exception(&value);
2355 self.timer_errors.push(text);
2356 }
2357 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2358 }
2359 self.drain_jobs()?;
2360 Ok(Turn::Ran)
2361 }
2362
2363 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2364 ///
2365 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2366 /// left is removed — the reference does the same, so a script can rely on
2367 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2368 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2369 let entry = self.fd_handlers.entry(fd).or_default();
2370 if readable {
2371 entry.read = callback;
2372 } else {
2373 entry.write = callback;
2374 }
2375 if entry.read.is_none() && entry.write.is_none() {
2376 self.fd_handlers.remove(&fd);
2377 }
2378 }
2379
2380 /// Register or clear an `os.signal` handler.
2381 ///
2382 /// `None` removes it; the host separately restores the default disposition or sets
2383 /// ignore, because which of those happened is the script's choice (`null` versus
2384 /// `undefined`) and not something this table can express.
2385 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2386 match handler {
2387 Some(handler) => {
2388 self.signal_handlers.insert(signal, handler);
2389 }
2390 None => {
2391 self.signal_handlers.remove(&signal);
2392 }
2393 }
2394 }
2395
2396 /// Run the handler for `signal`, reporting whether one ran.
2397 ///
2398 /// A throwing handler is reported and the loop continues, like a timer's.
2399 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2400 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2401 return Ok(false);
2402 };
2403 match self.call_value(handler, Value::Undefined, Vec::new()) {
2404 Ok(_) => {}
2405 Err(Signal::Throw(value)) => {
2406 let text = self.describe_exception(&value);
2407 self.timer_errors.push(text);
2408 }
2409 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2410 }
2411 self.drain_jobs()?;
2412 Ok(true)
2413 }
2414
2415 /// The descriptors the host has to poll, and in which direction.
2416 ///
2417 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2418 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2419 /// `os_poll` asks for.
2420 pub fn pending_fds(&self) -> Vec<FdInterest> {
2421 self.fd_handlers
2422 .iter()
2423 .map(|(fd, entry)| FdInterest {
2424 fd: *fd,
2425 read: entry.read.is_some(),
2426 write: entry.write.is_some(),
2427 })
2428 .collect()
2429 }
2430
2431 /// Call the handler registered for `fd`, reporting whether one ran.
2432 ///
2433 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2434 /// poll iteration and then restarts the loop, because the handler may have changed the
2435 /// registration list underneath it; doing the same here keeps a handler that
2436 /// unregisters itself from being called with stale state.
2437 ///
2438 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2439 /// every later one, exactly as with timers.
2440 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2441 let Some(entry) = self.fd_handlers.get(&fd) else {
2442 return Ok(false);
2443 };
2444 let callback = if readable {
2445 entry.read.clone()
2446 } else if writable {
2447 entry.write.clone()
2448 } else {
2449 None
2450 };
2451 let Some(callback) = callback else {
2452 return Ok(false);
2453 };
2454 self.drain_jobs()?;
2455 match self.call_value(callback, Value::Undefined, Vec::new()) {
2456 Ok(_) => {}
2457 Err(Signal::Throw(value)) => {
2458 let text = self.describe_exception(&value);
2459 self.timer_errors.push(text);
2460 }
2461 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2462 }
2463 self.drain_jobs()?;
2464 Ok(true)
2465 }
2466
2467 /// Take the errors timer callbacks threw, leaving the list empty.
2468 pub fn take_timer_errors(&mut self) -> Vec<String> {
2469 std::mem::take(&mut self.timer_errors)
2470 }
2471
2472 /// Whether anything is still pending: a microtask or a timer.
2473 pub fn has_pending_work(&self) -> bool {
2474 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2475 }
2476
2477 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2478 pub fn has_pending_timers_or_jobs(&self) -> bool {
2479 !self.jobs.is_empty() || !self.tasks.is_empty()
2480 }
2481
2482 /// Run every queued microtask, including ones queued while draining.
2483 pub fn drain_jobs(&mut self) -> JsResult<()> {
2484 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2485 // would spin forever, so the drain is bounded the way the call stack is.
2486 let mut budget = 1_000_000usize;
2487 while let Some(job) = self.jobs.pop_front() {
2488 if budget == 0 {
2489 return Err(Signal::Throw(
2490 self.make_error("InternalError", "promise job queue did not drain"),
2491 ));
2492 }
2493 budget -= 1;
2494 self.run_job(job)?;
2495 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2496 // engine may run script that the script itself did not ask for. Doing it here
2497 // rather than from a drop hook is what keeps the callback out of arbitrary
2498 // engine bookkeeping — see `builtins::weak`'s header.
2499 crate::builtins::weak::drain_finalizers(self)?;
2500 }
2501 // A script that queued no jobs may still have dropped targets, so the checkpoint
2502 // runs once more after the queue empties.
2503 crate::builtins::weak::drain_finalizers(self)?;
2504 Ok(())
2505 }
2506
2507 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2508 ///
2509 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2510 /// `None` and is swept out here. This is also where the realm learns that a registry
2511 /// died, which is why it is a mutation rather than a read.
2512 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2513 let handles = std::mem::take(&mut self.realm.finalization_registries);
2514 let mut live = Vec::with_capacity(handles.len());
2515 for handle in handles {
2516 let Some(object) = handle.upgrade() else {
2517 continue;
2518 };
2519 let Some(state) = object.finalization_state() else {
2520 continue;
2521 };
2522 live.push((object.clone(), *state));
2523 self.realm.finalization_registries.push(object.downgrade());
2524 }
2525 live
2526 }
2527
2528 /// Run one microtask.
2529 fn run_job(&mut self, job: Job) -> JsResult<()> {
2530 match job {
2531 Job::Reaction {
2532 handler: None,
2533 argument,
2534 rejected,
2535 promise,
2536 } => {
2537 // No handler: the settlement passes straight through to the derived
2538 // promise, which is why `p.catch(f)` ignores fulfilments.
2539 if rejected {
2540 self.reject_promise(&promise, argument);
2541 } else {
2542 self.fulfill_promise(&promise, argument);
2543 }
2544 Ok(())
2545 }
2546 Job::Reaction {
2547 handler: Some(handler),
2548 argument,
2549 promise,
2550 ..
2551 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2552 Ok(answer) => {
2553 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2554 self.reject_promise(&promise, error);
2555 }
2556 Ok(())
2557 }
2558 Err(Signal::Throw(reason)) => {
2559 self.reject_promise(&promise, reason);
2560 Ok(())
2561 }
2562 Err(other) => Err(other),
2563 },
2564 Job::Thenable {
2565 then,
2566 value,
2567 promise,
2568 } => {
2569 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2570 // the value it produces settles `promise`.
2571 // The thenable's `then` gets this promise's own pair, so whatever it
2572 // produces settles `promise`.
2573 // `length: 1`, `name: ""` — a resolve/reject function is a
2574 // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2575 // with `JsObject::function` left `length` at 0, which a test reads straight
2576 // off the function (`finally/resolved-observable-then-calls-argument`
2577 // requires `resolve.length === 1` for the pair handed to a thenable).
2578 let resolve =
2579 self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2580 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2581 // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2582 // so the one-shot record starts over. Without the reset the pair above was
2583 // already spent by the `resolve` that queued this job, and a thenable that
2584 // calls `reject` left the promise pending forever
2585 // (`Promise/all/reject-immed`).
2586 self.forget_resolution(&promise);
2587 let reject = Value::Object(reject);
2588 match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2589 Ok(_) => Ok(()),
2590 // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2591 // reject function, whose one-shot record makes this a no-op once `then`
2592 // has already resolved the promise
2593 // (`exception-after-resolve-in-thenable-job`).
2594 Err(Signal::Throw(reason)) => {
2595 self.call_value(reject, Value::Undefined, vec![reason])?;
2596 Ok(())
2597 }
2598 Err(other) => Err(other),
2599 }
2600 }
2601 Job::Resume {
2602 coroutine,
2603 promise,
2604 kind,
2605 value,
2606 } => self.drive_async(&coroutine, &promise, kind, value),
2607 Job::GeneratorResume {
2608 generator,
2609 promise,
2610 kind,
2611 value,
2612 } => self.step_async_generator(&generator, &promise, kind, value),
2613 Job::Import {
2614 specifier,
2615 referrer,
2616 promise,
2617 } => {
2618 self.run_dynamic_import(&specifier, &referrer, &promise);
2619 Ok(())
2620 }
2621 }
2622 }
2623
2624 /// One element of a `Promise` combinator settled.
2625 ///
2626 /// The shared state object holds the result array, the number still outstanding, and
2627 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2628 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2629 /// to settle, only whatever `Sub` said a capability is.
2630 ///
2631 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2632 /// and `any` must ignore every later settlement, and `all` must not report a second
2633 /// rejection after the first.
2634 fn settle_combinator(
2635 &mut self,
2636 state: &Gc<JsObject>,
2637 index: usize,
2638 fulfilled: bool,
2639 value: Value,
2640 ) -> JsResult<()> {
2641 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2642 // Each element settles at most once: a thenable may call `onFulfilled` twice
2643 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2644 // call a no-op. Without it the second call decremented `remaining` again and settled
2645 // `all` with a short values array (`call-resolve-element-items`).
2646 let done = field("done");
2647 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2648 let settled = field("settled").is_some_and(|value| value.to_boolean());
2649 if settled {
2650 return Ok(());
2651 }
2652 if let Some(Value::Object(done)) = &done {
2653 if done
2654 .array_get(index)
2655 .is_some_and(|value| value.to_boolean())
2656 {
2657 return Ok(());
2658 }
2659 done.array_set(self.heap, index, Value::Bool(true));
2660 }
2661 let resolve = field("resolve");
2662 let reject = field("reject");
2663 let keys = field("keys");
2664 let results = field("results").and_then(|value| value.as_object().cloned());
2665 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2666 // promise: the handler is a plain function the constructor chose.
2667 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2668 if let Some(handler) = handler {
2669 interp.call_value(handler, Value::Undefined, vec![value])?;
2670 }
2671 Ok(())
2672 };
2673 match kind {
2674 // `race`: the first settlement wins and stops the rest.
2675 3 => {
2676 state.define_data("settled", Value::Bool(true));
2677 let handler = if fulfilled { resolve } else { reject };
2678 settle_with(self, handler, value)?;
2679 return Ok(());
2680 }
2681 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2682 // the first rejection wins outright.
2683 0 | 4 if !fulfilled => {
2684 state.define_data("settled", Value::Bool(true));
2685 settle_with(self, reject, value)?;
2686 return Ok(());
2687 }
2688 // `any`: the first fulfilment wins.
2689 2 if fulfilled => {
2690 state.define_data("settled", Value::Bool(true));
2691 settle_with(self, resolve, value)?;
2692 return Ok(());
2693 }
2694 _ => {}
2695 }
2696 let Some(results) = &results else {
2697 return Ok(());
2698 };
2699 match kind {
2700 4 => {
2701 results.array_set(self.heap, index, value);
2702 }
2703 0 => {
2704 results.array_set(self.heap, index, value);
2705 }
2706 // `allSettled` (and its keyed twin) never rejects; each slot records what
2707 // happened.
2708 1 | 5 => {
2709 let record = self.new_object(Some(self.realm.object_proto.clone()));
2710 if fulfilled {
2711 record.define_data("status", self.string("fulfilled"));
2712 record.define_data("value", value);
2713 } else {
2714 record.define_data("status", self.string("rejected"));
2715 record.define_data("reason", value);
2716 }
2717 results.array_set(self.heap, index, Value::Object(record));
2718 }
2719 // `any`: a rejection is parked in the errors array and the sweep continues.
2720 2 => {
2721 results.array_set(self.heap, index, value);
2722 }
2723 _ => {}
2724 }
2725 let remaining = field("remaining")
2726 .map(|value| value.to_int32())
2727 .unwrap_or(0);
2728 let left = remaining - 1;
2729 state.define_data("remaining", Value::Int(left));
2730 if left != 0 {
2731 return Ok(());
2732 }
2733 state.define_data("settled", Value::Bool(true));
2734 match kind {
2735 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2736 // The keyed result: an ordinary object with a **null** prototype, holding the
2737 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2738 4 | 5 => {
2739 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2740 settle_with(self, resolve, keyed)?;
2741 }
2742 2 => {
2743 // The rejection is an `AggregateError` whose `errors` is the results array
2744 // itself — the slots are the reasons, in input order.
2745 let errors = results.array_elements().unwrap_or_default();
2746 let error = self.aggregate_error(errors, "all promises were rejected");
2747 settle_with(self, reject, error)?;
2748 }
2749 _ => {}
2750 }
2751 Ok(())
2752 }
2753
2754 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2755 ///
2756 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2757 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2758 /// prototype is load-bearing in both directions: a key called `toString` must not
2759 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2760 /// (`resolves-empty-object.js`).
2761 pub(crate) fn keyed_result_object(
2762 &mut self,
2763 keys: Option<&Value>,
2764 values: &Gc<JsObject>,
2765 ) -> JsResult<Value> {
2766 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2767 return Ok(Value::Object(self.new_object(None)));
2768 };
2769 let result = self.new_object(None);
2770 let count = values.array_length().unwrap_or(0);
2771 for index in 0..count {
2772 let Some(key) = keys.array_get(index) else {
2773 continue;
2774 };
2775 let Some(value) = values.array_get(index) else {
2776 continue;
2777 };
2778 let property = Property::with_attributes(value, true, true);
2779 match &key {
2780 Value::Symbol(symbol) => {
2781 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2782 }
2783 other => {
2784 let text = self.to_js_string(other)?;
2785 result.define_key(&PropertyKey::from(text.as_str()), property);
2786 }
2787 }
2788 }
2789 Ok(Value::Object(result))
2790 }
2791
2792 /// Build an async function's result: a promise whose body runs as a coroutine.
2793 pub fn new_async_function(
2794 &mut self,
2795 function: Value,
2796 this: Value,
2797 args: Vec<Value>,
2798 ) -> JsResult<Value> {
2799 let promise = self.new_promise();
2800 let coroutine = self.new_coroutine(function, this, args)?;
2801 if let Err(Signal::Throw(reason)) =
2802 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2803 {
2804 self.reject_promise(&promise, reason);
2805 }
2806 Ok(Value::Object(promise))
2807 }
2808
2809 /// The coroutine an async body runs in.
2810 ///
2811 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2812 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2813 /// than growing a second state machine. The difference is only in the ending — a
2814 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2815 /// Run `code` as an async function body, answering the promise it settles.
2816 ///
2817 /// Used for a module with top-level `await`: its body is an async function whose
2818 /// caller is the host, so there is no function object to pass through
2819 /// [`Interp::new_async_function`].
2820 pub fn run_async_body(
2821 &mut self,
2822 code: Gc<CompiledCode>,
2823 env: Gc<ClosureEnv>,
2824 this: Value,
2825 ) -> JsResult<Value> {
2826 let promise = self.new_promise();
2827 let coroutine = self.new_coroutine_from(code, env, this, Vec::new(), Value::Undefined)?;
2828 if let Err(Signal::Throw(reason)) =
2829 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2830 {
2831 self.reject_promise(&promise, reason);
2832 }
2833 Ok(Value::Object(promise))
2834 }
2835
2836 fn new_coroutine(
2837 &mut self,
2838 function: Value,
2839 this: Value,
2840 args: Vec<Value>,
2841 ) -> JsResult<Gc<JsObject>> {
2842 let Some(object) = function.as_object().cloned() else {
2843 return Err(self.type_error("not a function"));
2844 };
2845 let Some((code, env)) = bytecode_of(&object) else {
2846 return Err(self.type_error("not a function"));
2847 };
2848 self.new_coroutine_from(code, env, this, args, function)
2849 }
2850
2851 /// Build a coroutine over an already-resolved body.
2852 ///
2853 /// `callee` is the function object the body belongs to, or `undefined` when there is
2854 /// none — a module with top-level `await`. It has to be handed over rather than
2855 /// defaulted: the frame's callee is what `special_object 2` answers, and an async
2856 /// function's body uses that to initialise its own-name binding. Passing `undefined`
2857 /// made `var f = async function Binding(){ return typeof Binding }` answer
2858 /// `"undefined"`, so a named async function expression could not see its own name and
2859 /// `Binding = 1` inside it silently succeeded (`named-reassign-fn-name-in-body`).
2860 fn new_coroutine_from(
2861 &mut self,
2862 code: Gc<CompiledCode>,
2863 env: Gc<ClosureEnv>,
2864 this: Value,
2865 args: Vec<Value>,
2866 callee: Value,
2867 ) -> JsResult<Gc<JsObject>> {
2868 self.push_frame(code, env, this, args, callee)?;
2869 let frame = self.frames.pop().expect("push_frame just pushed it");
2870 let state = GeneratorState {
2871 frame: Some(frame),
2872 phase: GeneratorPhase::SuspendedStart,
2873 parked_on_await: false,
2874 parked_on_yield_star: false,
2875 requests: std::collections::VecDeque::new(),
2876 async_busy: false,
2877 // An `async function` body is driven by `drive_async`, never by the generator
2878 // protocol, and the object is not reachable from script.
2879 is_async: false,
2880 };
2881 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2882 coroutine.with_mut(|data| {
2883 data.kind = ObjectKind::Generator(Box::new(state));
2884 });
2885 Ok(coroutine)
2886 }
2887
2888 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2889 /// `await` and `value` is what it awaited.
2890 fn resume_coroutine(
2891 &mut self,
2892 coroutine: &Gc<JsObject>,
2893 kind: ResumeKind,
2894 value: Value,
2895 ) -> JsResult<(Value, bool)> {
2896 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2897 ObjectKind::Generator(state) => {
2898 let is_async = state.is_async;
2899 Some(std::mem::replace(
2900 state.as_mut(),
2901 GeneratorState {
2902 frame: None,
2903 phase: GeneratorPhase::Executing,
2904 parked_on_await: false,
2905 parked_on_yield_star: false,
2906 requests: std::collections::VecDeque::new(),
2907 async_busy: false,
2908 is_async,
2909 },
2910 ))
2911 }
2912 _ => None,
2913 }) else {
2914 return Err(self.type_error("not a coroutine"));
2915 };
2916 let result = self.step_generator(&mut state, kind, value);
2917 coroutine.with_mut(|data| {
2918 data.kind = ObjectKind::Generator(Box::new(state));
2919 });
2920 let (value, done, _ready, _reason) = result?;
2921 Ok((value, done))
2922 }
2923
2924 /// Advance an async body and settle its promise with the outcome.
2925 fn drive_async(
2926 &mut self,
2927 coroutine: &Gc<JsObject>,
2928 promise: &Gc<JsObject>,
2929 kind: ResumeKind,
2930 value: Value,
2931 ) -> JsResult<()> {
2932 match self.resume_coroutine(coroutine, kind, value) {
2933 Ok((value, true)) => {
2934 // `Ok` with `done` means the body finished *normally*, even when it was
2935 // resumed by a `throw` — `try { await p } catch {}` completes by
2936 // returning. Only the `Err` arm below is a rejection.
2937 //
2938 // Resolving rather than fulfilling matters: `return promise` in an async
2939 // body adopts the inner promise, so `async function f(){ return
2940 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2941 // promise.
2942 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2943 self.reject_promise(promise, reason);
2944 }
2945 Ok(())
2946 }
2947 Ok((value, false)) => {
2948 // Parked on `await`: follow what it awaited and resume with the outcome.
2949 let awaited = match self.promise_resolve_value(value) {
2950 Ok(awaited) => awaited,
2951 Err(Signal::Throw(error)) => {
2952 self.reject_promise(promise, error);
2953 return Ok(());
2954 }
2955 Err(other) => return Err(other),
2956 };
2957 self.hook_await(awaited, coroutine, promise)
2958 }
2959 Err(Signal::Throw(reason)) => {
2960 self.reject_promise(promise, reason);
2961 Ok(())
2962 }
2963 Err(other) => Err(other),
2964 }
2965 }
2966
2967 /// Arrange for `coroutine` to resume when `awaited` settles.
2968 fn hook_await(
2969 &mut self,
2970 awaited: Value,
2971 coroutine: &Gc<JsObject>,
2972 promise: &Gc<JsObject>,
2973 ) -> JsResult<()> {
2974 let resumed = JsObject::function(
2975 self.heap,
2976 Some(self.realm.function_proto.clone()),
2977 Callable::AwaitResume {
2978 coroutine: coroutine.clone(),
2979 promise: promise.clone(),
2980 kind: ResumeKind::Next,
2981 },
2982 );
2983 let raised = JsObject::function(
2984 self.heap,
2985 Some(self.realm.function_proto.clone()),
2986 Callable::AwaitResume {
2987 coroutine: coroutine.clone(),
2988 promise: promise.clone(),
2989 kind: ResumeKind::Throw,
2990 },
2991 );
2992 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2993 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2994 let Value::Object(awaited) = &awaited else {
2995 self.jobs.push_back(Job::Resume {
2996 coroutine: coroutine.clone(),
2997 promise: promise.clone(),
2998 kind: ResumeKind::Next,
2999 value: awaited,
3000 });
3001 return Ok(());
3002 };
3003 self.perform_then(
3004 awaited,
3005 Some(Value::Object(resumed)),
3006 Some(Value::Object(raised)),
3007 )?;
3008 Ok(())
3009 }
3010
3011 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
3012 /// things an engine keeps outside it — array elements and an array's `length`.
3013 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3014 if let Some(property) = object.own_property_key(key) {
3015 return Some(property);
3016 }
3017 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3018 // be synthesized too — and every one of them is a plain writable, enumerable,
3019 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3020 // `undefined` before this, which made `key-is-numericindex` fail on its own
3021 // side effect check.
3022 //
3023 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3024 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3025 // likewise not elements however numeric they look.
3026 if object.typed_array_element_type().is_some()
3027 && let Some(numeric) = canonical_numeric_index(key)
3028 && numeric.is_finite()
3029 && numeric.fract() == 0.0
3030 && !(numeric == 0.0 && numeric.is_sign_negative())
3031 && numeric >= 0.0
3032 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3033 {
3034 let value = object.typed_array_element(numeric as usize)?;
3035 return Some(Property::data(value));
3036 }
3037 // An array's elements live in their own vector rather than the property table, so
3038 // a descriptor for one has to be synthesized — with the attributes an element has.
3039 if let Some(index) = key.as_str().and_then(array_index)
3040 && let Some(value) = object.array_get(index as usize)
3041 && !matches!(value, Value::Hole)
3042 {
3043 return Some(Property::data(value));
3044 }
3045 // `length` is an own property of an array that is not in its property table
3046 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3047 // and non-enumerable.
3048 if key.as_str() == Some("length")
3049 && let Some(length) = object.array_length()
3050 {
3051 return Some(Property {
3052 value: Some(crate::object::length_value(length)),
3053 writable: object.length_writable(),
3054 enumerable: false,
3055 configurable: false,
3056 getter: None,
3057 setter: None,
3058 descriptor_fields: None,
3059 });
3060 }
3061 None
3062 }
3063
3064 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3065 pub fn object_get_own_property(
3066 &mut self,
3067 object: &Gc<JsObject>,
3068 key: &PropertyKey,
3069 ) -> JsResult<Option<Property>> {
3070 if let Some(answer) = self.proxy_get_own_property(object, key)? {
3071 return Ok(answer);
3072 }
3073 if let Some(exotic) = object.exotic()
3074 && let Some(answer) = exotic.get_own_property(self, object, key)?
3075 {
3076 return Ok(answer);
3077 }
3078 // A module namespace's bindings are accessors internally and data properties to
3079 // script; see `namespace_own_property`.
3080 if object.module_namespace_marker() {
3081 return self.namespace_own_property(object, key);
3082 }
3083 // A mapped `arguments` index is a data property as far as script can see: the
3084 // accessor pair that aliases the parameter is plumbing, and exposing it would
3085 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3086 // report a `get` where the spec has a `[[Value]]`.
3087 if let Some(index) = key.as_str().and_then(crate::object::array_index)
3088 && let Some(cell) = object.mapped_argument_cell(index as usize)
3089 {
3090 // Non-configurable is *not* the default: an ordinary mapped index is
3091 // configurable, and only becomes non-configurable once something
3092 // redefines it. Preserve whatever the property table currently says.
3093 // The attributes come from whatever the property table holds, because they
3094 // can be changed independently of the mapping; only the *value* and the
3095 // data-property *kind* are the accessor's secret.
3096 let flags = Self::ordinary_own_property(object, key);
3097 if let Some(existing) = &flags
3098 && !existing.is_accessor()
3099 {
3100 // Already demapped: the table entry is the answer, not the cell.
3101 return Ok(flags);
3102 }
3103 return Ok(Some(Property {
3104 value: Some(cell.get()),
3105 writable: true,
3106 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3107 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3108 ..Property::default()
3109 }));
3110 }
3111 Ok(Self::ordinary_own_property(object, key))
3112 }
3113
3114 /// Whether `object` is a module namespace exotic object (§10.4.6).
3115 ///
3116 /// Recognised by shape rather than by a flag: a namespace is the only object whose
3117 /// properties are all accessors over a `ModuleBinding` cell. That is the same
3118 /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3119 /// distinction in one place instead of adding a boolean every constructor has to
3120 /// remember to set.
3121 pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3122 object.module_namespace_marker()
3123 }
3124
3125 /// `[[GetOwnProperty]]` for a module namespace exotic object.
3126 ///
3127 /// The bindings are stored as getters — that is the only way a live binding can be read
3128 /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3129 /// descriptor:
3130 ///
3131 /// ```text
3132 /// { [[Value]]: current value, [[Writable]]: true,
3133 /// [[Enumerable]]: true, [[Configurable]]: false }
3134 /// ```
3135 ///
3136 /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3137 /// `undefined`. Reporting the accessor instead — which is what the property table holds
3138 /// — made every one of test262's namespace descriptor assertions fail, in both the
3139 /// `await-ns-*` and `promise-then-ns-*` families.
3140 ///
3141 /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3142 /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3143 /// property`); the ordinary descriptor machinery derives that from these attributes.
3144 pub fn namespace_own_property(
3145 &mut self,
3146 object: &Gc<JsObject>,
3147 key: &PropertyKey,
3148 ) -> JsResult<Option<Property>> {
3149 let Some(stored) = Self::ordinary_own_property(object, key) else {
3150 return Ok(None);
3151 };
3152 let Some(Property {
3153 getter: Some(getter),
3154 ..
3155 }) = Some(&stored)
3156 else {
3157 return Ok(Some(stored));
3158 };
3159 // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3160 // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3161 // rather than stored.
3162 let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3163 Ok(Some(Property {
3164 value: Some(value),
3165 writable: true,
3166 enumerable: true,
3167 configurable: false,
3168 ..Property::default()
3169 }))
3170 }
3171
3172 /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3173 ///
3174 /// Modelled as "does this descriptor describe the property that is already there?",
3175 /// because a namespace property's attributes are fixed and its value cannot be changed
3176 /// through the namespace. The three ways to succeed:
3177 ///
3178 /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3179 /// * one whose `[[Value]]` is `SameValue` the current binding value;
3180 /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3181 /// configurable: false}`.
3182 ///
3183 /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3184 /// false), so it goes through the same check against its stored value — which is what
3185 /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3186 /// answer `true` while `{value: "Other"}` answers `false`.
3187 fn namespace_define_own_property(
3188 &mut self,
3189 object: &Gc<JsObject>,
3190 key: &PropertyKey,
3191 property: &Property,
3192 ) -> JsResult<bool> {
3193 let Some(current) = self.namespace_own_property(object, key)? else {
3194 // A name the namespace does not export cannot be added to it.
3195 return Ok(false);
3196 };
3197 if let Some(value) = &property.value {
3198 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3199 if !self.same_value(value, current_value)? {
3200 return Ok(false);
3201 }
3202 }
3203 Ok(true)
3204 }
3205
3206 /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3207 ///
3208 /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3209 /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3210 /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3211 /// descriptor with no fields at all therefore succeeds, which is what
3212 /// `Reflect.defineProperty(ns, k, {})` checks.
3213 ///
3214 /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3215 /// stored property, and a namespace stores its bindings as accessors, so every
3216 /// definition looked like "accessor → data kind changed" or carried `writable: false`
3217 /// from the accessor's own entry. Presence is only available here, before the merge.
3218 pub fn namespace_define_from_descriptor(
3219 &mut self,
3220 object: &Gc<JsObject>,
3221 key: &PropertyKey,
3222 descriptor: &Gc<JsObject>,
3223 ) -> JsResult<bool> {
3224 let Some(current) = self.namespace_own_property(object, key)? else {
3225 return Ok(false);
3226 };
3227 // An accessor descriptor can never describe a namespace binding.
3228 if self.get_property(descriptor, "get")?.is_some()
3229 || self.get_property(descriptor, "set")?.is_some()
3230 {
3231 return Ok(false);
3232 }
3233 if let Some(value) = self.get_property(descriptor, "value")? {
3234 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3235 if !self.same_value(&value, current_value)? {
3236 return Ok(false);
3237 }
3238 }
3239 // The three attribute fields, when named, must restate what the property already
3240 // has. Not a fixed shape: an exported binding reports
3241 // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3242 // is a real own data property with `{false, false, false}`, and both are namespace
3243 // properties. Comparing against `current` is what makes one rule cover both.
3244 for (name, have) in [
3245 ("writable", current.writable),
3246 ("enumerable", current.enumerable),
3247 ("configurable", current.configurable),
3248 ] {
3249 if let Some(named) = self.get_property(descriptor, name)?
3250 && named.to_boolean() != have
3251 {
3252 return Ok(false);
3253 }
3254 }
3255 Ok(true)
3256 }
3257
3258 /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3259 /// compare a requested value against a live binding.
3260 pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3261 Ok(a.same_value(b))
3262 }
3263
3264 ///
3265 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3266 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3267 /// abstract operation here rather than a private helper in `error.rs`.
3268 ///
3269 /// The name is the whole point: the setter must behave as if the prototype were not
3270 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3271 /// the accessor for every error object in the realm. Everything below follows from that:
3272 ///
3273 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3274 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3275 /// accessor's own home an error rather than a self-shadow.
3276 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3277 /// either has a string or has made a mistake.
3278 /// 4. An existing *own* property decides the path — an own setter is called, an own
3279 /// non-writable data property is a `TypeError` — and only a missing own property
3280 /// falls through to defining one.
3281 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3282 /// traps and a non-extensible receiver is a `TypeError`.
3283 ///
3284 /// The installed shape is writable + configurable, not enumerable.
3285 pub fn setter_that_ignores_prototype_properties(
3286 &mut self,
3287 this_value: Value,
3288 home: &Gc<JsObject>,
3289 property_key: &str,
3290 args: &[Value],
3291 ) -> JsResult<Value> {
3292 self.setter_that_ignores_prototype_properties_key(
3293 this_value,
3294 home,
3295 &PropertyKey::from(property_key),
3296 args,
3297 )
3298 }
3299
3300 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3301 ///
3302 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3303 pub fn setter_that_ignores_prototype_properties_key(
3304 &mut self,
3305 this_value: Value,
3306 home: &Gc<JsObject>,
3307 key: &PropertyKey,
3308 args: &[Value],
3309 ) -> JsResult<Value> {
3310 let Some(receiver) = this_value.as_object().cloned() else {
3311 return Err(self.type_error("setter called on a non-object"));
3312 };
3313 if Gc::ptr_eq(&receiver, home) {
3314 return Err(self.type_error("cannot assign to the accessor's own home object"));
3315 }
3316 // No type check here: §7.3.40 takes an arbitrary `v`, and
3317 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3318 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3319 // before calling this.
3320 let value = args.first().cloned().unwrap_or(Value::Undefined);
3321 // Step 4: an own property on the receiver changes what happens, and there are three
3322 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3323 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3324 // `Set` with `throw = true`, and a test exists for each.
3325 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3326 if existing.is_accessor() && existing.setter.is_none() {
3327 // A getter-only own accessor cannot be written through.
3328 return Err(self.type_error("no setter for the own property"));
3329 }
3330 // Everything else — an own data property, or an own accessor *with* a setter —
3331 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3332 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3333 // an own user setter receives the value (`setter-own-accessor`), because
3334 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3335 // setter directly is the difference between one code path and two that can
3336 // disagree.
3337 self.set_property_with_key(
3338 &receiver,
3339 key,
3340 value.clone(),
3341 crate::interp::DeleteFailure::Throw,
3342 )?;
3343 return Ok(Value::Undefined);
3344 }
3345 let property = Property {
3346 value: Some(value.clone()),
3347 writable: true,
3348 // Enumerable, despite the accessor it shadows not being. The reference installs
3349 // it that way and six cases check it (`setter-creates-own-property` and friends).
3350 enumerable: true,
3351 configurable: true,
3352 ..Property::default()
3353 };
3354 if !self.object_define_own_property(&receiver, key, property)? {
3355 return Err(self.type_error("the receiver refused the definition"));
3356 }
3357 Ok(Value::Undefined)
3358 }
3359
3360 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3361 ///
3362 /// The indices of a typed array are not properties at all — they are bytes in the
3363 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3364 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3365 /// enumerable and configurable, so a definition can only ever change the *value*, and
3366 /// every other descriptor is refused rather than applied.
3367 ///
3368 /// The order of the checks is the spec's, and two of them are load-bearing:
3369 ///
3370 /// * the index is validated **before** the value is converted, because the conversion
3371 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3372 /// detaches from a `valueOf` and still expects `true` with no store, which only
3373 /// happens when the index was valid on the way in;
3374 /// * the store is attempted even when the index has gone out of bounds by the time the
3375 /// conversion finishes, because the store is a silent no-op rather than a failure —
3376 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3377 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3378 ///
3379 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3380 /// the existing element, which is harmless here: every valid index is already
3381 /// writable, enumerable and configurable, so a `false` in the merged property can only
3382 /// have come from the descriptor having named `false`.
3383 fn integer_indexed_define_own_property(
3384 &mut self,
3385 object: &Gc<JsObject>,
3386 numeric: f64,
3387 property: &Property,
3388 ) -> JsResult<bool> {
3389 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3390 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3391 if !typed_array_index_is_valid(object, numeric) {
3392 return Ok(false);
3393 }
3394 // Step 6: the indices are data properties, so an accessor descriptor is refused
3395 // rather than converted. `Object.defineProperty` turns the `false` into a
3396 // `TypeError`; `Reflect.defineProperty` reports it.
3397 if property.is_accessor() {
3398 return Ok(false);
3399 }
3400 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3401 // definition that asks for anything else cannot be honoured.
3402 if !property.writable || !property.enumerable || !property.configurable {
3403 return Ok(false);
3404 }
3405 // Step 10: only a descriptor that names a value stores anything.
3406 let Some(value) = property.value.clone() else {
3407 return Ok(true);
3408 };
3409 let Some(element) = object.typed_array_element_type() else {
3410 return Ok(false);
3411 };
3412 let stored = self.element_value(element, value)?;
3413 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3414 return Err(self.type_error(reason));
3415 }
3416 Ok(true)
3417 }
3418
3419 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3420 pub fn object_define_own_property(
3421 &mut self,
3422 object: &Gc<JsObject>,
3423 key: &PropertyKey,
3424 property: Property,
3425 ) -> JsResult<bool> {
3426 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3427 return Ok(accepted);
3428 }
3429 // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3430 //
3431 // The only definitions that can succeed are ones describing the property the
3432 // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3433 // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3434 // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3435 // `writable: false`, `configurable: true`, or any name the namespace does not
3436 // export is `false`.
3437 //
3438 // The ordinary path gets the no-change case right by accident — it compares against
3439 // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3440 // is an accessor internally while the definition script writes is a data descriptor.
3441 // Answering here is what makes that attribute-only definition a no-op rather than a
3442 // refusal (`namespace/await-ns-define-own-property`).
3443 if object.module_namespace_marker() {
3444 return self.namespace_define_own_property(object, key, &property);
3445 }
3446 // A proxy always answers above — with `Some` from its trap, or with `None` when
3447 // the trap is absent, and then the definition belongs to the **target**
3448 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3449 // when there is no trap). Falling through to the ordinary path here defined the
3450 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3451 // property the target never saw.
3452 if object.proxy_state().is_some() {
3453 let Some((target, _handler)) = self.proxy_parts(object)? else {
3454 return Err(self.type_error("cannot use a proxy that has been revoked"));
3455 };
3456 return self.object_define_own_property(&target, key, property);
3457 }
3458 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3459 // they accept exactly one descriptor shape. This has to happen before the
3460 // ordinary path, which would happily store a data property next to the buffer —
3461 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3462 // and `TypedArray/prototype/set` are about this section.
3463 if object.typed_array_element_type().is_some()
3464 && let Some(index) = canonical_numeric_index(key)
3465 {
3466 return self.integer_indexed_define_own_property(object, index, &property);
3467 }
3468 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3469 // non-extensible object. The check lives here rather than in the callers because
3470 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3471 // `Array.prototype.filter` uses to store its result, and a species object made
3472 // non-extensible by its own constructor must make that a `TypeError`
3473 // (`target-array-non-extensible`).
3474 // Note the `is_none()`: an already-present property may still be **redefined** on a
3475 // non-extensible object, and only *adding* one is refused (as Distinct from
3476 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3477 // properties — testing extensibility before looking for the property made every
3478 // `Object.freeze` of an ordinary object refuse its own second step).
3479 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3480 return Ok(false);
3481 }
3482 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3483 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3484 // an omitted field is left alone). Merging here rather than at each call site is
3485 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3486 // the value and `enumerable` in place.
3487 //
3488 // The merge is a no-op when the property is absent: there is nothing to keep.
3489 let was_partial = property.descriptor_fields.is_some();
3490 let property = match property.descriptor_fields {
3491 None => property,
3492 Some(fields) => {
3493 let base = self.object_get_own_property(object, key)?;
3494 let mut merged = base.clone().unwrap_or_default();
3495 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3496 // descriptor names, and switching kind discards the other half —
3497 // `{set: f}` on a data property is an accessor with no getter, not a data
3498 // property whose `get` happens to be absent.
3499 let wants_accessor = fields.get || fields.set;
3500 let wants_data = fields.value || fields.writable;
3501 if wants_accessor {
3502 merged.value = None;
3503 merged.writable = false;
3504 merged.getter = property.getter.clone();
3505 merged.setter = property.setter.clone();
3506 } else if wants_data {
3507 merged.getter = None;
3508 merged.setter = None;
3509 if fields.value {
3510 merged.value = property.value.clone();
3511 }
3512 if fields.writable {
3513 merged.writable = property.writable;
3514 }
3515 }
3516 if fields.enumerable {
3517 merged.enumerable = property.enumerable;
3518 }
3519 if fields.configurable {
3520 merged.configurable = property.configurable;
3521 }
3522 merged.descriptor_fields = None;
3523 merged
3524 }
3525 };
3526 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3527 // descriptor. `define_property_on` runs the same check before it calls here, so an
3528 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3529 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3530 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3531 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3532 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3533 // own define would have refused.
3534 //
3535 // Only partial descriptors are validated here. A whole `Property` passed by an
3536 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3537 // what the descriptor "named", and those callers rely on the write landing.
3538 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3539 // Every branch below is gated on `!existing.configurable`: a *configurable*
3540 // property may be reshaped however the descriptor likes, which is why an
3541 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3542 // must succeed. Testing only `writable` refused that and broke
3543 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3544 let same_kind = existing.is_accessor() == property.is_accessor();
3545 if !same_kind {
3546 // Step 4: a non-configurable property may not change kind.
3547 if !existing.configurable {
3548 return Ok(false);
3549 }
3550 } else if existing.is_accessor() {
3551 // Step 6: an accessor's halves are its value.
3552 if !existing.configurable
3553 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3554 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3555 {
3556 return Ok(false);
3557 }
3558 } else if !existing.configurable && !existing.writable {
3559 // Step 7: a non-configurable *and* non-writable data property's value is
3560 // fixed, and it may not become writable again.
3561 if property.writable {
3562 return Ok(false);
3563 }
3564 let current = existing.value.clone().unwrap_or(Value::Undefined);
3565 let requested = property.value.clone().unwrap_or(Value::Undefined);
3566 if !current.same_value(&requested) {
3567 return Ok(false);
3568 }
3569 }
3570 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3571 // is frozen with it.
3572 if !existing.configurable
3573 && (property.configurable || property.enumerable != existing.enumerable)
3574 {
3575 return Ok(false);
3576 }
3577 }
3578 // A host class that intercepts definitions owns the attributes of the properties it
3579 // defines: `_class`-style storage on the native side is the usual reason.
3580 if let Some(exotic) = object.exotic()
3581 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3582 {
3583 return Ok(accepted);
3584 }
3585 // An array index is stored in the element vector, which can hold a plain value and
3586 // nothing else. An accessor — or a data property with non-default attributes —
3587 // therefore has to live in the property table, and the element slot is blanked so
3588 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3589 // {get})` stored the accessor where no read ever looked, and the array kept
3590 // answering its old value.
3591 // An array's `length` is not stored in the property table, so defining it has to
3592 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3593 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3594 // {value: 1})` reported success and changed nothing.
3595 if key.as_str() == Some("length") && object.is_array() {
3596 // `{writable: false}` on `length` does not change the length, but it does make
3597 // it read-only — after which neither a later `{writable: true}` nor a store
3598 // past the end may succeed.
3599 if property.value.is_none() {
3600 if !object.length_writable() && property.writable {
3601 return Ok(false);
3602 }
3603 object.set_length_writable(property.writable);
3604 return Ok(true);
3605 }
3606 if !object.length_writable() {
3607 return Ok(false);
3608 }
3609 }
3610 if key.as_str() == Some("length")
3611 && object.is_array()
3612 && let Some(value) = property.value.clone()
3613 {
3614 let requested = value.to_number();
3615 let valid = requested.is_finite()
3616 && requested >= 0.0
3617 && requested.fract() == 0.0
3618 && requested <= u32::MAX as f64;
3619 if !valid {
3620 return Err(self.range_error("invalid array length"));
3621 }
3622 // Truncating deletes the elements above the new length, and a non-configurable
3623 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3624 // makes `a.length = 2` fail rather than quietly drop it.
3625 let current = object.array_length().unwrap_or(0);
3626 let requested = requested as usize;
3627 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3628 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3629 // `[[Writable]]: false` when the descriptor asked for it — the length is
3630 // left at its old value but locked. Returning `false` alone left it
3631 // writable, which `verifyProperty` catches
3632 // (`defineProperties/15.2.3.7-6-a-164`).
3633 if property
3634 .descriptor_fields
3635 .is_some_and(|fields| fields.writable)
3636 && !property.writable
3637 && object.length_writable()
3638 {
3639 object.set_length_writable(false);
3640 }
3641 return Ok(false);
3642 }
3643 object.array_set_length(self.heap, requested);
3644 return Ok(true);
3645 }
3646 let plain = property.writable
3647 && property.enumerable
3648 && property.configurable
3649 && !property.is_accessor();
3650 if let Some(index) = key.as_str().and_then(array_index)
3651 && object.is_array()
3652 {
3653 // Growing the array needs a writable `length`: after
3654 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3655 // be added.
3656 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3657 return Ok(false);
3658 }
3659 if plain && property.value.is_some() {
3660 // An ordinary element: the vector is where a read looks first, so it has
3661 // to be the vector that changes — unless the index is too far out to be
3662 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3663 // one property, because past its own limit it stores the index as an
3664 // ordinary key. Falling through to `define_key` below is the same choice,
3665 // and the alternative was worse: the store used to be *dropped* and the
3666 // length left at 0, which is a silent wrong answer.
3667 let value = property.value.clone().unwrap_or(Value::Undefined);
3668 object.delete_key(key);
3669 if object.array_set(self.heap, index as usize, value) {
3670 return Ok(true);
3671 }
3672 // Past the dense limit the element lives in the table like any property.
3673 object.note_element_descriptor();
3674 object.define_key(key, property);
3675 // A sparse store past the dense limit still extends `length`, which is what
3676 // `a[a.length] = v` relies on — but only extends: shortening would delete
3677 // the sparse properties above the index, including this one.
3678 if index as usize + 1 > object.array_length().unwrap_or(0) {
3679 object.array_set_length(self.heap, index as usize + 1);
3680 }
3681 return Ok(true);
3682 }
3683 // A non-plain element — an accessor, or an attribute that is not the default —
3684 // lives in the table while the slot becomes a hole. Recording it keeps every
3685 // later `a[i] = v` off the dense path, where the write would have shadowed the
3686 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3687 // replace the accessor with a plain data property.
3688 object.note_element_descriptor();
3689 object.define_key(key, property);
3690 // The slot stays, so `length` does not shrink; a hole is not an element, so
3691 // the table entry is now what a read finds.
3692 object.array_set(self.heap, index as usize, Value::Hole);
3693 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3694 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3695 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3696 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3697 if index as usize + 1 > object.array_length().unwrap_or(0) {
3698 object.array_set_length(self.heap, index as usize + 1);
3699 }
3700 return Ok(true);
3701 }
3702 object.define_key(key, property);
3703 Ok(true)
3704 }
3705
3706 /// Build a proxy object over `target`, with its traps read from `handler`.
3707 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3708 JsObject::proxy(self.heap, target, handler)
3709 }
3710
3711 /// The `revoke` function for a proxy's slots.
3712 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3713 let revoke = JsObject::function(
3714 self.heap,
3715 Some(self.realm.function_proto.clone()),
3716 Callable::Revoker(slots),
3717 );
3718 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3719 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3720 // inherited from `Function.prototype` reads the same but fails the three cases that
3721 // check the own-property list (`revocation-function-{length,name,property-order}`).
3722 revoke.define("length", Property::name_or_length(Value::Int(0)));
3723 revoke.define("name", Property::name_or_length(self.string("")));
3724 revoke
3725 }
3726
3727 /// A new array.
3728 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3729 let array = JsObject::array(
3730 self.heap,
3731 Some(self.realm.array_proto.clone()),
3732 elements.len(),
3733 );
3734 for (index, element) in elements.into_iter().enumerate() {
3735 array.array_set(self.heap, index, element);
3736 }
3737 array
3738 }
3739
3740 /// A new native function object.
3741 ///
3742 /// The observable `name` and `length` are installed as properties here, which is
3743 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3744 /// so `f.name = "x"` behaves like the writable property it is.
3745 /// A native constructor that builds its own instance after validating its arguments.
3746 ///
3747 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3748 /// check runs before `new.target.prototype` is read.
3749 pub fn new_native_ctor(
3750 &self,
3751 name: impl Into<String>,
3752 length: u32,
3753 func: NativeFn,
3754 ) -> Gc<JsObject> {
3755 let function = JsObject::function(
3756 self.heap,
3757 Some(self.realm.function_proto.clone()),
3758 Callable::Native {
3759 func,
3760 own_instance: true,
3761 },
3762 );
3763 function.set_constructible(true);
3764 function.define(
3765 "length",
3766 Property::name_or_length(Value::Int(length as i32)),
3767 );
3768 function.define("name", Property::name_or_length(self.string(name)));
3769 function
3770 }
3771
3772 /// A native constructor that lets `new` build the instance first.
3773 ///
3774 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3775 /// validation that must precede reading `new.target.prototype`, so the object can be
3776 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3777 /// which makes a *method* and therefore not a constructor at all.
3778 pub fn new_native_constructor(
3779 &self,
3780 name: impl Into<String>,
3781 length: u32,
3782 func: NativeFn,
3783 ) -> Gc<JsObject> {
3784 let function = self.new_native(name, length, func);
3785 function.set_constructible(true);
3786 function
3787 }
3788
3789 /// A new host function object: a native closure that carries its own state.
3790 ///
3791 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3792 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3793 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3794 /// this safe: the closure must not capture a `Gc`.
3795 pub fn new_host_function(
3796 &self,
3797 name: impl Into<String>,
3798 length: u32,
3799 func: crate::object::HostFn,
3800 ) -> Gc<JsObject> {
3801 self.new_host_inner(name.into(), length, func, false)
3802 }
3803
3804 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3805 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3806 pub fn new_host_ctor(
3807 &self,
3808 name: impl Into<String>,
3809 length: u32,
3810 func: crate::object::HostFn,
3811 ) -> Gc<JsObject> {
3812 let function = self.new_host_inner(name.into(), length, func, true);
3813 function.set_constructible(true);
3814 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3815 // installs its own methods on it, so it starts as a plain object.
3816 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3817 function.define(
3818 "prototype",
3819 Property {
3820 value: Some(Value::Object(proto)),
3821 writable: true,
3822 enumerable: false,
3823 configurable: false,
3824 ..Property::default()
3825 },
3826 );
3827 function
3828 }
3829
3830 fn new_host_inner(
3831 &self,
3832 name: String,
3833 length: u32,
3834 func: crate::object::HostFn,
3835 own_instance: bool,
3836 ) -> Gc<JsObject> {
3837 let function = JsObject::function(
3838 self.heap,
3839 Some(self.realm.function_proto.clone()),
3840 Callable::Host {
3841 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3842 own_instance,
3843 },
3844 );
3845 function.define(
3846 "length",
3847 Property::name_or_length(Value::Int(length as i32)),
3848 );
3849 function.define("name", Property::name_or_length(self.string(name)));
3850 function
3851 }
3852
3853 /// A callable object with the `length`/`name` a built-in function has, in that order.
3854 ///
3855 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3856 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3857 /// [`JsObject::function`] defines neither, which is why every capability helper built
3858 /// with it reported no own `length` and no own `name` at all.
3859 ///
3860 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3861 /// configurable.
3862 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3863 let function =
3864 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3865 function.define(
3866 "length",
3867 Property::name_or_length(Value::Int(length as i32)),
3868 );
3869 function.define("name", Property::name_or_length(self.string(name)));
3870 function
3871 }
3872
3873 /// A new native function object.
3874 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3875 let function = JsObject::function(
3876 self.heap,
3877 Some(self.realm.function_proto.clone()),
3878 Callable::Native {
3879 func,
3880 own_instance: false,
3881 },
3882 );
3883 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3884 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3885 // `length,name` and this listed `name,length`. A bytecode function already gets it
3886 // the right way round; only native ones were built backwards.
3887 function.define(
3888 "length",
3889 Property::name_or_length(Value::Int(length as i32)),
3890 );
3891 function.define("name", Property::name_or_length(self.string(name)));
3892 function
3893 }
3894
3895 /// A new bound function.
3896 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3897 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3898 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3899 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3900 let constructible = target
3901 .as_object()
3902 .is_some_and(|target| target.is_constructor());
3903 let bound = JsObject::function(
3904 self.heap,
3905 Some(self.realm.function_proto.clone()),
3906 Callable::Bound { target, this, args },
3907 );
3908 bound.set_constructible(constructible);
3909 bound
3910 }
3911
3912 /// A new reference cell.
3913 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3914 Gc::new(self.heap, Cell::new(value))
3915 }
3916
3917 // -- running ------------------------------------------------------------
3918
3919 /// Evaluate `code` as a script body and return its completion value.
3920 /// Compile and run `source` for the engine's own use, returning its completion value.
3921 ///
3922 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3923 /// needs to be a real async function, and the engine already runs those as coroutines,
3924 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3925 ///
3926 /// Differences from [`Self::eval_in_global`], both deliberate:
3927 ///
3928 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3929 /// being built, and the source is an IIFE that only constructs a closure, so there
3930 /// is nothing to drain — and draining here would run script-queued jobs in the
3931 /// middle of `install`.
3932 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3933 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3934 /// and it should not look like the user wrote something wrong.
3935 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3936 let program = match js_parse::parse_script(source) {
3937 Ok(program) => program,
3938 Err(error) => {
3939 let message = format!("builtin source does not parse: {error}");
3940 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3941 }
3942 };
3943 let mut code = match js_compile::compile_script_with_source(&program, source) {
3944 Ok(code) => code,
3945 Err(error) => {
3946 let message = format!("builtin source does not compile: {}", error.message);
3947 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3948 }
3949 };
3950 // The frame has to name something, and `<builtin>` is what a stack trace through
3951 // this code should say.
3952 code.set_filename("<builtin>");
3953 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3954 let closure_vars = compiled.code.closure_vars.clone();
3955 let env = self.global_env(&closure_vars);
3956 let this = Value::Object(self.realm.global.clone());
3957 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3958 }
3959
3960 /// Run an already-parsed script and drain the microtasks it queued.
3961 ///
3962 /// The drain is what lets an `async` function's body advance past its first `await`
3963 /// before the host sees the result: nothing else pumps the job queue.
3964 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3965 let this = Value::Object(self.realm.global.clone());
3966 self.run_script_with_this(code, this)
3967 }
3968
3969 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3970 ///
3971 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3972 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3973 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3974 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3975 /// state the next script evaluation tripped over.
3976 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3977 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3978 let closure_vars = compiled.code.closure_vars.clone();
3979 let env = self.global_env(&closure_vars);
3980 let callee = Value::Undefined;
3981 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3982 // The script is done, so the microtasks it queued run before the host sees the
3983 // result. Without this an `async` function's body would never advance past its
3984 // first `await`, because nothing else drains the queue.
3985 self.drain_jobs()?;
3986 Ok(result)
3987 }
3988
3989 /// Compile and run `source` in global scope, returning its completion value.
3990 ///
3991 /// This is what `eval` and `new Function` use. Running it as a script means it
3992 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3993 /// for a `Function` body; a *direct* eval that reads a local variable would need
3994 /// the compiler to hand its variable environment over, which is not implemented.
3995 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3996 self.eval_in_global_named(source, EVAL_FILE, false)
3997 }
3998
3999 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
4000 ///
4001 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
4002 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
4003 /// through the code, so they cannot share one constant.
4004 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
4005 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
4006 }
4007
4008 /// Evaluate `source` as a global script, reported under `file`.
4009 ///
4010 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
4011 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
4012 /// from inside a C callback, where the interpreter is the running one rather than a
4013 /// context's own.
4014 pub fn eval_in_global_named(
4015 &mut self,
4016 source: &str,
4017 file: &str,
4018 barrier: bool,
4019 ) -> JsResult<Value> {
4020 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4021 // eval-created global binding — configurable, unlike a script's own `var`.
4022 self.eval_depth += 1;
4023 if barrier {
4024 let depth = self.frames.len();
4025 self.trace_barriers.push(depth);
4026 }
4027 let result = self.eval_in_global_inner(source, file);
4028 if barrier {
4029 self.trace_barriers.pop();
4030 }
4031 self.eval_depth -= 1;
4032 result
4033 }
4034
4035 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
4036 let compiled = self.compile_global_script(source, file, false)?;
4037 let strict = compiled.strict;
4038 self.run_eval_script(compiled, strict)
4039 }
4040
4041 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4042 ///
4043 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4044 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4045 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4046 /// direct eval's is.
4047 pub fn eval_script_with_this(
4048 &mut self,
4049 source: &str,
4050 file: &str,
4051 this: Value,
4052 ) -> JsResult<Value> {
4053 let program = match js_parse::parse_script(source) {
4054 Ok(program) => program,
4055 Err(error) => {
4056 return Err(Signal::Throw(self.syntax_error_at(
4057 file,
4058 error.span.start.line,
4059 error.span.start.column,
4060 &error.message,
4061 )));
4062 }
4063 };
4064 let mut compiled = match js_compile::compile_script(&program) {
4065 Ok(compiled) => compiled,
4066 Err(error) => {
4067 return Err(Signal::Throw(self.syntax_error_at(
4068 file,
4069 error.span.start.line,
4070 error.span.start.column,
4071 &error.message,
4072 )));
4073 }
4074 };
4075 compiled.set_filename(file);
4076 self.run_script_with_this(compiled, this)
4077 }
4078
4079 /// Parse and compile `source` as a global script, without running it.
4080 ///
4081 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4082 /// before a promise exists to reject — while still evaluating in the same eval context
4083 /// (direct-eval strictness, `new.target`, `super`).
4084 fn compile_global_script(
4085 &mut self,
4086 source: &str,
4087 file: &str,
4088 async_body: bool,
4089 ) -> JsResult<CompiledFunction> {
4090 // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4091 // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4092 // context at all. The site is what tells the two apart — an indirect call leaves no
4093 // site behind, since only a bare `eval(...)` is recorded.
4094 let site = self.eval_site_at_cursor();
4095 // Strictness follows the same rule, and it is *not* a detail: §19.2.1.1 step 4
4096 // makes the eval code strict when the caller is strict **and the call is direct**.
4097 // So `var s = eval; s("var eval;")` called from strict code is sloppy — legal —
4098 // while `eval("var eval;")` there is a `SyntaxError`
4099 // (`statements/variable/12.2.1-*-s`). Inheriting unconditionally rejected the
4100 // indirect form. A `"use strict"` prologue in the source still works either way:
4101 // the parser reads the directive itself, which is how a script becomes strict.
4102 let strict = site.is_some() && self.current_strict();
4103 // `eval` runs in the caller's function context, so `new.target` is legal here
4104 // even though the source is a bare script — and so is `super.x` when the caller
4105 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4106 // caller's, which is what `special_object 4` already does.
4107 let private = site
4108 .map(|site| site.private_names.clone())
4109 .unwrap_or_default();
4110 let context = js_parse::EvalContext {
4111 in_method: site.is_some() && self.enclosing_home_object().is_some(),
4112 // `super()` belongs to a derived constructor, and an eval'd body is not a
4113 // constructor at all: the caller frame's `this` is already built.
4114 in_derived_constructor: false,
4115 // Private names are lexically scoped, so a direct `eval` inside a class body
4116 // can see them; see `Interp::eval_private_names`.
4117 private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4118 arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4119 new_target_allowed: site.is_some(),
4120 };
4121 // A *global* eval is not a function body: `new.target` and `super` are out of
4122 // reach there. Its `{async: true}` form differs in the other direction — the body
4123 // may `await` — so the two flags are independent and the reference sets both from
4124 // the eval type rather than from the caller.
4125 let parsed = if async_body {
4126 js_parse::parse_suspensible_global_eval(source, strict)
4127 } else {
4128 js_parse::parse_eval_script_in(source, strict, context)
4129 };
4130 let program = match parsed {
4131 Ok(program) => program,
4132 Err(error) => {
4133 // The message is bare: the position lives in `fileName`,
4134 // `lineNumber`, `columnNumber` and the stack frame above, which is where
4135 // the reference puts it. An `invalid source: L:C: ` prefix made
4136 // `e.message` differ from the reference while the stack already agreed.
4137 return Err(Signal::Throw(self.syntax_error_at(
4138 file,
4139 error.span.start.line,
4140 error.span.start.column,
4141 &error.message,
4142 )));
4143 }
4144 };
4145 let mut compiled = match if async_body {
4146 js_compile::compile_eval_with_private(&program, &private, true)
4147 } else {
4148 js_compile::compile_eval_with_private(&program, &private, false)
4149 } {
4150 Ok(compiled) => compiled,
4151 // A construct the compiler does not handle yet is reported the same way a
4152 // parse error is: it happens before anything runs, so the trace is the
4153 // position in the source followed by the caller.
4154 Err(error) => {
4155 return Err(Signal::Throw(self.syntax_error_at(
4156 file,
4157 error.span.start.line,
4158 error.span.start.column,
4159 &error.message,
4160 )));
4161 }
4162 };
4163 compiled.set_filename(file);
4164 Ok(compiled)
4165 }
4166
4167 /// The private names the code at the current position can see, innermost first.
4168 ///
4169 /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4170 /// direct `eval` runs inside its caller's scope, so
4171 /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4172 /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4173 /// here rather than being derivable from the eval'd source.
4174 ///
4175 /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4176 /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4177 /// [`Interp::run_eval_script`] uses for "direct".
4178 fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4179 let frame = self.frames.last()?;
4180 let (line, column) = frame
4181 .code
4182 .code
4183 .position_at(frame.at as u32)
4184 .unwrap_or_default();
4185 // The nearest site at or before the current position: the recorded position of the
4186 // `call` instruction is the callee's, which sits a few columns inside the call
4187 // expression the compiler recorded, so an exact match would never be found.
4188 frame
4189 .code
4190 .code
4191 .eval_sites
4192 .iter()
4193 .filter(|site| (site.line, site.column) <= (line, column))
4194 .max_by_key(|site| (site.line, site.column))
4195 }
4196
4197 /// Run an `eval`'d script in the caller's scope.
4198 ///
4199 /// Three things have to come from the calling frame, because the eval'd code is a
4200 /// script and would otherwise see only the global object:
4201 ///
4202 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4203 /// * `arguments`, exposed as a binding of the eval's own scope, so
4204 /// `f("arguments.length", 1)` sees the caller's arguments;
4205 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4206 /// `eval("var v = 1")` into the global object.
4207 ///
4208 /// Locals of the calling function are *not* reachable: that needs the compiler to
4209 /// hand its variable environment over, which this milestone does not do.
4210 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4211 // `this` and `arguments` come from the innermost frame only — those are not
4212 // lexical — while the name bindings come from the whole chain of frames, part
4213 // of it being ordinary scope resolution.
4214 // An arrow has no `this` of its own, so an `eval` inside one inherits the
4215 // enclosing function's receiver — the lexical `this` the arrow was compiled to
4216 // read from its closure.
4217 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4218 // variable environment is the innermost frame of all: an arrow's own body is where
4219 // `var`s declared by an `eval` inside it belong.
4220 let caller_index = self
4221 .frames
4222 .iter()
4223 .rposition(|frame| !frame.code.code.is_arrow)
4224 .or_else(|| self.frames.len().checked_sub(1));
4225 let env_index = self.frames.len().checked_sub(1);
4226 let caller = caller_index.and_then(|index| self.frames.get(index));
4227 let (this, passed) = match caller {
4228 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4229 // No frame at all: the eval is running at the top level, so there is
4230 // nothing to inherit and the global receiver is right.
4231 None => (Value::Object(self.realm.global.clone()), Vec::new()),
4232 };
4233 // Innermost frame first, so the first binding found for a name is the one that
4234 // shadows the rest. A script frame (`<eval>`) contributes nothing.
4235 let mut bindings: Vec<EvalBinding> = Vec::new();
4236 // The calling function's own bindings, resolved by the compiler at the call
4237 // site. That table is the only reliable answer when a name is declared twice in
4238 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4239 // body means, and guessing by declaration order picks the wrong one as soon as
4240 // two loops in a row use the same name.
4241 // Only a *direct* eval sees the caller's scope. The compiler records a site for
4242 // every direct call — a bare `eval(...)` callee — so finding one at the current
4243 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4244 // callee to a value first and leave no site behind.
4245 let mut direct = false;
4246 let mut resolved_here = false;
4247 if let Some(frame) = self.frames.last() {
4248 let (line, column) = frame
4249 .code
4250 .code
4251 .position_at(frame.at as u32)
4252 .unwrap_or_default();
4253 // The nearest site at or before the current position, not an exact match:
4254 // the recorded position of the `call` instruction is the callee's, which
4255 // sits a few columns inside the call expression the compiler recorded. A
4256 // site is unique per call, so "the closest one behind us" identifies it.
4257 if let Some(site) = frame
4258 .code
4259 .code
4260 .eval_sites
4261 .iter()
4262 .filter(|site| (site.line, site.column) <= (line, column))
4263 .max_by_key(|site| (site.line, site.column))
4264 {
4265 direct = true;
4266 resolved_here = true;
4267 for binding in &site.bindings {
4268 // An enclosing function's frame sits `owner` levels below the one
4269 // running the call.
4270 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4271 else {
4272 continue;
4273 };
4274 bindings.push(EvalBinding {
4275 name: binding.name.clone(),
4276 frame,
4277 slot: if binding.is_arg {
4278 EvalSlot::Arg
4279 } else {
4280 EvalSlot::Local
4281 },
4282 index: binding.index as usize,
4283 });
4284 }
4285 }
4286 }
4287 for frame_index in (0..self.frames.len()).rev() {
4288 // Skip the innermost frame's flat scan when the compiler already answered
4289 // for it; an enclosing frame still needs one, because the eval resolves
4290 // those names dynamically.
4291 if resolved_here && frame_index == self.frames.len() - 1 {
4292 continue;
4293 }
4294 let frame = &self.frames[frame_index];
4295 for (index, arg) in frame.code.code.args.iter().enumerate() {
4296 bindings.push(EvalBinding {
4297 name: arg.name.clone(),
4298 frame: frame_index,
4299 slot: EvalSlot::Arg,
4300 index,
4301 });
4302 }
4303 for (index, local) in frame.code.code.vars.iter().enumerate() {
4304 bindings.push(EvalBinding {
4305 name: local.name.clone(),
4306 frame: frame_index,
4307 slot: EvalSlot::Local,
4308 index,
4309 });
4310 }
4311 }
4312 let mut seen = BTreeSet::new();
4313 bindings.retain(|binding| seen.insert(binding.name.clone()));
4314
4315 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4316 // elements is all the spec's ordinary uses need.
4317 //
4318 // Known divergence: this is bound for a *global* eval too, where there is no
4319 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4320 // needs "does the calling frame have an `arguments` of its own", which is not
4321 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4322 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4323 // the call-site detection does not answer it. Modelled as a binding in the caller's
4324 // variable environment, this would fall out; that is a larger change than the one
4325 // this comment is attached to.
4326 let arguments = Value::Object(self.new_array(passed));
4327
4328 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4329 // declares its `var`s in the caller's — which for a top-level eval is the global
4330 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4331 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4332 // vanish into a scope nobody reads back from.
4333 let previous_scope = if code_strict {
4334 self.eval_scope.replace(BTreeMap::new())
4335 } else {
4336 None
4337 };
4338 // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4339 // in global scope, where `arguments` means whatever the global object says — which
4340 // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4341 // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4342 // answer the array instead.
4343 let previous_arguments = if direct {
4344 self.eval_arguments.replace(arguments)
4345 } else {
4346 None
4347 };
4348 let previous_with = self.eval_with.replace(self.with_objects());
4349 let inherited_new_target = self
4350 .frames
4351 .iter()
4352 .rev()
4353 .find(|frame| !frame.code.code.is_arrow)
4354 .map(|frame| frame.new_target.clone());
4355 let previous_new_target = self
4356 .eval_new_target
4357 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4358 let eval_cells = self.eval_cells_for(&bindings);
4359 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4360 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4361 // `declare_eval_local` needs to know which frame that is.
4362 // An indirect eval gets the global environment, so nothing of the caller's is
4363 // recorded as the place its `var`s belong.
4364 let previous_caller = self
4365 .eval_caller
4366 .replace(if direct { env_index } else { None });
4367 // The cell-based view of the same bindings, which is what a closure created
4368 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4369 // whose compiler did not put a binding in a cell simply does not appear here —
4370 // reads and writes still work through `eval_bindings`, they just cannot outlive
4371 // the eval.
4372 let previous_eval_scope = self
4373 .active_eval_scope
4374 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4375 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4376 let closure_vars = compiled.code.closure_vars.clone();
4377 // Declaration instantiation is where this belongs: the check needs the caller frame
4378 // (recorded just above) and the eval's own var names, and it raises before any of
4379 // the eval's code runs.
4380 self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4381 let env = self.global_env(&closure_vars);
4382 let callee = Value::Undefined;
4383 // An async body does not run here: it becomes a coroutine and answers a promise,
4384 // which is what makes `await` legal in it. `this` still has to be the caller's
4385 // (for a global eval, the global object), because `this` is not part of `await`.
4386 let result = if compiled.code.kind.is_async() {
4387 self.run_async_body(compiled, env, this)
4388 } else {
4389 self.execute(compiled, env, this, Vec::new(), callee)
4390 };
4391 self.eval_scope = previous_scope;
4392 self.eval_arguments = previous_arguments;
4393 self.eval_with = previous_with;
4394 self.eval_new_target = previous_new_target;
4395 self.eval_bindings = previous_bindings;
4396 self.eval_caller = previous_caller;
4397 self.active_eval_scope = previous_eval_scope;
4398 result
4399 }
4400
4401 /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4402 /// rather than bindings.
4403 ///
4404 /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4405 /// declaration that cannot exist:
4406 ///
4407 /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4408 /// parameter expressions a separate parameter environment, and `arguments` is bound
4409 /// implicitly there, so a `var` of that name collides. An arrow that binds no
4410 /// `arguments` of its own has nothing to collide with and is allowed — see the table in
4411 /// [`Interp::check_eval_var_named_arguments`].
4412 /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4413 /// false; the operation is a `TypeError`, and `eval("var x")` with
4414 /// `Object.preventExtensions(this)` must raise rather than quietly do nothing
4415 /// (`non-definable-global-var` and its four siblings).
4416 fn check_eval_var_named_arguments(
4417 &self,
4418 closure_vars: &[js_compile::bytecode::ClosureVar],
4419 strict: bool,
4420 ) -> JsResult<()> {
4421 if strict {
4422 return Ok(());
4423 }
4424 // A `var` this eval would declare on the global object, where there is no room for it.
4425 let global = &self.realm.global;
4426 if !global.is_extensible() {
4427 for var in closure_vars {
4428 if var.is_lexical || var.name == "*default*" {
4429 continue;
4430 }
4431 let declare = matches!(
4432 var.closure_type,
4433 js_compile::bytecode::ClosureType::GlobalDecl
4434 );
4435 if declare && global.own_property(&var.name).is_none() {
4436 return Err(Signal::Throw(self.make_error(
4437 "TypeError",
4438 "cannot declare a global in a non-extensible global object",
4439 )));
4440 }
4441 }
4442 }
4443 // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4444 // global environment, where `var arguments` is an ordinary global.
4445 let Some(caller) = self.eval_caller.flatten() else {
4446 return Ok(());
4447 };
4448 // §19.2.1.1 step 8: in a sloppy eval, a `var` name that the *running lexical
4449 // environment* already binds is a `SyntaxError`. While a default expression is being
4450 // evaluated that environment is the **parameter** scope, so
4451 // `function(a = eval("var a = 42")){}` throws rather than writing to the parameter —
4452 // the eval would otherwise declare into an environment that is about to be copied
4453 // into the body. A *different* name is fine, and so is the same name in a function
4454 // with a simple parameter list, where there is no separate parameter environment and
4455 // the `var` belongs to the function's own.
4456 //
4457 // The names come from `args`, which is exactly the plain-identifier parameters. A
4458 // pattern parameter's bindings are also in that scope but are not recoverable from
4459 // the bytecode, so `function([a] = eval("var a")){}` is still accepted; that gap is
4460 // narrower than the one this closes and needs the parameter scope published in the
4461 // compiled function to fix.
4462 if self.in_parameter_list_at(caller) {
4463 let parameter_names: Vec<String> = self
4464 .frames
4465 .get(caller)
4466 .map(|frame| {
4467 frame
4468 .code
4469 .code
4470 .args
4471 .iter()
4472 .map(|arg| arg.name.clone())
4473 .collect()
4474 })
4475 .unwrap_or_default();
4476 let collides = closure_vars.iter().any(|var| {
4477 !var.is_lexical && var.name != "*default*" && parameter_names.contains(&var.name)
4478 });
4479 if collides {
4480 return Err(Signal::Throw(self.make_error(
4481 "SyntaxError",
4482 "eval declares a var that the parameter scope already binds",
4483 )));
4484 }
4485 }
4486 if !closure_vars
4487 .iter()
4488 .any(|var| var.name == "arguments" && !var.is_lexical)
4489 {
4490 return Ok(());
4491 }
4492 // The body of a function is a different environment from its parameter list, and only
4493 // the parameter list is separate from `arguments`.
4494 if !self.in_parameter_list_at(caller) {
4495 return Ok(());
4496 }
4497 let caller_is_arrow = self
4498 .frames
4499 .get(caller)
4500 .is_some_and(|frame| frame.code.code.is_arrow);
4501 // A *parameter* named `arguments`, not merely a binding of that name: a body
4502 // `let arguments` is in the body's environment, which is the one that is separate and
4503 // therefore cannot collide. The slot tells them apart — an argument lives in
4504 // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4505 let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4506 binding.frame == caller
4507 && binding.name == "arguments"
4508 && matches!(binding.slot, EvalSlot::Arg)
4509 });
4510 if caller_is_arrow && !parameter_scope_binds_arguments {
4511 return Ok(());
4512 }
4513 Err(Signal::Throw(self.make_error(
4514 "SyntaxError",
4515 "eval declares 'arguments' in a function's parameter scope",
4516 )))
4517 }
4518
4519 /// The cell-backed subset of `bindings`, in the same priority order.
4520 ///
4521 /// Both lookup routes have to agree — the eval's own reads go through
4522 /// [`Interp::eval_binding_value`] and the closures it builds go through
4523 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4524 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4525 /// is not in a cell simply does not appear: reads and writes still work, they just
4526 /// cannot be handed to a closure that outlives the eval.
4527 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4528 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4529 for binding in bindings {
4530 let Some(frame) = self.frames.get(binding.frame) else {
4531 continue;
4532 };
4533 let cell = match binding.slot {
4534 EvalSlot::Arg => frame
4535 .code
4536 .arg_cell
4537 .get(binding.index)
4538 .copied()
4539 .unwrap_or(-1),
4540 EvalSlot::Local => frame
4541 .code
4542 .loc_cell
4543 .get(binding.index)
4544 .copied()
4545 .unwrap_or(-1),
4546 };
4547 if cell < 0 {
4548 continue;
4549 }
4550 if let Some(cell) = frame.cells.get(cell as usize) {
4551 names.push((binding.name.clone(), cell.clone()));
4552 }
4553 }
4554 names
4555 }
4556
4557 /// A `SyntaxError` that reports where in the source it happened.
4558 ///
4559 /// Compile-time failures never run, so they have no frame of their own; the
4560 /// reference still puts the position first in the trace, with no function name and
4561 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4562 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4563 /// reference borrows), which is how a script reads the position without parsing
4564 /// the trace.
4565 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4566 ///
4567 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4568 /// `columnNumber`, which is how the reference prints one. A positionless error
4569 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4570 /// the reference raises it from `js_resolve_module`, where there is no position.
4571 pub(crate) fn syntax_error_plain(
4572 &mut self,
4573 error: &js_parse::SyntaxError,
4574 file: &str,
4575 ) -> Value {
4576 if error.positionless {
4577 return self.make_error("SyntaxError", &error.message);
4578 }
4579 self.syntax_error_at(
4580 file,
4581 error.span.start.line,
4582 error.span.start.column,
4583 &error.message,
4584 )
4585 }
4586
4587 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4588 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4589 let value = self.make_error("SyntaxError", message);
4590 if let Value::Object(object) = &value {
4591 let text = self.string(blamed);
4592 // `stack` is an own data property, and the reference keeps it
4593 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4594 object.define("stack", Property::with_attributes(text, true, false));
4595 let name = self.string(file);
4596 object.define("fileName", Property::with_attributes(name, true, true));
4597 object.define(
4598 "lineNumber",
4599 Property::with_attributes(Value::Int(line as i32), true, true),
4600 );
4601 object.define(
4602 "columnNumber",
4603 Property::with_attributes(Value::Int(column as i32), true, true),
4604 );
4605 }
4606 value
4607 }
4608
4609 /// Run a compiled script whose completion value is a function, returning it.
4610 ///
4611 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4612 /// get the closure out, which keeps the constant-pool plumbing in one place.
4613 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4614 self.run_script(code)
4615 }
4616
4617 /// The environment of a script or of any function compiled at global scope:
4618 /// every entry is a global binding, so each one resolves to the realm's cell.
4619 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4620 let mut cells = Vec::with_capacity(closure_vars.len());
4621 for closure_var in closure_vars {
4622 let cell = match closure_var.closure_type {
4623 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4624 if closure_var.is_lexical =>
4625 {
4626 // A lexical declaration: the cell is created here holding the
4627 // dead-zone marker, which is what makes the binding exist and
4628 // unreadable before its initialiser runs.
4629 self.declare_global(&closure_var.name, closure_var.is_const);
4630 self.realm.globals[&closure_var.name].clone()
4631 }
4632 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4633 // A `var` or function declaration becomes a property of the global
4634 // object, and it exists from here on — which is why
4635 // `print(v); var v = 1` prints `undefined` instead of raising.
4636 // Declaring it at instantiation time (rather than at the
4637 // initialiser) is also what makes it non-configurable: the store
4638 // then lands on an existing property instead of creating one.
4639 self.declare_var_global(&closure_var.name);
4640 // The cell is a placeholder that nothing indexes; it cannot be
4641 // omitted because the slot has to hold something.
4642 self.new_cell(Value::Undefined)
4643 }
4644 _ => {
4645 // An undeclared global is read by name; the cell is a
4646 // placeholder that nothing indexes.
4647 self.new_cell(Value::Undefined)
4648 }
4649 };
4650 cells.push(cell);
4651 }
4652 Gc::new(
4653 self.heap,
4654 ClosureEnv {
4655 cells,
4656 eval_scope: None,
4657 local_vars: None,
4658 local_phase: 1,
4659 },
4660 )
4661 }
4662
4663 /// Push a frame and run until it returns.
4664 pub(crate) fn execute(
4665 &mut self,
4666 code: Gc<CompiledCode>,
4667 env: Gc<ClosureEnv>,
4668 this: Value,
4669 args: Vec<Value>,
4670 callee: Value,
4671 ) -> JsResult<Value> {
4672 let depth = self.frames.len();
4673 if depth == 0 {
4674 // A throw that reached the host ends the *active* mode: the next one is catchable
4675 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4676 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4677 // for the throw that evaluation will raise.
4678 self.uncatchable = false;
4679 }
4680 self.push_frame(code, env, this, args, callee)?;
4681 loop {
4682 // The fast loop first: it runs whole runs of records with `pc` in a register.
4683 //
4684 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4685 // reads it again — a store, a load and two bounds checks that a loop body does
4686 // not need, because nothing outside the loop can run in between. This is the
4687 // classic split: advance a register, and only spill it when leaving.
4688 //
4689 // `Some(value)` means the function ended by running off the end of its
4690 // instruction array, which is a normal return.
4691 let step = match self.run_fast() {
4692 Ok(Some(value)) => Ok(Step::Return(value)),
4693 Ok(None) => self.step(),
4694 Err(signal) => Err(signal),
4695 };
4696 match step {
4697 Ok(Step::Continue) => {}
4698 Ok(Step::Return(value)) => {
4699 self.pop_frame();
4700 // A frame that ended in a `tail_call` hands its value straight to
4701 // its caller: nothing after the call can run, so every frame above
4702 // the callee unwinds with the same value. See [`Frame::tail`] —
4703 // the reference does not reuse frames either, so recursion depth
4704 // and the stack-overflow limit behave the same way.
4705 while self.frames.len() > depth && self.frame().tail {
4706 self.pop_frame();
4707 }
4708 if self.frames.len() == depth {
4709 return Ok(value);
4710 }
4711 // The caller resumes with the value on its stack.
4712 self.frames
4713 .last_mut()
4714 .expect("a caller is live")
4715 .stack
4716 .push(value);
4717 }
4718 Err(Signal::Throw(value)) => {
4719 // The host's standing request becomes the active mode for this unwind,
4720 // and is consumed here so it does not leak into the next throw.
4721 if self.uncatchable_next {
4722 self.uncatchable_next = false;
4723 self.uncatchable = true;
4724 }
4725 // An uncatchable throw walks past every `catch` on the way out. The
4726 // frames are still popped, because the values they hold have to be
4727 // dropped — only the search for a handler is skipped.
4728 if self.uncatchable {
4729 while self.frames.len() > depth {
4730 self.frames.pop();
4731 }
4732 return Err(Signal::Throw(value));
4733 }
4734 // A handler lives on the stack of the frame that is throwing —
4735 // `catch` pushed it there — so this frame gets the first chance
4736 // to catch before it is popped.
4737 let mut value = value;
4738 loop {
4739 if self.frames.len() <= depth {
4740 return Err(Signal::Throw(value));
4741 }
4742 if self.catch_here(&mut value).is_some() {
4743 break;
4744 }
4745 self.frames.pop();
4746 }
4747 }
4748 // A `yield` in a frame that `execute` is running directly means a
4749 // generator body was entered as an ordinary call, which only happens if
4750 // the generator check in `call_or_push` was bypassed.
4751 Ok(Step::Suspend(_)) => {
4752 return Err(Signal::Throw(self.make_error(
4753 "InternalError",
4754 "a generator body ran as an ordinary call",
4755 )));
4756 }
4757 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4758 }
4759 }
4760 }
4761
4762 /// Install a handler for `value` if this frame has one, resuming at it.
4763 ///
4764 /// The scan is the reference's: walk the frame's stack downwards looking for the
4765 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4766 /// enumerator marker rather than a handler — `for of` keeps one under its record so
4767 /// that `break` and `return` can find the iterator — and an exception reaching one
4768 /// **closes that iterator** before the unwinding continues.
4769 ///
4770 /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4771 /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4772 /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4773 /// close the iterator while the reference to store into is being worked out.
4774 ///
4775 /// `value` is `&mut` because closing the iterator may replace it: see
4776 /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4777 fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4778 loop {
4779 // Popped one at a time so no frame borrow is held across the close below.
4780 let top = self.frames.last_mut()?.stack.pop()?;
4781 let Value::CatchOffset(offset) = top else {
4782 continue;
4783 };
4784 if offset != 0 {
4785 let frame = self.frames.last_mut().expect("the frame was just read");
4786 frame.stack.push(value.clone());
4787 frame.pc = offset as usize;
4788 return Some(());
4789 }
4790 // The record's `iter` and `next` sit directly below the marker.
4791 let close = {
4792 let frame = self.frames.last_mut().expect("the frame was just read");
4793 let next = frame.stack.pop();
4794 let iterator = frame.stack.pop();
4795 match (iterator, next) {
4796 (Some(iterator), Some(_next)) => Some(iterator),
4797 // A malformed record cannot be closed, but unwinding still has to go
4798 // on: this is not a handler, so there is nothing to resume at.
4799 _ => None,
4800 }
4801 };
4802 if let Some(iterator) = close {
4803 self.close_iterator_on_throw(iterator);
4804 }
4805 }
4806 }
4807
4808 /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4809 ///
4810 /// Two things differ from the ordinary close, both from the spec's step ordering:
4811 ///
4812 /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4813 /// return ? completion`) comes before step 5, so an exception raised by `return()`
4814 /// itself — or by reading it — is discarded;
4815 /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4816 ///
4817 /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4818 /// it saves the pending exception, clears the slot, and re-throws the saved one from
4819 /// `done:` no matter what happened in between.
4820 fn close_iterator_on_throw(&mut self, iterator: Value) {
4821 if matches!(iterator, Value::Undefined) {
4822 return;
4823 }
4824 let Ok(method) = self.read_field(&iterator, "return") else {
4825 return;
4826 };
4827 if matches!(method, Value::Undefined | Value::Null) {
4828 return;
4829 }
4830 // A throw from `return()` replaces nothing: the exception already being unwound is
4831 // the one that propagates.
4832 let _ = self.call_value(method, iterator, Vec::new());
4833 }
4834
4835 fn push_frame(
4836 &mut self,
4837 code: Gc<CompiledCode>,
4838 env: Gc<ClosureEnv>,
4839 this: Value,
4840 mut args: Vec<Value>,
4841 callee: Value,
4842 ) -> JsResult<()> {
4843 // Two bounds, and the byte budget is the one that decides in practice. The
4844 // reference's message is `stack overflow` on an `InternalError`, not V8's
4845 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4846 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4847 let frame_cost = Self::frame_cost(&code);
4848 let stack_base = self.stack_used();
4849 if self.frames.len() >= self.max_frames
4850 || stack_base.saturating_add(frame_cost) > self.stack_limit
4851 {
4852 return Err(Signal::Throw(
4853 self.make_error("InternalError", "stack overflow"),
4854 ));
4855 }
4856 let arg_count = code.code.args.len();
4857 // How many were actually passed, which `arguments.length` reports and
4858 // `assert(x)` depends on: a call with one argument must not look like a call
4859 // with one argument and an explicit `undefined`.
4860 let passed = args.len();
4861 // Missing arguments are `undefined` in their slots; extra ones are dropped
4862 // from the slots but still reachable through `arguments`.
4863 //
4864 // A call that passes no more than the declared parameters needs **no** copy:
4865 // after the resize below, `args[..passed]` *is* the passed values. Only the
4866 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4867 // the rare case. This used to copy every call: one `Value` clone per argument
4868 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4869 let passed_overflow = (passed > arg_count).then(|| {
4870 let mut values = self.take_values(passed, Value::Undefined);
4871 values[..passed].clone_from_slice(&args[..passed]);
4872 values
4873 });
4874 // Only when the counts differ, which for the overwhelmingly common call — as many
4875 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4876 // lengths is two length compares and nothing else, but this is the hottest few
4877 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4878 if passed != arg_count {
4879 args.resize(arg_count, Value::Undefined);
4880 args.truncate(arg_count);
4881 }
4882 let cell_count = code.code.var_ref_count as usize;
4883 let mut cells = Vec::with_capacity(cell_count);
4884 for _ in 0..cell_count {
4885 cells.push(self.new_cell(Value::Undefined));
4886 }
4887 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4888 // A captured argument lives in its cell, not in the argument slot, so the
4889 // incoming value has to be moved there before the body runs.
4890 for (slot, cell) in code.arg_cell.iter().enumerate() {
4891 if *cell >= 0
4892 && let Some(value) = args.get(slot).cloned()
4893 {
4894 cells[*cell as usize].set(value);
4895 }
4896 }
4897 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4898 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4899 // reports `object`. Strict mode passes the value through untouched.
4900 let this = if code.code.strict {
4901 this
4902 } else if this.is_nullish() {
4903 Value::Object(self.realm.global.clone())
4904 } else if matches!(this, Value::Object(_)) {
4905 this
4906 } else {
4907 match crate::builtins::this_object(self, &this) {
4908 Ok(boxed) => Value::Object(boxed),
4909 Err(_) => this,
4910 }
4911 };
4912 let stack_depth = code.code.stack_size as usize + 1;
4913 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4914 // out of the same recycle pool the locals did.
4915 let stack = self.take_values(stack_depth, Value::Undefined);
4916 self.frames.push(Frame {
4917 code,
4918 env,
4919 this,
4920 args,
4921 passed_count: passed,
4922 passed_overflow: passed_overflow.map(Box::new),
4923 locals,
4924 cells,
4925 local_vars: None,
4926 // Exactly the depth the compiler computed, so the operand stack never
4927 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4928 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4929 // the buffer between calls, so "exactly" costs nothing after the first one.
4930 stack,
4931 pc: 0,
4932 at: 0,
4933 callee,
4934 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4935 cost: frame_cost,
4936 stack_base,
4937 tail: false,
4938 });
4939 Ok(())
4940 }
4941
4942 /// A value buffer of `len` slots, from the recycle pool when there is one.
4943 ///
4944 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4945 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4946 // A frame with no locals asks for nothing, and that is most frames: taking a
4947 // buffer out of the pool, clearing it and resizing it to zero is four operations
4948 // and a pool pop for an empty `Vec`, which is free to construct.
4949 if len == 0 {
4950 return Vec::new();
4951 }
4952 let mut buffer = self.free_values.pop().unwrap_or_default();
4953 buffer.clear();
4954 buffer.resize(len, fill);
4955 buffer
4956 }
4957
4958 /// Return a finished frame's value buffers for the next call to reuse.
4959 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4960 for mut buffer in [
4961 std::mem::take(&mut frame.locals),
4962 frame
4963 .passed_overflow
4964 .take()
4965 .map(|buffer| *buffer)
4966 .unwrap_or_default(),
4967 std::mem::take(&mut frame.stack),
4968 ] {
4969 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4970 // GC root: it kept every value the frame held reachable, which is invisible
4971 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4972 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4973 // exactly that within one run — the target `{}` of a finished IIFE was still
4974 // in its operand stack, in the pool.
4975 buffer.clear();
4976 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4977 // fill the pool with nothing to offer.
4978 if free_values.len() < RECYCLE_SLOTS
4979 && buffer.capacity() > 0
4980 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4981 {
4982 free_values.push(buffer);
4983 }
4984 }
4985 }
4986
4987 /// Pop a finished frame and keep its buffers.
4988 ///
4989 /// Every place that drops a frame goes through here: a recycled buffer is also where
4990 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4991 /// nothing but the reuse.
4992 fn pop_frame(&mut self) -> Option<()> {
4993 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4994 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4995 let last = self.frames.len().checked_sub(1)?;
4996 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4997 self.frames.truncate(last);
4998 Some(())
4999 }
5000
5001 /// Poll the host's interrupt handler, if one is installed.
5002 ///
5003 /// The counter is what keeps this off the hot path when nobody asked: the early return is
5004 /// one `Option` test, and with no handler installed the whole function is that test —
5005 /// `check_memory` next door already costs more, so this cannot be what shows up in a
5006 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
5007 #[inline]
5008 fn check_interrupt(&mut self) -> JsResult<()> {
5009 if self.interrupt.is_none() {
5010 return Ok(());
5011 }
5012 if self.interrupt_counter > 0 {
5013 self.interrupt_counter -= 1;
5014 return Ok(());
5015 }
5016 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
5017 // The closure is taken out for the duration so that a handler which re-enters the
5018 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
5019 let mut handler = self.interrupt.take().expect("checked above");
5020 let abort = handler();
5021 self.interrupt = Some(handler);
5022 if abort {
5023 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
5024 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
5025 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
5026 // documentation says.
5027 self.uncatchable = true;
5028 return Err(Signal::Throw(
5029 self.make_error("InternalError", "interrupted"),
5030 ));
5031 }
5032 Ok(())
5033 }
5034
5035 /// A memory checkpoint: does the heap still fit under its limit?
5036 ///
5037 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
5038 /// a `Cell` read and a predictable branch, and the point of asking that often is that
5039 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
5040 /// only at calls would let it run until the machine died, which is the exact failure
5041 /// `--memory-limit` exists to prevent.
5042 ///
5043 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
5044 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
5045 /// script that catches it, drops the reference and carries on is legitimate: measured
5046 /// on `qjs --memory-limit 1M`, the engine recovers.
5047 fn check_memory(&mut self) -> JsResult<()> {
5048 // One `Cell` read and a predictable branch when no limit is set, and an integer
5049 // compare when one is. Containers report their own growth as it happens
5050 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
5051 // walking it here was the first version and it was O(live) per 256 instructions,
5052 // which turned a 100k-element push loop into a five-minute one.
5053 let Some(limit) = self.heap.memory_limit() else {
5054 return Ok(());
5055 };
5056 let used = self.heap.used_bytes();
5057 if used <= limit {
5058 // Back under the limit — a collection or a dropped reference did it. The next
5059 // time it goes over is a new failure, not a repeat of this one.
5060 self.oom_reported_at = 0;
5061 return Ok(());
5062 }
5063 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5064 // block runs normally after `out of memory` — it allocates nothing, so nothing
5065 // fails. A check that re-fired on every instruction made the handler itself throw,
5066 // which is a dead end: the error became unobservable from script.
5067 //
5068 // Comparing against the total at the last report gives the same behaviour: the
5069 // handler runs while the total is unchanged, and the very next allocation over the
5070 // limit fails.
5071 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5072 {
5073 return Ok(());
5074 }
5075 self.oom_reported_at = used;
5076 Err(Signal::Throw(
5077 self.make_error("InternalError", "out of memory"),
5078 ))
5079 }
5080
5081 /// Fail before allocating `payload` bytes, if they would not fit.
5082 ///
5083 /// For the allocations whose size comes from script data — `new Array(n)`,
5084 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5085 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5086 /// answering NULL for the one big request.
5087 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5088 if self.heap.fits(payload) {
5089 return Ok(());
5090 }
5091 Err(Signal::Throw(
5092 self.make_error("InternalError", "out of memory"),
5093 ))
5094 }
5095
5096 /// Bytes of frame state the live call chain accounts for.
5097 pub fn stack_used(&self) -> usize {
5098 match self.frames.last() {
5099 Some(frame) => frame.stack_base + frame.cost,
5100 None => 0,
5101 }
5102 }
5103
5104 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5105 ///
5106 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5107 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5108 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5109 /// instead. That is the whole difference between the two models: it rations C stack, we
5110 /// ration frame state, and both quantities are dominated by the value slots — which is
5111 /// why the two depths come out comparable rather than merely proportional.
5112 fn frame_cost(code: &CompiledCode) -> usize {
5113 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5114 std::mem::size_of::<Frame>()
5115 + std::mem::size_of::<Value>() * slots
5116 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5117 }
5118
5119 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5120 ///
5121 /// Only names the eval created are here: a name the frame already declared statically
5122 /// is written through to its own slot instead, so this cannot shadow a real local.
5123 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5124 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5125 let (local_vars, phase) = self.visible_local_vars()?;
5126 if !local_vars.contains(name) {
5127 return None;
5128 }
5129 local_vars.get(name, phase)
5130 }
5131
5132 /// The variables a direct `eval` declared, as the code currently running sees them.
5133 ///
5134 /// Inside an eval that is the *caller's* set — the eval's own variable environment
5135 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5136 /// else it is the current frame's, falling back to the frame the closure was created
5137 /// in.
5138 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5139 ///
5140 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5141 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5142 /// refcount operations (the clone out of the frame, the drop at the end of the match)
5143 /// just to be asked `is_none`.
5144 fn has_visible_local_vars(&self) -> bool {
5145 let index = match self.eval_caller.flatten() {
5146 Some(caller) => caller,
5147 None => match self.frames.len().checked_sub(1) {
5148 Some(top) => top,
5149 None => return false,
5150 },
5151 };
5152 match self.frames.get(index) {
5153 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5154 None => false,
5155 }
5156 }
5157
5158 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5159 // While an `eval` runs, its own frame is on top but its variable environment is
5160 // the *caller's* — so the caller is what the lookup has to start from.
5161 let (index, phase) = match self.eval_caller.flatten() {
5162 Some(caller) => (
5163 caller,
5164 if self.in_parameter_list_at(caller) {
5165 0
5166 } else {
5167 1
5168 },
5169 ),
5170 None => (
5171 self.frames.len().checked_sub(1)?,
5172 if self.in_parameter_list() { 0 } else { 1 },
5173 ),
5174 };
5175 let frame = self.frames.get(index)?;
5176 // The frame's own variables, or — for an arrow, which has no variable environment
5177 // of its own — the one it was created in, which `ClosureEnv` carries.
5178 if let Some(local_vars) = frame.local_vars.clone() {
5179 return Some((local_vars, phase));
5180 }
5181 frame
5182 .env
5183 .local_vars
5184 .clone()
5185 .map(|local_vars| (local_vars, frame.env.local_phase))
5186 }
5187
5188 /// Whether the innermost frame is still evaluating its parameter list.
5189 ///
5190 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5191 /// and a closure created there may only see that much of [`LocalVars`].
5192 fn in_parameter_list(&self) -> bool {
5193 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5194 }
5195
5196 /// [`Interp::in_parameter_list`] for a specific frame.
5197 fn in_parameter_list_at(&self, frame: usize) -> bool {
5198 let Some(frame) = self.frames.get(frame) else {
5199 return false;
5200 };
5201 let code = &frame.code.code;
5202 if !code.has_parameter_expressions {
5203 return false;
5204 }
5205 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5206 // function as its body and let a direct `eval` act accordingly.
5207 if code.body_start == (0, 0) {
5208 return false;
5209 }
5210 match code.position_at(frame.at as u32) {
5211 Some(position) => position < code.body_start,
5212 None => false,
5213 }
5214 }
5215
5216 fn frame(&self) -> &Frame {
5217 self.frames.last().expect("a frame is live")
5218 }
5219
5220 fn frame_mut(&mut self) -> &mut Frame {
5221 self.frames.last_mut().expect("a frame is live")
5222 }
5223
5224 // -- slot access --------------------------------------------------------
5225
5226 /// Move a local's value out, leaving `undefined` in the slot.
5227 ///
5228 /// `None` for a captured slot: its value lives in a cell shared with every closure
5229 /// that closed over it, so it can never be exclusively ours and must not be taken.
5230 ///
5231 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5232 /// for every read and fatal for this one — a clone is exactly the second handle that
5233 /// rules out growing the string in place.
5234 fn take_loc(&mut self, slot: usize) -> Option<Value> {
5235 let frame = self.frames.last_mut()?;
5236 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5237 return None;
5238 }
5239 frame
5240 .locals
5241 .get_mut(slot)
5242 .map(|value| std::mem::replace(value, Value::Undefined))
5243 }
5244
5245 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5246 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5247 ///
5248 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5249 /// it** — the value is put back before the general path runs — so a `valueOf` that
5250 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5251 /// error as it would have without the fusion. This is why the in-place attempt is a
5252 /// `take` and not a `get`: an optimisation that changes what an exception observes is
5253 /// a wrong answer with a good excuse.
5254 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5255 // The take is `matches!`-guarded on the *right* operand only, and the taken value
5256 // is put back on every path that does not append. An earlier version wrote the two
5257 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5258 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5259 // through with its value already taken and dropped: the general path below then
5260 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5261 // A wrong answer, from an optimisation, with every test green.
5262 if matches!(right, Value::String(_))
5263 && let Some(taken) = self.take_loc(slot)
5264 {
5265 if let Value::String(mut left) = taken {
5266 let appended = match left.get_mut() {
5267 Some(string) => string.append_in_place(
5268 // The pattern is the one `matches!` just checked.
5269 match &right {
5270 Value::String(text) => text,
5271 _ => unreachable!("guarded above"),
5272 },
5273 ),
5274 None => None,
5275 };
5276 self.put_loc(slot, Value::String(left));
5277 if let Some(added) = appended {
5278 // The buffer grew where it stood, so the heap's running total has to
5279 // be told: `measure_used` would report the new length, and the two must
5280 // agree or the subtraction at free time leaves the counter wrong.
5281 self.heap.adjust_payload(added as isize);
5282 return Ok(());
5283 }
5284 } else {
5285 self.put_loc(slot, taken);
5286 }
5287 }
5288 // The two-number case, without an operand stack round trip. Everything below
5289 // this point is the *general* path: push both, call `binary_add`, pop the answer,
5290 // store it — five operations and two `Value` clones for what is one integer add.
5291 // `AddImmLoc` already answers this shape that way; the fusion above it was written
5292 // for string append and never got the numeric half, so `t += i` — a counting loop
5293 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5294 let left = self.get_loc(slot);
5295 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5296 self.put_loc(
5297 slot,
5298 match a.checked_add(*b) {
5299 Some(sum) => Value::Int(sum),
5300 None => Value::Float(*a as f64 + *b as f64),
5301 },
5302 );
5303 return Ok(());
5304 }
5305 self.push(left);
5306 self.push(right);
5307 self.binary_add()?;
5308 let value = self.pop();
5309 self.put_loc(slot, value);
5310 Ok(())
5311 }
5312
5313 fn get_arg(&self, slot: usize) -> Value {
5314 self.frame().read_arg(slot)
5315 }
5316
5317 fn put_arg(&mut self, slot: usize, value: Value) {
5318 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5319 if cell == -1 {
5320 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5321 *slot = value;
5322 }
5323 } else {
5324 self.frame().cells[cell as usize].set(value);
5325 }
5326 }
5327
5328 fn get_loc(&self, slot: usize) -> Value {
5329 // The cell mapping is `-1` for every slot that was not captured — which is all of
5330 // them in a function that creates no closure. `Frame::read_loc` tests that first,
5331 // so the common case is one array read and a clone: 20% of every loop iteration
5332 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5333 // sample of `dispatch:arith`).
5334 self.frame().read_loc(slot)
5335 }
5336
5337 fn put_loc(&mut self, slot: usize, value: Value) {
5338 // One borrow instead of three, and the cell check on the frame we already hold.
5339 let frame = self.frames.last_mut().expect("a frame is live");
5340 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5341 if cell < 0 {
5342 if let Some(slot) = frame.locals.get_mut(slot) {
5343 *slot = value;
5344 }
5345 } else if let Some(cell) = frame.cells.get(cell as usize) {
5346 cell.set(value);
5347 }
5348 }
5349
5350 // -- globals ------------------------------------------------------------
5351
5352 /// The name a global-slot operand refers to.
5353 fn global_name(&self, slot: usize) -> String {
5354 self.frame()
5355 .code
5356 .code
5357 .closure_vars
5358 .get(slot)
5359 .map(|c| c.name.clone())
5360 .unwrap_or_default()
5361 }
5362
5363 /// The facts about a global binding that decide where it lives.
5364 ///
5365 /// A script's globals split in two, and the split is observable: `var` and
5366 /// function declarations become properties of the global object (`globalThis.v`
5367 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5368 /// declarations live in the global *lexical* environment and are invisible there
5369 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5370 /// `is_lexical` flag means the answer is already in the bytecode.
5371 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5372 let name = self.global_name(slot);
5373 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5374 // while forwarding a reference through a nested function is built with the
5375 // flags cleared, so `const c` would look like an ordinary `var` from inside a
5376 // closure. Presence in the realm's lexical table is the same fact, recorded
5377 // once, and every slot sees it.
5378 let lexical = self.realm.globals.contains_key(&name);
5379 let is_const = self.realm.lexical_consts.contains(&name);
5380 (name, lexical, is_const)
5381 }
5382
5383 /// The value of `name` in the innermost active `with` object, if any.
5384 ///
5385 /// The active objects are the [`VarKind::With`] locals of every frame still running,
5386 /// innermost frame first and innermost block first within one. Walking frames rather
5387 /// than keeping a separate stack is what makes a closure called from inside a `with`
5388 /// see it, and what keeps the object alive only as long as the block is.
5389 /// The innermost active `with` object that has `name`, if any.
5390 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5391 let objects = self.eval_with.clone().unwrap_or_default();
5392 for object in objects {
5393 let key = self.string(name.to_string());
5394 if self
5395 .has_property(&key, &Value::Object(object.clone()))
5396 .ok()?
5397 {
5398 return Some(object);
5399 }
5400 }
5401 None
5402 }
5403
5404 /// Every active `with` object, innermost first.
5405 fn with_objects(&self) -> Vec<Gc<JsObject>> {
5406 let mut objects = Vec::new();
5407 for frame in self.frames.iter().rev() {
5408 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5409 if var.kind != js_compile::VarKind::With {
5410 continue;
5411 }
5412 // A captured binding lives in its cell and not in the slot list, so the
5413 // cell is consulted first — a closure created inside the block is exactly
5414 // what makes the object captured. Before the store runs the slot still
5415 // holds `undefined`, and a `with` object is always boxed, so a non-object
5416 // entry is simply not in scope yet.
5417 let value = frame
5418 .code
5419 .loc_cell
5420 .get(index)
5421 .copied()
5422 .filter(|cell| *cell >= 0)
5423 .and_then(|cell| frame.cells.get(cell as usize))
5424 .map(|cell| cell.get())
5425 .or_else(|| frame.locals.get(index).cloned());
5426 if let Some(Value::Object(object)) = value {
5427 objects.push(object);
5428 }
5429 }
5430 }
5431 objects
5432 }
5433
5434 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5435 for object in self.eval_with.clone().unwrap_or_default() {
5436 let key = self.string(name.to_string());
5437 if self.has_property(&key, &Value::Object(object.clone()))? {
5438 return Ok(Some(self.read_field(&Value::Object(object), name)?));
5439 }
5440 }
5441 Ok(None)
5442 }
5443
5444 /// Whether every scope between here and the global object is an ordinary one.
5445 ///
5446 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5447 /// bytecode resolved; when any is live the general path has to run in full order. When
5448 /// none is — every ordinary program — a global read is a property read and nothing
5449 /// else, and that is worth caching.
5450 fn scopes_are_plain(&self) -> bool {
5451 self.eval_caller.is_none()
5452 && self.eval_with.is_none()
5453 && self.eval_arguments.is_none()
5454 && self.eval_bindings.is_empty()
5455 && self.eval_scope.is_none()
5456 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5457 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5458 // its `ClosureEnv`, so the test has to be the same one the general path makes.
5459 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5460 // upstream corpus caught and no unit test did.
5461 && !self.has_visible_local_vars()
5462 && self.frame().env.eval_scope.is_none()
5463 }
5464
5465 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5466 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5467 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5468 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5469 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5470 // borrow outlive the `&mut self` the lookup needs.
5471 //
5472 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5473 // forwarded through a nested function has its flags cleared, so the flag cannot
5474 // be believed.
5475 let code = self.frame().code.clone();
5476 let name = code
5477 .code
5478 .closure_vars
5479 .get(slot)
5480 .map(|c| c.name.as_str())
5481 .unwrap_or_default();
5482 let lexical = self.realm.globals.contains_key(name);
5483 // The common case, first: an ordinary global `var`, with a cache in front of the
5484 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5485 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5486 // cache hit and return without touching any of it.
5487 if !lexical && self.scopes_are_plain() {
5488 return self.get_plain_global(name, slot);
5489 }
5490 if name == "arguments"
5491 && let Some(arguments) = &self.eval_arguments
5492 {
5493 return Ok(arguments.clone());
5494 }
5495 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5496 // the objects live when the eval started are consulted before anything else. The
5497 // snapshot is taken at entry rather than scanning the frames on every read: a
5498 // block that has already finished still leaves its object in the slot, and a
5499 // bytecode read outside the block must not see it.
5500 if let Some(value) = self.with_lookup(name)? {
5501 return Ok(value);
5502 }
5503 // A variable a direct `eval` declared shadows everything the compiler resolved,
5504 // including an enclosing function's binding: the eval put it in the caller's own
5505 // variable environment, which is nearer than any captured scope.
5506 if let Some((local_vars, phase)) = self.visible_local_vars()
5507 && let Some(cell) = local_vars.get(name, phase)
5508 {
5509 return Ok(cell.get());
5510 }
5511 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5512 // its local `a` wins over a global `a`.
5513 if let Some(value) = self.eval_binding_value(name) {
5514 return Ok(value);
5515 }
5516 // A closure created by an `eval` resolves its free names against the bindings
5517 // that eval saw, even after the eval (and its frames) are gone.
5518 if let Some(cell) = self
5519 .frame()
5520 .env
5521 .eval_scope
5522 .as_ref()
5523 .and_then(|scope| scope.get(name))
5524 {
5525 let value = cell.get();
5526 if matches!(value, Value::Uninitialized) {
5527 return Err(self.throw_reference(name));
5528 }
5529 return Ok(value);
5530 }
5531 // A binding declared by the strict `eval` currently running shadows anything
5532 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5533 if let Some(scope) = &self.eval_scope
5534 && let Some(value) = scope.get(name)
5535 {
5536 return Ok(value.clone());
5537 }
5538 if lexical {
5539 // A lexical global is a binding in a side table, so the dead zone is
5540 // visible and it is nowhere on the global object.
5541 if let Some(cell) = self.realm.globals.get(name) {
5542 let value = cell.get();
5543 if matches!(value, Value::Uninitialized) {
5544 return Err(self.throw_reference(name));
5545 }
5546 return Ok(value);
5547 }
5548 return Err(self.throw_reference(name));
5549 }
5550 // A `var` global is an ordinary property, so the prototype chain and the
5551 // global object's own builtins are all reachable through it.
5552 match self.get_property(&self.realm.global.clone(), name)? {
5553 Some(value) => Ok(value),
5554 None => Err(self.throw_reference(name)),
5555 }
5556 }
5557
5558 /// Read a plain global `var`: a cached own data property, or the full lookup.
5559 ///
5560 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5561 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5562 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5563 let object = self.realm.global.clone();
5564 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5565 if let Some(cached) = &self.global_cache[site]
5566 && object.upgrades_to(&cached.object)
5567 && let Some(value) = object.data_property_at(cached.index, name)
5568 {
5569 return Ok(value);
5570 }
5571 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5572 // chain exactly as before, then remember the answer if it is worth remembering.
5573 let Some(value) = self.get_property(&object, name)? else {
5574 return Err(self.throw_reference(name));
5575 };
5576 if let Some(index) = object.own_data_index(name) {
5577 self.global_cache[site] = Some(GlobalCache {
5578 object: object.downgrade(),
5579 index,
5580 });
5581 }
5582 Ok(value)
5583 }
5584
5585 /// Store to a global binding.
5586 ///
5587 /// Returns a signal when the store is refused: a `const` global may only be
5588 /// written by its initialiser, and a non-configurable `var` global may not be
5589 /// deleted but is always writable.
5590 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5591 let (name, lexical, is_const) = self.global_binding(slot);
5592
5593 // An assignment inside a `with` writes through to the object that supplies the
5594 // name, which for an `eval` means consulting the same chain `get_global` does.
5595 if let Some(owner) = self.with_owner(&name) {
5596 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5597 return Ok(());
5598 }
5599 // A variable the running eval *declared* takes the write before any caller
5600 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5601 // environment even when an enclosing function has a `var c` of its own.
5602 if self.eval_caller.flatten().is_some()
5603 && let Some((local_vars, phase)) = self.visible_local_vars()
5604 && local_vars.contains(&name)
5605 && let Some(cell) = local_vars.get(&name, phase)
5606 {
5607 cell.set(value);
5608 return Ok(());
5609 }
5610 // A binding of the frame that called `eval` takes the write, which is what
5611 // makes `f("a = 3")` change the caller's `a`.
5612 if self.set_eval_binding(&name, &value)? {
5613 return Ok(());
5614 }
5615 // A closure that outlived its `eval` writes through to the same cell it reads.
5616 if let Some(cell) = self
5617 .frame()
5618 .env
5619 .eval_scope
5620 .as_ref()
5621 .and_then(|scope| scope.get(&name))
5622 .cloned()
5623 {
5624 cell.set(value);
5625 return Ok(());
5626 }
5627 // Inside a strict `eval`, a name it declared itself is stored there. An
5628 // *assignment* to a name nobody declared is not a declaration, so it falls
5629 // through: strict mode raises `ReferenceError` for it, which is what
5630 // `eval("1 + (@not_def = 1)")` has to do.
5631 if let Some(scope) = self.eval_scope.as_mut()
5632 && scope.contains_key(&name)
5633 {
5634 scope.insert(name, value);
5635 return Ok(());
5636 }
5637 if lexical {
5638 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5639 // A lexical global starts out `Uninitialized` and only `init_global` ends
5640 // that, so a store reaching here is either a plain assignment to a slot
5641 // still in its dead zone — `x = 1; let x` at the top level, a
5642 // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5643 if matches!(cell.get(), Value::Uninitialized) {
5644 return Err(self.dead_zone_global(&name));
5645 }
5646 if is_const {
5647 return Err(self.read_only_global(&name));
5648 }
5649 cell.set(value);
5650 return Ok(());
5651 }
5652 // Writing an undeclared lexical global is a `ReferenceError` in strict
5653 // mode and a silent global creation otherwise; creating the cell here
5654 // keeps both paths from losing the value.
5655 let cell = self.new_cell(value);
5656 self.realm.globals.insert(name, cell);
5657 return Ok(());
5658 }
5659 // A variable a direct `eval` declared in this call shadows the global object, even
5660 // when the global already has a property of that name — `var c = "global"` at the
5661 // top level must not capture `eval("var c = 1")` inside a function.
5662 if let Some((local_vars, phase)) = self.visible_local_vars()
5663 && local_vars.contains(&name)
5664 && let Some(cell) = local_vars.get(&name, phase)
5665 {
5666 cell.set(value);
5667 return Ok(());
5668 }
5669 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5670 // remembered a global's slot index since M12b, but the *store* side never did: it
5671 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5672 // global object's whole table — which holds every builtin — on every assignment to
5673 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5674 // full global lookup per iteration; measured with a counter, `s` as a global made
5675 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5676 //
5677 // Re-validated exactly like the read: same object, same index, still the name, and
5678 // — the one extra check a store needs — still writable. A global that is an
5679 // accessor, non-writable, or inherited fails here and falls through to the full
5680 // path below, which reports the failure the way it always did.
5681 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5682 let global = self.realm.global.clone();
5683 if let Some(cached) = &self.global_cache[site]
5684 && global.upgrades_to(&cached.object)
5685 && global.write_data_at(cached.index, &name, value.clone())
5686 {
5687 return Ok(());
5688 }
5689 match global.own_property(&name) {
5690 // A `var` global is writable, so the store goes straight through — but
5691 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5692 // store (a non-writable or accessor-without-setter global) is a silent
5693 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5694 // split every other assignment has.
5695 Some(_) => {
5696 let on_failure = if self.current_strict() {
5697 DeleteFailure::Throw
5698 } else {
5699 DeleteFailure::Ignore
5700 };
5701 let result = self.set_property_with(&global, &name, value, on_failure);
5702 // Teach the cache the slot for a plain writable own data property, which is
5703 // what a declared `var` is. Without this the fast path above could never
5704 // fire for a global that is only ever *written* — its entry would have to
5705 // be put there by a read of the same slot, and a write-only loop has none.
5706 if result.is_ok()
5707 && let Some(index) = global.own_data_index(&name)
5708 {
5709 self.global_cache[site] = Some(GlobalCache {
5710 object: global.downgrade(),
5711 index,
5712 });
5713 }
5714 result
5715 }
5716 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5717 // declaration creates a *configurable* property, which is what makes it
5718 // deletable and is the one way a global differs from a declared `var`.
5719 // In strict mode the same store is a `ReferenceError` instead: that is the
5720 // whole point of strict mode, and creating the global silently meant
5721 // `"use strict"; x = 1` looked like it worked.
5722 None => {
5723 if self.current_strict() {
5724 return Err(self.throw_reference(&name));
5725 }
5726 // A direct eval declares here rather than on the global object: its
5727 // `var`s belong to the caller's variable environment. `declare_eval_local`
5728 // also covers a plain assignment to a variable an earlier eval made.
5729 if let Some(cell) = self.declare_eval_local(&name) {
5730 cell.set(value);
5731 return Ok(());
5732 }
5733 global.define_data(&name, value);
5734 Ok(())
5735 }
5736 }
5737 }
5738
5739 /// The value of a binding of the frame that called `eval`, if there is one.
5740 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5741 let binding = self
5742 .eval_bindings
5743 .iter()
5744 .find(|binding| binding.name == name)?;
5745 let owner = self.frames.get(binding.frame)?;
5746 let (slot, index) = (binding.slot, binding.index);
5747 Some(match slot {
5748 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5749 cell if cell >= 0 => owner
5750 .cells
5751 .get(cell as usize)
5752 .map(|cell| cell.get())
5753 .unwrap_or(Value::Undefined),
5754 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5755 },
5756 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5757 cell if cell >= 0 => owner
5758 .cells
5759 .get(cell as usize)
5760 .map(|cell| cell.get())
5761 .unwrap_or(Value::Undefined),
5762 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5763 },
5764 })
5765 }
5766
5767 /// Write to a binding of the frame that called `eval`.
5768 ///
5769 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5770 /// matched binding can still refuse the store, which is why this is fallible: a
5771 /// `const` is read-only everywhere, and a named function expression's own name is
5772 /// read-only in strict mode.
5773 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5774 let Some(binding) = self
5775 .eval_bindings
5776 .iter()
5777 .find(|binding| binding.name == name)
5778 else {
5779 return Ok(false);
5780 };
5781 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5782 let strict = self.current_strict();
5783 let Some(owner) = self.frames.get_mut(frame) else {
5784 return Ok(false);
5785 };
5786 match slot {
5787 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5788 cell if cell >= 0 => {
5789 if let Some(cell) = owner.cells.get(cell as usize) {
5790 cell.set(value.clone());
5791 }
5792 }
5793 _ => {
5794 if let Some(slot) = owner.args.get_mut(index) {
5795 *slot = value.clone();
5796 }
5797 }
5798 },
5799 EvalSlot::Local => {
5800 let declared = owner.code.code.vars.get(index);
5801 // A `const` is read-only even through `eval`. The realm records this for
5802 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5803 // the bytecode, so this is where it has to be enforced.
5804 if declared.is_some_and(|var| var.is_const) {
5805 return Err(self.read_only_local(name));
5806 }
5807 // The name of a named function expression is read-only too, but only
5808 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5809 // such a name is ignored, the same as a direct store would be.
5810 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5811 return if strict {
5812 Err(self.read_only_local(name))
5813 } else {
5814 Ok(true)
5815 };
5816 }
5817 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5818 cell if cell >= 0 => {
5819 if let Some(cell) = owner.cells.get(cell as usize) {
5820 cell.set(value.clone());
5821 }
5822 }
5823 _ => {
5824 if let Some(slot) = owner.locals.get_mut(index) {
5825 *slot = value.clone();
5826 }
5827 }
5828 }
5829 }
5830 }
5831 Ok(true)
5832 }
5833
5834 /// The `TypeError` an assignment to a read-only binding raises.
5835 fn read_only_local(&self, name: &str) -> Signal {
5836 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5837 }
5838
5839 /// Declare `name` as a variable of the frame that called the running `eval`.
5840 ///
5841 /// `None` when there is no direct eval in progress, or it was called from the top
5842 /// level — then the caller's variable environment *is* the global one and the
5843 /// existing path is right.
5844 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5845 let caller = self.eval_caller.flatten()?;
5846 // The bottom frame is the top-level script, whose variable environment *is* the
5847 // global one — so `eval("var x = 1")` at the top level still creates a global.
5848 if caller == 0 {
5849 return None;
5850 }
5851 // A name the eval's *own* variable environment already binds is not a new
5852 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5853 // `arguments`, and creating a second binding would leave the first — the one
5854 // closures read — untouched. A binding of an *outer* frame does not count: a
5855 // declaration shadows it rather than writing through.
5856 if self
5857 .eval_bindings
5858 .iter()
5859 .any(|binding| binding.name == name && binding.frame == caller)
5860 {
5861 return None;
5862 }
5863 let phase = if self.in_parameter_list_at(caller) {
5864 0
5865 } else {
5866 1
5867 };
5868 self.frame_local_vars(caller)?;
5869 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5870 if let Some(cell) = local_vars.get(name, 1) {
5871 return Some(cell);
5872 }
5873 let cell = self.new_cell(Value::Undefined);
5874 Some(local_vars.declare(name, phase, cell))
5875 }
5876
5877 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5878 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5879 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5880 return Some(local_vars.clone());
5881 }
5882 let local_vars = Gc::new(self.heap, LocalVars::new());
5883 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5884 Some(local_vars)
5885 }
5886
5887 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5888 /// property of the global object. Used to decide whether a store inside an
5889 /// `eval` writes through to the realm or declares a binding of its own.
5890 ///
5891 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5892 /// write to `Object.prototype.toString`, and must not shadow it either.
5893 fn global_knows(&mut self, name: &str) -> bool {
5894 if self.realm.globals.contains_key(name) {
5895 return true;
5896 }
5897 self.realm.global.own_property(name).is_some()
5898 }
5899
5900 /// Whether the code currently running is strict.
5901 ///
5902 /// Read off the frame's function, which is where the parser's answer ended up; a
5903 /// native function never runs strict-only checks, and there is no frame at all
5904 /// before the first script.
5905 pub fn current_strict(&self) -> bool {
5906 self.frames
5907 .last()
5908 .is_some_and(|frame| frame.code.code.strict)
5909 }
5910
5911 /// Initialise a declared global, which is what ends its dead zone.
5912 ///
5913 /// A `var` global becomes a property of the global object: writable, so a later
5914 /// assignment goes through, and non-configurable, so `delete` refuses.
5915 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5916 let (name, lexical, _) = self.global_binding(slot);
5917 // A `var` declared by the strict `eval` currently running belongs to the
5918 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5919 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5920 // initialised in place, which is what a re-declaration inside eval does.
5921 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5922 self.eval_scope
5923 .as_mut()
5924 .expect("checked above")
5925 .insert(name, value);
5926 return Ok(());
5927 }
5928 if let Some(scope) = self.eval_scope.as_mut()
5929 && scope.contains_key(&name)
5930 {
5931 scope.insert(name, value);
5932 return Ok(());
5933 }
5934 if lexical {
5935 // The cell exists (created at declaration time) holding the dead-zone
5936 // marker; storing the value is what makes the binding readable.
5937 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5938 cell.set(value);
5939 return Ok(());
5940 }
5941 let cell = self.new_cell(value);
5942 self.realm.globals.insert(name, cell);
5943 return Ok(());
5944 }
5945 let global = self.realm.global.clone();
5946 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5947 // to answer `false` and leave the binding in place. `with_attributes` ties
5948 // `configurable` to `writable`, so the property is built field by field.
5949 global.define(
5950 &name,
5951 Property {
5952 value: Some(value),
5953 writable: true,
5954 enumerable: true,
5955 configurable: false,
5956 ..Property::default()
5957 },
5958 );
5959 Ok(())
5960 }
5961
5962 /// The `TypeError` a store to a `const` global raises.
5963 fn read_only_global(&self, name: &str) -> Signal {
5964 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5965 }
5966
5967 /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
5968 fn dead_zone_global(&self, name: &str) -> Signal {
5969 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
5970 }
5971
5972 // -- properties ---------------------------------------------------------
5973
5974 /// Read `object[key]`, following the prototype chain.
5975 ///
5976 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5977 /// lookup returns the owner rather than just the value.
5978 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5979 self.get_property_key(object, &PropertyKey::from(key))
5980 }
5981
5982 /// [`Interp::get_property`] with a key that may be a symbol.
5983 pub fn get_property_key(
5984 &mut self,
5985 object: &Gc<JsObject>,
5986 key: &PropertyKey,
5987 ) -> JsResult<Option<Value>> {
5988 self.get_property_key_for(object, None, key)
5989 }
5990
5991 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5992 ///
5993 /// The receiver matters when the property is found on a *prototype*: a getter has to
5994 /// see the object the read started from. For a primitive that is the primitive
5995 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5996 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5997 /// the owner.
5998 pub fn get_property_key_for(
5999 &mut self,
6000 object: &Gc<JsObject>,
6001 receiver: Option<&Value>,
6002 key: &PropertyKey,
6003 ) -> JsResult<Option<Value>> {
6004 // A proxy answers for itself, before any of the shortcuts below: `new
6005 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
6006 // have.
6007 if object.proxy_state().is_some() {
6008 let receiver = receiver
6009 .cloned()
6010 .unwrap_or_else(|| Value::Object(object.clone()));
6011 return self.proxy_get(object, &receiver, key);
6012 }
6013 // A host class's `get_property` trap replaces the whole read, prototype walk
6014 // included — that is what makes a native accessor free rather than a JavaScript
6015 // getter call.
6016 if let Some(exotic) = object.exotic() {
6017 let receiver_value = receiver
6018 .cloned()
6019 .unwrap_or_else(|| Value::Object(object.clone()));
6020 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
6021 return Ok(Some(value));
6022 }
6023 // With no `get_property` trap, a `get_own_property` trap still answers for the
6024 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
6025 // and the hook lives exactly there. A key the trap reports as absent is still
6026 // looked for on the prototype, which is why the search resumes *above*.
6027 if let Some(property) = exotic.get_own_property(self, object, key)? {
6028 return match property {
6029 Some(property) => self.read_property(property, object, receiver),
6030 None => match lookup_key_above(object, key) {
6031 Some((_, property)) => self.read_property(property, object, receiver),
6032 None => Ok(None),
6033 },
6034 };
6035 }
6036 }
6037 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
6038 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
6039 // The `[[Get]]` short-circuit therefore belongs to this one arm.
6040 //
6041 // Constructibility is exactly the split the reference makes: `function f(){}` and
6042 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
6043 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
6044 // function" — it *is* the predicate, which is why no extra marker is needed.
6045 if let Some(text) = key.as_str()
6046 && (text == "caller" || text == "arguments")
6047 && object.is_constructor()
6048 && object.is_callable()
6049 && !object.is_bound_function()
6050 // …and only when the body is **sloppy**. A strict body reaches the
6051 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
6052 // whole `Function/15.3.5.4_2-*gs` family is written against
6053 // (`onlyStrict`, so every function in them is strict).
6054 && !object.function_is_strict()
6055 && object.own_property(text).is_none()
6056 {
6057 return Ok(Some(Value::Undefined));
6058 }
6059 // The element-vector and `length` shortcuts are string-only: an array index
6060 // has no symbol spelling.
6061 if let Some(text) = key.as_str() {
6062 if let Some(value) = self.own_element(object, text) {
6063 return Ok(Some(value));
6064 }
6065 // `length` is not stored as a property: an array's length is its element
6066 // count, and keeping one copy of it is what makes `push`/`pop` and
6067 // `a.length = n` agree.
6068 if let Some(length) = object.array_length()
6069 && text == "length"
6070 {
6071 // Not `Value::Int(length as i32)`: see [`length_value`].
6072 return Ok(Some(crate::object::length_value(length)));
6073 }
6074 }
6075 // A proxy or a hooked exotic object anywhere above `object` makes the static
6076 // table walk below wrong: a proxy's own table is *empty by design* (the properties
6077 // live on its target), so the walk skipped that link entirely and everything behind
6078 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6079 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6080 // -target-is-proxy.js` are the four.
6081 if Self::chain_needs_dispatch(object) {
6082 return self.walk_get(object, receiver, key);
6083 }
6084 match lookup_key(object, key) {
6085 Some((_, property)) => self.read_property(property, object, receiver),
6086 None => Ok(None),
6087 }
6088 }
6089
6090 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6091 /// answer for itself.
6092 ///
6093 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6094 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6095 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6096 /// an inherited getter the object the read started from.
6097 fn walk_get(
6098 &mut self,
6099 start: &Gc<JsObject>,
6100 receiver: Option<&Value>,
6101 key: &PropertyKey,
6102 ) -> JsResult<Option<Value>> {
6103 let receiver = receiver
6104 .cloned()
6105 .unwrap_or_else(|| Value::Object(start.clone()));
6106 let mut current = Some(start.clone());
6107 while let Some(holder) = current {
6108 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6109 // has to ask it, not read its (empty) own-property table. `Object.create(new
6110 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6111 // instead found nothing.
6112 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6113 return Ok(Some(value));
6114 }
6115 // A host class's `get_property` trap replaces the whole read for that holder,
6116 // prototype walk included — the same rule `get_property_key_for` applies to the
6117 // first object.
6118 if let Some(exotic) = holder.exotic()
6119 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6120 {
6121 return Ok(Some(value));
6122 }
6123 if let Some(property) = self.object_get_own_property(&holder, key)? {
6124 return self.read_property(property, &holder, Some(&receiver));
6125 }
6126 current = self.object_prototype_of(&holder)?;
6127 }
6128 Ok(None)
6129 }
6130
6131 /// Whether `object` or anything above it has properties that cannot be read out of a
6132 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6133 ///
6134 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6135 /// is the hot path for every property read; this is the check that decides whether it
6136 /// is safe to take it.
6137 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6138 object
6139 .chain()
6140 .iter()
6141 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
6142 }
6143
6144 /// The value a property read answers.
6145 ///
6146 /// One place rather than three, because an accessor has to run with the *receiver* as
6147 /// `this` whether the descriptor came from the property table, an exotic
6148 /// `get_own_property` trap, or a prototype above one.
6149 fn read_property(
6150 &mut self,
6151 property: Property,
6152 object: &Gc<JsObject>,
6153 receiver: Option<&Value>,
6154 ) -> JsResult<Option<Value>> {
6155 if property.is_accessor() {
6156 match &property.getter {
6157 Some(getter) if !matches!(getter, Value::Undefined) => {
6158 let receiver = receiver
6159 .cloned()
6160 .unwrap_or_else(|| Value::Object(object.clone()));
6161 self.call_value(getter.clone(), receiver, Vec::new())
6162 .map(Some)
6163 }
6164 // An accessor with no getter reads as `undefined`.
6165 _ => Ok(Some(Value::Undefined)),
6166 }
6167 } else {
6168 Ok(property.value)
6169 }
6170 }
6171
6172 /// `super.key` — start the search at `proto`, but report to `receiver`.
6173 ///
6174 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6175 /// found on the prototype of a class has to see the *instance* as `this`, and a
6176 /// plain property read off `proto` would lose that.
6177 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6178 let start = self.require_object(proto)?;
6179 let key = self.propkey(key)?;
6180 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6181 if matches!(proto, Value::Null) {
6182 return Ok(Value::Undefined);
6183 }
6184 match lookup_key(&start, &key) {
6185 Some((_, property)) if property.is_accessor() => match &property.getter {
6186 Some(getter) if !matches!(getter, Value::Undefined) => {
6187 self.call_value(getter.clone(), receiver.clone(), Vec::new())
6188 }
6189 _ => Ok(Value::Undefined),
6190 },
6191 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6192 None => Ok(Value::Undefined),
6193 }
6194 }
6195
6196 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6197 ///
6198 /// A setter found on the prototype runs with `receiver` as `this`; a data property
6199 /// is shadowed by a new own property on the receiver, the same rule an ordinary
6200 /// assignment follows.
6201 fn super_write(
6202 &mut self,
6203 receiver: &Value,
6204 proto: &Value,
6205 key: &Value,
6206 value: Value,
6207 ) -> JsResult<()> {
6208 let target = self.require_object(receiver)?;
6209 let key = self.propkey(key)?;
6210 if !matches!(proto, Value::Null)
6211 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6212 {
6213 if property.is_accessor() {
6214 if let Some(setter) = &property.setter
6215 && !matches!(setter, Value::Undefined)
6216 {
6217 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6218 }
6219 return Ok(());
6220 }
6221 // A data property on the prototype is writable or not; reading `owner` at
6222 // all is only for the attribute check.
6223 if !property.writable {
6224 return Err(self.type_error(format!("'{key}' is read-only")));
6225 }
6226 let _ = owner;
6227 }
6228 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6229 }
6230
6231 /// The object a `super` operation needs, or the `TypeError` the spec raises.
6232 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6233 match value.as_object() {
6234 Some(object) => Ok(object.clone()),
6235 None => Err(Signal::Throw(
6236 self.make_error("TypeError", "value is not an object"),
6237 )),
6238 }
6239 }
6240
6241 /// Build the class object `define_class` produces.
6242 ///
6243 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6244 /// whose prototype property is a fresh object inheriting from the parent's
6245 /// prototype, and whose own prototype is the parent constructor — which is what makes
6246 /// a static method inherited too.
6247 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6248 let ctor = self.pop();
6249 let parent = self.pop();
6250 let Value::Object(function) = &ctor else {
6251 return Err(Signal::Throw(
6252 self.make_error("TypeError", "class constructor must be a function"),
6253 ));
6254 };
6255 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6256 // but gives the instances no prototype at all.
6257 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6258 match &parent {
6259 Value::Null => (Some(self.realm.function_proto.clone()), None),
6260 Value::Object(parent_class) => {
6261 // `IsConstructor`, not `IsCallable`: §15.7.14 ClassDefinitionEvaluation
6262 // step 9 rejects a heritage without `[[Construct]]` *before* reading
6263 // `superclass.prototype`, so an arrow function and a generator — both
6264 // callable, neither constructible — are a `TypeError` and their
6265 // `prototype` getter must never run
6266 // (`subclass/superclass-arrow-function`, `…-generator-function`).
6267 if !parent_class.is_constructor() {
6268 return Err(Signal::Throw(
6269 self.make_error("TypeError", "parent class must be constructor"),
6270 ));
6271 }
6272 let proto = self.get_property(parent_class, "prototype")?;
6273 match proto {
6274 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6275 Some(Value::Null) => (Some(parent_class.clone()), None),
6276 _ => {
6277 return Err(Signal::Throw(self.make_error(
6278 "TypeError",
6279 "parent prototype must be an object or null",
6280 )));
6281 }
6282 }
6283 }
6284 _ => {
6285 return Err(Signal::Throw(
6286 self.make_error("TypeError", "parent class must be constructor"),
6287 ));
6288 }
6289 }
6290 } else {
6291 (
6292 Some(self.realm.function_proto.clone()),
6293 Some(self.realm.object_proto.clone()),
6294 )
6295 };
6296 let proto = self.new_object(parent_proto);
6297 function.set_proto(parent_ctor);
6298 // A class is not callable without `new`, and its `prototype` is not writable —
6299 // both follow from being a class and are what `class A {}; A()` throws on.
6300 function.set_class_constructor(true);
6301 function.set_home_object(None);
6302 self.set_function_name(&ctor, name);
6303 self.define_class_properties(function, &ctor, &proto)?;
6304 Ok((ctor, proto))
6305 }
6306
6307 /// Give the constructor its `prototype` and `length`, and the prototype its
6308 /// `constructor` back-pointer.
6309 fn define_class_properties(
6310 &mut self,
6311 function: &Gc<JsObject>,
6312 ctor: &Value,
6313 proto: &Gc<JsObject>,
6314 ) -> JsResult<()> {
6315 proto.define(
6316 "constructor",
6317 Property::with_attributes(ctor.clone(), true, false),
6318 );
6319 function.define(
6320 "prototype",
6321 Property::prototype_of(Value::Object(proto.clone()), false),
6322 );
6323 if let Some((code, _)) = bytecode_of(function) {
6324 let length = code.code.defined_args;
6325 function.define(
6326 "length",
6327 Property::name_or_length(Value::Int(length as i32)),
6328 );
6329 }
6330 Ok(())
6331 }
6332
6333 /// The own array element `key` names, if this object has one.
6334 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6335 // A typed array's elements live in its buffer, not in a property list: reading one
6336 // goes through the view's element type so a bounds check and a detached buffer are
6337 // both handled there.
6338 //
6339 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6340 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6341 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6342 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6343 // consulted. Testing with `array_index` rejected all three, which let a throwing
6344 // getter installed on `TypedArray.prototype["-1"]` run.
6345 if object.typed_array_parts().is_some() {
6346 let property_key = PropertyKey::from(key);
6347 let numeric = canonical_numeric_index(&property_key)?;
6348 if typed_array_index_is_valid(object, numeric) {
6349 return object.typed_array_element(numeric as usize);
6350 }
6351 // Canonical, but not a valid index: `undefined`, and *final*.
6352 return Some(Value::Undefined);
6353 }
6354 let index = array_index(key)?;
6355 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6356 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6357 // search early, which is why `Array.prototype[1] = 9` could not be seen through
6358 // `[1,,3][1]`.
6359 match object.array_get(index as usize) {
6360 Some(Value::Hole) | None => None,
6361 other => other,
6362 }
6363 }
6364
6365 /// Store `object[key] = value`, honouring setters and inherited properties.
6366 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6367 self.set_property_with(object, key, value, DeleteFailure::Throw)
6368 }
6369
6370 /// Store a property, choosing what to do when the object refuses.
6371 ///
6372 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6373 /// mode, which is the one place assignment differs by mode. Native code (the array
6374 /// methods, `JSON`) always asks for the throw.
6375 pub fn set_property_with(
6376 &mut self,
6377 object: &Gc<JsObject>,
6378 key: &str,
6379 value: Value,
6380 on_failure: DeleteFailure,
6381 ) -> JsResult<()> {
6382 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6383 }
6384
6385 /// [`Interp::set_property_with`] with a key that may be a symbol.
6386 pub fn set_property_with_key(
6387 &mut self,
6388 object: &Gc<JsObject>,
6389 key: &PropertyKey,
6390 value: Value,
6391 on_failure: DeleteFailure,
6392 ) -> JsResult<()> {
6393 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6394 }
6395
6396 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6397 ///
6398 /// The receiver split lives one level up, in
6399 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6400 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6401 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6402 /// stores into `object` itself, which is why the element branch below converts `V`
6403 /// before asking whether the index is valid: `V` may put it back in bounds
6404 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6405 fn set_property_with_key_receiver_aware(
6406 &mut self,
6407 object: &Gc<JsObject>,
6408 key: &PropertyKey,
6409 value: Value,
6410 on_failure: DeleteFailure,
6411 ) -> JsResult<()> {
6412 // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6413 // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6414 // Nothing about the receiver or the value changes that, so the whole operation is
6415 // one answer.
6416 //
6417 // Not implementing it explicitly left the ordinary algorithm in charge, and that
6418 // says "true" for names the namespace does not own as soon as the value matches or
6419 // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6420 // assignment stopped throwing (`await-ns-set-strict`).
6421 if object.module_namespace_marker() {
6422 return match on_failure {
6423 DeleteFailure::Ignore => Ok(()),
6424 DeleteFailure::Throw => Err(self.type_error(format!(
6425 "cannot assign to property '{key}' of a module namespace object"
6426 ))),
6427 };
6428 }
6429 // A proxy's `set` trap decides, and its `false` means the same thing an
6430 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6431 if object.proxy_state().is_some() {
6432 let receiver = Value::Object(object.clone());
6433 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6434 return match (accepted, on_failure) {
6435 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6436 (false, DeleteFailure::Throw) => {
6437 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6438 }
6439 };
6440 }
6441 }
6442 // A host class's `set_property` trap decides for itself. `Some(false)` is a
6443 // refusal and means exactly what a proxy's `false` means.
6444 if let Some(exotic) = object.exotic() {
6445 let receiver = Value::Object(object.clone());
6446 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6447 return match (accepted, on_failure) {
6448 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6449 (false, DeleteFailure::Throw) => {
6450 Err(self.type_error(format!("property '{key}' is read-only")))
6451 }
6452 };
6453 }
6454 }
6455 // The element and `length` shortcuts only exist for string keys: an array
6456 // index has no symbol spelling, and a symbol named `length` is an ordinary
6457 // property.
6458 let text = key.as_str();
6459 // A typed array's elements are a window onto its buffer: the store has to go
6460 // through the view's element type so the value is wrapped (or clamped) and so an
6461 // out-of-range or detached write is a silent no-op, as the spec says.
6462 //
6463 // The key test is `CanonicalNumericIndexString`, like every other index operation
6464 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6465 // does not exist, so they do nothing and leave no own property behind
6466 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6467 // path, which created a property named `"-0"`.
6468 //
6469 // The conversion comes **first**, before the index is checked at all, and that
6470 // order is observable twice over:
6471 //
6472 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6473 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6474 // then store the converted value;
6475 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6476 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6477 // run and its exception to escape.
6478 //
6479 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6480 // validity check, not a validity check that skips the conversion. The store itself
6481 // is a no-op when the index is invalid by then, which is why no extra guard is
6482 // needed around `typed_array_set`.
6483 if let Some(element) = object.typed_array_element_type()
6484 && let Some(numeric) = canonical_numeric_index(key)
6485 {
6486 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6487 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6488 // in `Interp`, because it is script-observable and the storage borrow inside
6489 // `typed_array_set` must not be held across it.
6490 let stored = self.element_value(element, value)?;
6491 if typed_array_index_is_valid(object, numeric)
6492 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6493 {
6494 return Err(self.type_error(reason));
6495 }
6496 return Ok(());
6497 }
6498 if let Some(text) = text
6499 && let Some(index) = array_index(text)
6500 && object.is_array()
6501 {
6502 // An accessor defined on an index lives in the property table while the
6503 // element slot is a hole, so the store has to go through the property first.
6504 // Writing the vector directly skipped the setter entirely.
6505 if let Some(existing) = object.own_property_key(key) {
6506 if existing.is_accessor() {
6507 return match existing.setter.clone() {
6508 Some(setter) if !matches!(setter, Value::Undefined) => {
6509 let receiver = Value::Object(object.clone());
6510 self.call_value(setter, receiver, vec![value]).map(|_| ())
6511 }
6512 _ => match on_failure {
6513 DeleteFailure::Throw => Err(self.type_error(format!(
6514 "cannot set property '{text}', it has only a getter"
6515 ))),
6516 DeleteFailure::Ignore => Ok(()),
6517 },
6518 };
6519 }
6520 if !existing.writable {
6521 return match on_failure {
6522 DeleteFailure::Throw => {
6523 Err(self.type_error(format!("'{text}' is read-only")))
6524 }
6525 DeleteFailure::Ignore => Ok(()),
6526 };
6527 }
6528 }
6529 {
6530 // Growing the array needs a writable `length`.
6531 if (index as usize) >= object.array_length().unwrap_or(0)
6532 && !object.length_writable()
6533 {
6534 return match on_failure {
6535 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6536 DeleteFailure::Ignore => Ok(()),
6537 };
6538 }
6539 // Adding an index past the end makes the array longer, which a
6540 // non-extensible array refuses.
6541 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6542 return match on_failure {
6543 DeleteFailure::Throw => Err(self.type_error(format!(
6544 "cannot add property '{key}', object is not extensible"
6545 ))),
6546 DeleteFailure::Ignore => Ok(()),
6547 };
6548 }
6549 if object.element_is_locked(index) {
6550 return match on_failure {
6551 DeleteFailure::Throw => {
6552 Err(self.type_error(format!("'{key}' is read-only")))
6553 }
6554 DeleteFailure::Ignore => Ok(()),
6555 };
6556 }
6557 // The element vector is only half of `[[Set]]` for an index: the
6558 // prototype chain is consulted first, and a setter there answers instead
6559 // of the element store. This branch used to write the element directly, so
6560 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6561 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6562 // the reference calls the setter and the array keeps no own index.
6563 //
6564 // An *exotic* prototype has no entry to find, because its indices live
6565 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6566 // then looked like "nothing on the chain" and the store created the
6567 // element, where the view's `[[Set]]` answers `true` and does nothing for
6568 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6569 // checks the array's `length` stays 0). So the dispatch comes first.
6570 if !object.has_own_key(key)
6571 && let Some(proto) = object.proto()
6572 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6573 {
6574 let receiver = Value::Object(object.clone());
6575 let accepted =
6576 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6577 return if accepted {
6578 Ok(())
6579 } else {
6580 match on_failure {
6581 DeleteFailure::Throw => {
6582 Err(self.type_error(format!("'{key}' is read-only")))
6583 }
6584 DeleteFailure::Ignore => Ok(()),
6585 }
6586 };
6587 }
6588 if let Some((owner, property)) = lookup_key(object, key)
6589 && !owner.ptr_eq(object)
6590 {
6591 match &property {
6592 property if property.is_accessor() => {
6593 match &property.setter {
6594 Some(setter) if !matches!(setter, Value::Undefined) => {
6595 let receiver = Value::Object(object.clone());
6596 self.call_value(setter.clone(), receiver, vec![value])?;
6597 }
6598 _ => {
6599 return match on_failure {
6600 DeleteFailure::Throw => Err(self.type_error(format!(
6601 "cannot set property '{text}', it has only a getter"
6602 ))),
6603 DeleteFailure::Ignore => Ok(()),
6604 };
6605 }
6606 }
6607 return Ok(());
6608 }
6609 property if !property.writable => {
6610 return match on_failure {
6611 DeleteFailure::Throw => {
6612 Err(self.type_error(format!("'{text}' is read-only")))
6613 }
6614 DeleteFailure::Ignore => Ok(()),
6615 };
6616 }
6617 _ => {}
6618 }
6619 }
6620 if object.array_set(self.heap, index as usize, value.clone()) {
6621 return Ok(());
6622 }
6623 // Past the dense limit the slot is too far out to be worth one `Value`
6624 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6625 // constant time by keeping the index as an ordinary property. The store
6626 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6627 // to a legal program.
6628 object.define_key(key, Property::with_attributes(value, true, true));
6629 // Extend, never shorten: the index may be *inside* the current length (a
6630 // huge `length` with a sparse store), and shortening would delete the
6631 // sparse properties above it — including the one just stored.
6632 if index as usize + 1 > object.array_length().unwrap_or(0) {
6633 object.array_set_length(self.heap, index as usize + 1);
6634 }
6635 return Ok(());
6636 }
6637 }
6638 if text == Some("length") && object.is_array() {
6639 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6640 // test. A `valueOf` that locks `length` on its second call therefore turns the
6641 // store into a refused write rather than a silent success
6642 // (`length/define-own-prop-length-coercion-order-set`).
6643 let rounded = self.coerce_array_length_twice(&value)?;
6644 if !object.length_writable() {
6645 return match on_failure {
6646 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6647 DeleteFailure::Ignore => Ok(()),
6648 };
6649 }
6650 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6651 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6652 // answered `NaN`, which left the assignment silently ignored
6653 // (`S15.4.5.2_A3_T2`).
6654 let _ = rounded;
6655 let length = self.to_js_number(&value)?;
6656 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6657 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6658 // `RangeError`s; the old code only tested "finite and non-negative" and then
6659 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6660 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6661 let valid = length.is_finite()
6662 && length >= 0.0
6663 && length.fract() == 0.0
6664 && length <= u32::MAX as f64;
6665 if !valid {
6666 return Err(self.range_error("invalid array length"));
6667 }
6668 {
6669 let length = length as usize;
6670 // `a.length = n` with `n` below a non-configurable element cannot
6671 // drop that element, so the whole assignment fails. The spec makes
6672 // this a `TypeError` rather than a silent no-op, in any mode.
6673 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6674 // Sloppy mode stops the truncation at the blocking element
6675 // instead of failing; strict mode raises.
6676 // Both modes stop at the blocking element; they differ in
6677 // whether that is reported. The reference truncates *then*
6678 // throws, so the array is left in the shortened state.
6679 object.array_truncate(self.heap, blocked + 1);
6680 return match on_failure {
6681 DeleteFailure::Throw => {
6682 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6683 }
6684 DeleteFailure::Ignore => Ok(()),
6685 };
6686 }
6687 object.array_set_length(self.heap, length);
6688 return Ok(());
6689 }
6690 }
6691 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6692 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6693 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6694 //
6695 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6696 // applying whatever came back is the same thing for an ordinary prototype and
6697 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6698 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6699 // answers "not mine, the receiver is not me" without touching the buffer. This
6700 // code used to find nothing owned by `o`, find no property on the view either,
6701 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6702 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6703 // `key-is-canonical-invalid-index-prototype-chain-set`).
6704 //
6705 // The read-only and accessor rules of step 1 are what make
6706 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6707 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6708 let own = match self.lookup_for_write(object, key)? {
6709 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6710 _ => None,
6711 };
6712 if let Some(property) = own {
6713 if property.is_accessor() {
6714 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6715 Some(setter) => {
6716 let receiver = Value::Object(object.clone());
6717 self.call_value(setter, receiver, vec![value])?;
6718 Ok(())
6719 }
6720 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6721 // Sloppy code swallows that refusal, strict code raises — the same
6722 // rule the read-only *data* property below follows, and skipping it
6723 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6724 // return silently. The reference answers `TypeError: 'x' is
6725 // read-only`.
6726 None => match on_failure {
6727 DeleteFailure::Throw => {
6728 Err(self.type_error(format!("'{key}' is read-only")))
6729 }
6730 DeleteFailure::Ignore => Ok(()),
6731 },
6732 };
6733 }
6734 // An own non-writable data property stops here: nothing may change it.
6735 if !property.writable {
6736 return match on_failure {
6737 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6738 DeleteFailure::Ignore => Ok(()),
6739 };
6740 }
6741 // An existing writable own property keeps its attributes: only the value
6742 // moves. Redefining instead would reset them, which is how a
6743 // non-configurable global `var` used to become deletable.
6744 if object.write_value_key(key, value.clone()) {
6745 return Ok(());
6746 }
6747 }
6748 // Step 2: hand the store to the prototype, with `object` as the receiver.
6749 if let Some(proto) = object.proto() {
6750 let receiver = Value::Object(object.clone());
6751 let accepted =
6752 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6753 return if accepted {
6754 Ok(())
6755 } else {
6756 match on_failure {
6757 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6758 DeleteFailure::Ignore => Ok(()),
6759 }
6760 };
6761 }
6762 // Step 3: create one, and a non-extensible object cannot.
6763 if !object.is_extensible() {
6764 return match on_failure {
6765 DeleteFailure::Throw => Err(self.type_error(format!(
6766 "cannot add property {key}, object is not extensible"
6767 ))),
6768 DeleteFailure::Ignore => Ok(()),
6769 };
6770 }
6771 object.define_data_key(key, value);
6772 Ok(())
6773 }
6774
6775 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6776 ///
6777 /// The distinction the fast path above does not need: it is called with the store's
6778 /// receiver already being the object it writes to. Here `object` is the one whose
6779 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6780 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6781 /// and not a write to `object`.
6782 ///
6783 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6784 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6785 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6786 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6787 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6788 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6789 ///
6790 /// Answers `false` where the spec says `false`; the caller turns that into the
6791 /// strict-mode `TypeError` or the sloppy-mode silence.
6792 fn ordinary_set_with_receiver(
6793 &mut self,
6794 object: &Gc<JsObject>,
6795 receiver: &Value,
6796 key: &PropertyKey,
6797 value: Value,
6798 on_failure: DeleteFailure,
6799 ) -> JsResult<bool> {
6800 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6801 if object.proxy_state().is_some() {
6802 return Ok(self
6803 .proxy_set(object, key, value, receiver)?
6804 .unwrap_or(true));
6805 }
6806 // A host class decides for itself, with the receiver the caller named.
6807 if let Some(exotic) = object.exotic()
6808 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6809 {
6810 return Ok(accepted);
6811 }
6812 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6813 // rather than the receiver, but the receiver may still *be* the view:
6814 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6815 // itself as receiver, and then the first half applies — convert `V` once, store
6816 // if the index is valid, answer `true` either way. The conversion is the observable
6817 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6818 //
6819 // Only the second half, a view that is *not* the receiver, skips the conversion
6820 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6821 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6822 // below with the value still unconverted.
6823 if object.typed_array_element_type().is_some()
6824 && let Some(numeric) = canonical_numeric_index(key)
6825 {
6826 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6827 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6828 return Ok(true);
6829 }
6830 if !typed_array_index_is_valid(object, numeric) {
6831 return Ok(true);
6832 }
6833 }
6834 let own = self.object_get_own_property(object, key)?;
6835 if let Some(own) = own {
6836 if own.is_accessor() {
6837 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6838 Some(setter) => {
6839 self.call_value(setter, receiver.clone(), vec![value])?;
6840 Ok(true)
6841 }
6842 None => Ok(false),
6843 };
6844 }
6845 // A non-writable data descriptor refuses, own or inherited. Either way the
6846 // receiver must not gain a shadowing property.
6847 if !own.writable {
6848 return Ok(false);
6849 }
6850 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6851 // created or written, and it is created as an ordinary data property.
6852 let Some(receiver_object) = receiver.as_object().cloned() else {
6853 return Ok(false);
6854 };
6855 return match self.object_get_own_property(&receiver_object, key)? {
6856 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6857 Some(existing) => self.object_define_own_property(
6858 &receiver_object,
6859 key,
6860 Property {
6861 value: Some(value),
6862 ..existing
6863 },
6864 ),
6865 None => {
6866 self.object_define_own_property(&receiver_object, key, Property::data(value))
6867 }
6868 };
6869 }
6870 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6871 if let Some(proto) = object.proto() {
6872 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6873 }
6874 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6875 // *default* data descriptor here, so control falls into step 2 exactly as if the
6876 // target had owned a writable property — which means the **receiver's** own
6877 // descriptor is asked for before the write. Skipping that question went straight to
6878 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6879 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6880 // exactly those calls).
6881 let Some(receiver_object) = receiver.as_object().cloned() else {
6882 return Ok(false);
6883 };
6884 match self.object_get_own_property(&receiver_object, key)? {
6885 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6886 Some(existing) => self.object_define_own_property(
6887 &receiver_object,
6888 key,
6889 Property {
6890 value: Some(value),
6891 ..existing
6892 },
6893 ),
6894 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6895 }
6896 }
6897
6898 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6899 ///
6900 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6901 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6902 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6903 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6904 /// the prototype, so the walk resumes above the object.
6905 fn lookup_for_write(
6906 &mut self,
6907 object: &Gc<JsObject>,
6908 key: &PropertyKey,
6909 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6910 let Some(exotic) = object.exotic() else {
6911 return Ok(lookup_key(object, key));
6912 };
6913 Ok(match exotic.get_own_property(self, object, key)? {
6914 Some(Some(property)) => Some((object.clone(), property)),
6915 Some(None) => lookup_key_above(object, key),
6916 None => lookup_key(object, key),
6917 })
6918 }
6919
6920 /// Delete `object[key]`.
6921 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6922 self.delete_property_key(object, &PropertyKey::from(key))
6923 }
6924
6925 /// [`Interp::delete_property`] with a key that may be a symbol.
6926 pub fn delete_property_key(
6927 &mut self,
6928 object: &Gc<JsObject>,
6929 key: &PropertyKey,
6930 ) -> JsResult<bool> {
6931 // A proxy decides for itself, and may even throw; the invariant checks live in
6932 // `proxy_delete`.
6933 if let Some(answer) = self.proxy_delete(object, key)? {
6934 return Ok(answer);
6935 }
6936 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6937 // caller reports as a failed delete.
6938 if let Some(exotic) = object.exotic()
6939 && let Some(answer) = exotic.delete_property(self, object, key)?
6940 {
6941 return Ok(answer);
6942 }
6943 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6944 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6945 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6946 // one answers `false` because the elements are non-configurable. The prototype
6947 // chain is not consulted either, which is what makes a throwing getter on
6948 // `TypedArray.prototype["-1"]` stay unrun.
6949 if object.typed_array_parts().is_some()
6950 && object.proxy_state().is_none()
6951 && let Some(numeric) = canonical_numeric_index(key)
6952 {
6953 return Ok(!typed_array_index_is_valid(object, numeric));
6954 }
6955 let mapped_index = key.as_str().and_then(array_index);
6956 if let Some(index) = mapped_index
6957 && let Some(length) = object.array_length()
6958 && (index as usize) < length
6959 {
6960 // An accessor defined on an index lives in the property table rather than the
6961 // element vector, so both have to be cleared: `delete` after
6962 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6963 object.delete_key(key);
6964 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6965 // index stops answering `in`.
6966 if object.element_is_undeletable(index) {
6967 return Ok(false);
6968 }
6969 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6970 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6971 // and no longer through to the parameter. A refused delete leaves the
6972 // mapping alone.
6973 object.drop_mapped_argument(index as usize);
6974 object.array_set(self.heap, index as usize, Value::Hole);
6975 return Ok(true);
6976 }
6977 // An array's `length` is a non-configurable own property that lives outside the
6978 // property table, so `delete_key` finds nothing and reports success — `Reflect
6979 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6980 // §10.4.4.1 step 3 refuses it.
6981 if key.as_str() == Some("length") && object.array_length().is_some() {
6982 return Ok(false);
6983 }
6984 // The same for an object that is not an array: only a delete that actually
6985 // removed the property ends the alias.
6986 let deleted = object.delete_key(key);
6987 if deleted && let Some(index) = mapped_index {
6988 object.drop_mapped_argument(index as usize);
6989 }
6990 Ok(deleted)
6991 }
6992
6993 // -- proxy traps --------------------------------------------------------
6994 //
6995 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6996 // with the target and the operation's own arguments, then check the answer against
6997 // the target. The checks are not decoration — they are what stops a proxy from
6998 // reporting a `non-configurable` property as missing, which would let a frozen object
6999 // be rewritten by standing in front of it.
7000
7001 /// The target and handler of `object`, or `None` when it is not a proxy.
7002 ///
7003 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
7004 /// one has to fail: the slots the traps would have been read from are gone.
7005 pub(crate) fn proxy_parts(
7006 &mut self,
7007 object: &Gc<JsObject>,
7008 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
7009 let Some(state) = object.proxy_state() else {
7010 return Ok(None);
7011 };
7012 let state = state.borrow();
7013 match (&state.target, &state.handler) {
7014 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
7015 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
7016 }
7017 }
7018
7019 /// Call `handler[name]`, or answer `None` when the trap is absent.
7020 ///
7021 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
7022 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
7023 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
7024 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
7025 /// one per trap plus the `target-is-proxy` variants.
7026 ///
7027 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
7028 /// this cannot simply be "any non-callable means no trap".
7029 fn proxy_trap(
7030 &mut self,
7031 handler: &Value,
7032 name: &str,
7033 args: Vec<Value>,
7034 ) -> JsResult<Option<Value>> {
7035 let Value::Object(table) = handler else {
7036 return Err(self.type_error("proxy handler is not an object"));
7037 };
7038 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
7039 match trap {
7040 Value::Undefined | Value::Null => Ok(None),
7041 Value::Object(function) if function.is_callable() => {
7042 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
7043 Ok(Some(answer))
7044 }
7045 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
7046 }
7047 }
7048
7049 /// Whether the target's own property `key` is one it refuses to lose.
7050 ///
7051 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
7052 /// its value behind the target's back.
7053 ///
7054 /// A **method**, not a free function, because §10.5.1's invariants say
7055 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
7056 /// property table directly finds nothing (a proxy's table is empty by design), so every
7057 /// invariant check silently passed for a proxy target. That is what
7058 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
7059 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
7060 /// where an array's elements and its `length` — both fixed, both outside the table —
7061 /// are covered.
7062 fn fixed_property(
7063 &mut self,
7064 target: &Gc<JsObject>,
7065 key: &PropertyKey,
7066 ) -> JsResult<Option<Property>> {
7067 Ok(self
7068 .object_get_own_property(target, key)?
7069 .filter(|property| !property.configurable))
7070 }
7071
7072 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7073 fn proxy_get(
7074 &mut self,
7075 object: &Gc<JsObject>,
7076 receiver: &Value,
7077 key: &PropertyKey,
7078 ) -> JsResult<Option<Value>> {
7079 let Some((target, handler)) = self.proxy_parts(object)? else {
7080 return Ok(None);
7081 };
7082 let key_value = self.key_value(key);
7083 let Some(result) = self.proxy_trap(
7084 &handler,
7085 "get",
7086 vec![Value::Object(target.clone()), key_value, receiver.clone()],
7087 )?
7088 else {
7089 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7090 // inherited getter still sees the proxy.
7091 return Ok(Some(
7092 self.get_property_key_for(&target, Some(receiver), key)?
7093 .unwrap_or(Value::Undefined),
7094 ));
7095 };
7096 if let Some(fixed) = self.fixed_property(&target, key)? {
7097 if fixed.is_accessor() {
7098 // A fixed accessor with no getter must read as `undefined`.
7099 let has_getter = fixed
7100 .getter
7101 .as_ref()
7102 .is_some_and(|getter| !matches!(getter, Value::Undefined));
7103 if !has_getter && !matches!(result, Value::Undefined) {
7104 return Err(self.type_error(format!(
7105 "proxy 'get' must report undefined for the non-configurable property '{key}'"
7106 )));
7107 }
7108 } else if !fixed.writable {
7109 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7110 if !fixed_value.same_value(&result) {
7111 return Err(self.type_error(format!(
7112 "proxy 'get' disagrees with the non-configurable property '{key}'"
7113 )));
7114 }
7115 }
7116 }
7117 Ok(Some(result))
7118 }
7119
7120 /// `[[Set]]` on a proxy.
7121 ///
7122 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7123 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7124 /// read-only store has.
7125 fn proxy_set(
7126 &mut self,
7127 object: &Gc<JsObject>,
7128 key: &PropertyKey,
7129 value: Value,
7130 receiver: &Value,
7131 ) -> JsResult<Option<bool>> {
7132 let Some((target, handler)) = self.proxy_parts(object)? else {
7133 return Ok(None);
7134 };
7135 let key_value = self.key_value(key);
7136 let Some(result) = self.proxy_trap(
7137 &handler,
7138 "set",
7139 vec![
7140 Value::Object(target.clone()),
7141 key_value,
7142 value.clone(),
7143 receiver.clone(),
7144 ],
7145 )?
7146 else {
7147 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7148 // given — not the target. `OrdinarySet` step 3 is
7149 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7150 // object whose prototype is a typed array has to reach the proxy's own
7151 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7152 // calls and expects exactly one. Storing on the target instead put the value
7153 // in the target and never consulted the trap.
7154 let accepted = self.ordinary_set_with_receiver(
7155 &target,
7156 receiver,
7157 key,
7158 value,
7159 DeleteFailure::Ignore,
7160 )?;
7161 return Ok(Some(accepted));
7162 };
7163 if !result.to_boolean() {
7164 return Ok(Some(false));
7165 }
7166 if let Some(fixed) = self.fixed_property(&target, key)? {
7167 if fixed.is_accessor() {
7168 let has_setter = fixed
7169 .setter
7170 .as_ref()
7171 .is_some_and(|setter| !matches!(setter, Value::Undefined));
7172 if !has_setter {
7173 return Err(self.type_error(format!(
7174 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7175 )));
7176 }
7177 } else if !fixed.writable {
7178 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7179 if !fixed_value.same_value(&value) {
7180 return Err(self.type_error(format!(
7181 "proxy 'set' changed the non-configurable property '{key}'"
7182 )));
7183 }
7184 }
7185 }
7186 // A new property cannot appear on a target that refuses new properties.
7187 if self.object_get_own_property(&target, key)?.is_none()
7188 && !self.object_is_extensible(&target)?
7189 {
7190 return Err(self.type_error(format!(
7191 "proxy 'set' added '{key}' to a non-extensible target"
7192 )));
7193 }
7194 Ok(Some(true))
7195 }
7196
7197 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7198 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7199 let Some((target, handler)) = self.proxy_parts(object)? else {
7200 return Ok(None);
7201 };
7202 let key_value = self.key_value(key);
7203 let Some(result) = self.proxy_trap(
7204 &handler,
7205 "has",
7206 vec![Value::Object(target.clone()), key_value],
7207 )?
7208 else {
7209 return Ok(Some(self.has_own_or_inherited(&target, key)?));
7210 };
7211 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7212 return Err(self.type_error(format!(
7213 "proxy 'has' denied the non-configurable property '{key}'"
7214 )));
7215 }
7216 // A non-extensible target cannot grow, so every own property it *has* is fixed.
7217 if !result.to_boolean()
7218 && !self.object_is_extensible(&target)?
7219 && self.object_get_own_property(&target, key)?.is_some()
7220 {
7221 return Err(self.type_error(format!(
7222 "proxy 'has' denied the own property '{key}' of a non-extensible target"
7223 )));
7224 }
7225 Ok(Some(result.to_boolean()))
7226 }
7227
7228 /// `[[Delete]]` on a proxy.
7229 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7230 let Some((target, handler)) = self.proxy_parts(object)? else {
7231 return Ok(None);
7232 };
7233 let key_value = self.key_value(key);
7234 let Some(result) = self.proxy_trap(
7235 &handler,
7236 "deleteProperty",
7237 vec![Value::Object(target.clone()), key_value],
7238 )?
7239 else {
7240 return Ok(Some(self.delete_property_key(&target, key)?));
7241 };
7242 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7243 return Err(self.type_error(format!(
7244 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7245 )));
7246 }
7247 if result.to_boolean()
7248 && !self.object_is_extensible(&target)?
7249 && self.object_get_own_property(&target, key)?.is_some()
7250 {
7251 return Err(self.type_error(format!(
7252 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7253 )));
7254 }
7255 Ok(Some(result.to_boolean()))
7256 }
7257
7258 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7259 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7260 let Some((target, handler)) = self.proxy_parts(object)? else {
7261 return Ok(None);
7262 };
7263 let Some(result) =
7264 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7265 else {
7266 // No trap: the target's own keys, already in the order an object reports.
7267 return Ok(Some(self.object_own_property_keys(&target)?));
7268 };
7269 // `CreateListFromArrayLike` with the string-or-symbol restriction.
7270 let list = self.list_from_array_like(&result, true)?;
7271 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7272 for value in list {
7273 let key = self.propkey(&value)?;
7274 if keys.contains(&key) {
7275 return Err(self.type_error(format!(
7276 "proxy 'ownKeys' returned the duplicate key '{key}'"
7277 )));
7278 }
7279 keys.push(key);
7280 }
7281 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7282 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7283 // table is empty, which made every check below vacuous.
7284 let target_keys = self.object_own_property_keys(&target)?;
7285 let extensible = self.object_is_extensible(&target)?;
7286 for key in &target_keys {
7287 if keys.contains(key) {
7288 continue;
7289 }
7290 if self.fixed_property(&target, key)?.is_some() {
7291 return Err(self.type_error(format!(
7292 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7293 )));
7294 }
7295 if !extensible {
7296 return Err(self.type_error(format!(
7297 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7298 )));
7299 }
7300 }
7301 if !extensible {
7302 // §10.5.11 step 12: the lists must match one for one, in any order.
7303 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7304 {
7305 return Err(
7306 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7307 );
7308 }
7309 }
7310 Ok(Some(keys))
7311 }
7312
7313 /// `[[GetOwnProperty]]` on a proxy.
7314 fn proxy_get_own_property(
7315 &mut self,
7316 object: &Gc<JsObject>,
7317 key: &PropertyKey,
7318 ) -> JsResult<Option<Option<Property>>> {
7319 let Some((target, handler)) = self.proxy_parts(object)? else {
7320 return Ok(None);
7321 };
7322 let key_value = self.key_value(key);
7323 let Some(result) = self.proxy_trap(
7324 &handler,
7325 "getOwnPropertyDescriptor",
7326 vec![Value::Object(target.clone()), key_value],
7327 )?
7328 else {
7329 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7330 // property table. Two things ride on that choice: a target that is itself a
7331 // proxy has to re-dispatch (its own table is empty, so reading it reported
7332 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7333 // indices and `length` live outside the table and need the ordinary synthesis.
7334 // `object_get_own_property` does both.
7335 return Ok(Some(self.object_get_own_property(&target, key)?));
7336 };
7337 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7338 // `ToPropertyDescriptor` runs, because that operation would box the primitive
7339 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7340 // empty descriptor instead of refusing.
7341 if !matches!(result, Value::Undefined | Value::Object(_)) {
7342 return Err(self.type_error(
7343 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7344 ));
7345 }
7346 let target_desc = self.object_get_own_property(&target, key)?;
7347 let extensible = self.object_is_extensible(&target)?;
7348 let Some(descriptor) = (match result {
7349 Value::Undefined => None,
7350 _ => Some(self.property_from_descriptor(&result)?),
7351 }) else {
7352 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7353 // descriptor is configurable *and* the target can still grow back.
7354 if let Some(target_desc) = &target_desc {
7355 if !target_desc.configurable {
7356 return Err(self.type_error(format!(
7357 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7358 )));
7359 }
7360 if !extensible {
7361 return Err(self.type_error(format!(
7362 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7363 )));
7364 }
7365 }
7366 return Ok(Some(None));
7367 };
7368 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7369 // which is a stronger requirement than "the target is not contradicting it" — the
7370 // four branches below are each one test262 case.
7371 if !descriptor.configurable {
7372 let Some(target_desc) = &target_desc else {
7373 return Err(self.type_error(format!(
7374 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7375 )));
7376 };
7377 if target_desc.configurable {
7378 return Err(self.type_error(format!(
7379 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7380 )));
7381 }
7382 let target_is_data = !target_desc.is_accessor();
7383 let result_is_data = !descriptor.is_accessor();
7384 if result_is_data && !target_is_data {
7385 return Err(self.type_error(format!(
7386 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7387 )));
7388 }
7389 if target_is_data && !target_desc.writable {
7390 if !result_is_data {
7391 return Err(self.type_error(format!(
7392 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7393 )));
7394 }
7395 if descriptor.writable {
7396 return Err(self.type_error(format!(
7397 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7398 )));
7399 }
7400 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7401 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7402 if !fixed_value.same_value(&reported) {
7403 return Err(self.type_error(format!(
7404 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7405 )));
7406 }
7407 }
7408 // Step 16.d: a reported *read-only* data property needs a real read-only data
7409 // property behind it. Missing this let a trap bolt a frozen property onto a
7410 // writable target intent (`resultdesc-is-not-configurable-not-writable-
7411 // targetdesc-is-writable`).
7412 if result_is_data && !descriptor.writable {
7413 if !target_is_data {
7414 return Err(self.type_error(format!(
7415 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7416 )));
7417 }
7418 if target_desc.writable {
7419 return Err(self.type_error(format!(
7420 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7421 )));
7422 }
7423 }
7424 if descriptor.is_accessor() {
7425 // Step 16.e: a getter the target does not have may not be invented, and
7426 // vice versa.
7427 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7428 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7429 (Some(a), Some(b)) => a.same_value(b),
7430 _ => false,
7431 };
7432 if !same(&target_desc.getter, &descriptor.getter)
7433 || !same(&target_desc.setter, &descriptor.setter)
7434 {
7435 return Err(self.type_error(format!(
7436 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7437 )));
7438 }
7439 }
7440 }
7441 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7442 // where the target's own is locked. Without it a handler could advertise
7443 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7444 // that believed it would try to redefine something it cannot.
7445 if descriptor.configurable
7446 && let Some(target_desc) = &target_desc
7447 && !target_desc.configurable
7448 {
7449 return Err(self.type_error(format!(
7450 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7451 )));
7452 }
7453 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7454 // through the trap either, however well-formed the descriptor is. This is the
7455 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7456 // the frozen target does not own.
7457 if !extensible {
7458 let Some(target_desc) = &target_desc else {
7459 return Err(self.type_error(format!(
7460 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7461 )));
7462 };
7463 if target_desc.is_accessor() == descriptor.is_accessor() {
7464 let target_is_data = !target_desc.is_accessor();
7465 let result_is_data = !descriptor.is_accessor();
7466 if target_is_data && !target_desc.writable && descriptor.writable {
7467 return Err(self.type_error(format!(
7468 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7469 )));
7470 }
7471 if !result_is_data && !target_is_data {
7472 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7473 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7474 (Some(a), Some(b)) => a.same_value(b),
7475 _ => false,
7476 };
7477 if !same(&target_desc.getter, &descriptor.getter)
7478 || !same(&target_desc.setter, &descriptor.setter)
7479 {
7480 return Err(self.type_error(format!(
7481 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7482 )));
7483 }
7484 }
7485 }
7486 }
7487 Ok(Some(Some(descriptor)))
7488 }
7489
7490 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7491 ///
7492 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7493 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7494 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7495 /// for a data property. `Property` cannot express "this field is absent", so the whole
7496 /// property path is skipped and the descriptor is assembled here field by field.
7497 ///
7498 /// `current` is the property the trap reported, used only to tell a data property from
7499 /// an accessor.
7500 pub fn proxy_seal_property(
7501 &mut self,
7502 object: &Gc<JsObject>,
7503 key: &PropertyKey,
7504 frozen: bool,
7505 current: &Property,
7506 ) -> JsResult<bool> {
7507 let Some((_target, handler)) = self.proxy_parts(object)? else {
7508 return Err(self.type_error("not a proxy"));
7509 };
7510 let descriptor = self.new_object(None);
7511 descriptor.define_data("configurable", Value::Bool(false));
7512 if frozen && !current.is_accessor() {
7513 descriptor.define_data("writable", Value::Bool(false));
7514 }
7515 let key_value = self.key_value(key);
7516 let target = object
7517 .proxy_state()
7518 .and_then(|state| state.borrow().target.clone());
7519 let Some(target) = target else {
7520 return Err(self.type_error("cannot use a proxy that has been revoked"));
7521 };
7522 let Some(result) = self.proxy_trap(
7523 &handler,
7524 "defineProperty",
7525 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7526 )?
7527 else {
7528 // No trap means the definition belongs to the target; `false` is its answer.
7529 return Ok(false);
7530 };
7531 Ok(result.to_boolean())
7532 }
7533
7534 /// `[[DefineOwnProperty]]` on a proxy.
7535 fn proxy_define_property(
7536 &mut self,
7537 object: &Gc<JsObject>,
7538 key: &PropertyKey,
7539 property: Property,
7540 ) -> JsResult<Option<bool>> {
7541 let Some((target, handler)) = self.proxy_parts(object)? else {
7542 return Ok(None);
7543 };
7544 let key_value = self.key_value(key);
7545 let descriptor = self.descriptor_from_property(&property);
7546 let Some(result) = self.proxy_trap(
7547 &handler,
7548 "defineProperty",
7549 vec![Value::Object(target.clone()), key_value, descriptor],
7550 )?
7551 else {
7552 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7553 // going" answer and `object_define_own_property` turns it into exactly that
7554 // forwarding — see the note there. (Reading it as "not a proxy" would define
7555 // the property on the proxy object itself, whose table is empty and which no
7556 // read ever consults.)
7557 return Ok(None);
7558 };
7559 if !result.to_boolean() {
7560 return Ok(Some(false));
7561 }
7562 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7563 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7564 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7565 // and treating them alike made four cases pass a descriptor the target contradicts.
7566 let target_desc = self.object_get_own_property(&target, key)?;
7567 let extensible = self.object_is_extensible(&target)?;
7568 let named = property
7569 .descriptor_fields
7570 .unwrap_or(crate::object::DescriptorFields {
7571 value: false,
7572 writable: false,
7573 enumerable: false,
7574 configurable: false,
7575 get: false,
7576 set: false,
7577 });
7578 if named.configurable && !property.configurable {
7579 let Some(target_desc) = &target_desc else {
7580 return Err(self.type_error(format!(
7581 "proxy 'defineProperty' invented the non-configurable '{key}'"
7582 )));
7583 };
7584 if target_desc.configurable {
7585 return Err(self.type_error(format!(
7586 "proxy 'defineProperty' made '{key}' non-configurable"
7587 )));
7588 }
7589 }
7590 // Step 11's other half: reporting that a property was made *configurable* needs a
7591 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7592 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7593 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7594 // target`).
7595 if named.configurable
7596 && property.configurable
7597 && let Some(target_desc) = &target_desc
7598 && !target_desc.configurable
7599 {
7600 return Err(
7601 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7602 );
7603 }
7604 // Step 12: a property cannot be reported *made writable* when the target's copy is
7605 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7606 // the trap is allowed to claim a definition it did not perform, as long as the
7607 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7608 // legal, and refusing it broke the commonest way to seed a proxy).
7609 if named.writable
7610 && property.writable
7611 && let Some(target_desc) = &target_desc
7612 && !target_desc.writable
7613 {
7614 return Err(self.type_error(format!(
7615 "proxy 'defineProperty' made the read-only '{key}' writable"
7616 )));
7617 }
7618 // Step 13: making a property read-only needs an existing read-only property.
7619 if named.writable
7620 && !property.writable
7621 && let Some(target_desc) = &target_desc
7622 && !target_desc.is_accessor()
7623 && target_desc.writable
7624 {
7625 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7626 }
7627 // Step 14: a non-writable, non-configurable property's value is fixed.
7628 if named.value
7629 && let Some(target_desc) = &target_desc
7630 && !target_desc.is_accessor()
7631 && !target_desc.writable
7632 && !target_desc.configurable
7633 {
7634 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7635 let reported = property.value.clone().unwrap_or(Value::Undefined);
7636 if !fixed_value.same_value(&reported) {
7637 return Err(self.type_error(format!(
7638 "proxy 'defineProperty' changed the value of '{key}'"
7639 )));
7640 }
7641 }
7642 // Step 15: a non-extensible target cannot grow.
7643 if target_desc.is_none() && !extensible {
7644 return Err(self.type_error(format!(
7645 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7646 )));
7647 }
7648 Ok(Some(true))
7649 }
7650
7651 /// `[[GetPrototypeOf]]` on a proxy.
7652 fn proxy_get_prototype_of(
7653 &mut self,
7654 object: &Gc<JsObject>,
7655 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7656 let Some((target, handler)) = self.proxy_parts(object)? else {
7657 return Ok(None);
7658 };
7659 let Some(result) = self.proxy_trap(
7660 &handler,
7661 "getPrototypeOf",
7662 vec![Value::Object(target.clone())],
7663 )?
7664 else {
7665 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7666 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7667 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7668 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7669 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7670 return Ok(Some(self.object_prototype_of(&target)?));
7671 };
7672 let proto = match &result {
7673 Value::Null => None,
7674 Value::Object(proto) => Some(proto.clone()),
7675 _ => {
7676 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7677 }
7678 };
7679 if !self.object_is_extensible(&target)? {
7680 let actual = self.object_prototype_of(&target)?;
7681 if !same_proto(proto.as_ref(), actual.as_ref()) {
7682 return Err(self.type_error(
7683 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7684 ));
7685 }
7686 }
7687 Ok(Some(proto))
7688 }
7689
7690 /// `[[SetPrototypeOf]]` on a proxy.
7691 fn proxy_set_prototype_of(
7692 &mut self,
7693 object: &Gc<JsObject>,
7694 proto: Option<Gc<JsObject>>,
7695 ) -> JsResult<Option<bool>> {
7696 let Some((target, handler)) = self.proxy_parts(object)? else {
7697 return Ok(None);
7698 };
7699 let proto_value = match &proto {
7700 Some(proto) => Value::Object(proto.clone()),
7701 None => Value::Null,
7702 };
7703 let Some(result) = self.proxy_trap(
7704 &handler,
7705 "setPrototypeOf",
7706 vec![Value::Object(target.clone()), proto_value],
7707 )?
7708 else {
7709 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7710 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7711 // its stored prototype overwritten behind its back.
7712 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7713 };
7714 if result.to_boolean()
7715 && !self.object_is_extensible(&target)?
7716 && !same_proto(
7717 Some(&proto).and_then(|p| p.clone()).as_ref(),
7718 self.object_prototype_of(&target)?.as_ref(),
7719 )
7720 {
7721 return Err(self.type_error(
7722 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7723 ));
7724 }
7725 Ok(Some(result.to_boolean()))
7726 }
7727
7728 /// `[[IsExtensible]]` on a proxy.
7729 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7730 let Some((target, handler)) = self.proxy_parts(object)? else {
7731 return Ok(None);
7732 };
7733 let Some(result) = self.proxy_trap(
7734 &handler,
7735 "isExtensible",
7736 vec![Value::Object(target.clone())],
7737 )?
7738 else {
7739 return Ok(Some(self.object_is_extensible(&target)?));
7740 };
7741 // The answer is not the proxy's to invent: it must agree with the target, or a
7742 // script could learn `false` while the target keeps accepting new properties.
7743 if result.to_boolean() != self.object_is_extensible(&target)? {
7744 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7745 }
7746 Ok(Some(result.to_boolean()))
7747 }
7748
7749 /// `[[PreventExtensions]]` on a proxy.
7750 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7751 let Some((target, handler)) = self.proxy_parts(object)? else {
7752 return Ok(None);
7753 };
7754 let Some(result) = self.proxy_trap(
7755 &handler,
7756 "preventExtensions",
7757 vec![Value::Object(target.clone())],
7758 )?
7759 else {
7760 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7761 // its answer can be `false`.
7762 return Ok(Some(self.object_prevent_extensions(&target)?));
7763 };
7764 if result.to_boolean() && self.object_is_extensible(&target)? {
7765 return Err(self.type_error(
7766 "proxy 'preventExtensions' reported success but the target is still extensible",
7767 ));
7768 }
7769 Ok(Some(result.to_boolean()))
7770 }
7771
7772 /// `[[Call]]` on a proxy, through the `apply` trap.
7773 fn proxy_apply(
7774 &mut self,
7775 object: &Gc<JsObject>,
7776 this: Value,
7777 args: Vec<Value>,
7778 ) -> JsResult<Option<Value>> {
7779 let Some((target, handler)) = self.proxy_parts(object)? else {
7780 return Ok(None);
7781 };
7782 // The trap gets the arguments as one array, which is the shape the spec passes
7783 // and the shape `apply` traps are written against (`args[0]` is the first one).
7784 let arguments = self.new_array(args.clone());
7785 let this_for_trap = this.clone();
7786 let Some(result) = self.proxy_trap(
7787 &handler,
7788 "apply",
7789 vec![
7790 Value::Object(target.clone()),
7791 this_for_trap,
7792 Value::Object(arguments),
7793 ],
7794 )?
7795 else {
7796 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7797 };
7798 Ok(Some(result))
7799 }
7800
7801 /// `[[Construct]]` on a proxy, through the `construct` trap.
7802 fn proxy_construct(
7803 &mut self,
7804 object: &Gc<JsObject>,
7805 args: Vec<Value>,
7806 new_target: &Value,
7807 ) -> JsResult<Option<Value>> {
7808 let Some((target, handler)) = self.proxy_parts(object)? else {
7809 return Ok(None);
7810 };
7811 if !target.is_callable() {
7812 return Err(self.type_error("proxy target is not a constructor"));
7813 }
7814 let arguments = self.new_array(args.clone());
7815 let Some(result) = self.proxy_trap(
7816 &handler,
7817 "construct",
7818 vec![
7819 Value::Object(target.clone()),
7820 Value::Object(arguments),
7821 new_target.clone(),
7822 ],
7823 )?
7824 else {
7825 return Ok(Some(self.construct(
7826 Value::Object(target),
7827 new_target.clone(),
7828 args,
7829 )?));
7830 };
7831 if !matches!(result, Value::Object(_)) {
7832 return Err(self.type_error("proxy 'construct' must return an object"));
7833 }
7834 Ok(Some(result))
7835 }
7836
7837 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7838 pub(crate) fn has_own_or_inherited(
7839 &mut self,
7840 object: &Gc<JsObject>,
7841 key: &PropertyKey,
7842 ) -> JsResult<bool> {
7843 // The object itself first: it may be a proxy, and then the answer is its trap's.
7844 if let Some(answer) = self.proxy_has(object, key)? {
7845 return Ok(answer);
7846 }
7847 // An integer-indexed exotic object answers a canonical numeric index from
7848 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7849 // prototype chain. That is observable twice: a view the buffer has been resized
7850 // away from has no indices, so `2 in view` is `false` even when
7851 // `Object.getPrototypeOf(view)[2]` exists (what
7852 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7853 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7854 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7855 // goes through here, which is why the same rule is repeated in `has_property_key`
7856 // rather than living only there.
7857 if object.typed_array_parts().is_some()
7858 && let Some(numeric) = canonical_numeric_index(key)
7859 {
7860 return Ok(typed_array_index_is_valid(object, numeric));
7861 }
7862 // A host class answers `in` for its own keys, which may live nowhere in a property
7863 // table — `"x" in point` is true because the class says so, not because a property
7864 // exists.
7865 if let Some(exotic) = object.exotic()
7866 && let Some(answer) = exotic.has_property(self, object, key)?
7867 {
7868 return Ok(answer);
7869 }
7870 // `has_own` rather than `own_property_key`: an array's elements and its derived
7871 // `length` are invisible to the property table, and `Array.prototype` is an array.
7872 // A host class's `get_own_property` counts too, because the reference's
7873 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7874 // lives — a class with only `get_own_property` answers `in` through it.
7875 if self.exotic_has_own(object, key)? {
7876 return Ok(true);
7877 }
7878 // A hole is *not* the end of the search: the chain may still have the key, which
7879 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7880 for ancestor in object.chain() {
7881 // A proxy further up the chain answers for itself.
7882 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7883 return Ok(answer);
7884 }
7885 // Same for a host class: a prototype may be one, and `in` reaches it.
7886 if let Some(exotic) = ancestor.exotic()
7887 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7888 {
7889 return Ok(answer);
7890 }
7891 if self.exotic_has_own(&ancestor, key)? {
7892 return Ok(true);
7893 }
7894 }
7895 Ok(false)
7896 }
7897
7898 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7899 /// trap included.
7900 ///
7901 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7902 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7903 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7904 if let Some(exotic) = object.exotic()
7905 && let Some(answer) = exotic.get_own_property(self, object, key)?
7906 {
7907 return Ok(answer.is_some());
7908 }
7909 Ok(has_own(object, key))
7910 }
7911
7912 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7913 ///
7914 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7915 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7916 /// `TypeError` instead of a property named `"1.5"`.
7917 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7918 let object = self.object_from(value)?;
7919 let length = self
7920 .get_property(&object, "length")?
7921 .map(|value| value.to_number())
7922 .unwrap_or(0.0);
7923 if !length.is_finite() || length < 0.0 {
7924 return Err(self.type_error("invalid array-like length"));
7925 }
7926 let length = length as usize;
7927 let mut items = Vec::with_capacity(length.min(1024));
7928 for index in 0..length {
7929 let item = self
7930 .get_property(&object, &index.to_string())?
7931 .unwrap_or(Value::Undefined);
7932 if keys_only && matches!(&item, Value::Symbol(_)) {
7933 items.push(item);
7934 continue;
7935 }
7936 if keys_only && !matches!(&item, Value::String(_)) {
7937 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7938 }
7939 items.push(item);
7940 }
7941 Ok(items)
7942 }
7943
7944 /// A `Property` from the descriptor object a trap returned.
7945 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7946 let object = self.object_from(value)?;
7947 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7948 interp.get_property(&object, name)
7949 };
7950 let getter = field(self, "get")?;
7951 let setter = field(self, "set")?;
7952 let accessor = getter.is_some() || setter.is_some();
7953 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7954 Ok(interp
7955 .get_property(&object, name)?
7956 .is_some_and(|value| value.to_boolean()))
7957 };
7958 let enumerable = boolean(self, "enumerable")?;
7959 let configurable = boolean(self, "configurable")?;
7960 if accessor {
7961 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7962 return Err(
7963 self.type_error("a descriptor cannot be both a data property and an accessor")
7964 );
7965 }
7966 Ok(Property {
7967 getter: getter.or(Some(Value::Undefined)),
7968 setter: setter.or(Some(Value::Undefined)),
7969 enumerable,
7970 configurable,
7971 writable: false,
7972 value: None,
7973 descriptor_fields: None,
7974 })
7975 } else {
7976 Ok(Property {
7977 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7978 writable: boolean(self, "writable")?,
7979 enumerable,
7980 configurable,
7981 getter: None,
7982 setter: None,
7983 descriptor_fields: None,
7984 })
7985 }
7986 }
7987
7988 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7989 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7990 let object = self.new_object(None);
7991 // A partial descriptor names only some fields, and the trap must see exactly those:
7992 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7993 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7994 // case, where every field is present.
7995 let fields = property.descriptor_fields;
7996 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7997 fields.is_none_or(|fields| field(&fields))
7998 };
7999 if property.is_accessor() {
8000 let getter = property.getter.clone().unwrap_or(Value::Undefined);
8001 let setter = property.setter.clone().unwrap_or(Value::Undefined);
8002 object.define_data("get", getter);
8003 object.define_data("set", setter);
8004 } else {
8005 if names(|fields| fields.value) {
8006 let value = property.value.clone().unwrap_or(Value::Undefined);
8007 object.define_data("value", value);
8008 }
8009 if names(|fields| fields.writable) {
8010 object.define_data("writable", Value::Bool(property.writable));
8011 }
8012 }
8013 if names(|fields| fields.enumerable) {
8014 object.define_data("enumerable", Value::Bool(property.enumerable));
8015 }
8016 if names(|fields| fields.configurable) {
8017 object.define_data("configurable", Value::Bool(property.configurable));
8018 }
8019 Value::Object(object)
8020 }
8021
8022 // -- calling ------------------------------------------------------------
8023
8024 /// Call `callee` with `this` and `args`.
8025 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
8026 let Value::Object(function) = &callee else {
8027 // `typeof x === "function"` is not enough to make `x()` legal: only a
8028 // callable object is. `null` and `undefined` need no special wording
8029 // here — their `ToString` already reads the way the reference's does.
8030 let what = format!("{} is not a function", callee.to_js_string());
8031 return Err(Signal::Throw(self.make_error("TypeError", &what)));
8032 };
8033 // A proxy of a function is called through its `apply` trap. It has no
8034 // `ObjectKind::Function` of its own, so this has to come before the dispatch
8035 // below, and a proxy of a non-function has nothing to forward to.
8036 if function.proxy_state().is_some() {
8037 return match self.proxy_apply(function, this, args)? {
8038 Some(result) => Ok(result),
8039 None => Err(Signal::Throw(
8040 self.make_error("TypeError", "proxy target is not callable"),
8041 )),
8042 };
8043 }
8044 let callable = function.with(|data| match &data.kind {
8045 ObjectKind::Function(callable) => match callable {
8046 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
8047 // The `Rc` is cloned out so the borrow of this object's data is released
8048 // before the closure runs: the closure may touch the same object.
8049 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
8050 Callable::Bound {
8051 target,
8052 this,
8053 args: leading,
8054 } => Some(NativeCall::Bound {
8055 target: target.clone(),
8056 this: this.clone(),
8057 leading: leading.clone(),
8058 }),
8059 Callable::Bytecode { code, env } => {
8060 Some(NativeCall::Bytecode(code.clone(), env.clone()))
8061 }
8062 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
8063 Callable::PromiseResolve(promise) => {
8064 Some(NativeCall::PromiseResolve(promise.clone()))
8065 }
8066 Callable::PromiseReject(promise) => {
8067 Some(NativeCall::PromiseReject(promise.clone()))
8068 }
8069 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8070 state: state.clone(),
8071 }),
8072 Callable::ThenShim {
8073 handler,
8074 resolve,
8075 reject,
8076 fulfilled,
8077 } => Some(NativeCall::ThenShim {
8078 handler: handler.clone(),
8079 resolve: resolve.clone(),
8080 reject: reject.clone(),
8081 fulfilled: *fulfilled,
8082 }),
8083 Callable::AwaitResume {
8084 coroutine,
8085 promise,
8086 kind,
8087 } => Some(NativeCall::AwaitResume {
8088 coroutine: coroutine.clone(),
8089 promise: promise.clone(),
8090 kind: *kind,
8091 }),
8092 Callable::CombinatorSettle {
8093 state,
8094 index,
8095 fulfilled,
8096 } => Some(NativeCall::CombinatorSettle {
8097 state: state.clone(),
8098 index: *index,
8099 fulfilled: *fulfilled,
8100 }),
8101 Callable::FinallyShim {
8102 callback,
8103 fulfilled,
8104 constructor,
8105 } => Some(NativeCall::FinallyShim {
8106 callback: callback.clone(),
8107 fulfilled: *fulfilled,
8108 constructor: constructor.clone(),
8109 }),
8110 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8111 Callable::CompletedReturn {
8112 generator,
8113 promise,
8114 rejected,
8115 } => Some(NativeCall::CompletedReturn {
8116 generator: generator.clone(),
8117 promise: promise.clone(),
8118 rejected: *rejected,
8119 }),
8120 Callable::YieldResult {
8121 generator,
8122 promise,
8123 done,
8124 } => Some(NativeCall::YieldResult {
8125 generator: generator.clone(),
8126 promise: promise.clone(),
8127 done: *done,
8128 }),
8129 Callable::DisposeStep {
8130 remaining,
8131 promise,
8132 error,
8133 rejected,
8134 awaited,
8135 needs_await,
8136 } => Some(NativeCall::DisposeStep {
8137 remaining: remaining.clone(),
8138 promise: promise.clone(),
8139 error: error.clone(),
8140 rejected: *rejected,
8141 awaited: *awaited,
8142 needs_await: *needs_await,
8143 }),
8144 Callable::GeneratorResume {
8145 generator,
8146 promise,
8147 kind,
8148 } => Some(NativeCall::GeneratorResume {
8149 generator: generator.clone(),
8150 promise: promise.clone(),
8151 kind: *kind,
8152 }),
8153 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8154 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8155 Callable::SettlePromise {
8156 promise,
8157 value,
8158 rejected,
8159 } => Some(NativeCall::SettlePromise {
8160 promise: promise.clone(),
8161 value: value.clone(),
8162 rejected: *rejected,
8163 }),
8164 },
8165 _ => None,
8166 });
8167 match callable {
8168 Some(NativeCall::Host(func)) => {
8169 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8170 // function by name rather than stopping at the caller.
8171 let frame_less = function
8172 .own_property("_frame_less")
8173 .and_then(|property| property.value)
8174 .is_some_and(|value| value.to_boolean());
8175 let outer = if frame_less {
8176 None
8177 } else {
8178 self.native_frames
8179 .push((function.clone(), self.frames.len()));
8180 Some(self.current_native.replace(function.clone()))
8181 };
8182 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8183 // constructor reads it through `current_new_target` because it is handed
8184 // `undefined` for `this`. Taking the parked value here is what stops a
8185 // *plain* call made from inside a constructor body from seeing the
8186 // enclosing `new.target`.
8187 let parked = self.pending_new_target.take();
8188 let result = {
8189 let outer_new_target = std::mem::replace(
8190 &mut self.active_new_target,
8191 parked.unwrap_or(Value::Undefined),
8192 );
8193 let result = {
8194 let mut body = func.borrow_mut();
8195 body(self, this, &args)
8196 };
8197 self.active_new_target = outer_new_target;
8198 result
8199 };
8200 if !frame_less {
8201 self.native_frames.pop();
8202 self.current_native = outer.flatten();
8203 }
8204 result
8205 }
8206 Some(NativeCall::Native(func)) => {
8207 // A function marked `_frame_less` is one the reference implements
8208 // without a call frame — `eval` is the only one so far.
8209 let frame_less = function
8210 .own_property("_frame_less")
8211 .and_then(|property| property.value)
8212 .is_some_and(|value| value.to_boolean());
8213 let outer = if frame_less {
8214 None
8215 } else {
8216 self.native_frames
8217 .push((function.clone(), self.frames.len()));
8218 Some(self.current_native.replace(function.clone()))
8219 };
8220 let parked = self.pending_new_target.take();
8221 let outer_new_target = std::mem::replace(
8222 &mut self.active_new_target,
8223 parked.unwrap_or(Value::Undefined),
8224 );
8225 let result = func(self, this, &args);
8226 self.active_new_target = outer_new_target;
8227 if !frame_less {
8228 self.native_frames.pop();
8229 self.current_native = outer.flatten();
8230 }
8231 result
8232 }
8233 Some(NativeCall::Revoker(slots)) => {
8234 // Idempotent: revoking twice answers `undefined` again rather than
8235 // complaining, which is what the spec says and what a `finally` block
8236 // relies on.
8237 let mut state = slots.borrow_mut();
8238 state.target = None;
8239 state.handler = None;
8240 Ok(Value::Undefined)
8241 }
8242 Some(NativeCall::PromiseResolve(promise)) => {
8243 // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8244 // else, so a resolve after a reject does nothing *and* a resolve after a
8245 // resolve-with-thenable does nothing — the promise is still `Pending` then,
8246 // because the adoption is a queued job.
8247 let value = args.first().cloned().unwrap_or(Value::Undefined);
8248 if !self.claim_resolution(&promise) {
8249 return Ok(Value::Undefined);
8250 }
8251 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8252 // the resolve function performs `RejectPromise` and returns `undefined`.
8253 // (`ResolvePromise` itself throws as well, so the engine's own callers see
8254 // it; only this wrapper swallows it.)
8255 let _ = self.resolve_promise_with(&promise, value);
8256 Ok(Value::Undefined)
8257 }
8258 Some(NativeCall::PromiseReject(promise)) => {
8259 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8260 // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8261 if !self.claim_resolution(&promise) {
8262 return Ok(Value::Undefined);
8263 }
8264 self.reject_promise(&promise, reason);
8265 Ok(Value::Undefined)
8266 }
8267 Some(NativeCall::ThenShim {
8268 handler,
8269 resolve,
8270 reject,
8271 fulfilled,
8272 }) => {
8273 // `PerformPromiseThen` with a capability: run the handler, then settle
8274 // through the capability's own pair. A throw from the handler is the
8275 // rejection, and a throw from the capability's `resolve` is not caught —
8276 // exactly the spec's `?`.
8277 let value = args.first().cloned().unwrap_or(Value::Undefined);
8278 match handler {
8279 Some(handler) => {
8280 match self.call_value(handler, Value::Undefined, vec![value]) {
8281 Ok(result) => {
8282 self.call_value(resolve, Value::Undefined, vec![result])?;
8283 }
8284 Err(Signal::Throw(reason)) => {
8285 self.call_value(reject, Value::Undefined, vec![reason])?;
8286 }
8287 Err(signal) => return Err(signal),
8288 }
8289 }
8290 None => {
8291 let handler = if fulfilled { resolve } else { reject };
8292 self.call_value(handler, Value::Undefined, vec![value])?;
8293 }
8294 }
8295 Ok(Value::Undefined)
8296 }
8297 Some(NativeCall::CapabilityExecutor { state }) => {
8298 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8299 // slot holds a value yet. The test is on the *values*, not on a call count —
8300 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8301 // called-twice`'s first case does exactly that), while a second call after a
8302 // real pair is the `TypeError`.
8303 let defined = |name: &str| {
8304 state
8305 .own_property(name)
8306 .and_then(|property| property.value)
8307 .is_some_and(|value| !matches!(value, Value::Undefined))
8308 };
8309 if defined("resolve") || defined("reject") {
8310 return Err(self.type_error("promise capability executor called twice"));
8311 }
8312 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8313 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8314 state.define_data("resolve", resolve);
8315 state.define_data("reject", reject);
8316 Ok(Value::Undefined)
8317 }
8318 Some(NativeCall::CombinatorSettle {
8319 state,
8320 index,
8321 fulfilled,
8322 }) => {
8323 let value = args.first().cloned().unwrap_or(Value::Undefined);
8324 self.settle_combinator(&state, index, fulfilled, value)?;
8325 Ok(Value::Undefined)
8326 }
8327 Some(NativeCall::AwaitResume {
8328 coroutine,
8329 promise,
8330 kind,
8331 }) => {
8332 // Resume *inline*, in the reaction that delivered the value. Deferring it
8333 // by another job inserts a tick between every `await` and its
8334 // continuation, which reorders `await` against unrelated `then` chains —
8335 // `f().then(g)` then runs before `f`'s own next statement.
8336 self.drive_async(
8337 &coroutine,
8338 &promise,
8339 kind,
8340 args.first().cloned().unwrap_or(Value::Undefined),
8341 )
8342 .map(|()| Value::Undefined)
8343 }
8344 Some(NativeCall::ReturnValue(value)) => Ok(value),
8345 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8346 Some(NativeCall::FinallyShim {
8347 callback,
8348 fulfilled,
8349 constructor,
8350 }) => {
8351 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8352 // own value is discarded; what the caller sees is the *original* outcome,
8353 // delayed until `PromiseResolve(C, result)` has settled.
8354 //
8355 // Two details are observable and both have a test:
8356 //
8357 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8358 // `PerformPromiseThen`. A callback that returns a thenable with its own
8359 // `then` must have that `then` called
8360 // (`resolved-observable-then-calls` counts it);
8361 // * only the **fulfil** handler is supplied. A returned promise that
8362 // *rejects* rejects the whole `finally`, rather than having its failure
8363 // swallowed and the original value passed through.
8364 let original = args.first().cloned().unwrap_or(Value::Undefined);
8365 let result = match &callback {
8366 Some(callback) => {
8367 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8368 }
8369 None => Value::Undefined,
8370 };
8371 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8372 // constructor is reused rather than rewrapped, which is what keeps
8373 // `mp1.finally(() => mp2)` from gaining a layer.
8374 let resolved = self.promise_resolve_for(&constructor, result)?;
8375 let thunk = if fulfilled {
8376 Callable::ReturnValue(original)
8377 } else {
8378 Callable::ThrowValue(original)
8379 };
8380 // `length: 0` and `name: ""`, and **not** a constructor — the three things
8381 // `resolved-observable-then-calls-argument` reads off the thunk while it has
8382 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8383 // function with no `length` at all.
8384 let thunk = self.builtin_function("", 0, thunk);
8385 let then = self.read_field(&resolved, "then")?;
8386 if !matches!(&then, Value::Object(object) if object.is_callable()) {
8387 return Err(self.type_error("then is not a function"));
8388 }
8389 self.call_value(then, resolved, vec![Value::Object(thunk)])
8390 }
8391 Some(NativeCall::DisposeStep {
8392 remaining,
8393 promise,
8394 error,
8395 rejected,
8396 awaited,
8397 needs_await,
8398 }) => {
8399 let error = if rejected {
8400 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8401 self.merge_dispose_error(reason, error)
8402 } else {
8403 error
8404 };
8405 self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8406 Ok(Value::Undefined)
8407 }
8408 Some(NativeCall::ModuleBinding(cell)) => {
8409 // §10.4.6.8 `[[Get]]` step 4: a binding that has not been initialised yet
8410 // throws rather than reading `undefined`. A namespace can be observed
8411 // before its module has finished evaluating — a cycle, or
8412 // `Object.freeze(ns)` in the importer — and every read of the still-dead
8413 // `let` must be a `ReferenceError`
8414 // (`module-code/namespace/internals/get-str-found-uninit` and seven
8415 // siblings).
8416 let value = cell.get();
8417 if matches!(value, Value::Uninitialized) {
8418 return Err(Signal::Throw(
8419 self.make_error("ReferenceError", "module binding is not initialized"),
8420 ));
8421 }
8422 Ok(value)
8423 }
8424 Some(NativeCall::CompletedReturn {
8425 generator,
8426 promise,
8427 rejected,
8428 }) => {
8429 let value = args.first().cloned().unwrap_or(Value::Undefined);
8430 let outcome = if rejected {
8431 AsyncOutcome::Error(value)
8432 } else {
8433 AsyncOutcome::Value(self.iterator_result(value, true)?)
8434 };
8435 self.settle_async_request(&generator, &promise, outcome)?;
8436 Ok(Value::Undefined)
8437 }
8438 Some(NativeCall::YieldResult {
8439 generator,
8440 promise,
8441 done,
8442 }) => {
8443 let value = args.first().cloned().unwrap_or(Value::Undefined);
8444 let result = self.iterator_result(value, done)?;
8445 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8446 Ok(Value::Undefined)
8447 }
8448 Some(NativeCall::GeneratorResume {
8449 generator,
8450 promise,
8451 kind,
8452 }) => {
8453 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8454 // tick and reorders the generator against other chains.
8455 self.step_async_generator(
8456 &generator,
8457 &promise,
8458 kind,
8459 args.first().cloned().unwrap_or(Value::Undefined),
8460 )
8461 .map(|()| Value::Undefined)
8462 }
8463 Some(NativeCall::SettlePromise {
8464 promise,
8465 value,
8466 rejected,
8467 }) => {
8468 if rejected {
8469 self.reject_promise(&promise, value);
8470 } else {
8471 self.fulfill_promise(&promise, value);
8472 }
8473 Ok(Value::Undefined)
8474 }
8475 Some(NativeCall::Bound {
8476 target,
8477 this: bound_this,
8478 leading,
8479 }) => {
8480 let mut all = leading;
8481 all.extend(args);
8482 self.call_value(target, bound_this, all)
8483 }
8484 Some(NativeCall::Bytecode(code, env)) => {
8485 if code.code.kind.is_generator() {
8486 return self.new_generator(callee, this, args);
8487 }
8488 if code.code.kind.is_async() {
8489 // Same coroutine machinery as a generator; the difference is only in
8490 // what the completion does — see `new_async_function`.
8491 return self.new_async_function(callee, this, args);
8492 }
8493 self.execute(code, env, this, args, callee)
8494 }
8495 None => Err(Signal::Throw(
8496 self.make_error("TypeError", "not a function"),
8497 )),
8498 }
8499 }
8500
8501 /// Give a freshly built function its own `prototype` object.
8502 ///
8503 /// Every function that can be used with `new` carries one, and its
8504 /// `constructor` points back at the function — a reference cycle, which is
8505 /// exactly what the collector's cycle pass exists to reclaim.
8506 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8507 self.install_function_prototype_with(function, None);
8508 }
8509
8510 /// [`Interp::install_function_prototype`] with an explicit parent for the new
8511 /// `prototype` object.
8512 ///
8513 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8514 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8515 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8516 /// `None` means `%Object.prototype%`.
8517 fn install_function_prototype_with(
8518 &mut self,
8519 function: &Gc<JsObject>,
8520 parent: Option<Gc<JsObject>>,
8521 ) {
8522 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8523 let prototype = self.new_object(Some(parent));
8524 let constructor = Value::Object(function.clone());
8525 prototype.define(
8526 "constructor",
8527 Property::with_attributes(constructor, true, false),
8528 );
8529 let value = Value::Object(prototype);
8530 function.define("prototype", Property::prototype_of(value, true));
8531 }
8532
8533 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8534 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8535 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8536 ///
8537 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8538 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8539 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8540 /// is `[]` there.
8541 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8542 let prototype = self.new_object(Some(parent));
8543 let value = Value::Object(prototype);
8544 function.define("prototype", Property::prototype_of(value, true));
8545 }
8546
8547 /// The `[[Prototype]]` a newly created generator object gets:
8548 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8549 ///
8550 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8551 /// function's `prototype` is writable, so a script can replace it with anything, and
8552 /// only an *object* is consulted.
8553 fn generator_instance_proto(
8554 &mut self,
8555 function: &Gc<JsObject>,
8556 default: Gc<JsObject>,
8557 ) -> JsResult<Gc<JsObject>> {
8558 match self.get_property(function, "prototype")? {
8559 Some(Value::Object(prototype)) => Ok(prototype),
8560 _ => Ok(default),
8561 }
8562 }
8563
8564 /// A getter or setter that reads or writes the reference cell behind a mapped
8565 /// `arguments` index.
8566 ///
8567 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8568 /// count — which is what the collector treats as "a reference from outside the
8569 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8570 /// accessor is reachable, which is the same lifetime the arguments object has.
8571 ///
8572 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8573 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8574 /// parameter value and the arguments object reaches the closure, never the other
8575 /// way round. Nothing the collector has to see is hidden.
8576 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8577 let name = if is_setter { "set" } else { "get" };
8578 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8579 if is_setter {
8580 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8581 Ok(Value::Undefined)
8582 } else {
8583 Ok(cell.get())
8584 }
8585 };
8586 self.new_host_function(name, 1, Box::new(func))
8587 }
8588
8589 /// The object `special_object` builds.
8590 ///
8591 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8592 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8593 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8594 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8595 /// write through `arguments` does not reach the parameter.
8596 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8597 match magic {
8598 0 | 1 => {
8599 let args = self.frame().passed().to_vec();
8600 let proto = self.realm.object_proto.clone();
8601 let object = self.new_object(Some(proto));
8602 // The marker `Object.prototype.toString` needs: an arguments object is an
8603 // ordinary object apart from reporting `[object Arguments]`, and that has
8604 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8605 // show up ahead of them in a key listing anyway — it is non-enumerable.
8606 self.internal_set(&object, "_class", self.string("Arguments"));
8607 // `length` is writable and configurable but neither enumerable nor a
8608 // plain data property: `Object.keys(arguments)` lists the indices only,
8609 // which is how `{...arguments}` copies them without the length.
8610 object.define(
8611 "length",
8612 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8613 );
8614 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8615 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8616 // change `a`, and assigning `a` has to change `arguments[0]`.
8617 //
8618 // The shared storage is the parameter's reference cell. The compiler
8619 // gives every parameter of such a function one (see
8620 // `provide_body_arguments`), and the cell outlives the frame, so this
8621 // keeps working after the arguments object escapes.
8622 //
8623 // The index becomes an accessor rather than a data property. A mapped
8624 // index reports as a plain writable/enumerable data property through
8625 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8626 // the getter/setter pair is only the plumbing underneath.
8627 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8628 let frame = self.frame();
8629 frame
8630 .code
8631 .arg_cell
8632 .iter()
8633 .map(|cell| {
8634 (*cell >= 0)
8635 .then(|| frame.cells.get(*cell as usize).cloned())
8636 .flatten()
8637 })
8638 .collect()
8639 } else {
8640 Vec::new()
8641 };
8642 // Tell the object which indices are mapped, so
8643 // `Object.getOwnPropertyDescriptor` can report them as the data
8644 // properties the spec describes instead of the accessors that
8645 // implement the aliasing.
8646 if magic == 1 {
8647 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8648 for cell in &mapped_cells {
8649 table.push(cell.clone());
8650 }
8651 object.set_mapped_arguments(table);
8652 }
8653 for (index, value) in args.into_iter().enumerate() {
8654 match mapped_cells.get(index).cloned().flatten() {
8655 Some(cell) => {
8656 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8657 let setter = self.new_mapped_arguments_accessor(cell, true);
8658 object.define(
8659 &index.to_string(),
8660 Property::accessor_with(
8661 Some(Value::Object(getter)),
8662 Some(Value::Object(setter)),
8663 true,
8664 ),
8665 );
8666 }
8667 None => object.define_data(&index.to_string(), value),
8668 }
8669 }
8670 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8671 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8672 // non-enumerable and non-configurable. It is not a nicety — it is the only
8673 // documented way to reach `%ThrowTypeError%`:
8674 //
8675 // Object.getOwnPropertyDescriptor(function(){"use strict";
8676 // return arguments;}(), "callee").get
8677 //
8678 // and the whole `ThrowTypeError/` directory is written against that
8679 // expression. Without it 13 cases failed with `cannot read property 'get'
8680 // of undefined`, which reads like a test harness bug rather than a missing
8681 // accessor.
8682 //
8683 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8684 // writable data property holding the function being called, and
8685 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8686 // `hasOwnProperty("callee")` hold there.
8687 if magic == 1 {
8688 let callee = self.frame().callee.clone();
8689 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8690 object.define("callee", Property::with_attributes(callee, true, false));
8691 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8692 && object.own_property("callee").is_none()
8693 {
8694 object.define(
8695 "callee",
8696 Property {
8697 getter: Some(Value::Object(thrower.clone())),
8698 setter: Some(Value::Object(thrower)),
8699 enumerable: false,
8700 configurable: false,
8701 ..Property::default()
8702 },
8703 );
8704 }
8705 // An arguments object is iterable: `[...arguments]` and
8706 // `for (const a of arguments)` both work, through the *array* iterator
8707 // because the object is array-like. Without this the whole spread form
8708 // reported "not iterable".
8709 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8710 let values = self
8711 .realm
8712 .array_proto
8713 .own_property("values")
8714 .and_then(|property| property.value);
8715 if let Some(values) = values {
8716 object.define_key(
8717 &iterator_key,
8718 Property::with_attributes(values, true, false),
8719 );
8720 }
8721 Ok(Value::Object(object))
8722 }
8723 // `this.active_func`: the constructor `super()` resolves against.
8724 //
8725 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8726 // own, so it inherits this from the function it was written in along with `this`
8727 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8728 // the constructor and is called back later (`iter.return = () => super()`) has
8729 // the constructor nowhere on the stack. The compiler therefore reads it out of
8730 // a closure variable of the enclosing function, exactly as the reference does
8731 // with its `this_active_func` local.
8732 2 => Ok(self
8733 .current_callee()
8734 .map_or(Value::Undefined, Value::Object)),
8735 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8736 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8737 // its own either, so the lookup walks out to the nearest non-arrow frame for
8738 // the same reason as `this.active_func` above — without that, `super()` inside
8739 // an arrow passed `undefined` as the new target and the parent constructor was
8740 // then rejected for being invoked without `new`.
8741 3 => Ok(self
8742 .eval_new_target
8743 .clone()
8744 .unwrap_or_else(|| self.frame().new_target.clone())),
8745 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8746 // An arrow has none of its own, so the lookup walks out to the enclosing
8747 // method — which is why `super` works inside an arrow inside a method.
8748 4 => Ok(self
8749 .frames
8750 .iter()
8751 .rev()
8752 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8753 .map_or(Value::Undefined, Value::Object)),
8754 // `import.meta`: the innermost module body's meta object. Outside a module
8755 // the compiler never emits this, so an empty fallback is unreachable rather
8756 // than permissive.
8757 6 => {
8758 let name = self.module_stack.last().cloned();
8759 let meta = name
8760 .and_then(|name| self.modules.get(&name).cloned())
8761 .and_then(|module| module.with(|r| r.import_meta.clone()));
8762 Ok(meta.map_or(Value::Undefined, Value::Object))
8763 }
8764 other => Err(Signal::Throw(self.make_error(
8765 "InternalError",
8766 &format!("special_object {other} is not implemented yet"),
8767 ))),
8768 }
8769 }
8770
8771 /// `[[HomeObject]]` of the innermost function that has one, if any.
8772 ///
8773 /// An arrow has none, so the search walks out to the enclosing method — the same
8774 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8775 /// inside a method.
8776 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8777 self.frames
8778 .iter()
8779 .rev()
8780 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8781 }
8782
8783 /// The dispose method a `using` declaration should snapshot, or an error.
8784 ///
8785 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8786 /// is what makes a resource that only knows the synchronous protocol usable in both
8787 /// forms.
8788 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8789 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8790 if value.is_nullish() {
8791 return Ok(Value::Undefined);
8792 }
8793 let Some(object) = value.as_object() else {
8794 return Err(self.type_error("not an object"));
8795 };
8796 let mut method = if await_form {
8797 let found = self.get_property_key(
8798 object,
8799 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8800 )?;
8801 match found {
8802 Some(found) if !found.is_nullish() => Some(found),
8803 _ => self
8804 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8805 }
8806 } else {
8807 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8808 };
8809 let Some(found) = method.take() else {
8810 return Err(self.type_error("value is not disposable"));
8811 };
8812 if found.is_nullish() {
8813 return Err(self.type_error("value is not disposable"));
8814 }
8815 let callable = found.as_object().is_some_and(|object| object.is_callable());
8816 if !callable {
8817 return Err(self.type_error("dispose method is not a function"));
8818 }
8819 Ok(found)
8820 }
8821
8822 /// Call one resource's disposer, folding a failure into `error_state`.
8823 ///
8824 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8825 /// because a captured `using` binding lives in its reference cell and the local slot is
8826 /// stale — a closure over the resource is legal and must not change what is disposed.
8827 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8828 let value = self.get_loc(slot);
8829 let method = self.get_loc(slot + 1);
8830 // A resource that was never initialised — its declaration threw — or that is
8831 // `null`/`undefined` has nothing to dispose.
8832 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8833 return Ok(error_state);
8834 }
8835 if matches!(method, Value::Undefined | Value::Uninitialized) {
8836 return Ok(error_state);
8837 }
8838 match self.call_value(method, value, Vec::new()) {
8839 Ok(_) => Ok(error_state),
8840 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8841 Err(other) => Err(other),
8842 }
8843 }
8844
8845 /// Combine a disposal failure with whatever was already going wrong.
8846 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8847 if matches!(error_state, Value::Uninitialized) {
8848 return new_error;
8849 }
8850 self.new_suppressed_error(new_error, error_state)
8851 }
8852
8853 /// A `SuppressedError` instance built straight from its prototype.
8854 ///
8855 /// Not through the constructor: a script that rewrites
8856 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8857 /// error wrapping.
8858 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8859 let proto = self
8860 .realm
8861 .suppressed_error_proto
8862 .clone()
8863 .unwrap_or_else(|| self.realm.error_proto.clone());
8864 let object = self.new_object(Some(proto));
8865 object.define("error", Property::with_attributes(error, true, true));
8866 object.define(
8867 "suppressed",
8868 Property::with_attributes(suppressed, true, true),
8869 );
8870 object.define(
8871 "message",
8872 Property::with_attributes(self.string("SuppressedError"), true, true),
8873 );
8874 self.internal_set(&object, "_class", self.string("Error"));
8875 self.add_stack(&object);
8876 Value::Object(object)
8877 }
8878
8879 /// Call `callee`, or push its frame and let the main loop run it.
8880 ///
8881 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8882 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8883 /// continues, so `function f(){ return f() }` costs heap and stops at
8884 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8885 /// is entered directly, and natives do not re-enter JavaScript in this
8886 /// milestone.
8887 ///
8888 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8889 /// because the returning frame will.
8890 /// The elements of an array-like value, as a call argument list.
8891 ///
8892 /// `apply` accepts any array-like, not only a real array: the reference reads
8893 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8894 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8895 ///
8896 /// Used by the paths that take a *length* from script data — the typed-array
8897 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8898 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8899 /// `RangeError` rather than a silently clamped count.
8900 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8901 let number = self.to_js_number(value)?;
8902 if number.is_nan() {
8903 return Ok(0);
8904 }
8905 let number = number.trunc();
8906 if number < 0.0 || number > 9_007_199_254_740_991.0 {
8907 return Err(self.range_error("invalid length"));
8908 }
8909 Ok(number as usize)
8910 }
8911
8912 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8913 /// other callers that take an argument list from script data.
8914 ///
8915 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8916 /// constructor and `Array.from` need `ToIndex` instead (see
8917 /// [`Interp::to_index`]), which is why they do not go through here.
8918 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8919 let Some(object) = value.as_object().cloned() else {
8920 if value.is_nullish() {
8921 // `f.apply(this, null)` passes no arguments at all.
8922 return Ok(Vec::new());
8923 }
8924 return Err(self.type_error("createListFromArrayLike called on non-object"));
8925 };
8926 let length = match self.get_property(&object, "length")? {
8927 Some(length) => length.to_number(),
8928 None => 0.0,
8929 };
8930 if !length.is_finite() || length <= 0.0 {
8931 return Ok(Vec::new());
8932 }
8933 let length = (length as usize).min(1_000_000);
8934 let mut args = Vec::with_capacity(length);
8935 for index in 0..length {
8936 let element = self.get_property(&object, &index.to_string())?;
8937 args.push(element.unwrap_or(Value::Undefined));
8938 }
8939 Ok(args)
8940 }
8941
8942 /// Turn a call to a generator function into a generator object.
8943 ///
8944 /// The frame is built exactly as an ordinary call would build it, then detached and
8945 /// stored in the generator before any body instruction runs — which is what makes
8946 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8947 /// is `initial_yield`, the first instruction of every suspending body.
8948 pub fn new_generator(
8949 &mut self,
8950 function: Value,
8951 this: Value,
8952 args: Vec<Value>,
8953 ) -> JsResult<Value> {
8954 let Some(object) = function.as_object().cloned() else {
8955 return Err(self.type_error("not a generator function"));
8956 };
8957 let Some((code, env)) = bytecode_of(&object) else {
8958 return Err(self.type_error("not a generator function"));
8959 };
8960 let is_async = code.code.kind.is_async();
8961 self.push_frame(code, env, this, args, function)?;
8962 let frame = self.frames.pop().expect("push_frame just pushed it");
8963 // A fresh generator is *suspended at start*: the body has not run, so a
8964 // `return`/`throw` on it finishes without executing anything.
8965 let mut state = GeneratorState {
8966 frame: Some(frame),
8967 phase: GeneratorPhase::SuspendedStart,
8968 parked_on_await: false,
8969 parked_on_yield_star: false,
8970 requests: std::collections::VecDeque::new(),
8971 async_busy: false,
8972 is_async,
8973 };
8974 // Run to the first suspension. For a generator that is `initial_yield`, so no
8975 // body code runs; for a malformed body it would be the first `yield`.
8976 // An `async function*` answers an async generator: same coroutine, but its
8977 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8978 let default_proto = if is_async {
8979 self.realm
8980 .async_generator_proto
8981 .clone()
8982 .unwrap_or_else(|| self.realm.generator_proto.clone())
8983 } else {
8984 self.realm.generator_proto.clone()
8985 };
8986 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8987 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8988 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8989 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8990 let proto = self.generator_instance_proto(&object, default_proto)?;
8991 let generator = self.new_object(Some(proto));
8992 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8993 Ok(_) => {}
8994 Err(error) => return Err(error),
8995 }
8996 generator.with_mut(|data| {
8997 data.kind = ObjectKind::Generator(Box::new(state));
8998 });
8999 Ok(Value::Object(generator))
9000 }
9001
9002 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9003 ///
9004 /// Returns the `{value, done}` object itself rather than the pair, because a
9005 /// `yield*` suspension already has one — the inner iterator's own result — and the
9006 /// protocol says to hand that straight through rather than nest it.
9007 /// Advance a generator and report *why* it parked.
9008 ///
9009 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
9010 /// "hand this value to the caller" — but an async generator does: an `await` has to
9011 /// settle before it can answer, while a `yield` is the answer.
9012 fn resume_generator_detailed(
9013 &mut self,
9014 generator: &Gc<JsObject>,
9015 kind: ResumeKind,
9016 value: Value,
9017 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9018 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
9019 ObjectKind::Generator(state) => {
9020 let is_async = state.is_async;
9021 Some(std::mem::replace(
9022 state.as_mut(),
9023 GeneratorState {
9024 frame: None,
9025 phase: GeneratorPhase::Executing,
9026 parked_on_await: false,
9027 parked_on_yield_star: false,
9028 requests: std::collections::VecDeque::new(),
9029 // **Busy while the body runs**, so a `next()` called *from inside*
9030 // the body queues instead of being served. §27.6.3.7
9031 // `AsyncGeneratorResumeNext` returns immediately for the state
9032 // "executing", and the request is served once the body suspends;
9033 // with `false` here the re-entrant call found an empty frame and
9034 // rejected (`request-queue-order-state-executing`).
9035 async_busy: is_async,
9036 is_async,
9037 },
9038 ))
9039 }
9040 _ => None,
9041 }) else {
9042 return Err(self.type_error("not a generator"));
9043 };
9044 let result = self.step_generator(&mut state, kind, value);
9045 // Requests queued *while* the body ran live on the placeholder, because the real
9046 // state is out of the object for the duration. They have to be folded back in
9047 // before the placeholder is overwritten, or the promise they carry never settles.
9048 let queued = generator.with_mut(|data| match &mut data.kind {
9049 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
9050 _ => std::collections::VecDeque::new(),
9051 });
9052 state.requests.extend(queued);
9053 generator.with_mut(|data| {
9054 data.kind = ObjectKind::Generator(Box::new(state));
9055 });
9056 result
9057 }
9058
9059 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9060 ///
9061 /// Returns the `{value, done}` object itself rather than the pair, because a
9062 /// `yield*` suspension already has one — the inner iterator's own result — and the
9063 /// protocol says to hand that straight through rather than nest it.
9064 pub fn resume_generator(
9065 &mut self,
9066 generator: &Gc<JsObject>,
9067 kind: ResumeKind,
9068 value: Value,
9069 ) -> JsResult<Value> {
9070 let (value, done, ready, _reason) =
9071 self.resume_generator_detailed(generator, kind, value)?;
9072 if ready {
9073 return Ok(value);
9074 }
9075 self.iterator_result(value, done)
9076 }
9077
9078 /// `next`/`return`/`throw` on an async generator, which answer a promise.
9079 ///
9080 /// The body is the same coroutine a sync generator runs; what changes is that an
9081 /// `await` inside it has to settle before the method can answer, so the step is
9082 /// driven off the job queue rather than returning inline.
9083 pub fn resume_async_generator(
9084 &mut self,
9085 generator: &Gc<JsObject>,
9086 kind: ResumeKind,
9087 value: Value,
9088 ) -> JsResult<Value> {
9089 let promise = self.new_promise();
9090 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9091 // that order, and the second value must reach the *second* `yield`.
9092 let idle = generator.with_mut(|data| match &mut data.kind {
9093 ObjectKind::Generator(state) => {
9094 state.requests.push_back(AsyncRequest {
9095 kind,
9096 value,
9097 promise: promise.clone(),
9098 });
9099 !state.async_busy
9100 }
9101 _ => false,
9102 });
9103 if idle {
9104 self.next_async_request(generator)?;
9105 }
9106 Ok(Value::Object(promise))
9107 }
9108
9109 /// Serve the front queued request, if the generator is free to run one.
9110 ///
9111 /// A finished generator answers from the queue without running anything:
9112 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9113 /// first, and `throw(e)` rejects.
9114 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9115 enum Front {
9116 Idle,
9117 Run(ResumeKind, Value, Gc<JsObject>),
9118 Finished(ResumeKind, Value, Gc<JsObject>),
9119 }
9120 let front = generator.with_mut(|data| match &mut data.kind {
9121 ObjectKind::Generator(state) => {
9122 let Some(request) = state.requests.front() else {
9123 return Front::Idle;
9124 };
9125 // Busy means a request is still in flight — awaiting inside the body, not
9126 // finished. Serving another now would interleave two requests.
9127 if state.async_busy && state.phase != GeneratorPhase::Completed {
9128 return Front::Idle;
9129 }
9130 let kind = request.kind;
9131 let value = request.value.clone();
9132 let promise = request.promise.clone();
9133 state.async_busy = true;
9134 if state.phase == GeneratorPhase::Completed {
9135 Front::Finished(kind, value, promise)
9136 } else {
9137 Front::Run(kind, value, promise)
9138 }
9139 }
9140 _ => Front::Idle,
9141 });
9142 match front {
9143 Front::Idle => Ok(()),
9144 Front::Run(kind, value, promise) => {
9145 self.step_async_generator(generator, &promise, kind, value)
9146 }
9147 Front::Finished(kind, value, promise) => match kind {
9148 ResumeKind::Throw => {
9149 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9150 }
9151 ResumeKind::Next | ResumeKind::Start => {
9152 let result = self.iterator_result(Value::Undefined, true)?;
9153 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9154 }
9155 ResumeKind::Return => {
9156 // `js_async_generator_completed_return`: the value is awaited before it
9157 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9158 // finished generator answers `1`, not a promise.
9159 let resolved = match self.promise_resolve_intrinsic(value) {
9160 Ok(resolved) => resolved,
9161 Err(Signal::Throw(reason)) => {
9162 return self.settle_async_request(
9163 generator,
9164 &promise,
9165 AsyncOutcome::Error(reason),
9166 );
9167 }
9168 Err(other) => return Err(other),
9169 };
9170 let done = JsObject::function(
9171 self.heap,
9172 Some(self.realm.function_proto.clone()),
9173 Callable::CompletedReturn {
9174 generator: generator.clone(),
9175 promise: promise.clone(),
9176 rejected: false,
9177 },
9178 );
9179 let failed = JsObject::function(
9180 self.heap,
9181 Some(self.realm.function_proto.clone()),
9182 Callable::CompletedReturn {
9183 generator: generator.clone(),
9184 promise: promise.clone(),
9185 rejected: true,
9186 },
9187 );
9188 let Value::Object(resolved) = resolved else {
9189 return self.settle_async_request(
9190 generator,
9191 &promise,
9192 AsyncOutcome::Error(Value::Undefined),
9193 );
9194 };
9195 self.perform_then(
9196 &resolved,
9197 Some(Value::Object(done)),
9198 Some(Value::Object(failed)),
9199 )?;
9200 Ok(())
9201 }
9202 },
9203 }
9204 }
9205
9206 /// Settle the front request and start the next one.
9207 ///
9208 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9209 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9210 /// generator would strand every later request.
9211 fn settle_async_request(
9212 &mut self,
9213 generator: &Gc<JsObject>,
9214 promise: &Gc<JsObject>,
9215 outcome: AsyncOutcome,
9216 ) -> JsResult<()> {
9217 let settled = generator.with_mut(|data| match &mut data.kind {
9218 ObjectKind::Generator(state) => {
9219 let front = state.requests.front();
9220 debug_assert!(
9221 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9222 "a request settled outside its turn"
9223 );
9224 state.requests.pop_front();
9225 state.async_busy = false;
9226 true
9227 }
9228 _ => false,
9229 });
9230 if settled {
9231 match outcome {
9232 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9233 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9234 }
9235 }
9236 self.next_async_request(generator)
9237 }
9238
9239 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9240 ///
9241 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9242 /// disposer runs **synchronously** — the reference starts it before returning, which
9243 /// a test can observe by logging after the call — and the rest follow once their
9244 /// predecessor settles.
9245 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9246 let promise = self.new_promise();
9247 // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9248 // any resource at all, because every `await using` resource has the async-dispose
9249 // hint — including the null/undefined ones that have nothing to call. If none of them
9250 // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9251 // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9252 // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9253 let needs_await = !resources.is_empty();
9254 let mut pairs = Vec::with_capacity(resources.len());
9255 for (value, method) in resources {
9256 let pair = self.new_array(vec![value, method]);
9257 pairs.push(Value::Object(pair));
9258 }
9259 let remaining = self.new_array(pairs);
9260 self.dispose_step(
9261 &remaining,
9262 &promise,
9263 Value::Uninitialized,
9264 false,
9265 needs_await,
9266 )?;
9267 Ok(Value::Object(promise))
9268 }
9269
9270 /// One link of the `disposeAsync` chain.
9271 ///
9272 /// Loops while the disposers finish synchronously, and parks on the first thenable it
9273 /// meets — pushing itself back in as the continuation, with the accumulated error
9274 /// carried along so a later failure can still be folded into the `SuppressedError`.
9275 fn dispose_step(
9276 &mut self,
9277 remaining: &Gc<JsObject>,
9278 promise: &Gc<JsObject>,
9279 mut error: Value,
9280 awaited: bool,
9281 needs_await: bool,
9282 ) -> JsResult<()> {
9283 loop {
9284 let length = remaining.array_length().unwrap_or(0);
9285 if length == 0 {
9286 // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9287 // still has to happen. Re-entering this same step past an already-fulfilled
9288 // promise is exactly one tick, and it keeps the folding of `error` in one place.
9289 if needs_await && !awaited {
9290 let finished = self.new_array(Vec::new());
9291 let thunk = JsObject::function(
9292 self.heap,
9293 Some(self.realm.function_proto.clone()),
9294 Callable::DisposeStep {
9295 remaining: finished.clone(),
9296 promise: promise.clone(),
9297 error,
9298 rejected: false,
9299 awaited: true,
9300 needs_await: false,
9301 },
9302 );
9303 let tick = self.promise_resolve_value(Value::Undefined)?;
9304 if let Value::Object(tick) = tick {
9305 self.perform_then(
9306 &tick,
9307 Some(Value::Object(thunk.clone())),
9308 Some(Value::Object(thunk)),
9309 )?;
9310 }
9311 return Ok(());
9312 }
9313 if matches!(error, Value::Uninitialized) {
9314 self.fulfill_promise(promise, Value::Undefined);
9315 } else {
9316 self.reject_promise(promise, error);
9317 }
9318 return Ok(());
9319 }
9320 let Some(Value::Object(pair)) = remaining
9321 .array_get(length - 1)
9322 .filter(|v| !matches!(v, Value::Hole))
9323 else {
9324 remaining.array_truncate(self.heap, length - 1);
9325 continue;
9326 };
9327 remaining.array_truncate(self.heap, length - 1);
9328 let value = pair.array_get(0).unwrap_or(Value::Undefined);
9329 let Some(Value::Object(method)) = pair.array_get(1) else {
9330 continue;
9331 };
9332 if !method.is_callable() {
9333 continue;
9334 }
9335 match self.call_value(Value::Object(method), value, Vec::new()) {
9336 Ok(result) => {
9337 if !self.is_thenable(&result)? {
9338 // Finished synchronously; the next disposer is the next iteration.
9339 continue;
9340 }
9341 let awaited = match self.promise_resolve_value(result) {
9342 Ok(awaited) => awaited,
9343 Err(Signal::Throw(reason)) => {
9344 self.reject_promise(promise, reason);
9345 return Ok(());
9346 }
9347 Err(other) => return Err(other),
9348 };
9349 let Value::Object(awaited) = awaited else {
9350 continue;
9351 };
9352 let ok = JsObject::function(
9353 self.heap,
9354 Some(self.realm.function_proto.clone()),
9355 Callable::DisposeStep {
9356 remaining: remaining.clone(),
9357 promise: promise.clone(),
9358 error: error.clone(),
9359 rejected: false,
9360 awaited: true,
9361 needs_await,
9362 },
9363 );
9364 let failed = JsObject::function(
9365 self.heap,
9366 Some(self.realm.function_proto.clone()),
9367 Callable::DisposeStep {
9368 remaining: remaining.clone(),
9369 promise: promise.clone(),
9370 error,
9371 rejected: true,
9372 awaited: true,
9373 needs_await,
9374 },
9375 );
9376 self.perform_then(
9377 &awaited,
9378 Some(Value::Object(ok)),
9379 Some(Value::Object(failed)),
9380 )?;
9381 return Ok(());
9382 }
9383 Err(Signal::Throw(thrown)) => {
9384 error = self.merge_dispose_error(thrown, error);
9385 }
9386 Err(other) => return Err(other),
9387 }
9388 }
9389 }
9390
9391 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9392 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9393 let Value::Object(object) = value else {
9394 return Ok(false);
9395 };
9396 Ok(matches!(
9397 self.get_property(object, "then")?,
9398 Some(Value::Object(then)) if then.is_callable()
9399 ))
9400 }
9401
9402 /// One step of an async generator, settling `promise` with an `{value, done}` result.
9403 fn step_async_generator(
9404 &mut self,
9405 generator: &Gc<JsObject>,
9406 promise: &Gc<JsObject>,
9407 kind: ResumeKind,
9408 value: Value,
9409 ) -> JsResult<()> {
9410 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9411 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9412 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9413 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9414 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9415 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9416 // out of the same read, one as a rejection and one as a rethrow.
9417 //
9418 // Narrow on purpose: only a value that is *already a promise* is inspected, so
9419 // nothing changes for `return 1` and the extra read is a plain data-property
9420 // lookup on the intrinsic case.
9421 if kind == ResumeKind::Return
9422 && let Value::Object(object) = &value
9423 && self.promise_state(object).is_some()
9424 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9425 {
9426 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9427 }
9428 let stepped = self.resume_generator_detailed(generator, kind, value);
9429 let (value, done, ready, reason) = match stepped {
9430 Ok(stepped) => stepped,
9431 Err(Signal::Throw(reason)) => {
9432 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9433 }
9434 Err(other) => return Err(other),
9435 };
9436 // Only an `await` has to wait before the method can answer.
9437 if !done && reason == Some(SuspendKind::Await) {
9438 let awaited = match self.promise_resolve_value(value) {
9439 Ok(awaited) => awaited,
9440 Err(Signal::Throw(reason)) => {
9441 return self.settle_async_request(
9442 generator,
9443 promise,
9444 AsyncOutcome::Error(reason),
9445 );
9446 }
9447 Err(other) => return Err(other),
9448 };
9449 let Value::Object(awaited) = awaited else {
9450 return Ok(());
9451 };
9452 let resumed = JsObject::function(
9453 self.heap,
9454 Some(self.realm.function_proto.clone()),
9455 Callable::GeneratorResume {
9456 generator: generator.clone(),
9457 promise: promise.clone(),
9458 kind: ResumeKind::Next,
9459 },
9460 );
9461 let raised = JsObject::function(
9462 self.heap,
9463 Some(self.realm.function_proto.clone()),
9464 Callable::GeneratorResume {
9465 generator: generator.clone(),
9466 promise: promise.clone(),
9467 kind: ResumeKind::Throw,
9468 },
9469 );
9470 self.perform_then(
9471 &awaited,
9472 Some(Value::Object(resumed)),
9473 Some(Value::Object(raised)),
9474 )?;
9475 return Ok(());
9476 }
9477 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9478 // completes it — both arrive as the settled value rather than as the promise
9479 // object. A plain value skips the round trip, which is also what keeps `yield 1`
9480 // from costing an extra tick.
9481 let awaits_value = self.is_thenable(&value)?;
9482 if awaits_value {
9483 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9484 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9485 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9486 // no `PromiseResolve` appears, so that path keeps the shortcut.
9487 let awaited = match if done {
9488 self.promise_resolve_intrinsic(value)
9489 } else {
9490 self.promise_resolve_value(value)
9491 } {
9492 Ok(awaited) => awaited,
9493 Err(Signal::Throw(reason)) => {
9494 return self.settle_async_request(
9495 generator,
9496 promise,
9497 AsyncOutcome::Error(reason),
9498 );
9499 }
9500 Err(other) => return Err(other),
9501 };
9502 let Value::Object(awaited) = awaited else {
9503 return Ok(());
9504 };
9505 // A rejected yield throws *at the yield* inside the body, so the rejection
9506 // resumes the generator rather than the method's promise.
9507 let answer = JsObject::function(
9508 self.heap,
9509 Some(self.realm.function_proto.clone()),
9510 Callable::YieldResult {
9511 generator: generator.clone(),
9512 promise: promise.clone(),
9513 done,
9514 },
9515 );
9516 let raise = JsObject::function(
9517 self.heap,
9518 Some(self.realm.function_proto.clone()),
9519 Callable::GeneratorResume {
9520 generator: generator.clone(),
9521 promise: promise.clone(),
9522 kind: ResumeKind::Throw,
9523 },
9524 );
9525 self.perform_then(
9526 &awaited,
9527 Some(Value::Object(answer)),
9528 Some(Value::Object(raise)),
9529 )?;
9530 return Ok(());
9531 }
9532 let result = if ready {
9533 // `yield*` handed back the inner iterator's own result object.
9534 value
9535 } else {
9536 self.iterator_result(value, done)?
9537 };
9538 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9539 }
9540
9541 /// The `{value, done}` object an iterator method answers with.
9542 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9543 let result = self.new_object(Some(self.realm.object_proto.clone()));
9544 result.define_data("value", value);
9545 result.define_data("done", Value::Bool(done));
9546 Ok(Value::Object(result))
9547 }
9548
9549 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9550 fn step_generator(
9551 &mut self,
9552 state: &mut GeneratorState,
9553 kind: ResumeKind,
9554 value: Value,
9555 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9556 match state.phase {
9557 GeneratorPhase::Executing => {
9558 return Err(self.type_error("cannot invoke a running generator"));
9559 }
9560 GeneratorPhase::Completed => {
9561 // A finished generator answers every resumption without running.
9562 return Ok(match kind {
9563 ResumeKind::Throw => return Err(Signal::Throw(value)),
9564 ResumeKind::Return => (value, true, false, None),
9565 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9566 });
9567 }
9568 GeneratorPhase::SuspendedStart => {
9569 if kind != ResumeKind::Next && kind != ResumeKind::Start {
9570 // The body never started, so there is nothing to unwind or return
9571 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9572 state.frame = None;
9573 state.phase = GeneratorPhase::Completed;
9574 return Ok(match kind {
9575 ResumeKind::Throw => return Err(Signal::Throw(value)),
9576 _ => (value, true, false, None),
9577 });
9578 }
9579 }
9580 GeneratorPhase::SuspendedYield => {}
9581 }
9582
9583 let Some(mut frame) = state.frame.take() else {
9584 return Ok((Value::Undefined, true, false, None));
9585 };
9586 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9587 // number that says which method resumed it; the emitted `if_false` branches on
9588 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9589 let mut raised = None;
9590 match kind {
9591 ResumeKind::Next | ResumeKind::Start => {
9592 if state.phase == GeneratorPhase::SuspendedYield {
9593 frame.stack.push(value);
9594 // An `await` resumes with its value alone; only a `yield` gets the
9595 // magic number that says which of `next`/`return` resumed it.
9596 if !state.parked_on_await {
9597 frame.stack.push(Value::Int(RESUME_NEXT));
9598 }
9599 }
9600 }
9601 ResumeKind::Return => {
9602 // A `return` on a not-yet-started generator is handled above, so this is
9603 // always a real resumption.
9604 frame.stack.push(value);
9605 frame.stack.push(Value::Int(RESUME_RETURN));
9606 }
9607 ResumeKind::Throw => {
9608 // At a `yield*` the exception is *data* for the delegation: the compiled
9609 // code resumes with the value and magic `2` and calls the inner iterator's
9610 // `throw`. Everywhere else it is raised at the suspension point, so the
9611 // body's own handler sees it.
9612 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9613 frame.stack.push(value);
9614 frame.stack.push(Value::Int(RESUME_THROW));
9615 } else {
9616 raised = Some(value);
9617 }
9618 }
9619 }
9620 state.phase = GeneratorPhase::Executing;
9621
9622 let depth = self.frames.len();
9623 self.frames.push(frame);
9624 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9625 // happened at the `yield`.
9626 if let Some(mut exception) = raised {
9627 if self.catch_here(&mut exception).is_none() {
9628 self.pop_frame();
9629 state.phase = GeneratorPhase::Completed;
9630 return Err(Signal::Throw(exception));
9631 }
9632 }
9633
9634 // Only the generator's *own* frame ends the generator. The body may call ordinary
9635 // functions, and those push frames of their own: a `Step::Return` from one of them
9636 // is a nested call finishing, not the generator completing. Miscounting that is
9637 // silent — the generator reports the callee's value as its own result and marks
9638 // itself done — so the depth comparison is load-bearing, not defensive.
9639 let own_frame = depth + 1;
9640 loop {
9641 match self.step() {
9642 Ok(Step::Continue) => {}
9643 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9644 let mut frame = self.frames.pop().expect("a frame is live");
9645 // `yield` left the value on the stack; `initial_yield` left nothing.
9646 let yielded = if reason == SuspendKind::Initial {
9647 Value::Undefined
9648 } else {
9649 frame.stack.pop().unwrap_or(Value::Undefined)
9650 };
9651 state.frame = Some(frame);
9652 state.parked_on_await = reason == SuspendKind::Await;
9653 state.parked_on_yield_star =
9654 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9655 state.phase = if reason == SuspendKind::Initial {
9656 GeneratorPhase::SuspendedStart
9657 } else {
9658 GeneratorPhase::SuspendedYield
9659 };
9660 // `yield*` hands the inner iterator's own result object straight
9661 // back, so the caller sees one `{value, done}` rather than a nested
9662 // one — which is why the third field says "already a result".
9663 return Ok((
9664 yielded,
9665 false,
9666 reason == SuspendKind::YieldStar,
9667 Some(reason),
9668 ));
9669 }
9670 Ok(Step::Suspend(_)) => {
9671 // A `yield` in a frame other than the generator's would mean a
9672 // generator body entered as an ordinary call, which
9673 // `call_or_push` prevents.
9674 self.unwind_to(depth);
9675 state.phase = GeneratorPhase::Completed;
9676 return Err(Signal::Throw(self.make_error(
9677 "InternalError",
9678 "a generator body ran as an ordinary call",
9679 )));
9680 }
9681 Ok(Step::Return(value)) => {
9682 self.pop_frame();
9683 if self.frames.len() > depth {
9684 // A nested call finished: hand the value back to its caller and
9685 // keep running the generator body.
9686 self.frames
9687 .last_mut()
9688 .expect("a caller is live")
9689 .stack
9690 .push(value);
9691 continue;
9692 }
9693 state.phase = GeneratorPhase::Completed;
9694 // The reference closes the generator's closure variables here; ours
9695 // live in cells the frame owned, which the drop below releases.
9696 return Ok((value, true, false, None));
9697 }
9698 Err(Signal::Throw(exception)) => {
9699 // The frame that threw gets the first chance to catch, exactly as in
9700 // the ordinary call loop; a frame above the generator's is popped and
9701 // the exception carries on down.
9702 let mut exception = exception;
9703 loop {
9704 if self.frames.len() <= depth {
9705 // The generator's own frame is gone, so nothing here caught it.
9706 state.phase = GeneratorPhase::Completed;
9707 return Err(Signal::Throw(exception));
9708 }
9709 if self.catch_here(&mut exception).is_some() {
9710 break;
9711 }
9712 self.pop_frame();
9713 }
9714 }
9715 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9716 }
9717 }
9718 }
9719
9720 /// Pop frames until `depth` are left, keeping their buffers.
9721 fn unwind_to(&mut self, depth: usize) {
9722 while self.frames.len() > depth {
9723 self.pop_frame();
9724 }
9725 }
9726 fn call_or_push(
9727 &mut self,
9728 callee: Value,
9729 this: Value,
9730 args: Vec<Value>,
9731 ) -> JsResult<Option<Value>> {
9732 if let Value::Object(function) = &callee
9733 && let Some((code, env)) = bytecode_of(function)
9734 {
9735 // Calling a generator function does not run anything: it captures the
9736 // arguments in a frame and hands back the generator object.
9737 if code.code.kind.is_generator() {
9738 return self.new_generator(callee, this, args).map(Some);
9739 }
9740 // An async function answers a promise and runs its body as a coroutine, so it
9741 // takes the same path as a plain call into it.
9742 if code.code.kind.is_async() {
9743 return self.new_async_function(callee, this, args).map(Some);
9744 }
9745 self.push_frame(code, env, this, args, callee)?;
9746 return Ok(None);
9747 }
9748 self.call_value(callee, this, args).map(Some)
9749 }
9750
9751 /// `new callee(args)`.
9752 ///
9753 /// A constructor differs from a plain call in three ways: it gets a fresh object
9754 /// as `this` whose prototype is the constructor's `prototype` property, its
9755 /// return value is *replaced* by that object unless it returns an object itself,
9756 /// and a native constructor is expected to initialise the object it is given
9757 /// rather than build one.
9758 pub fn construct(
9759 &mut self,
9760 callee: Value,
9761 new_target: Value,
9762 args: Vec<Value>,
9763 ) -> JsResult<Value> {
9764 // `new` on a bound function constructs its *target*, prepending the arguments
9765 // the bind fixed and ignoring the bound `this` — a bound function is a
9766 // constructor only when its target is one, and `new` always makes a fresh
9767 // object of the target's prototype rather than reusing the bound receiver.
9768 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9769 // ran the body with `this === null` and threw on `this.x = a`.
9770 let mut callee = callee;
9771 let mut new_target = new_target;
9772 let mut args = args;
9773 loop {
9774 let Some(object) = callee.as_object().cloned() else {
9775 return Err(Signal::Throw(
9776 self.make_error("TypeError", "not a constructor"),
9777 ));
9778 };
9779 // A proxy of a function constructs through its `construct` trap, and the
9780 // trap's answer is the result directly — no fresh object is made here.
9781 if object.proxy_state().is_some() {
9782 return match self.proxy_construct(&object, args, &new_target)? {
9783 Some(result) => Ok(result),
9784 None => Err(Signal::Throw(
9785 self.make_error("TypeError", "proxy target is not a constructor"),
9786 )),
9787 };
9788 }
9789 // A generator function has no `[[Construct]]`, and the reference names it in
9790 // the message: `new (function* G(){})()` reports "G is not a constructor".
9791 if object.with(|data| match &data.kind {
9792 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9793 code.code.kind.is_generator()
9794 }
9795 _ => false,
9796 }) {
9797 let name = object
9798 .own_property("name")
9799 .and_then(|property| property.value)
9800 .map(|value| value.to_js_string())
9801 .unwrap_or_default();
9802 return Err(Signal::Throw(
9803 self.make_error("TypeError", &format!("{name} is not a constructor")),
9804 ));
9805 }
9806 let bound = object.with(|data| match &data.kind {
9807 ObjectKind::Function(Callable::Bound {
9808 target,
9809 args: leading,
9810 ..
9811 }) => Some((target.clone(), leading.clone())),
9812 _ => None,
9813 });
9814 let Some((target, leading)) = bound else {
9815 // Not a bound function, so this object is the callee. §7.2.4
9816 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9817 // refusals above cover only the built-ins the reference also refuses by
9818 // name. Everything else — a method, an arrow, an async function — has no
9819 // `[[Construct]]` either, and answering "yes" here made
9820 // `new (Array.prototype.map)` build an object instead of throwing.
9821 if !object.is_constructor() {
9822 let name = object
9823 .own_property("name")
9824 .and_then(|property| property.value)
9825 .map(|value| value.to_js_string())
9826 .unwrap_or_default();
9827 return Err(Signal::Throw(
9828 self.make_error("TypeError", &format!("{name} is not a constructor")),
9829 ));
9830 }
9831 break;
9832 };
9833 let mut all = leading;
9834 all.extend(args);
9835 args = all;
9836 // A bound function that is its own `new.target` stands in for its target:
9837 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9838 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9839 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9840 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9841 _ => false,
9842 };
9843 if same_wrapper {
9844 new_target = target.clone();
9845 }
9846 callee = target;
9847 }
9848 let Value::Object(function) = &callee else {
9849 unreachable!("the loop above only breaks on an object");
9850 };
9851 // The fresh object's prototype comes from `new.target`, not from the callee: a
9852 // derived constructor reaches here through `super()`, and the instance must be a
9853 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9854 // an object inheriting `D.prototype` rather than `C.prototype`.
9855 let prototype_source = match new_target.as_object() {
9856 Some(target) => target.clone(),
9857 None => function.clone(),
9858 };
9859 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9860 // has validated its arguments. Pre-building one here would read
9861 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9862 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9863 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9864 let is_native = function.native_creates_own_instance();
9865 let this = if is_native {
9866 Value::Undefined
9867 } else {
9868 let prototype = self.get_property(&prototype_source, "prototype")?;
9869 let prototype = match prototype {
9870 Some(Value::Object(proto)) => Some(proto),
9871 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9872 // object, the answer is the realm's *intrinsic* prototype for this
9873 // constructor, not `%Object.prototype%`.
9874 _ => {
9875 // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9876 // and that is a `TypeError` for a revoked proxy. Without it, `new
9877 // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9878 // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9879 // trap, so it is already revoked when this fallback runs.
9880 if prototype_source.proxy_state().is_some() {
9881 self.proxy_parts(&prototype_source)?;
9882 }
9883 let fallback = self.get_property(function, "prototype")?;
9884 match fallback {
9885 Some(Value::Object(proto)) => Some(proto),
9886 _ => Some(self.realm.object_proto.clone()),
9887 }
9888 }
9889 };
9890 Value::Object(self.new_object(prototype))
9891 };
9892 // `new.target` inside the body is the constructor that was written, so a bound
9893 // function's target sees itself rather than the bound wrapper.
9894 //
9895 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9896 // `?`, so assigning `None` after the call would be skipped and the failed
9897 // `new.target` would stay visible to every later native call. The symptom was a
9898 // native constructor refusing a plain call — `var s = Symbol(); new
9899 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9900 // "FinalizationRegistry is not a constructor".
9901 let outer_new_target = self.pending_new_target.replace(new_target);
9902 let callee = callee.clone();
9903 let result = self.call_value(callee, this.clone(), args);
9904 self.pending_new_target = outer_new_target;
9905 let result = result?;
9906 // A constructor that returns an object overrides `this`; any other return value
9907 // (including `undefined`) is ignored — **except** in a derived constructor, where
9908 // §15.7.1 step 12 makes a non-object return a `TypeError`
9909 // (`Function/internals/Construct/derived-return-val`).
9910 let derived = function.with(|data| match &data.kind {
9911 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9912 code.code.is_derived_constructor
9913 }
9914 _ => false,
9915 });
9916 Ok(match result {
9917 Value::Object(_) => result,
9918 // A bare `return;` answers `undefined`, which is **legal** even in a derived
9919 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9920 Value::Undefined => this,
9921 _ if derived => {
9922 return Err(Signal::Throw(self.make_error(
9923 "TypeError",
9924 "derived constructor may only return an object or undefined",
9925 )));
9926 }
9927 _ => this,
9928 })
9929 }
9930
9931 /// `new.target` for the call currently being made.
9932 ///
9933 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9934 /// it as `this`), but a *host* constructor that builds its own instance is handed
9935 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9936 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9937 /// it here.
9938 ///
9939 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9940 /// receives for a plain call.
9941 pub fn current_new_target(&self) -> Value {
9942 self.active_new_target.clone()
9943 }
9944
9945 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9946 ///
9947 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9948 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9949 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9950 let constructor = self.realm.errors.get("AggregateError").cloned();
9951 let Some(constructor) = constructor else {
9952 return self.make_error("AggregateError", message);
9953 };
9954 let list = self.new_array(errors);
9955 match self.construct(
9956 Value::Object(constructor.clone()),
9957 Value::Object(constructor),
9958 vec![Value::Object(list), self.string(message)],
9959 ) {
9960 Ok(value) => value,
9961 // A user could have replaced `AggregateError` with something that throws; the
9962 // engine still owes the caller a rejection, so it falls back rather than
9963 // turning `Promise.any`'s rejection into a throw.
9964 Err(_) => self.make_error("AggregateError", message),
9965 }
9966 }
9967
9968 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9969 ///
9970 /// The error classes themselves arrive with the builtins milestone; what
9971 /// matters here is that the thrown value stringifies the way a script printing
9972 /// the caught value expects.
9973 ///
9974 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9975 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9976 /// rely on when they print a caught value.
9977 pub fn make_error(&self, name: &str, message: &str) -> Value {
9978 let proto = self
9979 .realm
9980 .errors
9981 .get(name)
9982 .map(|constructor| self.prototype_of(constructor))
9983 .unwrap_or_else(|| self.realm.error_proto.clone());
9984 let error = self.new_object(Some(proto));
9985 // `name` and `message` are own properties of the instance, which is what
9986 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9987 // `Error`.
9988 error.define(
9989 "name",
9990 Property::with_attributes(self.string(name), true, false),
9991 );
9992 error.define(
9993 "message",
9994 Property::with_attributes(self.string(message), true, false),
9995 );
9996 // The internal class, which is what tells a printer this is an error rather than a
9997 // plain object with `name` and `message` properties. The constructor path sets it
9998 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9999 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
10000 // literally `"Error"` in both places — the *name* is read from `name`, which is why
10001 // a `RangeError` still prints as `RangeError`.
10002 self.internal_set(&error, "_class", self.string("Error"));
10003 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
10004 // answered `false` from `Error.isError` while a constructed one answered `true`,
10005 // because only the constructor set the slot. The reference answers `true` for both
10006 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
10007 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
10008 // tests `typeof stack === "string"` to decide on a trailing newline, so every
10009 // engine-thrown error lost its blank line.
10010 self.internal_set(&error, "_error_data", Value::Bool(true));
10011 // The trace is captured where the error is *made*, which is where the reference
10012 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
10013 // way out, so a caught engine error already has its stack even if the handler
10014 // never rethrows it.
10015 self.add_stack(&error);
10016 Value::Object(error)
10017 }
10018
10019 /// Give an error object its `stack` property, from the current frame stack.
10020 ///
10021 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
10022 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
10023 /// `stack` a script set, is not rewritten.
10024 pub fn add_stack(&self, object: &Gc<JsObject>) {
10025 self.add_stack_skipping(object, 0);
10026 }
10027
10028 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
10029 ///
10030 /// An `Error` constructor passes 1: the reference builds those traces with
10031 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
10032 /// constructor itself, while a `RangeError` raised inside `toISOString` does
10033 /// report `at toISOString (native)`.
10034 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
10035 if object.has_own("stack") {
10036 return;
10037 }
10038 // The trace is *captured* here but not installed as a property: `stack` is an
10039 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
10040 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
10041 // is kept in a hidden slot and the getter materialises it on first read.
10042 //
10043 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
10044 // shows it — this is the same discipline `_error_data` and `_class` follow.
10045 let trace = self.stack_trace_skipping(skip);
10046 let text = self.string(trace);
10047 self.internal_set(object, "_stack_trace", text);
10048 }
10049
10050 /// The function object currently being called, if any.
10051 ///
10052 /// A native function is a bare `fn` pointer, so it cannot capture which class
10053 /// it belongs to; it reads that from the callee instead. This is also what a
10054 /// stack trace would use.
10055 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
10056 // A native has no frame of its own — it is recorded in `current_native` — so asking
10057 // `frames` answered with the *bytecode caller's* callee. `Error`'s constructor reads
10058 // the class off this, and every plain call therefore built an `Error`:
10059 // `EvalError(1)` had the name `"Error"` (`try/S12.14_A19_T1`).
10060 //
10061 // Only while the native is the innermost thing running. It stays recorded while the
10062 // native drives *through* user code — `Iterator.prototype.take` calls the `next` a
10063 // script wrote — and answering with it there gave that user code the native's callee:
10064 // `super()` looked up the native's prototype instead of its own constructor's.
10065 // `native_frames` records `frames.len()` from before the native ran, so an equal
10066 // length means nothing has been pushed since.
10067 if let Some(native) = &self.current_native
10068 && self
10069 .native_frames
10070 .last()
10071 .is_some_and(|(_, depth)| *depth == self.frames.len())
10072 {
10073 return Some(native.clone());
10074 }
10075 match &self.frames.last()?.callee {
10076 Value::Object(object) => Some(object.clone()),
10077 _ => None,
10078 }
10079 }
10080
10081 /// The `prototype` property of a constructor, falling back to
10082 /// `Object.prototype` for anything that is not shaped like one.
10083 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
10084 constructor
10085 .own_property("prototype")
10086 .and_then(|property| property.value)
10087 .and_then(|value| value.as_object().cloned())
10088 .unwrap_or_else(|| self.realm.object_proto.clone())
10089 }
10090
10091 /// Throw a `TypeError` carrying `message`.
10092 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
10093 Signal::Throw(self.make_error("TypeError", message.as_ref()))
10094 }
10095
10096 /// Throw a `RangeError` carrying `message`.
10097 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
10098 Signal::Throw(self.make_error("RangeError", message.as_ref()))
10099 }
10100
10101 /// A `ReferenceError`, as the value to throw.
10102 ///
10103 /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10104 /// and its siblings report a `ReferenceError` there, which is what
10105 /// `adopt|defer|move/throws-if-disposed` assert.
10106 pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10107 Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10108 }
10109
10110 /// The `ReferenceError` a read of an uninitialised binding raises.
10111 /// The name of the binding `slot` refers to, for an error message.
10112 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10113 match kind {
10114 VarSlot::Loc => self
10115 .frame()
10116 .code
10117 .code
10118 .vars
10119 .get(slot)
10120 .map(|v| v.name.clone()),
10121 VarSlot::Closure => self
10122 .frame()
10123 .code
10124 .code
10125 .closure_vars
10126 .get(slot)
10127 .map(|c| c.name.clone()),
10128 }
10129 .unwrap_or_default()
10130 }
10131
10132 /// Whether `slot` names a `const` binding, which rejects every store after its
10133 /// initialiser.
10134 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10135 match kind {
10136 VarSlot::Loc => self
10137 .frame()
10138 .code
10139 .code
10140 .vars
10141 .get(slot)
10142 .is_some_and(|v| v.is_const),
10143 VarSlot::Closure => self
10144 .frame()
10145 .code
10146 .code
10147 .closure_vars
10148 .get(slot)
10149 .is_some_and(|c| c.is_const),
10150 }
10151 }
10152
10153 /// The `TypeError` a store to a `const` binding raises.
10154 ///
10155 /// `const` is enforced here rather than at compile time because the binding can be
10156 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10157 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10158 /// both halves of what "checked store" means: the dead zone is over, and the
10159 /// binding is writable.
10160 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10161 let name = self.binding_name(slot, kind);
10162 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10163 }
10164
10165 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10166 let name = match kind {
10167 VarSlot::Loc => self
10168 .frame()
10169 .code
10170 .code
10171 .vars
10172 .get(slot)
10173 .map(|v| v.name.clone()),
10174 VarSlot::Closure => self
10175 .frame()
10176 .code
10177 .code
10178 .closure_vars
10179 .get(slot)
10180 .map(|c| c.name.clone()),
10181 }
10182 .unwrap_or_default();
10183 // The reference has a wording of its own for `this`, because the dead zone it sits
10184 // in is the derived constructor's rather than a `let`'s: `constructor(){ return; }`
10185 // reports `this is not initialized`.
10186 let message = if name == "this" {
10187 "this is not initialized".to_string()
10188 } else {
10189 format!("cannot access '{name}' before initialization")
10190 };
10191 Signal::Throw(self.make_error("ReferenceError", &message))
10192 }
10193
10194 fn throw_reference(&self, name: &str) -> Signal {
10195 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10196 }
10197
10198 // -- the instruction loop -----------------------------------------------
10199
10200 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10201 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10202 // measured at 16% of a tight arithmetic loop's total time.
10203 #[inline(always)]
10204 fn step(&mut self) -> JsResult<Step> {
10205 // The instruction is already decoded (see [`crate::insn`]), so this is an index
10206 // and a `Copy` read rather than a table lookup plus a width switch. Only the
10207 // borrow lives across the boundary; nothing is cloned.
10208 // **One** borrow of the frame: fetch the record, then advance in the same scope.
10209 // The obvious version borrowed it three times (`last` to read, `last_mut` to
10210 // write, and once more inside the handler), and each is a bounds check plus an
10211 // `Option` unwrap — on the one path every instruction takes.
10212 let Some((insn, next)) = ({
10213 let frame = self
10214 .frames
10215 .last_mut()
10216 .expect("step() is only called with a live frame");
10217 // Past the last instruction is a normal return: the compiler ends a function
10218 // with `return`, and a jump to the end of a block lands here.
10219 let insn = frame.insns().get(frame.pc).copied();
10220 match insn {
10221 None => None,
10222 Some(insn) => {
10223 // A fused record stands for the next few instructions, so the next
10224 // `pc` is its width ahead — the instructions it replaces are never
10225 // dispatched. `at` is the byte offset a stack trace reports; it stays
10226 // an offset because the line table is keyed by bytes.
10227 frame.at = insn.offset as usize;
10228 frame.pc += insn.width();
10229 Some((insn, frame.pc))
10230 }
10231 }
10232 }) else {
10233 return Ok(Step::Return(Value::Undefined));
10234 };
10235 self.check_memory()?;
10236 self.check_interrupt()?;
10237 if insn.fused == crate::insn::Fused::None {
10238 self.execute_instruction(insn.op, insn.a, insn.b, next)
10239 } else {
10240 self.execute_fused(insn)
10241 }
10242 }
10243
10244 /// Run a fused instruction: several bytecode instructions in one dispatch.
10245 ///
10246 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10247 /// it cannot throw and cannot allocate — and anything else falls back to the real
10248 /// instructions, in their real order, so an exception leaves the operand stack
10249 /// exactly as it would have been.
10250 #[inline]
10251 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10252 use crate::insn::Fused;
10253 let slot = insn.a as usize;
10254 match insn.fused {
10255 // `x = k`: `push k; put_loc x`.
10256 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10257 // `x += k`: `get_loc x; push k; add; put_loc x`.
10258 Fused::AddImmLoc => {
10259 let delta = insn.b as i32;
10260 match self.get_loc(slot) {
10261 Value::Int(left) => {
10262 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10263 // that built two `Value`s, called a function, and matched on them
10264 // again to reach this same `checked_add`. It is the innermost
10265 // operation of every accumulator in every program.
10266 let answer = match left.checked_add(delta) {
10267 Some(sum) => Value::Int(sum),
10268 None => Value::Float(left as f64 + delta as f64),
10269 };
10270 self.put_loc(slot, answer);
10271 }
10272 other => {
10273 self.push(other);
10274 self.push(Value::Int(delta));
10275 self.binary_add()?;
10276 let value = self.pop();
10277 self.put_loc(slot, value);
10278 }
10279 }
10280 }
10281 // `x += "literal"` and `x += y`: the two shapes that can append in place.
10282 Fused::AddAtomLoc => {
10283 let text = self.atom_wtf8(insn.b as usize);
10284 let right = self.string_wtf8(text);
10285 self.add_into_loc(slot, right)?;
10286 }
10287 Fused::AddLocLoc => {
10288 let source = (insn.a & 0xFFFF) as usize;
10289 let target = (insn.a >> 16) as usize;
10290 let right = self.get_loc(source);
10291 self.add_into_loc(target, right)?;
10292 }
10293 Fused::AddArgLoc => {
10294 let source = (insn.a & 0xFFFF) as usize;
10295 let target = (insn.a >> 16) as usize;
10296 let right = self.get_arg(source);
10297 self.add_into_loc(target, right)?;
10298 }
10299 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10300 Fused::PostIncLoc => match self.get_loc(slot) {
10301 Value::Int(left) => {
10302 let answer = match left.checked_add(1) {
10303 Some(sum) => Value::Int(sum),
10304 None => Value::Float(left as f64 + 1.0),
10305 };
10306 self.put_loc(slot, answer);
10307 }
10308 other => {
10309 self.push(other);
10310 let raw = self.pop();
10311 let (old, updated) = self.advance_numeric(raw, true)?;
10312 self.push(old);
10313 self.push(updated);
10314 let value = self.pop();
10315 self.put_loc(slot, value);
10316 self.pop();
10317 }
10318 },
10319 // `if (!(x < arg)) goto target`: a loop header.
10320 //
10321 // The comparison is computed rather than replayed on the operand stack. That
10322 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10323 // that throws: the effects happen in the same order, and a handler truncates
10324 // the stack down to its marker, so the intermediate values are unobservable.
10325 Fused::LtLocArgJump => {
10326 let loc = (insn.a >> 16) as usize;
10327 let arg = (insn.a & 0xFFFF) as usize;
10328 let left = self.get_loc(loc);
10329 let right = self.get_arg(arg);
10330 let taken = match (&left, &right) {
10331 (Value::Int(left), Value::Int(right)) => !(left < right),
10332 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10333 };
10334 if taken {
10335 self.frame_mut().pc = insn.b as usize;
10336 }
10337 }
10338 // `i < k` in a loop header, where `k` is an integer literal.
10339 Fused::LtLocImmJump => {
10340 let left = self.get_loc(insn.a as usize);
10341 let right = Value::Int(insn.imm as i32);
10342 let taken = match &left {
10343 Value::Int(left) => !(*left < insn.imm as i32),
10344 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10345 };
10346 if taken {
10347 self.frame_mut().pc = insn.b as usize;
10348 }
10349 }
10350 Fused::None => unreachable!("only called for a fused record"),
10351 }
10352 Ok(Step::Continue)
10353 }
10354
10355 /// Run records that cannot call script, cannot throw and cannot change frames.
10356 ///
10357 /// Returns `Some(value)` when the function ran off the end of its instructions (a
10358 /// normal return), and `None` when it stopped in front of an instruction the slow path
10359 /// has to handle — `pc` is written back either way, so `step` resumes at the right
10360 /// place.
10361 ///
10362 /// **The invariant is the whole point.** Every arm here is restricted to work that
10363 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10364 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10365 /// that the memory limit has to see. An opcode whose operands turn out to need any of
10366 /// that **stops the loop** instead of trying, so the slow path gets the instruction
10367 /// untouched and with its operands still on the stack. That is why the fallback is a
10368 /// `break` and not a duplicated slow arm: a second implementation of the same
10369 /// semantics is how a wrong answer gets in with no test noticing.
10370 ///
10371 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10372 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10373 fn run_fast(&mut self) -> JsResult<Option<Value>> {
10374 use crate::insn::Fused;
10375 // The outer loop exists only so a `Call` can come back through here: once a
10376 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10377 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10378 // frame. Re-entering re-reads both from whichever frame is now on top. Every
10379 // other exit from the inner loop returns, so this costs one loop per call.
10380 'outer: loop {
10381 // One reference-count bump per *slow* instruction (a call, an allocation, a
10382 // property access), never one per instruction — that distinction is worth
10383 // two orders of magnitude and was measured as such.
10384 let (code, mut pc) = {
10385 let frame = self.frame();
10386 (frame.code.clone(), frame.pc)
10387 };
10388 let insns = &code.insns;
10389 loop {
10390 let Some(insn) = insns.get(pc).copied() else {
10391 self.frame_mut().pc = pc;
10392 return Ok(Some(Value::Undefined));
10393 };
10394 match insn.fused {
10395 // `x = k`
10396 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10397 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10398 // object — stops the loop so `binary_add` can decide.
10399 Fused::AddImmLoc => {
10400 let slot = insn.a as usize;
10401 let delta = insn.b as i32;
10402 let Value::Int(left) = self.get_loc(slot) else {
10403 return Ok(self.stop(pc));
10404 };
10405 let sum = match left.checked_add(delta) {
10406 Some(sum) => Value::Int(sum),
10407 None => Value::Float(left as f64 + delta as f64),
10408 };
10409 self.put_loc(slot, sum);
10410 }
10411 // `x += "literal"` / `x += y`: the operand is a string, so the append
10412 // either allocates one or grows one. Both are the slow path's business;
10413 // the fusion's job is only to make the *slot* the sole owner, which is what
10414 // `execute_fused` needs and what `get_loc` alone destroys.
10415 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10416 return Ok(self.stop(pc));
10417 }
10418 // `x++` on an integer, old value dropped.
10419 Fused::PostIncLoc => {
10420 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10421 // value is read in place and overwritten in place, so the reference
10422 // count it held is released by the same assignment that stores the
10423 // new one. `get_loc` plus `put_loc` did two borrows, two table
10424 // lookups and a clone, and this arm is the whole body of a counting
10425 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10426 let slot = insn.a as usize;
10427 let frame = self.frames.last_mut().expect("a frame is live");
10428 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10429 let target = if cell < 0 {
10430 frame.locals.get_mut(slot)
10431 } else {
10432 None
10433 };
10434 let Some(target) = target else {
10435 return Ok(self.stop(pc));
10436 };
10437 let Value::Int(left) = *target else {
10438 return Ok(self.stop(pc));
10439 };
10440 *target = match left.checked_add(1) {
10441 Some(sum) => Value::Int(sum),
10442 None => Value::Float(left as f64 + 1.0),
10443 };
10444 }
10445 // A loop header, `if (!(x < arg)) goto target`, with both sides already
10446 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10447 // bound stayed small integers.
10448 Fused::LtLocArgJump => {
10449 let loc = (insn.a >> 16) as usize;
10450 let arg = (insn.a & 0xFFFF) as usize;
10451 // One borrow for both slots: this arm *is* the whole loop of a
10452 // `for (i = 0; i < n; i++)` with an argument bound, so a second
10453 // `frames.last()` here is paid on every iteration. Measured 7.5% on
10454 // `dispatch:empty-loop`.
10455 let (left, right) = {
10456 let frame = self.frame();
10457 (frame.read_loc(loc), frame.read_arg(arg))
10458 };
10459 // Heavily measured: the bound is very often a `Float` even when the
10460 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10461 // `JSON.parse` or a division is one — so requiring both sides to be
10462 // `Int` sent every iteration of those loops down the slow path. The
10463 // comparison below is the same one `relational` makes for two numbers.
10464 if !is_number(&left) || !is_number(&right) {
10465 return Ok(self.stop(pc));
10466 }
10467 // `if_false` branches on the comparison being false, which is **not**
10468 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10469 // `>=` is also false and would keep it running forever. Clippy wants the
10470 // negation folded; that would be a wrong answer.
10471 let ordered = left.to_number() < right.to_number();
10472 let take_branch = !ordered;
10473 if take_branch {
10474 pc = insn.b as usize;
10475 continue;
10476 }
10477 }
10478 // The same header with a literal bound: `if (!(x < k)) goto target`.
10479 // The bound is an immediate, so only the counter needs a type test.
10480 #[allow(clippy::neg_cmp_op_on_partial_ord)]
10481 Fused::LtLocImmJump => {
10482 let left = self.get_loc(insn.a as usize);
10483 if !is_number(&left) {
10484 return Ok(self.stop(pc));
10485 }
10486 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10487 if take_branch {
10488 pc = insn.b as usize;
10489 continue;
10490 }
10491 }
10492 Fused::None => match insn.op {
10493 // -- branches ---------------------------------------------------
10494 // A jump is an assignment now, because the target is an instruction
10495 // index. No arithmetic, no resolution table.
10496 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10497 let target = insn.a as usize;
10498 // A **back-edge** is a loop, and it is the only place an
10499 // instruction-level checkpoint can stop one: `for(;;){}` compiles
10500 // to a jump to itself and never leaves this loop, so the
10501 // per-instruction checks in `step` never run. That is exactly the
10502 // hole this arm closes — a host's `JS_SetInterruptHandler` did
10503 // nothing to a `for(;;){}` until it did, which is what
10504 // `tests/c/embed.c` is for.
10505 //
10506 // Polling here rather than on every instruction in this loop is
10507 // also the reference's choice (`OP_goto` calls
10508 // `js_poll_interrupts`), and it costs one compare per branch
10509 // instead of one decrement per instruction.
10510 if target <= pc {
10511 self.frame_mut().pc = target;
10512 self.check_memory()?;
10513 self.check_interrupt()?;
10514 }
10515 pc = target;
10516 continue;
10517 }
10518 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10519 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10520 let taken = self.pop().to_boolean();
10521 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10522 if taken == want {
10523 pc = insn.a as usize;
10524 continue;
10525 }
10526 }
10527 // -- slot access -------------------------------------------------
10528 // A load's slot is already an operand (see `insn::implicit_operand`);
10529 // a captured one goes through its cell, which runs no script.
10530 Opcode::GetLoc
10531 | Opcode::GetLoc8
10532 | Opcode::GetLoc0
10533 | Opcode::GetLoc1
10534 | Opcode::GetLoc2
10535 | Opcode::GetLoc3 => {
10536 let value = self.get_loc(insn.a as usize);
10537 self.push(value);
10538 }
10539 Opcode::PutLoc
10540 | Opcode::PutLoc8
10541 | Opcode::PutLoc0
10542 | Opcode::PutLoc1
10543 | Opcode::PutLoc2
10544 | Opcode::PutLoc3 => {
10545 let value = self.pop();
10546 self.put_loc(insn.a as usize, value);
10547 }
10548 Opcode::GetArg
10549 | Opcode::GetArg0
10550 | Opcode::GetArg1
10551 | Opcode::GetArg2
10552 | Opcode::GetArg3 => {
10553 let value = self.get_arg(insn.a as usize);
10554 self.push(value);
10555 }
10556 Opcode::PutArg
10557 | Opcode::PutArg0
10558 | Opcode::PutArg1
10559 | Opcode::PutArg2
10560 | Opcode::PutArg3 => {
10561 let value = self.pop();
10562 self.put_arg(insn.a as usize, value);
10563 }
10564 // `a[i]` with an integer index on a dense array: see `fast_array_get`
10565 // for why a non-hole own element is exactly the slow path's answer.
10566 // The two operands are *peeked*, so a miss leaves the stack as the
10567 // slow path expects to find it.
10568 Opcode::GetArrayEl => {
10569 // One lookup, not two. The guard used `if …is_some()` and the arm
10570 // then called it again to get the value — two `peek`s, two
10571 // `array_get`s and two `Value` clones for one element.
10572 // `fast_array_get` was 13.1% of `array:indexed`, and the same
10573 // double call was the first version of the `get_field` fast path.
10574 let Some(value) = self.fast_array_get() else {
10575 return Ok(self.stop(pc));
10576 };
10577 // `a[i]` consumes both operands and leaves the element in their
10578 // place: one `truncate` and one write, no `pop`/`push` pair.
10579 let frame = self.frame_mut();
10580 frame.stack.truncate(frame.stack.len() - 2);
10581 frame.stack.push(value);
10582 }
10583 // `a[i] = v` on a dense array with an integer index: see
10584 // `fast_array_set` for why the whole store is one step.
10585 Opcode::PutArrayEl if self.fast_array_set() => {}
10586 // `o.x` resolved from the inline cache without leaving the loop.
10587 //
10588 // The cache is keyed by `(receiver identity, atom, site)` and a
10589 // monomorphic read re-validates the same chain every iteration, so
10590 // each one used to cost a `stop(pc)` — a write of `pc` into the
10591 // frame, a return out of this loop, a re-dispatch through `step` and
10592 // a re-entry. `property:monomorphic` spent 18% in
10593 // `read_field_cached` and 21% in `push`, both across that boundary.
10594 //
10595 // The site is `pc + width`, which is exactly the `next` the slow arm
10596 // passes — the two must agree or every fast lookup misses and
10597 // re-records the same entry forever.
10598 //
10599 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10600 // slow arm finds the receiver where it expects it.
10601 // `name` resolved from the global-variable cache inside the loop.
10602 //
10603 // Same shape as `get_field` above and for the same reason: `get_var`
10604 // was not in the fast loop, so reading a global — which `fib` does
10605 // once per recursive call, for its own name — cost a `stop(pc)`, a
10606 // return out of the loop, a `step` re-dispatch and a re-entry, before
10607 // `get_global` even started its `scopes_are_plain` checks.
10608 //
10609 // Everything here is exactly `get_global`'s first branch: not lexical,
10610 // no `eval` scope, cache hit. Anything else leaves the stack untouched
10611 // and lets the slow arm decide.
10612 Opcode::GetVar => {
10613 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10614 return Ok(self.stop(pc));
10615 };
10616 self.push(value);
10617 }
10618 Opcode::GetField | Opcode::GetField2 => {
10619 let Some(value) =
10620 self.fast_field_get(insn.a as usize, pc + insn.width())
10621 else {
10622 return Ok(self.stop(pc));
10623 };
10624 if insn.op == Opcode::GetField2 {
10625 // `get_field2` keeps the receiver for the `call_method` that
10626 // follows.
10627 self.push(value);
10628 } else {
10629 // `get_field` replaces the receiver, so this is one store over
10630 // the top slot rather than a `pop` and a `push`: the length
10631 // never changes, so neither `Vec` arm has a capacity check or a
10632 // drop to run beyond the one the overwrite itself does.
10633 let frame = self.frame_mut();
10634 match frame.stack.last_mut() {
10635 Some(slot) => *slot = value,
10636 None => return Ok(self.stop(pc)),
10637 }
10638 }
10639 }
10640 // -- constants ---------------------------------------------------
10641 Opcode::PushMinus1
10642 | Opcode::Push0
10643 | Opcode::Push1
10644 | Opcode::Push2
10645 | Opcode::Push3
10646 | Opcode::Push4
10647 | Opcode::Push5
10648 | Opcode::Push6
10649 | Opcode::Push7
10650 | Opcode::PushI8
10651 | Opcode::PushI16
10652 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10653 // -- stack shuffling ---------------------------------------------
10654 Opcode::Drop => {
10655 self.pop();
10656 }
10657 // -- arithmetic on two integers ----------------------------------
10658 //
10659 // The operands are *looked at* before they are popped, so a non-integer
10660 // pair leaves the stack exactly as the slow path expects to find it.
10661 Opcode::Add if self.numeric_pair() => {
10662 let right = self.pop();
10663 let left = self.pop();
10664 // Exactly [`add_numbers`], which is what the slow arm reaches.
10665 let answer = match (&left, &right) {
10666 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10667 Some(sum) => Value::Int(sum),
10668 None => Value::Float(*a as f64 + *b as f64),
10669 },
10670 _ => Value::Float(left.to_number() + right.to_number()),
10671 };
10672 self.push(answer);
10673 }
10674 Opcode::Sub
10675 | Opcode::And
10676 | Opcode::Or
10677 | Opcode::Xor
10678 | Opcode::Shl
10679 | Opcode::Sar
10680 | Opcode::Shr
10681 if self.numeric_pair() =>
10682 {
10683 let right = self.pop();
10684 let left = self.pop();
10685 let answer =
10686 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10687 self.push(answer);
10688 }
10689 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10690 if self.numeric_pair() =>
10691 {
10692 let right = self.pop();
10693 let left = self.pop();
10694 let answer = self
10695 .relational(insn.op, left, right)
10696 .expect("numbers cannot throw");
10697 self.push(answer);
10698 }
10699 // -- calls -------------------------------------------------------
10700 //
10701 // A plain call: `callee(arg0, …, argN) -> result`.
10702 //
10703 // This arm exists because of one measurement. `call:recursion` had
10704 // **20.4% of its profile in `execute_instruction`** — the *slow*
10705 // executor — and `fib`'s recursive call is the only thing in that
10706 // function which is not a fast arm. Every call therefore left this
10707 // loop via `stop()`, went through `step()`'s dispatch and
10708 // `execute_instruction`'s match over every opcode, and came back here
10709 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10710 //
10711 // Two things make it safe to do here rather than only in the slow path:
10712 //
10713 // * the caller's `pc` is stored *before* the call, which is what
10714 // `step` does too — so when the callee returns, the caller resumes
10715 // after the call and not at it;
10716 // * `check_memory` runs, because `step` calls it once per instruction
10717 // and a call allocates a frame, its locals and its cells. Skipping
10718 // the checkpoint here would let a `--memory-limit` script overshoot
10719 // by one call per instruction.
10720 Opcode::Call
10721 | Opcode::Call0
10722 | Opcode::Call1
10723 | Opcode::Call2
10724 | Opcode::Call3 => {
10725 let argc = self.argc_operand(insn.op, insn.a);
10726 let next = pc + insn.width();
10727 {
10728 let frame = self
10729 .frames
10730 .last_mut()
10731 .expect("run_fast() is only called with a live frame");
10732 // `at` is what a stack trace reports for this frame, so a throw
10733 // inside the callee has to see the call site and not whatever
10734 // the last `stop()` left there.
10735 frame.at = insn.offset as usize;
10736 frame.pc = next;
10737 }
10738 self.check_memory()?;
10739 self.check_interrupt()?;
10740 let args = self.pop_n(argc);
10741 let callee = self.pop();
10742 // A plain call has no receiver; the callee decides what to do with
10743 // `undefined` (a sloppy function substitutes the global object).
10744 if let Some(result) =
10745 self.call_or_push(callee, Value::Undefined, args)?
10746 {
10747 // Native, host, generator, async, bound — no frame was pushed,
10748 // so this loop is still describing the right function. `pc`
10749 // is advanced by the loop tail like every other arm; only the
10750 // frame's copy had to be written here, and it already was.
10751 self.push(result);
10752 } else {
10753 // A bytecode callee: its frame is on top now, and `insns` and
10754 // `pc` both belong to the caller. Start over on the new frame.
10755 continue 'outer;
10756 }
10757 }
10758 // -- return ------------------------------------------------------
10759 Opcode::Return => {
10760 let value = self.pop();
10761 self.frame_mut().pc = pc + insn.width();
10762 return Ok(Some(value));
10763 }
10764 Opcode::ReturnUndef => {
10765 self.frame_mut().pc = pc + insn.width();
10766 return Ok(Some(Value::Undefined));
10767 }
10768 // Everything else needs the slow path.
10769 _ => return Ok(self.stop(pc)),
10770 },
10771 }
10772 pc += insn.width();
10773 }
10774 }
10775 }
10776
10777 /// Whether the top two operand-stack values are both numbers.
10778 ///
10779 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10780 /// cannot run script, so the arm may not throw and may not change frames.
10781 fn numeric_pair(&self) -> bool {
10782 is_number(&self.peek(0)) && is_number(&self.peek(1))
10783 }
10784
10785 /// `a[i]` for a dense array and an integer index, without the string round trip.
10786 ///
10787 /// The slow path answers this by turning `i` into a string (`propkey` →
10788 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10789 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10790 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10791 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10792 /// without even the cheap `Int` formatting.
10793 ///
10794 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10795 /// unambiguously the one the slow path would give:
10796 ///
10797 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10798 /// `2^32-1` is the length, not an index),
10799 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10800 /// typed array or an ordinary object, all of which have their own rules),
10801 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10802 /// starts walking the prototype chain, and `a[i]` on a hole must find
10803 /// `Array.prototype[i]` if it exists rather than `undefined`.
10804 ///
10805 /// The last condition is the one that makes this safe rather than merely fast: an own
10806 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10807 /// `get_var` answered from the global-variable cache, or `None`.
10808 ///
10809 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10810 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10811 /// records nothing — the slow arm is about to walk the chain and record it.
10812 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10813 let frame = self.frame();
10814 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10815 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10816 // `GlobalRef` forwarded through a nested function has its flags cleared.
10817 if self.realm.globals.contains_key(name) {
10818 return None;
10819 }
10820 if !self.scopes_are_plain() {
10821 return None;
10822 }
10823 let object = &self.realm.global;
10824 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10825 let cached = self.global_cache[site].as_ref()?;
10826 if !object.upgrades_to(&cached.object) {
10827 return None;
10828 }
10829 object.data_property_at(cached.index, name)
10830 }
10831
10832 /// `o.x` answered entirely from the inline cache, or `None`.
10833 ///
10834 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10835 /// about to do exactly that and recording it twice would rebuild the chain for every
10836 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10837 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10838 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10839 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10840 // an object receiver is a reference-count bump that the answer never needs.
10841 let frame = self.frame();
10842 let object = frame.stack.last()?;
10843 let Value::Object(target) = object else {
10844 return None;
10845 };
10846 // A proxy traps the lookup, so no cache entry ever describes it.
10847 if target.proxy_state().is_some() {
10848 return None;
10849 }
10850 let key = frame.code.atom_keys.get(atom)?;
10851 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10852 if cached.key != *key {
10853 return None;
10854 }
10855 Self::cached_hit(target, cached)
10856 }
10857
10858 fn fast_array_get(&self) -> Option<Value> {
10859 let Value::Int(index) = self.peek(0) else {
10860 return None;
10861 };
10862 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10863 // set for an `i32`.
10864 if index < 0 {
10865 return None;
10866 }
10867 let Value::Object(object) = self.peek(1) else {
10868 return None;
10869 };
10870 match object.array_get(index as usize) {
10871 Some(value) if !matches!(value, Value::Hole) => Some(value),
10872 _ => None,
10873 }
10874 }
10875
10876 /// `a[i] = v` on a dense array with an integer index, as one store.
10877 ///
10878 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10879 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10880 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10881 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10882 /// reference at the time it was measured (14.7x).
10883 ///
10884 /// Every condition here is one the slow path would also have to satisfy before
10885 /// storing into the element vector:
10886 ///
10887 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10888 /// accepts as an index;
10889 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10890 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10891 /// one inside a recorded descriptor, reports `false` and the caller stops.
10892 ///
10893 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10894 /// writes the own element too once `array_set` says it did.
10895 fn fast_array_set(&mut self) -> bool {
10896 // Every test runs *before* anything is popped: a refusal has to leave the stack
10897 // exactly as the slow path expects to find it. Popping first and reporting the
10898 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10899 // then ran the slow path with nothing to write.
10900 let Value::Int(index) = self.peek(1) else {
10901 return false;
10902 };
10903 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10904 if index < 0 {
10905 return false;
10906 }
10907 // Only a real array: a typed array's elements live in its buffer, a string-like
10908 // object has no element vector, and `array_set` on either does nothing.
10909 let Value::Object(object) = self.peek(2) else {
10910 return false;
10911 };
10912 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10913 return false;
10914 }
10915 // A non-extensible array reports `false` here, but the *slow* path has to decide
10916 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10917 // that with the key and the stack still intact.
10918 if !object.is_extensible() {
10919 return false;
10920 }
10921 // Inside the logical length, so the store cannot change `length`. Combined with
10922 // extensibility above, the only growth left for `array_set` is filling a hole in
10923 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10924 // shape this fast path exists for. A store past the length would grow the array,
10925 // and whether that is allowed is the slow path's question.
10926 if index as usize >= object.array_length().unwrap_or(0) {
10927 return false;
10928 }
10929 // Only an *own element* can take the inline store. A hole is not an own property,
10930 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10931 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10932 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10933 // the one case this path used to swallow.
10934 //
10935 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10936 // `array:push` appends past the length, which this path already refused.
10937 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10938 {
10939 return false;
10940 }
10941 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10942 // to report a failure after the operands are gone.
10943 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10944 return false;
10945 }
10946 let value = self.pop();
10947 self.pop();
10948 self.pop();
10949 object.array_store(self.heap, index as usize, value)
10950 }
10951
10952 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10953 fn stop(&mut self, pc: usize) -> Option<Value> {
10954 self.frame_mut().pc = pc;
10955 None
10956 }
10957
10958 fn push(&mut self, value: Value) {
10959 self.frame_mut().stack.push(value);
10960 }
10961
10962 fn pop(&mut self) -> Value {
10963 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10964 }
10965
10966 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10967 let frame = self.frame_mut();
10968 let start = frame.stack.len().saturating_sub(count);
10969 frame.stack.split_off(start)
10970 }
10971
10972 fn peek(&self, back: usize) -> Value {
10973 let frame = self.frame();
10974 frame
10975 .stack
10976 .get(frame.stack.len().wrapping_sub(1 + back))
10977 .cloned()
10978 .unwrap_or(Value::Undefined)
10979 }
10980
10981 #[allow(clippy::too_many_lines)]
10982 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10983 use Opcode::*;
10984 match op {
10985 // -- constants and stack shuffling -----------------------------
10986 Nop => {}
10987 PushMinus1 => self.push(Value::Int(-1)),
10988 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10989 let value = match op {
10990 Push0 => 0,
10991 Push1 => 1,
10992 Push2 => 2,
10993 Push3 => 3,
10994 Push4 => 4,
10995 Push5 => 5,
10996 Push6 => 6,
10997 _ => 7,
10998 };
10999 self.push(Value::Int(value));
11000 }
11001 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
11002 PushBigintI32 => {
11003 // The immediate form of a `BigInt` literal; the reference has the same
11004 // split between this and a constant-pool entry.
11005 let value = crate::bigint::BigInt::from_i64(a as i64);
11006 self.push(self.bigint(value));
11007 }
11008 PushTrue => self.push(Value::Bool(true)),
11009 PushFalse => self.push(Value::Bool(false)),
11010 PushEmptyString => self.push(self.string("")),
11011 Undefined => self.push(Value::Undefined),
11012 Null => self.push(Value::Null),
11013 Object => {
11014 let proto = self.realm.object_proto.clone();
11015 self.push(Value::Object(self.new_object(Some(proto))));
11016 }
11017 PushThis => {
11018 let this = self.frame().this.clone();
11019 self.push(this);
11020 }
11021 PushConst | PushConst8 => {
11022 let value = self.constant(a as usize)?;
11023 self.push(value);
11024 }
11025 PushAtomValue => {
11026 let text = self.atom_wtf8(a as usize);
11027 self.push(self.string_wtf8(text));
11028 }
11029 Dup => {
11030 let value = self.peek(0);
11031 self.push(value);
11032 }
11033 Dup2 => {
11034 // `a b -> a b a b`
11035 let b = self.peek(0);
11036 let a = self.peek(1);
11037 self.push(a);
11038 self.push(b);
11039 }
11040 Dup3 => {
11041 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
11042 // prototype and key while reading the current value through them.
11043 let c = self.peek(0);
11044 let b = self.peek(1);
11045 let a = self.peek(2);
11046 self.push(a);
11047 self.push(b);
11048 self.push(c);
11049 }
11050 Swap => {
11051 // `a b -> b a`
11052 let bottom = self.pop();
11053 let top = self.pop();
11054 self.push(bottom);
11055 self.push(top);
11056 }
11057 Perm3 => {
11058 // `a b c -> b a c`, the reference's reordering for a spread method
11059 // call: `obj func array` becomes the `func this array` that `apply`
11060 // takes.
11061 let c = self.pop();
11062 let b = self.pop();
11063 let a = self.pop();
11064 self.push(b);
11065 self.push(a);
11066 self.push(c);
11067 }
11068 Dup1 => {
11069 let value = self.peek(1);
11070 self.push(value);
11071 }
11072 Drop => {
11073 self.pop();
11074 }
11075 Nip => {
11076 // `a b -> b`
11077 let top = self.pop();
11078 self.pop();
11079 self.push(top);
11080 }
11081 Perm4 => {
11082 // `obj prop a b -> a obj prop b`, the reference's reordering for a
11083 // postfix update of a computed element: it puts the *old* value
11084 // underneath the receiver and key so `put_array_el` can consume them
11085 // and leave the old value as the expression's result.
11086 let d = self.pop();
11087 let c = self.pop();
11088 let b = self.pop();
11089 let a = self.pop();
11090 self.push(c);
11091 self.push(a);
11092 self.push(b);
11093 self.push(d);
11094 }
11095 Insert2 => {
11096 // `obj a -> a obj a`
11097 let value = self.pop();
11098 let object = self.pop();
11099 self.push(value.clone());
11100 self.push(object);
11101 self.push(value);
11102 }
11103 Insert3 => {
11104 // `obj prop a -> a obj prop a`
11105 let value = self.pop();
11106 let key = self.pop();
11107 let object = self.pop();
11108 self.push(value.clone());
11109 self.push(object);
11110 self.push(key);
11111 self.push(value);
11112 }
11113 Insert4 => {
11114 // `this obj prop a -> a this obj prop a`
11115 //
11116 // `put_super_value` consumes all four and yields nothing, so the copy
11117 // underneath is what leaves the assignment an expression value.
11118 let value = self.pop();
11119 let key = self.pop();
11120 let object = self.pop();
11121 let receiver = self.pop();
11122 self.push(value.clone());
11123 self.push(receiver);
11124 self.push(object);
11125 self.push(key);
11126 self.push(value);
11127 }
11128 Swap2 => {
11129 // `a b c d -> c d a b`
11130 let d = self.pop();
11131 let c = self.pop();
11132 let b = self.pop();
11133 let a = self.pop();
11134 self.push(c);
11135 self.push(d);
11136 self.push(a);
11137 self.push(b);
11138 }
11139 Rot3l => {
11140 // `x a b -> a b x`
11141 let b = self.pop();
11142 let a = self.pop();
11143 let x = self.pop();
11144 self.push(a);
11145 self.push(b);
11146 self.push(x);
11147 }
11148 Rot3r => {
11149 // `a b c -> c a b`
11150 let c = self.pop();
11151 let b = self.pop();
11152 let a_value = self.pop();
11153 self.push(c);
11154 self.push(a_value);
11155 self.push(b);
11156 }
11157
11158 Rest => {
11159 // `...rest` in a parameter list: the arguments from index `a` on, as a
11160 // real array. It takes nothing off the stack — the arguments are in the
11161 // frame, not on it.
11162 let frame = self.frame();
11163 let from = a as usize;
11164 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11165 let array = self.new_array(collected);
11166 self.push(Value::Object(array));
11167 }
11168
11169 // -- slots ------------------------------------------------------
11170 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11171 let slot = self.slot_operand(op, a);
11172 let value = self.get_loc(slot);
11173 self.push(value);
11174 }
11175 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11176 let slot = self.slot_operand(op, a);
11177 let value = self.pop();
11178 self.put_loc(slot, value);
11179 }
11180 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11181 let slot = self.slot_operand(op, a);
11182 let value = self.pop();
11183 self.put_loc(slot, value.clone());
11184 self.push(value);
11185 }
11186 // The `_check` forms are the temporal dead zone: they throw when the
11187 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11188 // *reads*, so only the two writes may pop — mishandling that quietly
11189 // consumes the value the caller pushed just before.
11190 GetLocCheck => {
11191 let slot = self.slot_operand(op, a);
11192 let value = self.get_loc(slot);
11193 if matches!(value, Value::Uninitialized) {
11194 return Err(self.dead_zone(slot, VarSlot::Loc));
11195 }
11196 self.push(value);
11197 }
11198 PutLocCheck | SetLocCheck => {
11199 let slot = self.slot_operand(op, a);
11200 let value = self.pop();
11201 // The dead zone is a property of the **slot**, not of the value being
11202 // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11203 // initialised yet. Testing the value instead — which is never
11204 // `Uninitialized` in practice — let every such store through, so the check
11205 // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11206 // (`get_loc_check`) were already asking the slot, which is why
11207 // `print(x); let x` threw while `x = 1; let x` did not.
11208 if matches!(self.get_loc(slot), Value::Uninitialized) {
11209 return Err(self.dead_zone(slot, VarSlot::Loc));
11210 }
11211 // The initialiser goes through `put_loc`, not this, so any store that
11212 // reaches here is a later assignment — which a `const` refuses.
11213 if self.is_read_only(slot, VarSlot::Loc) {
11214 return Err(self.read_only(slot, VarSlot::Loc));
11215 }
11216 if op == SetLocCheck {
11217 self.put_loc(slot, value.clone());
11218 self.push(value);
11219 } else {
11220 self.put_loc(slot, value);
11221 }
11222 }
11223 PutLocCheckInit => {
11224 // The one store that *initialises* a lexical slot: `this` in a derived
11225 // constructor, which only exists after `super()` has run. A second
11226 // initialisation is the error the reference reports as
11227 // "'this' can be initialized only once".
11228 let slot = self.slot_operand(op, a);
11229 let value = self.pop();
11230 if !matches!(self.get_loc(slot), Value::Uninitialized) {
11231 return Err(Signal::Throw(self.make_error(
11232 "ReferenceError",
11233 "'this' can be initialized only once",
11234 )));
11235 }
11236 self.put_loc(slot, value);
11237 }
11238 CheckCtor => {
11239 // A class constructor may only run under `new`, which is what makes
11240 // `class A {}; A()` a TypeError.
11241 if matches!(self.frame().new_target, Value::Undefined) {
11242 return Err(Signal::Throw(self.make_error(
11243 "TypeError",
11244 "class constructors must be invoked with 'new'",
11245 )));
11246 }
11247 }
11248 InitCtor => {
11249 // The body a derived class gets when it declares no constructor:
11250 // forward every argument to the parent constructor, keeping `new.target`.
11251 if matches!(self.frame().new_target, Value::Undefined) {
11252 return Err(Signal::Throw(self.make_error(
11253 "TypeError",
11254 "class constructors must be invoked with 'new'",
11255 )));
11256 }
11257 let Some(callee) = self.current_callee() else {
11258 return Err(Signal::Throw(
11259 self.make_error("TypeError", "no constructor to inherit from"),
11260 ));
11261 };
11262 let parent = callee.proto().map_or(Value::Null, Value::Object);
11263 let new_target = self.frame().new_target.clone();
11264 let args = self.frame().passed().to_vec();
11265 let result = self.construct(parent, new_target, args)?;
11266 self.push(result);
11267 }
11268 SetLocUninitialized => {
11269 let slot = self.slot_operand(op, a);
11270 self.put_loc(slot, Value::Uninitialized);
11271 }
11272 CloseLoc => {
11273 // "Close" a binding: give it a *fresh* cell holding the current
11274 // value. Closures created before this point keep the old cell and the
11275 // ones created after see the new one, which is what makes every
11276 // iteration of `for (let i ...)` capture its own `i`, and what freezes
11277 // a block-scoped binding when the block ends.
11278 //
11279 // Clearing the slot instead (which this used to do) broke both: a
11280 // closure over a captured block variable read `undefined`, and a loop
11281 // terminated after one iteration.
11282 let slot = self.slot_operand(op, a);
11283 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11284 if index >= 0 {
11285 let current = self.frame().cells[index as usize].get();
11286 let fresh = self.new_cell(current);
11287 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11288 *cell = fresh;
11289 }
11290 }
11291 }
11292 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11293 let slot = self.slot_operand(op, a);
11294 let value = self.get_arg(slot);
11295 self.push(value);
11296 }
11297 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11298 let slot = self.slot_operand(op, a);
11299 let value = self.pop();
11300 self.put_arg(slot, value);
11301 }
11302 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11303 let slot = self.slot_operand(op, a);
11304 let value = self.pop();
11305 self.put_arg(slot, value.clone());
11306 self.push(value);
11307 }
11308
11309 // -- closure variables ------------------------------------------
11310 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11311 let slot = self.slot_operand(op, a);
11312 // A name a direct `eval` created shadows the binding the compiler chose.
11313 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11314 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11315 // and only a runtime lookup can know that.
11316 if let Some(cell) = self.eval_created_local(slot) {
11317 self.push(cell.get());
11318 return self.step();
11319 }
11320 let value = self.cell_value(slot)?;
11321 self.push(value);
11322 }
11323 GetVarRefCheck => {
11324 let slot = self.slot_operand(op, a);
11325 let value = self.cell_value(slot)?;
11326 if matches!(value, Value::Uninitialized) {
11327 return Err(self.dead_zone(slot, VarSlot::Closure));
11328 }
11329 self.push(value);
11330 }
11331 PutVarRefCheckInit => {
11332 // The captured-form twin of `PutLocCheckInit`. Both exist because `super()`
11333 // may be written inside an arrow, and there `this` is a var-ref rather than
11334 // a local.
11335 let slot = self.slot_operand(op, a);
11336 let value = self.pop();
11337 // The wording differs from the local form because the reference reaches
11338 // this case through `get_var_ref_checkthis`, which reports the dead zone
11339 // rather than the double initialisation.
11340 if !matches!(self.cell_value(slot)?, Value::Uninitialized) {
11341 return Err(Signal::Throw(
11342 self.make_error("ReferenceError", "this is not initialized"),
11343 ));
11344 }
11345 self.set_cell(slot, value)?;
11346 }
11347 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11348 let slot = self.slot_operand(op, a);
11349 let value = self.pop();
11350 if let Some(cell) = self.eval_created_local(slot) {
11351 cell.set(value);
11352 return self.step();
11353 }
11354 // Same two rules as `PutLocCheck`: a checked store to a captured binding
11355 // asks the cell about the dead zone, then refuses a `const` whose
11356 // initialiser has already run.
11357 if op == PutVarRefCheck {
11358 let current = self.cell_value(slot)?;
11359 if matches!(current, Value::Uninitialized) {
11360 return Err(self.dead_zone(slot, VarSlot::Closure));
11361 }
11362 if self.is_read_only(slot, VarSlot::Closure) {
11363 return Err(self.read_only(slot, VarSlot::Closure));
11364 }
11365 }
11366 self.set_cell(slot, value)?;
11367 }
11368 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11369 let slot = self.slot_operand(op, a);
11370 let value = self.pop();
11371 if let Some(cell) = self.eval_created_local(slot) {
11372 cell.set(value.clone());
11373 self.push(value);
11374 return self.step();
11375 }
11376 self.set_cell(slot, value.clone())?;
11377 self.push(value);
11378 }
11379
11380 // -- globals ----------------------------------------------------
11381 GetVar => {
11382 let value = self.get_global(a as usize)?;
11383 self.push(value);
11384 }
11385 GetVarUndef => {
11386 let slot = a as usize;
11387 // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11388 // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11389 // and `GetValue`s it, and only the unresolvable case is forgiven).
11390 //
11391 // The distinction is made by asking whether a binding exists at all: a name
11392 // in the realm's lexical table is declared, so a `ReferenceError` from
11393 // reading it is the dead zone talking. Swallowing every error made
11394 // `eval("typeof x; let x;")` print `"undefined"`.
11395 let declared = self.realm.globals.contains_key(&self.global_name(slot));
11396 let value = if declared {
11397 self.get_global(slot)?
11398 } else {
11399 match self.get_global(slot) {
11400 Ok(value) => value,
11401 Err(Signal::Throw(_)) => Value::Undefined,
11402 Err(other) => return Err(other),
11403 }
11404 };
11405 self.push(value);
11406 }
11407 DeleteVar => {
11408 // `delete name` for a name that is not a declared binding. A lexical
11409 // global lives in the reference table and cannot be deleted; anything
11410 // reachable only as a property of the global object is *implicit* —
11411 // `x = 1` with no declaration — and goes away if it is configurable,
11412 // which is what `delete` on an implicit global answers.
11413 let name = self.atom_text(a as usize);
11414 let global = self.realm.global.clone();
11415 let deleted = if self.realm.globals.contains_key(&name) {
11416 false
11417 } else if global.own_property(&name).is_some() {
11418 self.delete_property(&global, &name)?
11419 } else {
11420 true
11421 };
11422 self.push(Value::Bool(deleted));
11423 }
11424 PutVar => {
11425 let value = self.pop();
11426 self.put_global(a as usize, value)?;
11427 }
11428 PutVarInit => {
11429 let slot = a as usize;
11430 let value = self.pop();
11431 self.init_global(slot, value)?;
11432 }
11433
11434 // -- arithmetic -------------------------------------------------
11435 Add => self.binary_add()?,
11436 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11437 let raw_right = self.pop();
11438 let raw_left = self.pop();
11439 // Two numbers need no `ToPrimitive` at all, which is every `x - y` and
11440 // `flags | mask` in real code.
11441 if is_number(&raw_left) && is_number(&raw_right) {
11442 self.push(arithmetic(op, raw_left, raw_right)?);
11443 } else {
11444 // §13.15.3 steps 1–3: **both** operands are made primitive before the
11445 // disjointness check, left first. Getting the order wrong was observable
11446 // — `ToPrimitive` on the right ran first, so a `valueOf` log read `b,a`
11447 // and a throw from the *left* operand never happened
11448 // (`S11.10.1_A2.3_T1`, `order-of-evaluation`).
11449 //
11450 // Doing the check on the *primitives* rather than on the raw values is
11451 // the second half: `Object(5n) & Object(3n)` has a bigint on neither
11452 // side of the stack yet, so the old check sent it down the `ToNumber`
11453 // path and raised "cannot convert bigint to number"
11454 // (`bigint-non-primitive`).
11455 let left = self.primitive_of(raw_left)?;
11456 let right = self.primitive_of(raw_right)?;
11457 // BigInt arithmetic is a separate path, and not only for the type of
11458 // the result: `ToNumber` of a bigint throws, so mixing the two must be
11459 // an error rather than a silent conversion.
11460 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11461 let value = self.bigint_arithmetic(op, left, right)?;
11462 self.push(value);
11463 } else {
11464 let right = self.numeric(right)?;
11465 let left = self.numeric(left)?;
11466 self.push(arithmetic(op, left, right)?);
11467 }
11468 }
11469 }
11470 Neg => {
11471 let raw = self.pop();
11472 match raw {
11473 // A bigint negates exactly, however wide it is.
11474 Value::BigInt(big) => {
11475 let negated = big.negate();
11476 self.push(self.bigint(negated));
11477 }
11478 other => {
11479 let value = self.numeric_operand(other)?;
11480 if let Value::BigInt(big) = &value {
11481 let negated = big.negate();
11482 self.push(self.bigint(negated));
11483 } else {
11484 self.push(negate(value));
11485 }
11486 }
11487 }
11488 }
11489 Plus => {
11490 let value = self.pop();
11491 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11492 // unary plus is defined to produce a *number*, which a bigint cannot
11493 // become without loss. It used to fall through to `NaN`.
11494 if matches!(value, Value::BigInt(_)) {
11495 return Err(self.type_error("cannot convert bigint to number"));
11496 }
11497 let numeric = self.numeric_of(value)?;
11498 self.push(numeric);
11499 }
11500 Inc => {
11501 let raw = self.pop();
11502 let (_, updated) = self.advance_numeric(raw, true)?;
11503 self.push(updated);
11504 }
11505 Dec => {
11506 let raw = self.pop();
11507 let (_, updated) = self.advance_numeric(raw, false)?;
11508 self.push(updated);
11509 }
11510 PostInc | PostDec => {
11511 // `x -> x x+1`: the *new* value ends up on top, so the store the
11512 // compiler emits right after (`put_var`) writes the incremented
11513 // one, while the old value stays underneath for the expression's
11514 // own result. Getting this backwards makes `i++` a no-op, which
11515 // turns `while (i < 3)` into an infinite loop.
11516 let raw = self.pop();
11517 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11518 self.push(old);
11519 self.push(updated);
11520 }
11521 Not => {
11522 let raw = self.pop();
11523 match raw {
11524 // `~x` on a bigint is `-x - 1`, exact at any width.
11525 Value::BigInt(big) => {
11526 let inverted = big.bitnot();
11527 self.push(self.bigint(inverted));
11528 }
11529 other => {
11530 let value = self.numeric_operand(other)?;
11531 if let Value::BigInt(big) = &value {
11532 let inverted = big.bitnot();
11533 self.push(self.bigint(inverted));
11534 } else {
11535 self.push(Value::Int(!value.to_int32()));
11536 }
11537 }
11538 }
11539 }
11540 Lnot => {
11541 let value = self.pop();
11542 self.push(Value::Bool(!value.to_boolean()));
11543 }
11544
11545 // -- comparison -------------------------------------------------
11546 Lt | Lte | Gt | Gte => {
11547 let right = self.pop();
11548 let left = self.pop();
11549 let answer = self.relational(op, left, right)?;
11550 self.push(answer);
11551 }
11552 Eq | Neq => {
11553 let right = self.pop();
11554 let left = self.pop();
11555 let equal = self.abstract_equals(left, right)?;
11556 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11557 }
11558 StrictEq => {
11559 let right = self.pop();
11560 let left = self.pop();
11561 self.push(Value::Bool(left.strict_equals(&right)));
11562 }
11563 StrictNeq => {
11564 let right = self.pop();
11565 let left = self.pop();
11566 self.push(Value::Bool(!left.strict_equals(&right)));
11567 }
11568 IsUndefined => {
11569 // `=== undefined`, which is what a destructuring default tests. It is
11570 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11571 let value = self.pop();
11572 self.push(Value::Bool(matches!(value, Value::Undefined)));
11573 }
11574 IsUndefinedOrNull => {
11575 let value = self.pop();
11576 self.push(Value::Bool(value.is_nullish()));
11577 }
11578 Typeof => {
11579 let value = self.pop();
11580 self.push(self.string(value.type_of()));
11581 }
11582 ToObject => {
11583 // A destructuring *object* pattern starts here, which is why
11584 // `var {} = null` throws. Only `undefined` and `null` are refused; a
11585 // primitive is boxed.
11586 let value = self.pop();
11587 let object = self.object_from(&value)?;
11588 self.push(Value::Object(object));
11589 }
11590 Instanceof => {
11591 let constructor = self.pop();
11592 let object = self.pop();
11593 // `InstanceofOperator`, not `OrdinaryHasInstance`: the operator consults
11594 // `Symbol.hasInstance` first and throws for a right-hand side that is not an
11595 // object (step 1) or not callable (step 4). Calling `instance_of` directly
11596 // skipped both the protocol and the two `TypeError`s.
11597 let answer = self.instance_of_operator(&object, &constructor)?;
11598 self.push(Value::Bool(answer));
11599 }
11600 In => {
11601 let object = self.pop();
11602 let key = self.pop();
11603 let answer = self.has_property(&key, &object)?;
11604 self.push(Value::Bool(answer));
11605 }
11606 WithHasVar => {
11607 // `obj -> bool`: does this `with` object bind the name?
11608 //
11609 // §9.1.1.2.1 `HasBinding` for an Object Environment Record is **not**
11610 // `HasProperty`: step 2 skips the property entirely when the object's
11611 // `Symbol.unscopables` lists it. So `globalThis[Symbol.unscopables] = {v:
11612 // true}` makes `with (globalThis) { v }` read the *outer* `v`, which is what
11613 // the thirty-odd `unscopables-with` cases assert.
11614 //
11615 // One instruction rather than a hand-expanded sequence of `in`, a
11616 // `Symbol.unscopables` lookup and a second `in`: the same question is asked
11617 // by both the read/write guard and `delete`, and a compiler-side expansion
11618 // would be about ten instructions per name per `with` object.
11619 let object = self.pop();
11620 let name = self.atom_text(a as usize);
11621 let bound = self.with_has_binding(&object, &name)?;
11622 self.push(Value::Bool(bound));
11623 }
11624 WithGetVar => {
11625 // `obj -> value`: the second half of `GetBindingValue`.
11626 let object = self.pop();
11627 let name = self.atom_text(a as usize);
11628 let value = self.with_get_binding(&object, &name)?;
11629 self.push(value);
11630 }
11631 WithPutVar => {
11632 // `obj value ->`: the second half of `SetMutableBinding`. The operand order
11633 // is `put_field`'s (value on top), not the reference's, so that the
11634 // read-modify-write shapes (`perm3`/`insert2`) can be shared with the
11635 // member-expression forms.
11636 let value = self.pop();
11637 let object = self.pop();
11638 let name = self.atom_text(a as usize);
11639 self.with_put_binding(&object, &name, value)?;
11640 }
11641
11642 // -- control flow -----------------------------------------------
11643 Goto | Goto8 | Goto16 => {
11644 self.frame_mut().pc = a as usize;
11645 }
11646 IfTrue | IfTrue8 => {
11647 let value = self.pop();
11648 if value.to_boolean() {
11649 self.frame_mut().pc = a as usize;
11650 }
11651 }
11652 IfFalse | IfFalse8 => {
11653 let value = self.pop();
11654 if !value.to_boolean() {
11655 self.frame_mut().pc = a as usize;
11656 }
11657 }
11658 Catch => {
11659 // Pushes the handler target onto the value stack; `unwind` finds it.
11660 self.push(Value::CatchOffset(a));
11661 }
11662 Gosub => {
11663 self.push(Value::ReturnAddress(next as u32));
11664 self.frame_mut().pc = a as usize;
11665 }
11666 Ret => {
11667 let value = self.pop();
11668 match value {
11669 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11670 _ => {
11671 return Err(Signal::Throw(
11672 self.make_error("InternalError", "invalid return address"),
11673 ));
11674 }
11675 }
11676 }
11677 NipCatch => {
11678 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11679 // including the marker, keeping the top value.
11680 let top = self.pop();
11681 loop {
11682 match self.pop() {
11683 Value::CatchOffset(_) | Value::Undefined => break,
11684 _ => {}
11685 }
11686 if self.frame().stack.is_empty() {
11687 break;
11688 }
11689 }
11690 self.push(top);
11691 }
11692 Throw => {
11693 let value = self.pop();
11694 return Err(Signal::Throw(value));
11695 }
11696 ThrowError => {
11697 let name = self.atom_text(a as usize);
11698 let (class, message) = match b {
11699 0 => ("TypeError", format!("'{name}' is read-only")),
11700 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11701 2 => ("ReferenceError", format!("'{name}' is not initialized")),
11702 // `delete super.x` is a syntax-level mistake the reference reports
11703 // with this wording, not a property-access failure.
11704 3 => (
11705 "ReferenceError",
11706 "unsupported reference to 'super'".to_string(),
11707 ),
11708 4 => (
11709 "TypeError",
11710 "iterator does not have a throw method".to_string(),
11711 ),
11712 5 => (
11713 "ReferenceError",
11714 "invalid assignment left-hand side".to_string(),
11715 ),
11716 _ => ("TypeError", format!("invalid operation on '{name}'")),
11717 };
11718 return Err(Signal::Throw(self.make_error(class, &message)));
11719 }
11720 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11721 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11722 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11723 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11724 Await => return Ok(Step::Suspend(SuspendKind::Await)),
11725 ReturnAsync => {
11726 // The reference's `return_async` returns `undefined` and lets the resume
11727 // machinery pick the real value off `sp[-1]`, which is how it tells a
11728 // completion from a suspension. Carrying the value explicitly says the
11729 // same thing without the implicit stack slot.
11730 let value = self.pop();
11731 return Ok(Step::Return(value));
11732 }
11733 Return => {
11734 let value = self.pop();
11735 return Ok(Step::Return(value));
11736 }
11737 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11738
11739 // -- calls ------------------------------------------------------
11740 Call | Call0 | Call1 | Call2 | Call3 => {
11741 let argc = self.argc_operand(op, a);
11742 let args = self.pop_n(argc);
11743 let callee = self.pop();
11744 // A plain call has no receiver; the callee decides what to do with
11745 // `undefined` (a sloppy function substitutes the global object).
11746 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11747 self.push(result);
11748 }
11749 }
11750 CallConstructor => {
11751 // `constructor this_obj args… -> object`. The duplicated
11752 // constructor is `new.target`; this milestone does not expose it,
11753 // so the extra copy is simply consumed here.
11754 let argc = a as usize;
11755 let args = self.pop_n(argc);
11756 let new_target = self.pop();
11757 let callee = self.pop();
11758 let result = self.construct(callee, new_target, args)?;
11759 self.push(result);
11760 }
11761 CallMethod => {
11762 let argc = a as usize;
11763 let args = self.pop_n(argc);
11764 let callee = self.pop();
11765 let this = self.pop();
11766 if let Some(result) = self.call_or_push(callee, this, args)? {
11767 self.push(result);
11768 }
11769 }
11770 Apply => {
11771 // `func this array -> result`, the spread-call form: the compiler
11772 // builds one array of arguments, and all that is left here is to
11773 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11774 let array = self.pop();
11775 let this = self.pop();
11776 let callee = self.pop();
11777 let args = self.array_like_to_args(&array)?;
11778 if a & 1 != 0 {
11779 let result = self.construct(callee, this, args)?;
11780 self.push(result);
11781 } else if let Some(result) = self.call_or_push(callee, this, args)? {
11782 self.push(result);
11783 }
11784 }
11785 TailCall | TailCallMethod => {
11786 // `tail_call` is `call` whose result is returned immediately — the
11787 // reference jumps straight to `done` instead of storing the value and
11788 // running on. The callee still gets its own frame, so deep tail
11789 // recursion hits the stack limit exactly like plain recursion does;
11790 // marking this frame lets the return path unwind without needing
11791 // instructions after the call.
11792 let argc = if op == TailCallMethod {
11793 a as usize
11794 } else {
11795 self.argc_operand(op, a)
11796 };
11797 let args = self.pop_n(argc);
11798 let callee = self.pop();
11799 let this = if op == TailCallMethod {
11800 self.pop()
11801 } else {
11802 Value::Undefined
11803 };
11804 if let Value::Object(function) = &callee
11805 && let Some((code, env)) = bytecode_of(function)
11806 {
11807 // A generator or async body is not run here at all: calling it only
11808 // *creates* the generator/coroutine, so it must not inherit this
11809 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11810 // onto `f`'s frame, and the first `yield`/`await` then reported
11811 // "a generator body ran as an ordinary call".
11812 if code.code.kind.is_generator() || code.code.kind.is_async() {
11813 let value = self.call_value(callee, this, args)?;
11814 return Ok(Step::Return(value));
11815 }
11816 self.frame_mut().tail = true;
11817 self.push_frame(code, env, this, args, callee)?;
11818 return Ok(Step::Continue);
11819 }
11820 // A native callee has no frame to reuse, so its value is simply
11821 // returned.
11822 let value = self.call_value(callee, this, args)?;
11823 return Ok(Step::Return(value));
11824 }
11825
11826 // -- objects ----------------------------------------------------
11827 SpecialObject => {
11828 let value = self.special_object(a)?;
11829 self.push(value);
11830 }
11831 PrivateSymbol => {
11832 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11833 // symbol each time it is evaluated, which is why the compiler evaluates it
11834 // once (at class definition) and stores it in a class-scope binding.
11835 let name = self.atom_text(a as usize);
11836 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11837 self.push(Value::Symbol(symbol));
11838 }
11839 GetPrivateField => {
11840 // `obj symbol -> value`. A missing private field is a TypeError, which is what
11841 // makes `#x` inaccessible on any object not built by this class.
11842 let symbol = self.pop();
11843 let object = self.pop();
11844 let value = self.read_private_field(&object, &symbol)?;
11845 self.push(value);
11846 }
11847 PutPrivateField => {
11848 // `obj value symbol ->`, and the store is a plain assignment to a property the
11849 // class already created, so there is no setter to consult.
11850 let symbol = self.pop();
11851 let value = self.pop();
11852 let object = self.pop();
11853 self.write_private_field(&object, &symbol, value)?;
11854 }
11855 DefinePrivateField => {
11856 // `obj symbol value -> obj`: a field initialiser creates the property, and
11857 // redefining one is a TypeError ("already exists").
11858 let value = self.pop();
11859 let symbol = self.pop();
11860 let object = self.pop();
11861 self.define_private_field(&object, &symbol, value)?;
11862 self.push(object);
11863 }
11864 PrivateIn => {
11865 // `obj key -> bool`: `#x in o`. The second operand decides which question is
11866 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11867 // is a field, so this is an own-property test; a *function* is a method or
11868 // accessor, so this is a brand check.
11869 let key = self.pop();
11870 let object = self.pop();
11871 let Some(target) = object.as_object() else {
11872 return Err(Signal::Throw(
11873 self.make_error("TypeError", "invalid 'in' operand"),
11874 ));
11875 };
11876 let present = match &key {
11877 Value::Object(_) => self.check_brand(target, &key)?,
11878 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11879 };
11880 self.push(Value::Bool(present));
11881 }
11882 AddBrand => {
11883 // `obj home ->`: create the class brand on `home` if it has none, then give
11884 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11885 // class definition: only the prototype's copy of the symbol is wanted.
11886 let home = self.pop();
11887 let object = self.pop();
11888 self.add_brand(&object, &home)?;
11889 }
11890 CheckBrand => {
11891 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11892 // Both stay, because the caller needs them — `nip` halves a read into its
11893 // value and `call_method` uses the pair as receiver and callee.
11894 let function = self.peek(0);
11895 let object = self.peek(1);
11896 let Some(target) = object.as_object() else {
11897 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11898 };
11899 if !self.check_brand(target, &function)? {
11900 return Err(Signal::Throw(
11901 self.make_error("TypeError", "invalid brand on object"),
11902 ));
11903 }
11904 }
11905 GetLength => {
11906 // `get_length` is the `.length` read; an array and a string answer
11907 // from their own length, anything else from the property.
11908 let target = self.pop();
11909 let value = match &target {
11910 Value::Object(object) => match object.array_length() {
11911 Some(length) => crate::object::length_value(length),
11912 None => self.read_field(&target, "length")?,
11913 },
11914 Value::String(text) => Value::Int(text.utf16_len() as i32),
11915 _ => self.read_field(&target, "length")?,
11916 };
11917 self.push(value);
11918 }
11919 GetField | GetField2 => {
11920 let object = self.pop();
11921 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11922 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11923 // just below is what lets the borrow outlive the `&mut self` the lookup
11924 // needs — one refcount bump instead of a key clone plus its drop, on the
11925 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11926 let code = self.frame().code.clone();
11927 let key = &code.atom_keys[a as usize];
11928 let value = self.read_field_cached(&object, key, next)?;
11929 if op == GetField2 {
11930 self.push(object);
11931 }
11932 self.push(value);
11933 }
11934 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11935 let key = self.pop();
11936 let object = self.pop();
11937 // §7.1.1 `GetValue` step 3 orders these two conversions: `ToObject(V.[[Base]])`
11938 // first, then `ToPropertyKey(V.[[ReferencedName]])`. So a nullish base is a
11939 // `TypeError` and the key is **never coerced** — `null[{toString(){throw}}]`
11940 // throws the TypeError, not the key's exception
11941 // (`S11.3.1_A6_T1`). A write has the opposite order, which is why
11942 // `PutArrayEl` deliberately does not do this.
11943 //
11944 // Only nullish is checked here, and the full boxing is still left to
11945 // `read_field_key`: a string base has an index fast path that turning it
11946 // into a `String` object up front would throw away.
11947 if object.is_nullish() {
11948 return Err(Signal::Throw(self.make_error(
11949 "TypeError",
11950 &format!("cannot read property of {}", object.to_js_string()),
11951 )));
11952 }
11953 let key = self.propkey(&key)?;
11954 let value = self.read_field_key(&object, &key)?;
11955 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11956 self.push(object);
11957 }
11958 if op == GetArrayEl3 {
11959 // The key goes back in its *value* form, which the compiler stores
11960 // into the target of a destructuring assignment.
11961 self.push(match &key {
11962 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11963 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11964 });
11965 }
11966 self.push(value);
11967 }
11968 PutField => {
11969 let value = self.pop();
11970 let object = self.pop();
11971 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11972 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11973 // only reads. `this.value = …` is the write half of the hottest loop in
11974 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11975 let code = self.frame().code.clone();
11976 let key = &code.atom_keys[a as usize];
11977 self.write_field_key(&object, key, value)?;
11978 }
11979 PutArrayEl => {
11980 let value = self.pop();
11981 let key = self.pop();
11982 let object = self.pop();
11983 let key = self.propkey(&key)?;
11984 self.write_field_key(&object, &key, value)?;
11985 }
11986 DefineField => {
11987 let value = self.pop();
11988 let object = self.pop();
11989 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11990 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11991 // three U+FFFD — a property under a different name from the one
11992 // `o["\uD800"]` reads.
11993 let code = self.frame().code.clone();
11994 let key = code.atom_keys[a as usize].clone();
11995 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11996 // emits `set_name` — and only where `NamedEvaluation` applies, so
11997 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11998 // reaches a property definition got that case wrong, and the compiler is
11999 // the only place that can tell the two apart.
12000 self.define_field(&object, &key, value)?;
12001 self.push(object);
12002 }
12003 DefineArrayEl => {
12004 // `obj key value -> obj key`. The *value* form of the key is what goes
12005 // back on the stack — the compiler stores it into the pattern's binding —
12006 // so the symbol is not stringified on the way through.
12007 //
12008 // `define_field` and not `write_field_key`: this is `CreateDataProperty`,
12009 // and only the define algorithm gives `{ ['__proto__']: v }` an ordinary
12010 // own property. Going through `[[Set]]` found `Object.prototype`'s
12011 // `__proto__` accessor on the prototype chain and *changed the prototype*
12012 // instead, and it would have called a user setter from a literal
12013 // (`computed-__proto__`, `__proto__-duplicate-computed`).
12014 let value = self.pop();
12015 let key_value = self.pop();
12016 let object = self.peek(0);
12017 let key = self.propkey(&key_value)?;
12018 self.define_field(&object, &key, value)?;
12019 self.push(key_value);
12020 }
12021 SetHomeObject => {
12022 // `obj func -> obj func`: records the object a method was defined on so
12023 // `super` inside it resolves against that object's prototype.
12024 let function = self.peek(0);
12025 let home = self.peek(1);
12026 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
12027 function.set_home_object(Some(home.clone()));
12028 }
12029 }
12030 Regexp => {
12031 // `pattern flags -> regexp`. A literal compiles here rather than through the
12032 // constructor, which is both what the reference's dedicated opcode is for
12033 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
12034 let flags = self.pop();
12035 let pattern = self.pop();
12036 let pattern = self.checked_to_wtf8(&pattern)?;
12037 let flags = self.to_js_string(&flags)?;
12038 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
12039 self.push(Value::Object(object));
12040 }
12041 UsingDisposeInit => {
12042 // The error state a disposal accumulates into. Uninitialised means "no
12043 // failure yet"; anything else is the exception being propagated.
12044 self.push(Value::Uninitialized);
12045 }
12046 UsingCheck => {
12047 // `value -> value, method`: validate and snapshot the disposer now, so a
12048 // later change to `Symbol.dispose` cannot change what gets called, and so a
12049 // value that is not disposable fails before the body runs.
12050 let value = self.pop();
12051 let method = self.using_method_for(&value, a as u8 == 1)?;
12052 self.push(value);
12053 self.push(method);
12054 }
12055 UsingDispose => {
12056 // `error_state -> error_state'`: dispose the variable at `slot` — its value
12057 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
12058 // the pending error.
12059 let slot = self.slot_operand(op, a);
12060 let error_state = self.pop();
12061 let merged = self.using_dispose_once(slot, error_state)?;
12062 self.push(merged);
12063 }
12064 UsingDisposeMerge => {
12065 let new_error = self.pop();
12066 let error_state = self.pop();
12067 let merged = self.merge_dispose_error(new_error, error_state);
12068 self.push(merged);
12069 }
12070 UsingDisposeEnd => {
12071 // A disposal that failed replaces the block's normal completion, so the
12072 // error state becomes a real throw here rather than at the call site.
12073 let error_state = self.pop();
12074 if !matches!(error_state, Value::Uninitialized) {
12075 return Err(Signal::Throw(error_state));
12076 }
12077 }
12078 UsingDisposeAsync => {
12079 // `error_state -> error_state, promise`: the disposer is called here and
12080 // its result wrapped, so the `await` the compiler emits next is what
12081 // actually waits. Calling it and dropping the result lost every failure
12082 // from an `async [Symbol.asyncDispose]` — the rejection had no handler and
12083 // no path back into the error state
12084 // (`throws-error-as-is-if-only-one-error-during-disposal`).
12085 let slot = self.slot_operand(op, a);
12086 let error_state = self.pop();
12087 let value = self.get_loc(slot);
12088 let method = self.get_loc(slot + 1);
12089 let promise = if value.is_nullish()
12090 || matches!(value, Value::Uninitialized)
12091 || matches!(method, Value::Undefined | Value::Uninitialized)
12092 {
12093 // Nothing to dispose: `await undefined` is a no-op, as it is in the
12094 // reference (`sp[0] = JS_UNDEFINED`).
12095 Value::Undefined
12096 } else {
12097 let result = self.call_value(method, value, Vec::new())?;
12098 self.promise_resolve_value(result)?
12099 };
12100 self.push(error_state);
12101 self.push(promise);
12102 }
12103 GetSuper => {
12104 // `obj -> obj's prototype`: the starting point of a `super` lookup.
12105 let object = self.pop();
12106 let proto = match &object {
12107 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
12108 _ => Value::Null,
12109 };
12110 self.push(proto);
12111 }
12112 GetSuperValue => {
12113 // `receiver proto key -> value`, searching from `proto` but reporting to
12114 // `receiver`, which is what `super.g` must do for a getter to see `this`.
12115 //
12116 // Three values in, one out: the receiver is *consumed*, not left under the
12117 // result. Leaving it there was invisible for `super.x` in `return` or
12118 // statement position (the result is what gets popped) and corrupted the
12119 // frame everywhere else — `print(super.x)` left the class where the call
12120 // opcode looks for the receiver and called the class itself.
12121 let key = self.pop();
12122 let proto = self.pop();
12123 let receiver = self.pop();
12124 let value = self.super_read(&receiver, &proto, &key)?;
12125 self.push(value);
12126 }
12127 PutSuperValue => {
12128 // `receiver proto key value ->`: a store that starts at `proto` but
12129 // assigns to `receiver`.
12130 let value = self.pop();
12131 let key = self.pop();
12132 let proto = self.pop();
12133 let receiver = self.pop();
12134 self.super_write(&receiver, &proto, &key, value)?;
12135 }
12136 DefineClass => {
12137 // `parent ctor -> ctor proto`: the constructor becomes the class and a
12138 // fresh prototype object lands on top for the methods to go on.
12139 let name = self.atom_text(a as usize);
12140 let (ctor, proto) = self.define_class(&name, b)?;
12141 self.push(ctor);
12142 self.push(Value::Object(proto));
12143 }
12144 DefineClassComputed => {
12145 // `parent ctor key -> ctor proto key`: the computed name stays put so
12146 // `define_field`-style consumers can still read it.
12147 let key = self.pop();
12148 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12149 let (ctor, proto) = self.define_class(&name, b)?;
12150 self.push(ctor);
12151 self.push(Value::Object(proto));
12152 self.push(key);
12153 }
12154 DefineMethod => {
12155 let function = self.pop();
12156 let object = self.pop();
12157 // The exact key, like `define_field`: a quoted method key may hold an
12158 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
12159 // that `o["\uD800"]` finds.
12160 let code = self.frame().code.clone();
12161 let key = code.atom_keys[a as usize].clone();
12162 // A method's `[[HomeObject]]` is the object it was defined on, which is
12163 // what `super` inside it resolves against.
12164 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12165 function.set_home_object(Some(object.clone()));
12166 }
12167 let name = match key.as_wtf8() {
12168 Some(text) => text.clone(),
12169 // A symbol atom — one of the well-known symbols, which the lexer keeps
12170 // as an atom rather than a runtime value. Its name is the bracketed
12171 // description, like any other symbol key.
12172 None => symbol_key_name(&key),
12173 };
12174 self.set_function_name_wtf8(&function, &accessor_prefixed(&name, b));
12175 if let Some(array) = object.as_object()
12176 && !define_function_property(array, &key, function, b)
12177 {
12178 return Err(self.type_error("property is not configurable"));
12179 }
12180 self.push(object);
12181 }
12182 DefineMethodComputed => {
12183 let function = self.pop();
12184 let key = self.pop();
12185 let object = self.pop();
12186 let key = self.propkey(&key)?;
12187 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
12188 // the name: `super` inside a computed method resolves through it. Without
12189 // this, `class B extends A { [k]() { return super.m() } }` read the
12190 // home object as null and threw.
12191 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12192 function.set_home_object(Some(object.clone()));
12193 }
12194 // A symbol key names the method `[description]`, or `""` without one —
12195 // §7.3.24, the same rule [`Interp::function_name_from_key`] applies to
12196 // `set_name_computed`. Falling back to `to_string` here named every
12197 // `{ [sym](){} }` method `Symbol()` instead.
12198 match &key {
12199 PropertyKey::Symbol(_) => {
12200 // The accessor prefix still applies: `get [Symbol.iterator](){}`
12201 // is named `"get [Symbol.iterator]"`.
12202 let name = accessor_prefixed(&symbol_key_name(&key), a);
12203 self.set_function_name_wtf8(&function, &name);
12204 }
12205 PropertyKey::String(text) => {
12206 let name = accessor_prefixed(text, a);
12207 self.set_function_name_wtf8(&function, &name);
12208 }
12209 }
12210 if let Some(array) = object.as_object()
12211 && !define_function_property(array, &key, function, a)
12212 {
12213 return Err(self.type_error("property is not configurable"));
12214 }
12215 self.push(object);
12216 }
12217 SetProto => {
12218 // `{ __proto__: v }` — §13.2.5.1 step 6: nothing is defined and nothing is
12219 // changed unless `v` is an object or `null`. A primitive was taken as "no
12220 // prototype" instead, so `{ __proto__: undefined }` came out with `null`
12221 // where the answer is an ordinary object
12222 // (`__proto__-value-non-object`).
12223 let proto = self.pop();
12224 let object = self.pop();
12225 if matches!(proto, Value::Null | Value::Object(_))
12226 && let Some(target) = object.as_object()
12227 {
12228 target.set_proto(proto.as_object().cloned());
12229 }
12230 self.push(object);
12231 }
12232 CopyDataProperties => {
12233 let exclusion = self.pop();
12234 let source = self.pop();
12235 let target = self.peek(0);
12236 self.copy_properties(&target, &source, &exclusion)?;
12237 self.push(source);
12238 self.push(exclusion);
12239 }
12240 ToPropkey => {
12241 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12242 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12243 // ordinary `"Symbol(b)"` property.
12244 let value = self.pop();
12245 let key = match self.propkey(&value)? {
12246 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12247 PropertyKey::String(text) => self.string_wtf8(text),
12248 };
12249 self.push(key);
12250 }
12251 SetName => {
12252 let function = self.peek(0);
12253 let name = self.atom_wtf8(a as usize);
12254 self.set_function_name_wtf8(&function, &name);
12255 }
12256 SetNameComputed => {
12257 let key = self.peek(1);
12258 let function = self.peek(0);
12259 let name = self.function_name_from_key(&key)?;
12260 self.set_function_name_wtf8(&function, &name);
12261 }
12262
12263 // -- arrays -----------------------------------------------------
12264 ArrayFrom => {
12265 let count = a as usize;
12266 let elements = self.pop_n(count);
12267 let array = self.new_array(elements);
12268 self.push(Value::Object(array));
12269 }
12270 Append => {
12271 // `array index iterable -> array new_index`
12272 let iterable = self.pop();
12273 self.pop();
12274 let array = self.peek(0);
12275 let added = self.append_enumerate(&array, &iterable)?;
12276 self.push(Value::Int(added));
12277 }
12278
12279 // -- iteration --------------------------------------------------
12280 ForInStart => {
12281 let value = self.pop();
12282 let record = self.for_in_record(&value)?;
12283 self.push(Value::Object(record));
12284 }
12285 ForInNext => {
12286 // `record -> record key done`. The flag is *done*, not "found":
12287 // the compiler tests it with `if_false` to jump back into the body,
12288 // so reporting `true` while keys remain would end the loop at once.
12289 let record = self.peek(0);
12290 match self.for_in_advance(&record)? {
12291 Some(key) => {
12292 let text = self.string(key);
12293 self.push(text);
12294 self.push(Value::Bool(false));
12295 }
12296 None => {
12297 self.push(Value::Undefined);
12298 self.push(Value::Bool(true));
12299 }
12300 }
12301 }
12302 ForOfStart => {
12303 let value = self.pop();
12304 let iterator = self.get_iterator(&value)?;
12305 self.push(iterator.object);
12306 self.push(iterator.next);
12307 self.push(Value::CatchOffset(0));
12308 }
12309 ForOfNext => {
12310 // `iter next catch_offset -> iter next catch_offset value done`.
12311 //
12312 // The operand is how many values sit *above* the iterator triple: a
12313 // destructuring rest element keeps its target array and running index
12314 // there while draining the iterator, so the triple is not at the top.
12315 let extra = a as usize;
12316 let iterator_slot = 2 + extra;
12317 // An exhausted iterator is replaced by `undefined` (see below), so a
12318 // second step must not call `next` again — `Array.from` and a
12319 // destructuring pattern both keep stepping past the end.
12320 let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12321 Ok((Value::Undefined, true))
12322 } else {
12323 let iterator = Iterator {
12324 object: self.peek(iterator_slot),
12325 next: self.peek(1 + extra),
12326 };
12327 self.iterator_step(&iterator)
12328 };
12329 let (value, done) = match stepped {
12330 Ok(stepped) => stepped,
12331 Err(signal) => {
12332 // An exception from `next()` is not an abrupt completion of the
12333 // *body*, so §7.4.6 does not apply and the iterator must not be
12334 // closed: `[ , ] = iterable` with a throwing `next` expects
12335 // `returnCount === 0`. Clearing the slot is how the reference says
12336 // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12337 // returns -1), and it is also what makes the destructor below — the
12338 // exception path's `catch_offset 0` close — a no-op here.
12339 self.clear_iterator_slot(iterator_slot);
12340 return Err(signal);
12341 }
12342 };
12343 if done {
12344 // The result's `value` is meaningless once the iterator is done:
12345 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12346 // rather than binding the generator's return value.
12347 let top = self.frame().stack.len() - 1 - iterator_slot;
12348 self.frame_mut().stack[top] = Value::Undefined;
12349 self.push(Value::Undefined);
12350 self.push(Value::Bool(true));
12351 } else {
12352 self.push(value);
12353 self.push(Value::Bool(false));
12354 }
12355 }
12356 IteratorNext => {
12357 // `iter next catch val -> iter next catch val'`: replace the argument with
12358 // the result of `next(val)`. The triple below stays put, which is why the
12359 // three instructions of the `yield*` loop all address the stack the same way.
12360 let value = self.pop();
12361 let object = self.peek(2);
12362 let next = self.peek(1);
12363 let result = self.call_value(next, object, vec![value])?;
12364 self.push(result);
12365 }
12366 IteratorCall => {
12367 // `iter next catch val -> iter next catch val' flag`.
12368 //
12369 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12370 // The flag is `true` when the method was missing, which is how the
12371 // caller learns that the inner iterator cannot take part in the
12372 // unwinding.
12373 let value = self.pop();
12374 let object = self.peek(2);
12375 let key = if a & 1 != 0 { "throw" } else { "return" };
12376 let method = self.read_field(&object, key)?;
12377 if matches!(method, Value::Undefined | Value::Null) {
12378 self.push(value);
12379 self.push(Value::Bool(true));
12380 } else {
12381 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12382 let result = self.call_value(method, object, argument)?;
12383 self.push(result);
12384 self.push(Value::Bool(false));
12385 }
12386 }
12387 IteratorCheckObject => {
12388 if !matches!(self.peek(0), Value::Object(_)) {
12389 return Err(Signal::Throw(
12390 self.make_error("TypeError", "iterator must return an object"),
12391 ));
12392 }
12393 }
12394 IteratorClose => {
12395 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12396 // calling the iterator's `return` so it can release whatever it holds.
12397 //
12398 // The catch offset goes first, so an exception from `return` is not caught
12399 // by the loop being abandoned. This used to pop the three operands and call
12400 // nothing at all, which made `break` out of a `for of` invisible to an
12401 // iterator with a `return` method.
12402 self.pop();
12403 self.pop();
12404 let iterator = self.pop();
12405 if !matches!(iterator, Value::Undefined) {
12406 let method = self.read_field(&iterator, "return")?;
12407 if !matches!(method, Value::Undefined | Value::Null) {
12408 let result = self.call_value(method, iterator.clone(), Vec::new())?;
12409 // §7.4.6: a `return` that answers a non-object is a TypeError.
12410 if !matches!(result, Value::Object(_)) {
12411 return Err(Signal::Throw(
12412 self.make_error("TypeError", "iterator must return an object"),
12413 ));
12414 }
12415 }
12416 }
12417 }
12418 Import => {
12419 // `import(specifier, options)`: the options slot is on top. Both are
12420 // `GetValue`-ed by the compiler, which is why this pops values rather than
12421 // references — and why the validation of `options` (§13.3.10.1 step 10)
12422 // happens inside `dynamic_import`, where its failures can be turned into a
12423 // rejection instead of a throw.
12424 let options = self.pop();
12425 let specifier = self.pop();
12426 let promise = self.dynamic_import(specifier, options)?;
12427 self.push(promise);
12428 }
12429 ForAwaitOfStart => {
12430 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12431 // `Symbol.iterator` fallback.
12432 let value = self.pop();
12433 let iterator = self.get_async_iterator(&value)?;
12434 self.push(iterator.object);
12435 self.push(iterator.next);
12436 self.push(Value::CatchOffset(0));
12437 }
12438 ForAwaitOfNext => {
12439 // `for await` steps the iterator and leaves the *result* wrapped in a
12440 // promise, so the `await` the compiler emits right after this can suspend
12441 // on it. Unwrapping happens in `iterator_get_value_done`.
12442 let extra = a as usize;
12443 let iterator_slot = 2 + extra;
12444 // The enumerator marker is **disabled for the step**, and
12445 // `iterator_get_value_done` puts it back once the result has survived the
12446 // awaiting. Both halves are load-bearing for the async case:
12447 //
12448 // * a rejection is not "the body threw", so the loop must not close the
12449 // iterator *again* — the wrapper already did;
12450 // * but until the result arrives the record is live, so a later failure
12451 // still has to close it.
12452 //
12453 // The reference says the same in one line each
12454 // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12455 // offset so that exceptions do not close the iterator */`).
12456 self.clear_iterator_slot(extra);
12457 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12458 Value::Undefined
12459 } else {
12460 let iterator = Iterator {
12461 object: self.peek(iterator_slot),
12462 next: self.peek(1 + extra),
12463 };
12464 let next = iterator.next.clone();
12465 self.call_value(next, iterator.object, Vec::new())?
12466 };
12467 let promise = self.promise_resolve_value(result)?;
12468 self.push(promise);
12469 }
12470 IteratorGetValueDone => {
12471 // `result -> value done`. A missing result object means the iterator was
12472 // already exhausted, which the loop treats as `done`.
12473 let result = self.pop();
12474 // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12475 // from here on the record is closeable again.
12476 {
12477 let depth = self.frame().stack.len();
12478 if depth >= 2 {
12479 self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12480 }
12481 }
12482 let done = match &result {
12483 Value::Object(object) => self
12484 .get_property(object, "done")?
12485 .is_some_and(|value| value.to_boolean()),
12486 _ => true,
12487 };
12488 if done {
12489 // Clear the iterator object so the `iterator_close` the loop emits on
12490 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12491 // on normal completion, and this is where a normal completion is
12492 // recognised — the same trick `for_of_next` uses, which also replaces
12493 // the slot with `undefined`.
12494 //
12495 // The layout is fixed because only `for await` emits this opcode:
12496 // `iter next catch [result]`, so the iterator is three below the top.
12497 let depth = self.frame().stack.len();
12498 if depth >= 3 {
12499 self.frame_mut().stack[depth - 3] = Value::Undefined;
12500 }
12501 self.push(Value::Undefined);
12502 self.push(Value::Bool(true));
12503 } else {
12504 let Value::Object(object) = &result else {
12505 self.push(Value::Undefined);
12506 self.push(Value::Bool(true));
12507 return Ok(Step::Continue);
12508 };
12509 let value = self
12510 .get_property(object, "value")?
12511 .unwrap_or(Value::Undefined);
12512 self.push(value);
12513 self.push(Value::Bool(false));
12514 }
12515 }
12516
12517 Delete => {
12518 // `delete obj[key]`, where the key was just pushed. Deleting an array
12519 // index leaves a *hole* rather than closing the gap, and a
12520 // non-configurable property answers `false` and stays.
12521 let key = self.pop();
12522 let target = self.pop();
12523 let key = self.propkey(&key)?;
12524 let text_label = key.as_str().unwrap_or("").to_string();
12525 let deleted = match &target {
12526 Value::Object(object) => {
12527 let object = object.clone();
12528 self.delete_property_key(&object, &key)?
12529 }
12530 // A string's `length` and its index properties are
12531 // non-configurable, so deleting one answers `false`.
12532 Value::String(text) => {
12533 !(text_label == "length"
12534 || array_index(&text_label)
12535 .is_some_and(|index| (index as usize) < text.utf16_len()))
12536 }
12537 // "delete null.a" is a TypeError, not a no-op: the operator needs an
12538 // object to delete from, and only a *boxable* primitive has one.
12539 Value::Undefined | Value::Null => {
12540 return Err(Signal::Throw(
12541 self.make_error("TypeError", "cannot convert to object"),
12542 ));
12543 }
12544 // Any other primitive has no own properties; deleting nothing
12545 // succeeds.
12546 _ => true,
12547 };
12548 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12549 // `TypeError` rather than a `false` result. Sloppy mode silently reports
12550 // the refusal, which is why the same statement throws here but not there.
12551 if !deleted && self.current_strict() {
12552 return Err(Signal::Throw(
12553 self.make_error("TypeError", "cannot delete property"),
12554 ));
12555 }
12556 self.push(Value::Bool(deleted));
12557 }
12558
12559 // -- exceptions and bookkeeping ---------------------------------
12560 Fclosure | Fclosure8 => {
12561 let value = self.closure(a as usize)?;
12562 self.push(value);
12563 }
12564
12565 other => {
12566 let name = other.info().name;
12567 return Err(Signal::Throw(self.make_error(
12568 "InternalError",
12569 &format!("{name} is not implemented yet"),
12570 )));
12571 }
12572 }
12573 Ok(Step::Continue)
12574 }
12575
12576 // -- operand helpers ----------------------------------------------------
12577
12578 /// The slot index an operand names, taking short forms into account.
12579 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12580 use Opcode::*;
12581 match op {
12582 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12583 | SetVarRef0 => 0,
12584 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12585 | SetVarRef1 => 1,
12586 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12587 | SetVarRef2 => 2,
12588 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12589 | SetVarRef3 => 3,
12590 _ => a as usize,
12591 }
12592 }
12593
12594 /// The argument count of a call, taking `call0`…`call3` into account.
12595 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12596 use Opcode::*;
12597 match op {
12598 Call0 => 0,
12599 Call1 => 1,
12600 Call2 => 2,
12601 Call3 => 3,
12602 _ => a as usize,
12603 }
12604 }
12605
12606 /// The atom's name as a property key.
12607 ///
12608 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12609 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12610 /// `String::clone` was a heap allocation and a copy — per property access.
12611 /// The atom at `index`, as a property key.
12612 ///
12613 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12614 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12615 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12616 /// 5.3% of `property:monomorphic`.
12617 /// The atom's text, exactly — including an unpaired surrogate.
12618 ///
12619 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12620 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12621 /// `atom_text` below is for the other kind of use, where the atom is a key in the
12622 /// engine's own tables.
12623 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12624 self.frame()
12625 .code
12626 .code
12627 .atoms
12628 .get(index)
12629 .map(|atom| match atom {
12630 Atom::Str(text) => text.clone(),
12631 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12632 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12633 Atom::Null => crate::value::Wtf8::new(String::new()),
12634 })
12635 .unwrap_or_default()
12636 }
12637
12638 fn atom_text(&self, index: usize) -> String {
12639 self.frame()
12640 .code
12641 .code
12642 .atoms
12643 .get(index)
12644 .map(|atom| match atom {
12645 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12646 // compare it to an identifier, and a surrogate-bearing name is reachable
12647 // through `atom_wtf8` where it matters.
12648 Atom::Str(text) => text.to_string_lossy().into_owned(),
12649 Atom::Index(value) => value.to_string(),
12650 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12651 // `throw_error`, `delete super.x`) never read it.
12652 Atom::Null => String::new(),
12653 })
12654 .unwrap_or_default()
12655 }
12656
12657 fn constant(&mut self, index: usize) -> JsResult<Value> {
12658 let constant = self.frame().code.code.cpool.get(index).cloned();
12659 Ok(match &constant {
12660 Some(Constant::Number(number)) => Value::Float(*number),
12661 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12662 Some(Constant::BigInt { digits, radix }) => {
12663 match crate::bigint::BigInt::from_radix(digits, *radix) {
12664 Some(big) => self.bigint(big),
12665 // A literal the parser accepted is always parseable; a failure here
12666 // would be a compiler bug, so it reads as an `InternalError`.
12667 None => {
12668 return Err(Signal::Throw(
12669 self.make_error("InternalError", "unparseable bigint literal"),
12670 ));
12671 }
12672 }
12673 }
12674 Some(Constant::Function(_)) => {
12675 return Err(Signal::Throw(
12676 self.make_error("InternalError", "a bare function constant"),
12677 ));
12678 }
12679 // A tagged template's call site: a frozen array of the cooked chunks with a
12680 // frozen `raw` array beside it, which is what `String.raw` reads back.
12681 //
12682 // §13.2.8.1 caches it on the realm: `runTemplate()` called twice must hand the
12683 // tag the *same* object, and only a registry gives that. The site is
12684 // (code object, constant index) — see [`Realm::template_map`].
12685 Some(Constant::Template { site, cooked, raw }) => {
12686 // Weakly held, and reaped when the map gets crowded: a program that calls
12687 // `eval` with a tagged template in a loop compiles a fresh site each time,
12688 // and keeping a strong handle would grow this map without bound. Losing an
12689 // expired entry costs nothing — nothing is using the object it named.
12690 if let Some(cached) = self
12691 .realm
12692 .template_map
12693 .get(site)
12694 .and_then(|weak| weak.upgrade())
12695 {
12696 return Ok(Value::Object(cached));
12697 }
12698 let cooked_values: Vec<Value> = cooked
12699 .iter()
12700 .map(|chunk| match chunk {
12701 Some(text) => self.string_wtf8(text.clone()),
12702 None => Value::Undefined,
12703 })
12704 .collect();
12705 let raw_values: Vec<Value> =
12706 raw.iter().map(|text| self.string(text.clone())).collect();
12707 let raw_array = self.new_array(raw_values);
12708 let template = self.new_array(cooked_values);
12709 template.define(
12710 "raw",
12711 Property::with_attributes(Value::Object(raw_array.clone()), false, false),
12712 );
12713 // `SetIntegrityLevel(…, frozen)`, not just a refusal of new properties: the
12714 // template object's indices have to be non-writable and non-configurable, and
12715 // so does `length`. `set_extensible(false)` alone left every index writable,
12716 // which is what `template-object` checks with `verifyProperty`.
12717 // An array of template strings cannot be a proxy, so neither call can be
12718 // refused — `freeze_object` is `?` rather than best-effort on purpose.
12719 crate::builtins::object::freeze_object(self, &raw_array)?;
12720 crate::builtins::object::freeze_object(self, &template)?;
12721 if self.realm.template_map.len() > 256 {
12722 self.realm
12723 .template_map
12724 .retain(|_, weak| weak.upgrade().is_some());
12725 }
12726 self.realm.template_map.insert(*site, template.downgrade());
12727 Value::Object(template)
12728 }
12729 _ => Value::Undefined,
12730 })
12731 }
12732
12733 /// The reference cell a closure-variable slot names.
12734 ///
12735 /// Two kinds of binding share this addressing: a genuine closure variable
12736 /// (captured from an enclosing function) lives in this frame's environment,
12737 /// while a *declared global* lives in the realm so that a script, a function
12738 /// declaration and their uses all see one binding. A plain `Global` — an
12739 /// undeclared name that may be satisfied by the global object — has no cell at
12740 /// all, which is how `typeof x` still works for a name that does not exist.
12741 /// The reference cell a closure-variable slot names.
12742 ///
12743 /// The environment is resolved once, when the closure is built, and this is
12744 /// just the lookup afterwards. A *declared global* is in there too, pointing at
12745 /// the realm's cell, so a script, a hoisted function declaration and their uses
12746 /// all share one binding. A plain `Global` — a name the script never declared —
12747 /// is read and written through `get_var`/`put_var` by name instead, which is
12748 /// what lets the global object satisfy it.
12749 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12750 self.frame().env.cells.get(slot).cloned()
12751 }
12752
12753 /// Whether `slot` refers to a global binding through the reference table.
12754 ///
12755 /// A global's cell in the closure environment only exists so the slot has
12756 /// something to point at; the binding itself lives on the global object (a `var`)
12757 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12758 /// be routed, not performed on the placeholder.
12759 fn is_global_slot(&self, slot: usize) -> bool {
12760 self.frame()
12761 .code
12762 .code
12763 .closure_vars
12764 .get(slot)
12765 .is_some_and(|c| {
12766 // A module's declarations and imports are *not* globals: their cells are
12767 // the module environment's, filled by the host, so the placeholder routing
12768 // must not apply to them.
12769 matches!(
12770 c.closure_type,
12771 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12772 )
12773 })
12774 }
12775
12776 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12777 if self.is_global_slot(slot) {
12778 return self.get_global(slot);
12779 }
12780 Ok(self
12781 .var_ref_cell(slot)
12782 .map(|cell| cell.get())
12783 .unwrap_or(Value::Undefined))
12784 }
12785
12786 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12787 // A function declaration is hoisted by storing into a global reference before
12788 // the body runs, so this path is also what puts it on the global object.
12789 if self.is_global_slot(slot) {
12790 return self.put_global(slot, value);
12791 }
12792 if let Some(cell) = self.var_ref_cell(slot) {
12793 cell.set(value);
12794 }
12795 Ok(())
12796 }
12797
12798 // -- closures -----------------------------------------------------------
12799
12800 /// Build the closure for the function constant `index`.
12801 ///
12802 /// Every entry in the child's closure table names where its binding lives in
12803 /// *this* frame: a local or argument slot that was marked captured, or a cell
12804 /// this frame is itself holding. That is how a variable three functions deep
12805 /// stays one binding.
12806 fn closure(&mut self, index: usize) -> JsResult<Value> {
12807 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12808 else {
12809 return Err(Signal::Throw(
12810 self.make_error("InternalError", "fclosure of a non-function"),
12811 ));
12812 };
12813 let mut cells = Vec::with_capacity(function.closure_vars.len());
12814 for closure_var in &function.closure_vars {
12815 let cell = match closure_var.closure_type {
12816 ClosureType::Arg => {
12817 let slot = closure_var.var_idx as usize;
12818 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12819 }
12820 ClosureType::Local => {
12821 let slot = closure_var.var_idx as usize;
12822 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12823 }
12824 ClosureType::Ref | ClosureType::GlobalRef => {
12825 // A `Ref` names a cell in this frame's own closure table; a
12826 // `GlobalRef` also starts there, then resolves by name below.
12827 let slot = closure_var.var_idx as usize;
12828 if let Some(cell) = self.frame().env.cells.get(slot) {
12829 cells.push(cell.clone());
12830 continue;
12831 }
12832 -1
12833 }
12834 _ => -1,
12835 };
12836 if cell >= 0 {
12837 let cell = self.frame().cells[cell as usize].clone();
12838 cells.push(cell);
12839 continue;
12840 }
12841 // A global: the cell is created on demand and shared through the realm,
12842 // so every function sees one binding.
12843 let name = closure_var.name.clone();
12844 let cell = match self.realm.globals.get(&name) {
12845 Some(cell) => cell.clone(),
12846 None => {
12847 let cell = self.new_cell(Value::Undefined);
12848 self.realm.globals.insert(name.clone(), cell.clone());
12849 cell
12850 }
12851 };
12852 cells.push(cell);
12853 }
12854 let name = function.name.clone();
12855 // `.length` is the arity before any default or rest parameter, not the number
12856 // of slots a pattern parameter needs.
12857 let length = function.defined_args;
12858 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12859 // function and an arrow function do not. A *method* also does not, but that is not
12860 // known here — the method is marked when the `[[HomeObject]]` is attached (see
12861 // `set_home_object`), which is the moment it becomes a method.
12862 let function_kind = function.kind;
12863 let constructible =
12864 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12865 let code = Gc::new(self.heap, CompiledCode::new(*function));
12866 // A closure built inside an `eval` inherits the eval's view of the enclosing
12867 // bindings, so it can still read them once the eval has returned.
12868 let eval_scope = self
12869 .active_eval_scope
12870 .clone()
12871 .or_else(|| self.frame().env.eval_scope.clone());
12872 // A closure sees the variables a direct `eval` declared in the frame it was
12873 // created in — the ones declared before *and after* it, so the same object is
12874 // shared; only the phase bounds which of them are visible.
12875 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12876 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12877 let env = Gc::new(
12878 self.heap,
12879 ClosureEnv {
12880 cells,
12881 eval_scope,
12882 local_vars,
12883 local_phase,
12884 },
12885 );
12886 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12887 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12888 // the only thing that carries `Symbol.toStringTag`, so without it
12889 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12890 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12891 let proto = match function_kind {
12892 js_compile::bytecode::FunctionKind::AsyncGenerator => self
12893 .realm
12894 .async_generator_function_proto
12895 .clone()
12896 .or_else(|| self.realm.function_proto.clone().into()),
12897 js_compile::bytecode::FunctionKind::Generator => self
12898 .realm
12899 .generator_function_proto
12900 .clone()
12901 .or_else(|| self.realm.function_proto.clone().into()),
12902 js_compile::bytecode::FunctionKind::Async => self
12903 .realm
12904 .async_function_proto
12905 .clone()
12906 .or_else(|| self.realm.function_proto.clone().into()),
12907 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12908 };
12909 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12910 object.set_constructible(constructible);
12911 object.define(
12912 "length",
12913 Property::name_or_length(Value::Int(length as i32)),
12914 );
12915 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12916 // that checks the own-property descriptor fails if the property is missing.
12917 object.define("name", Property::name_or_length(self.string(name)));
12918 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12919 // when `[[Construct]]` is created, so an async function and an arrow function have
12920 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12921 // function) an own `prototype` property, which `builtin.js` checks for absence.
12922 //
12923 // A **generator** function is the exception that is not constructible: it still
12924 // gets a `prototype` field, because that object is what a generator *instance*
12925 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12926 // made `function* g(){}; g.prototype` `undefined` and every generator share
12927 // `%GeneratorPrototype%` as its direct prototype.
12928 if constructible {
12929 self.install_function_prototype(&object);
12930 } else if matches!(
12931 function_kind,
12932 js_compile::bytecode::FunctionKind::Generator
12933 | js_compile::bytecode::FunctionKind::AsyncGenerator
12934 ) {
12935 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12936 self.realm.generator_proto.clone()
12937 } else {
12938 self.realm
12939 .async_generator_proto
12940 .clone()
12941 .unwrap_or_else(|| self.realm.generator_proto.clone())
12942 };
12943 self.install_generator_prototype(&object, parent);
12944 }
12945 Ok(Value::Object(object))
12946 }
12947
12948 // -- conversions used by the operators ----------------------------------
12949
12950 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12951 // `+x` is `ToNumber`, which for a string parses it and for an object runs
12952 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12953 // string, which then behaves differently in every later comparison.
12954 match value {
12955 Value::Int(_) | Value::Float(_) => Ok(value),
12956 other => Ok(Value::Float(self.to_js_number(&other)?)),
12957 }
12958 }
12959
12960 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12961 ///
12962 /// Returns the *converted* old value and the new one, because the two callers need
12963 /// different halves: `++x` yields the new value, while `x++` yields the old one and
12964 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12965 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12966 /// boolean.
12967 ///
12968 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12969 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12970 /// a bigint algorithm then ran exactly once.
12971 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12972 if let Value::BigInt(big) = &value {
12973 let one = crate::bigint::BigInt::from_i64(1);
12974 let next = if up { big.add(&one) } else { big.sub(&one) };
12975 return Ok((value, self.bigint(next)));
12976 }
12977 let old = self.numeric_operand(value)?;
12978 if let Value::BigInt(big) = &old {
12979 let one = crate::bigint::BigInt::from_i64(1);
12980 let next = if up { big.add(&one) } else { big.sub(&one) };
12981 return Ok((old, self.bigint(next)));
12982 }
12983 let new = if up {
12984 increment(old.clone())
12985 } else {
12986 decrement(old.clone())
12987 };
12988 Ok((old, new))
12989 }
12990
12991 /// `ToNumeric` for a unary or update operand: `ToPrimitive(number)`, then either branch.
12992 ///
12993 /// The unary operators are defined on `Numeric`, not on `Number`: `-x` and `~x` are
12994 /// `Numeric::unaryMinus`/`bitwiseNOT`, which a bigint answers exactly. [`Interp::numeric`]
12995 /// is `ToNumber` and collapses a bigint to a float, so an operand that is a *wrapper
12996 /// object* — `-Object(5n)` — lost its bigint-ness before the operator ever saw it and
12997 /// raised "cannot convert bigint to number". A primitive bigint never took that path
12998 /// (`Neg`/`Not` matched `Value::BigInt` first), which is why only the boxed form broke.
12999 fn numeric_operand(&mut self, value: Value) -> JsResult<Value> {
13000 let primitive = match value {
13001 Value::Int(_) | Value::Float(_) | Value::BigInt(_) => value,
13002 other => self.to_primitive(other, Hint::Number)?,
13003 };
13004 match primitive {
13005 Value::BigInt(_) => Ok(primitive),
13006 other => self.numeric(other),
13007 }
13008 }
13009
13010 fn numeric(&mut self, value: Value) -> JsResult<Value> {
13011 // `ToNumber` on an object runs `ToPrimitive` first, which is how
13012 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
13013 // heard at all. Reading the object's own tag instead (`other.to_number()`)
13014 // turned the whole operand into `NaN` and swallowed the exception.
13015 match value {
13016 Value::Int(_) | Value::Float(_) => Ok(value),
13017 other => Ok(Value::Float(self.to_js_number(&other)?)),
13018 }
13019 }
13020
13021 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
13022 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
13023 match value {
13024 Value::BigInt(big) => Ok((**big).clone()),
13025 // The reference words this the same way for every operator, so a failing
13026 // script reads identically; the operator itself adds nothing a caller can use.
13027 _ => Err(Signal::Throw(
13028 self.make_error("TypeError", "cannot convert bigint to number"),
13029 )),
13030 }
13031 }
13032
13033 /// Arithmetic where at least one operand is a `BigInt`.
13034 ///
13035 /// The two numeric types never mix, so a bigint paired with anything else is an error
13036 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
13037 /// that the relational operators handle it separately.
13038 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13039 use Opcode::*;
13040 let a = self.bigint_operand(&left)?;
13041 let b = self.bigint_operand(&right)?;
13042 let result = match op {
13043 Add => a.add(&b),
13044 Sub => a.sub(&b),
13045 Mul => a.mul(&b),
13046 Div | Mod => {
13047 let Some((quotient, remainder)) = a.div_rem(&b) else {
13048 return Err(Signal::Throw(
13049 self.make_error("RangeError", "division by zero"),
13050 ));
13051 };
13052 if op == Div { quotient } else { remainder }
13053 }
13054 Pow => {
13055 let Some(value) = a.pow(&b) else {
13056 return Err(Signal::Throw(self.make_error(
13057 "RangeError",
13058 "BigInt exponent must be non-negative and not absurdly large",
13059 )));
13060 };
13061 value
13062 }
13063 And => a.bitand(&b),
13064 Or => a.bitor(&b),
13065 Xor => a.bitxor(&b),
13066 Shl | Sar => {
13067 // A shift count is a `BigInt` here, and both directions are exact; a
13068 // negative count would be the other direction, which the spec forbids.
13069 let Some(count) = b.to_i64() else {
13070 return Err(Signal::Throw(
13071 self.make_error("RangeError", "BigInt shift count is too large"),
13072 ));
13073 };
13074 if count < 0 {
13075 return Err(Signal::Throw(self.make_error(
13076 "RangeError",
13077 "BigInt shift count must be non-negative",
13078 )));
13079 }
13080 if op == Shl {
13081 a.shl(count as u64)
13082 } else {
13083 a.shr(count as u64)
13084 }
13085 }
13086 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
13087 _ => {
13088 return Err(Signal::Throw(self.make_error(
13089 "TypeError",
13090 "BigInts have no unsigned right shift, use >> instead",
13091 )));
13092 }
13093 };
13094 Ok(self.bigint(result))
13095 }
13096
13097 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
13098 ///
13099 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
13100 /// is on the mathematical values, and nothing is rounded first.
13101 /// `<`, `<=`, `>`, `>=`.
13102 ///
13103 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
13104 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
13105 /// It is a `?`-returning function for exactly that reason: an object operand can run
13106 /// script, and script can throw. The old version compared `to_number` of the raw
13107 /// values, which answered `false` for every object instead of calling `valueOf` —
13108 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
13109 /// never ran.
13110 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13111 // The hot arm first: `i < n` with both sides already integers. No conversion, no
13112 // call, nothing that can throw.
13113 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13114 let ordering = Some(left.cmp(right));
13115 return Ok(ordering_answer(op, ordering));
13116 }
13117 // Anything that can run script has to be converted first, in this order.
13118 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
13119 {
13120 (
13121 self.to_primitive(left, Hint::Number)?,
13122 self.to_primitive(right, Hint::Number)?,
13123 )
13124 } else {
13125 (left, right)
13126 };
13127 let ordering = match (&left, &right) {
13128 // The loop condition `i < n` is integer against integer, and it runs once
13129 // per iteration of every loop in every program. Without this arm it took the
13130 // `to_number` path twice, which is a `match` plus a conversion each.
13131 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
13132 // **Code unit** order, not code point order. They differ exactly where a
13133 // surrogate pair meets a BMP character above U+E000: `"\uDC00" > "\uD800"` is
13134 // true because 0xDC00 > 0xD800, while comparing code points would have turned
13135 // both lone surrogates into U+FFFD and called them equal
13136 // (`greater-than/S11.8.2_A4.12_T1`).
13137 (Value::String(a), Value::String(b)) => Some(compare_code_units(a, b)),
13138 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
13139 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
13140 // is true even though `2.5` has no bigint form.
13141 // §7.2.13 step 3.d-3.e: a bigint against a string goes through
13142 // `StringToBigInt`, **not** `ToNumber` — `"9007199254740993" > 9007199254740992n`
13143 // is true because both sides stay exact integers, which converting the string to
13144 // a double would destroy. A string that is not an integer literal makes the
13145 // whole comparison `undefined`, i.e. `false` for every relational operator.
13146 (Value::BigInt(a), Value::String(text)) => {
13147 string_to_bigint(&text.to_string_lossy()).map(|b| a.cmp(&b))
13148 }
13149 (Value::String(text), Value::BigInt(b)) => {
13150 string_to_bigint(&text.to_string_lossy()).map(|a| b.cmp(&a).reverse())
13151 }
13152 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
13153 let b = self.number_operand(other)?;
13154 if b.is_nan() {
13155 None
13156 } else {
13157 compare_bigint_and_f64(a, b)
13158 }
13159 }
13160 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
13161 let a = self.number_operand(other)?;
13162 if a.is_nan() {
13163 None
13164 } else {
13165 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
13166 }
13167 }
13168 // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
13169 // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
13170 // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
13171 _ => self
13172 .to_js_number(&left)?
13173 .partial_cmp(&self.to_js_number(&right)?),
13174 };
13175 Ok(ordering_answer(op, ordering))
13176 }
13177
13178 /// `ToNumber(V)`, refusing a Symbol instead of answering `NaN`.
13179 ///
13180 /// §7.1.4 throws for a Symbol, and the relational operators inherit that: `3n < Symbol()`
13181 /// is a `TypeError`, not `false`. `Value::to_number` is a total function — it has to be,
13182 /// because it is also what `Number(x)` uses — so the check lives here.
13183 fn number_operand(&self, value: &Value) -> JsResult<f64> {
13184 if matches!(value, Value::Symbol(_)) {
13185 return Err(self.type_error("cannot convert symbol to number"));
13186 }
13187 Ok(value.to_number())
13188 }
13189
13190 fn binary_add(&mut self) -> JsResult<()> {
13191 let right = self.pop();
13192 let left = self.pop();
13193 // Two integers add without any of the machinery below: no `ToPrimitive` (an
13194 // `Int` is already primitive), no string check, no bigint check, no allocation.
13195 // `x += 1` in a loop is the single most common instruction sequence in real
13196 // script, and it used to walk every one of those checks before reaching the
13197 // same `checked_add`.
13198 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13199 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
13200 return Ok(());
13201 }
13202 let left = self.primitive_of(left)?;
13203 let right = self.primitive_of(right)?;
13204 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
13205 // that check comes before the bigint one: `"" + 1n` is a string, not a
13206 // mixed-type error.
13207 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
13208 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
13209 // `TypeError`, the one place a symbol and a string do not mix.
13210 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
13211 // between a copy and a rope from their lengths, and a rope is what turns
13212 // `text += "abc"` in a loop from quadratic into linear.
13213 if let (Value::String(left), Value::String(right)) = (&left, &right) {
13214 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
13215 // reports as `InternalError: string too long`.
13216 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
13217 return Err(Signal::Throw(
13218 self.make_error("InternalError", "string too long"),
13219 ));
13220 };
13221 self.push(Value::String(Gc::new(self.heap, joined)));
13222 return Ok(());
13223 }
13224 // At least one operand was not a string, so `ToString` it. This rejects a
13225 // symbol, which is the one place a symbol and a string do not mix.
13226 let left = self.checked_to_wtf8(&left)?;
13227 let right = self.checked_to_wtf8(&right)?;
13228 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
13229 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
13230 let text = left.concat(&right);
13231 self.push(self.string_wtf8(text));
13232 return Ok(());
13233 }
13234 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
13235 // not a conversion.
13236 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
13237 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
13238 self.push(value);
13239 return Ok(());
13240 }
13241 let left = self.numeric(left)?;
13242 let right = self.numeric(right)?;
13243 self.push(add_numbers(left, right));
13244 Ok(())
13245 }
13246
13247 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
13248 self.to_primitive(value, Hint::Default)
13249 }
13250
13251 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
13252 ///
13253 /// The order depends on the hint: the "number" order tries `valueOf` first and
13254 /// `toString` second, the "string" order the other way round, and the default
13255 /// hint uses the number order. A result that is still an object is a `TypeError`,
13256 /// because no built-in `valueOf`/`toString` returns one.
13257 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
13258 let Value::Object(object) = &value else {
13259 return Ok(value);
13260 };
13261 // A Date overrides the default hint to mean "string", which is what
13262 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
13263 // this, `"" + new Date()` would print the milliseconds, not the date.
13264 let hint = if hint == Hint::Default && is_date_object(self, object) {
13265 Hint::String
13266 } else {
13267 hint
13268 };
13269 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
13270 // handed the hint as a string. This is the hook a Date uses for its default hint
13271 // and a script uses to take over conversion entirely.
13272 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
13273 // `GetMethod`, not "is it a callable object": the property has to be read and then
13274 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
13275 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
13276 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
13277 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
13278 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
13279 // callable.
13280 match self.get_property_key(object, &key)? {
13281 None | Some(Value::Undefined) | Some(Value::Null) => {}
13282 Some(Value::Object(function)) if function.is_callable() => {
13283 let hint = match hint {
13284 Hint::String => "string",
13285 Hint::Number => "number",
13286 Hint::Default => "default",
13287 };
13288 let hint = self.string(hint);
13289 let result = self.call_value(
13290 Value::Object(function),
13291 Value::Object(object.clone()),
13292 vec![hint],
13293 )?;
13294 if !matches!(result, Value::Object(_)) {
13295 return Ok(result);
13296 }
13297 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
13298 }
13299 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
13300 }
13301 let order: [&str; 2] = match hint {
13302 Hint::String => ["toString", "valueOf"],
13303 Hint::Number | Hint::Default => ["valueOf", "toString"],
13304 };
13305 let receiver = object.clone();
13306 for method in order {
13307 if let Some(function) = self.get_property(&receiver, method)?
13308 && matches!(&function, Value::Object(object) if object.is_callable())
13309 {
13310 let result =
13311 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13312 if !matches!(result, Value::Object(_)) {
13313 return Ok(result);
13314 }
13315 }
13316 }
13317 Err(self.type_error("cannot convert object to primitive value"))
13318 }
13319
13320 /// `ToString` with the object case going through `ToPrimitive`.
13321 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13322 if matches!(value, Value::Object(_)) {
13323 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13324 return Ok(primitive.to_js_string());
13325 }
13326 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13327 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13328 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13329 // check here broke `String(Symbol())` and 45 cases that print a symbol.
13330 Ok(value.to_js_string())
13331 }
13332
13333 /// `ToString(value)`, with §7.1.19's symbol refusal.
13334 ///
13335 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13336 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13337 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13338 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13339 if matches!(value, Value::Symbol(_)) {
13340 return Err(self.type_error("cannot convert a Symbol to a string"));
13341 }
13342 if matches!(value, Value::Object(_)) {
13343 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13344 if matches!(primitive, Value::Symbol(_)) {
13345 return Err(self.type_error("cannot convert a Symbol to a string"));
13346 }
13347 return Ok(primitive.to_js_string());
13348 }
13349 Ok(value.to_js_string())
13350 }
13351
13352 /// `ToString` that keeps the string's code units instead of flattening them.
13353 ///
13354 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13355 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13356 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13357 if matches!(value, Value::Symbol(_)) {
13358 return Err(Signal::Throw(
13359 self.make_error("TypeError", "cannot convert symbol to string"),
13360 ));
13361 }
13362 // An object runs `ToPrimitive` first, which may itself produce a symbol.
13363 let value = self.to_primitive(value.clone(), Hint::String)?;
13364 match value {
13365 Value::Symbol(_) => Err(Signal::Throw(
13366 self.make_error("TypeError", "cannot convert symbol to string"),
13367 )),
13368 Value::String(text) => Ok(text.wtf8().clone()),
13369 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13370 }
13371 }
13372
13373 /// `ToNumber` with the object case going through `ToPrimitive`.
13374 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13375 let value = if matches!(value, Value::Object(_)) {
13376 self.to_primitive(value.clone(), Hint::Number)?
13377 } else {
13378 value.clone()
13379 };
13380 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13381 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13382 // `NaN` to stay total, and the operators check for the bigint themselves — but
13383 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13384 // refuse, and answering `NaN` made them silently wrong instead.
13385 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13386 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13387 match value {
13388 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13389 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13390 other => Ok(other.to_number()),
13391 }
13392 }
13393
13394 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13395 /// [`ElementType::write`].
13396 ///
13397 /// This is separated from the write because both conversions are observable script —
13398 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13399 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13400 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13401 /// setters, and a plain `a[i] = v`.
13402 pub(crate) fn element_value(
13403 &mut self,
13404 element: crate::builtins::typedarray::ElementType,
13405 value: Value,
13406 ) -> JsResult<Value> {
13407 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13408 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13409 let primitive = match &value {
13410 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13411 _ => value,
13412 };
13413 if element.is_bigint() {
13414 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13415 Ok(Value::BigInt(Gc::new(self.heap, big)))
13416 } else {
13417 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13418 Ok(Value::Float(self.to_js_number(&primitive)?))
13419 }
13420 }
13421
13422 /// `ToPropertyKey`: what a computed member access uses as its key.
13423 ///
13424 /// A symbol is returned as itself, never stringified — that is what keeps
13425 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13426 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13427 match value {
13428 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13429 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13430 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13431 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13432 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13433 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13434 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13435 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13436 other.to_js_string(),
13437 ))),
13438 },
13439 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13440 }
13441 }
13442
13443 /// `ToPropertyKey` for the callers that can only use a string key.
13444 ///
13445 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13446 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13447 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13448 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13449 /// program continues with a value nobody asked for.
13450 /// `SetFunctionName`'s name for a computed key, which is not `ToPropertyKey`.
13451 ///
13452 /// §7.3.24 step 1: when the key is a **Symbol**, the name is `"[" + description + "]"`
13453 /// — or the empty string when the symbol has no description. Going through
13454 /// `ToPropertyKey` instead gave `Symbol(test262)` and `Symbol()`, so every
13455 /// `{ [sym](){} }` method had the wrong `name` (`fn-name-fn` and its generated
13456 /// relatives, in both `expressions/object` and `statements/class`).
13457 ///
13458 /// Everything else is an ordinary `ToPropertyKey` — a string key keeps its code units,
13459 /// which is what makes `{ "\uD800": function () {} }.name` the lone surrogate.
13460 fn function_name_from_key(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13461 if let Value::Symbol(symbol) = value {
13462 return Ok(match symbol.description() {
13463 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
13464 None => crate::value::Wtf8::default(),
13465 });
13466 }
13467 self.propkey_of(value)
13468 }
13469
13470 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13471 use crate::value::Wtf8;
13472 Ok(match value {
13473 // A string key keeps its code units. Going through a lossy `String` would make
13474 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13475 Value::String(text) => text.wtf8().clone(),
13476 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13477 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13478 // falling back to its `ToString` would print `[object Object]`.
13479 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13480 Value::String(text) => text.wtf8().clone(),
13481 other => Wtf8::new(other.to_js_string()),
13482 },
13483 other => Wtf8::new(other.to_js_string()),
13484 })
13485 }
13486
13487 // -- object operations used by instructions -----------------------------
13488
13489 /// Read `object[key]`, returning `undefined` when the property is missing.
13490 ///
13491 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13492 /// primitive (looking through its prototype) as well as an object — which is what
13493 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13494 /// argument needs too.
13495 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13496 self.read_field_key(object, &PropertyKey::from(key))
13497 }
13498
13499 /// [`Interp::read_field`] with a key that may be a symbol.
13500 ///
13501 /// A symbol key never reaches the string shortcuts: a string's `length` and its
13502 /// indices are string properties, and a symbol named `length` is a different
13503 /// property that a string primitive cannot have.
13504 /// [`Interp::read_field_key`], with an inline cache in front of it.
13505 ///
13506 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13507 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13508 /// without this the engine walked the chain and compared ~40 property names on each
13509 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13510 ///
13511 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13512 /// missing property. Those answers depend on running code or on state the guard below
13513 /// does not cover, and a wrong answer here is far more expensive than a lookup.
13514 ///
13515 /// A hit is re-validated against the *whole* walked chain, not just the level that
13516 /// answered: the receiver and every prototype down to that level must still be the same
13517 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13518 /// property-table *lengths* — which is what catches a property appearing on an
13519 /// intermediate prototype and shadowing the cached one.
13520 pub fn read_field_cached(
13521 &mut self,
13522 object: &Value,
13523 key: &PropertyKey,
13524 slot: usize,
13525 ) -> JsResult<Value> {
13526 let index = Self::field_cache_slot(object, key, slot);
13527 let Value::Object(target) = object else {
13528 return self.read_field_key(object, key);
13529 };
13530 if target.proxy_state().is_some() {
13531 return self.read_field_key(object, key);
13532 }
13533 if let Some(cached) = &self.field_cache[index]
13534 && cached.key == *key
13535 && let Some(value) = Self::cached_hit(target, cached)
13536 {
13537 return Ok(value);
13538 }
13539 let value = self.read_field_key(object, key)?;
13540 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13541 Ok(value)
13542 }
13543
13544 /// Whether a cache entry still describes this lookup, and if so the value.
13545 ///
13546 /// The guard is the whole point of the entry: identity plus property-table length for
13547 /// every level walked. Re-checked per level rather than once at the receiving end,
13548 /// because a shadowing property can appear anywhere along the chain.
13549 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13550 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13551 // starts with: a clone is a reference-count bump and a drop, and for
13552 // `property:monomorphic` every single hit takes only this arm.
13553 let (weak, len) = cached.chain[0].as_ref()?;
13554 if !target.upgrades_to(weak) {
13555 return None;
13556 }
13557 if cached.level == 0 {
13558 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13559 return target.cached_property_at(cached.index, &cached.key, *len);
13560 }
13561 if target.props_len() != *len {
13562 return None;
13563 }
13564 let mut level = 1;
13565 let mut current = target.proto()?;
13566 loop {
13567 let (weak, len) = cached.chain[level].as_ref()?;
13568 if !current.upgrades_to(weak) || current.props_len() != *len {
13569 return None;
13570 }
13571 if level == cached.level as usize {
13572 // The level that answered: the value is only reusable while the key is
13573 // still there and still a plain data property.
13574 return current.cached_data_property(cached.index, &cached.key);
13575 }
13576 current = current.proto()?;
13577 level += 1;
13578 }
13579 }
13580
13581 /// Build a cache entry for a lookup that just went through the slow path.
13582 ///
13583 /// Records the chain only when the answer came from a plain data property at a level
13584 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13585 /// costs the next lookup the walk it would have cost anyway.
13586 fn record_field_lookup(
13587 target: &Gc<JsObject>,
13588 key: &PropertyKey,
13589 _value: Value,
13590 ) -> Option<FieldCache> {
13591 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13592 [None, None, None];
13593 let mut current = target.clone();
13594 for level in 0..MAX_CACHED_CHAIN {
13595 chain[level] = Some((current.downgrade(), current.props_len()));
13596 if let Some((found, _)) = current.own_property_index(key) {
13597 // `own_property_index` declines an accessor and a hole, which is exactly
13598 // the set that must not be cached.
13599 return Some(FieldCache {
13600 key: key.clone(),
13601 index: found,
13602 level: level as u8,
13603 chain,
13604 });
13605 }
13606 current = current.proto()?;
13607 }
13608 None
13609 }
13610
13611 /// Which cache slot a lookup uses.
13612 ///
13613 /// Mixes the object's address, the name and the site, so that two properties of one
13614 /// object, and one property of two objects, land in different slots — which is what lets
13615 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13616 /// other iteration.
13617 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13618 let mut hash = match object {
13619 Value::Object(object) => object.address(),
13620 _ => 0,
13621 };
13622 hash = hash
13623 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13624 .rotate_left(17)
13625 .wrapping_add(key.hash_code());
13626 hash = hash.wrapping_add(site.wrapping_mul(31));
13627 // The table is a power of two, so the low bits are the slot.
13628 hash & (FIELD_CACHE_SLOTS - 1)
13629 }
13630
13631 /// Read `key` from `object`, without the inline cache.
13632 ///
13633 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13634 /// prototype chain, while the cached form answers an own data property from memory.
13635 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13636 let text = key.as_str().unwrap_or("");
13637 let Value::Object(object) = object else {
13638 // Reading a property of `undefined`/`null` is the classic TypeError.
13639 if object.is_nullish() {
13640 return Err(Signal::Throw(self.make_error(
13641 "TypeError",
13642 &format!("cannot read property '{key}' of {}", object.to_js_string()),
13643 )));
13644 }
13645 // A string has `length` and index access without being boxed.
13646 if let Value::String(value) = object {
13647 if text == "length" {
13648 return Ok(Value::Int(value.utf16_len() as i32));
13649 }
13650 if let Some(index) = array_index(text) {
13651 return Ok(match value.wtf8().unit_at(index as usize) {
13652 Some(unit) => self.string_wtf8(unit),
13653 None => Value::Undefined,
13654 });
13655 }
13656 }
13657 // A property of a primitive is looked up on its prototype: this is what
13658 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13659 let prototype = match object {
13660 Value::String(_) => self.realm.string_proto.clone(),
13661 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13662 Value::Bool(_) => self.realm.boolean_proto.clone(),
13663 // A symbol's methods live on `Symbol.prototype`, reached the same way —
13664 // `sym.description` reads through the prototype, not off the symbol.
13665 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13666 // …and a bigint's on `BigInt.prototype`, which is how
13667 // `(255n).toString(16)` reaches its method.
13668 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13669 _ => None,
13670 };
13671 if let Some(prototype) = prototype
13672 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13673 {
13674 return Ok(value);
13675 }
13676 return Ok(Value::Undefined);
13677 };
13678 Ok(self
13679 .get_property_key(object, key)?
13680 .unwrap_or(Value::Undefined))
13681 }
13682
13683 /// The `#name` a private symbol stands for, for error messages.
13684 ///
13685 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13686 /// was made from.
13687 fn private_name(symbol: &Value) -> Option<String> {
13688 match symbol {
13689 Value::Symbol(symbol) if symbol.is_private() => Some(
13690 symbol
13691 .description()
13692 .map(|text| text.to_string())
13693 .unwrap_or_default(),
13694 ),
13695 _ => None,
13696 }
13697 }
13698
13699 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
13700 ///
13701 /// Every private-field opcode takes the symbol the class stored in its own scope; a
13702 /// non-symbol here would be a compiler bug, and the reference guards it with
13703 /// `JS_ThrowTypeErrorNotASymbol`.
13704 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
13705 match symbol {
13706 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
13707 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
13708 }
13709 }
13710
13711 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
13712 ///
13713 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
13714 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
13715 /// would hit if the parser did not reject it first.
13716 fn define_private_field(
13717 &mut self,
13718 object: &Value,
13719 symbol: &Value,
13720 value: Value,
13721 ) -> JsResult<()> {
13722 let key = self.private_key(symbol)?;
13723 let Some(target) = object.as_object() else {
13724 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13725 };
13726 if !target.is_extensible() {
13727 return Err(Signal::Throw(
13728 self.make_error("TypeError", "object is not extensible"),
13729 ));
13730 }
13731 if target.own_property_key(&key).is_some() {
13732 let name = Self::private_name(symbol).unwrap_or_default();
13733 return Err(Signal::Throw(self.make_error(
13734 "TypeError",
13735 &format!("private class field '{name}' already exists"),
13736 )));
13737 }
13738 target.define_data_key(&key, value);
13739 Ok(())
13740 }
13741
13742 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
13743 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
13744 let key = self.private_key(symbol)?;
13745 let Some(target) = object.as_object() else {
13746 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13747 };
13748 match target.own_property_key(&key) {
13749 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
13750 None => {
13751 let name = Self::private_name(symbol).unwrap_or_default();
13752 Err(Signal::Throw(self.make_error(
13753 "TypeError",
13754 &format!("private class field '{name}' does not exist"),
13755 )))
13756 }
13757 }
13758 }
13759
13760 /// `JS_SetPrivateField`: the store half of the same rule.
13761 fn write_private_field(
13762 &mut self,
13763 object: &Value,
13764 symbol: &Value,
13765 value: Value,
13766 ) -> JsResult<()> {
13767 let key = self.private_key(symbol)?;
13768 let Some(target) = object.as_object() else {
13769 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13770 };
13771 if target.write_value_key(&key, value) {
13772 return Ok(());
13773 }
13774 let name = Self::private_name(symbol).unwrap_or_default();
13775 Err(Signal::Throw(self.make_error(
13776 "TypeError",
13777 &format!("private class field '{name}' does not exist"),
13778 )))
13779 }
13780
13781 /// The `in` half: does `object` have this private field?
13782 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
13783 ///
13784 /// The symbol is created once per class — the first `add_brand` on a given home object
13785 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
13786 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
13787 /// emit for the *instance* brand passes null because all it wants is the symbol.
13788 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
13789 let Some(home_object) = home.as_object() else {
13790 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13791 };
13792 let symbol = match home_object.private_brand() {
13793 Some(symbol) => symbol,
13794 None => {
13795 let symbol = Gc::new(
13796 self.heap,
13797 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13798 );
13799 home_object.set_private_brand(symbol.clone());
13800 symbol
13801 }
13802 };
13803 let Some(target) = object.as_object() else {
13804 // Not an object: nothing to brand. The reference does the same, and `undefined`
13805 // here would otherwise turn a field initialiser into a TypeError.
13806 return Ok(());
13807 };
13808 if !target.is_extensible() {
13809 return Err(Signal::Throw(
13810 self.make_error("TypeError", "object is not extensible"),
13811 ));
13812 }
13813 if target.carries_brand(&symbol) {
13814 return Err(Signal::Throw(
13815 self.make_error("TypeError", "private method is already present"),
13816 ));
13817 }
13818 target.add_brand(symbol);
13819 Ok(())
13820 }
13821
13822 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13823 ///
13824 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13825 /// decides whether to throw.
13826 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13827 let Some(function) = function.as_object() else {
13828 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13829 };
13830 let Some(home) = function.home_object() else {
13831 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13832 };
13833 let Some(brand) = home.private_brand() else {
13834 return Err(Signal::Throw(
13835 self.make_error("TypeError", "expecting <brand> private field"),
13836 ));
13837 };
13838 Ok(object.carries_brand(&brand))
13839 }
13840
13841 /// `CreateDataPropertyOrThrow(object, key, value)` — §7.3.3.
13842 ///
13843 /// What a property definition does: `[[DefineOwnProperty]]` with all three attributes
13844 /// true. Not `[[Set]]`, which walks the prototype chain and may run a setter there.
13845 fn define_field(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13846 if let Some(target) = object.as_object() {
13847 // `CreateDataProperty` cannot reshape a non-configurable own property: its
13848 // descriptor asks for `writable` and `configurable`, and a non-configurable
13849 // property may become neither (`class C { static ['prototype'] = 1 }` is a
13850 // `TypeError`, since the constructor's `prototype` is both). The general define
13851 // path only validates *partial* descriptors — see the note there — so this has
13852 // to be said here.
13853 if self
13854 .object_get_own_property(target, key)?
13855 .is_some_and(|existing| {
13856 !existing.configurable && (existing.is_accessor() || !existing.writable)
13857 })
13858 {
13859 return Err(Signal::Throw(self.make_error(
13860 "TypeError",
13861 &format!(
13862 "cannot define property '{key}' of {}",
13863 Value::Object(target.clone()).to_js_string()
13864 ),
13865 )));
13866 }
13867 // Only an *array* stores into the element vector. A numeric key
13868 // on an ordinary object is an ordinary property, which is what
13869 // makes `{1: 'a'}` iterate as a key rather than disappear.
13870 let stored = target.is_array()
13871 && key.as_str().and_then(array_index).is_some_and(|index| {
13872 target.array_set(self.heap, index as usize, value.clone())
13873 });
13874 if !stored {
13875 // `CreateDataPropertyOrThrow`, not a raw table insert: a class
13876 // field is defined with `[[DefineOwnProperty]]`, so a frozen
13877 // receiver throws (`class Test { f = Object.freeze(this); g = 1 }`
13878 // must fail on `g`) and a **proxy** receiver runs its
13879 // `defineProperty` trap (`class-field-is-observable-by-proxy`
13880 // counts the trap's calls). `define_data_key` writes straight into
13881 // the table, which did neither.
13882 // `?` and not `unwrap_or(false)`: a proxy's `defineProperty` trap
13883 // may *throw*, and that exception is the answer
13884 // (`public-class-field-initialization-is-visible-to-proxy` throws
13885 // a `Test262Error` from the trap and expects it, not a `TypeError`).
13886 let defined =
13887 self.object_define_own_property(target, key, Property::data(value))?;
13888 if !defined {
13889 let target = Value::Object(target.clone());
13890 return Err(Signal::Throw(self.make_error(
13891 "TypeError",
13892 &format!(
13893 "cannot define property '{key}' of {}",
13894 target.to_js_string()
13895 ),
13896 )));
13897 }
13898 }
13899 }
13900 Ok(())
13901 }
13902
13903 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13904 let Value::Object(object) = object else {
13905 // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13906 // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13907 // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13908 // `undefined` still throw, with their own message.
13909 if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13910 return Ok(());
13911 }
13912 return Err(Signal::Throw(self.make_error(
13913 "TypeError",
13914 &format!("cannot set property '{key}' of {}", object.to_js_string()),
13915 )));
13916 };
13917 // The write half of the property inline cache, in effect: an own, writable,
13918 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13919 // decide — no prototype walk (an own property shadows the chain before a setter
13920 // there could matter), no extensibility check (the object already has the key),
13921 // and no `[[DefineOwnProperty]]`.
13922 //
13923 // `this.value = …` inside a method is the whole write side of
13924 // `property:method-call`, and it was reaching `set_property_with_key` with its
13925 // proxy test, its typed-array test, its array-index test and finally a linear
13926 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13927 //
13928 // Every disqualifier is checked here: a proxy traps the set, an array index and
13929 // `length` live outside the property table, and a typed array's element is stored
13930 // through its view's element type.
13931 if object.proxy_state().is_none()
13932 && !object.is_array()
13933 && object.typed_array_element_type().is_none()
13934 && object.write_value_key(key, value.clone())
13935 {
13936 return Ok(());
13937 }
13938 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13939 let on_failure = if self.frame().code.code.strict {
13940 DeleteFailure::Throw
13941 } else {
13942 DeleteFailure::Ignore
13943 };
13944 self.set_property_with_key(object, key, value, on_failure)
13945 }
13946
13947 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13948 ///
13949 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13950 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13951 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13952 /// `Number.parseInt(sym)` — so those callers use this instead.
13953 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13954 if matches!(value, Value::Symbol(_)) {
13955 return Err(Signal::Throw(
13956 self.make_error("TypeError", "cannot convert symbol to string"),
13957 ));
13958 }
13959 // An object runs `ToPrimitive` first, which may itself produce a symbol —
13960 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13961 let value = self.to_primitive(value.clone(), Hint::String)?;
13962 if matches!(value, Value::Symbol(_)) {
13963 return Err(Signal::Throw(
13964 self.make_error("TypeError", "cannot convert symbol to string"),
13965 ));
13966 }
13967 Ok(value.to_js_string())
13968 }
13969
13970 /// `ToPropertyKey` for a builtin that takes a key argument.
13971 ///
13972 /// Fallible: a key whose `toString` throws has to propagate that error, both for
13973 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13974 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13975 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13976 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13977 self.propkey(value)
13978 }
13979
13980 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13981 ///
13982 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13983 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13984 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13985 /// `RangeError` — and why this cannot be a plain `ToNumber`.
13986 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13987 ///
13988 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13989 /// then a `RangeError` when they disagree. Two conversions rather than one is
13990 /// observable: a `valueOf` that runs the first time can make `length` non-writable
13991 /// before the second, which turns the store into a refused write
13992 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13993 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13994 let first = self.array_length_of(value)?;
13995 let second = self.array_length_of(value)?;
13996 debug_assert_eq!(first, second);
13997 Ok(first)
13998 }
13999
14000 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
14001 ///
14002 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
14003 /// conversion can say so; a caller that needs the spec's two uses that instead.
14004 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
14005 let number = match value {
14006 Value::Int(number) => *number as f64,
14007 Value::Float(number) => *number,
14008 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
14009 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
14010 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
14011 // reference answers 0.
14012 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
14013 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
14014 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
14015 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
14016 _ => {
14017 // The primitive comes back through this same conversion, so a wrapper of a
14018 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
14019 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
14020 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
14021 return self.array_length_of(&primitive);
14022 }
14023 };
14024 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
14025 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
14026 // is a `RangeError`, not `0`.
14027 if !number.is_finite()
14028 || number.fract() != 0.0
14029 || !(0.0..=u32::MAX as f64).contains(&number)
14030 {
14031 return Err(self.range_error("invalid array length"));
14032 }
14033 Ok(number as u32)
14034 }
14035
14036 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
14037 /// `Object.getOwnPropertySymbols` put in their result array.
14038 pub fn key_value(&self, key: &PropertyKey) -> Value {
14039 match key {
14040 PropertyKey::String(text) => self.string_wtf8(text.clone()),
14041 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
14042 }
14043 }
14044
14045 /// Fill in a String exotic object: `_value`, `length` and the index properties.
14046 ///
14047 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
14048 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
14049 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
14050 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
14051 /// the two paths had drifted; this is the one both now use.
14052 ///
14053 /// The indices are *code units*, so an astral character occupies two of them — the
14054 /// same rule `s.length` and `s[i]` follow.
14055 /// Give an already-created object the internal slot that makes it a wrapper of
14056 /// `value`, so the primitive's prototype methods work on it.
14057 ///
14058 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
14059 /// which are wrappers of their own type holding the empty value.
14060 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
14061 self.internal_set(object, "_value", value);
14062 }
14063
14064 pub(crate) fn init_string_wrapper(
14065 &mut self,
14066 object: &Gc<JsObject>,
14067 text: &Gc<crate::value::JsString>,
14068 ) {
14069 object.define(
14070 "length",
14071 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
14072 );
14073 for index in 0..text.utf16_len() {
14074 if let Some(unit) = text.wtf8().unit_at(index) {
14075 object.define(
14076 &index.to_string(),
14077 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
14078 Property::with_attributes(self.string_wtf8(unit), false, true),
14079 );
14080 }
14081 }
14082 object.define_key(
14083 &self.internal_slot("_value"),
14084 Property::with_attributes(Value::String(text.clone()), false, false),
14085 );
14086 }
14087
14088 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
14089 ///
14090 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
14091 /// throws. The wrapper carries its primitive in `_value` — the same slot
14092 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
14093 /// on a boxed value no constructor ever built.
14094 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14095 let (prototype, primitive) = match value {
14096 Value::Object(object) => return Ok(object.clone()),
14097 Value::String(text) => {
14098 let object = self.new_object(self.realm.string_proto.clone());
14099 self.init_string_wrapper(&object, text);
14100 return Ok(object);
14101 }
14102 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
14103 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
14104 // A symbol and a bigint box into wrappers whose methods live on
14105 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
14106 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
14107 // branch below instead produced an object with *no* prototype, so those
14108 // methods were unreachable on a box.
14109 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
14110 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
14111 Value::Undefined | Value::Null => {
14112 return Err(Signal::Throw(self.make_error(
14113 "TypeError",
14114 &format!("cannot convert {} to object", value.to_js_string()),
14115 )));
14116 }
14117 _ => (None, value.clone()),
14118 };
14119 let object = self.new_object(prototype);
14120 self.internal_set(&object, "_value", primitive);
14121 Ok(object)
14122 }
14123
14124 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
14125 ///
14126 /// Split out for a reader that has to create the object *before* it knows what it wraps:
14127 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
14128 /// written before its primitive, so the placeholder has to exist first and be filled in
14129 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
14130 /// than a second in the deserialiser.
14131 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
14132 let prototype = match value {
14133 Value::String(_) => self.realm.string_proto.clone(),
14134 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14135 Value::Bool(_) => self.realm.boolean_proto.clone(),
14136 Value::Symbol(_) => self.realm.symbol_proto.clone(),
14137 Value::BigInt(_) => self.realm.bigint_proto.clone(),
14138 _ => {
14139 return Err(Signal::Throw(self.make_error(
14140 "TypeError",
14141 &format!("cannot box {}", value.to_js_string()),
14142 )));
14143 }
14144 };
14145 object.set_proto(prototype);
14146 if let Value::String(text) = value {
14147 self.init_string_wrapper(object, text);
14148 return Ok(());
14149 }
14150 self.internal_set(object, "_value", value.clone());
14151 Ok(())
14152 }
14153
14154 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
14155 ///
14156 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
14157 /// through the `Symbol` function object, so the registry is reachable as a method rather
14158 /// than only from `builtins::symbol`.
14159 pub fn symbol_for(&mut self, key: &str) -> Value {
14160 if let Some(existing) = self.realm.symbol_registry.get(key) {
14161 return existing.clone();
14162 }
14163 let symbol = crate::builtins::symbol::symbol_value(
14164 self,
14165 crate::value::JsSymbol::registered(key.to_string()),
14166 );
14167 self.realm
14168 .symbol_registry
14169 .insert(key.to_string(), symbol.clone());
14170 symbol
14171 }
14172
14173 /// `a == b`, the coercing comparison.
14174 ///
14175 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
14176 /// which is what makes `[] == ""` true: `[]` becomes `""` via
14177 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
14178 /// because the conversion is allowed to call script code, so the two primitive
14179 /// operands are handed back to it.
14180 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
14181 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
14182 return Ok(left.loose_equals(&right));
14183 }
14184 // `null == undefined` holds even though neither is an object.
14185 if matches!(left, Value::Undefined | Value::Null)
14186 && matches!(right, Value::Undefined | Value::Null)
14187 {
14188 return Ok(true);
14189 }
14190 if matches!(left, Value::Undefined | Value::Null)
14191 || matches!(right, Value::Undefined | Value::Null)
14192 {
14193 return Ok(false);
14194 }
14195 // Two objects compare by identity. Only an object *against a primitive* is
14196 // converted, which is why `{} == {}` is false while `[] == ""` is true.
14197 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
14198 return Ok(a.ptr_eq(b));
14199 }
14200 let left = self.to_primitive(left, Hint::Default)?;
14201 let right = self.to_primitive(right, Hint::Default)?;
14202 Ok(left.loose_equals(&right))
14203 }
14204
14205 /// `HasBinding(N)` for an Object Environment Record whose binding object is `object`.
14206 ///
14207 /// §9.1.1.2.1: `HasProperty` **and then** not listed in the object's
14208 /// `Symbol.unscopables`. The `unscopables` object is read with a plain `Get`, so a
14209 /// getter on it runs exactly once per lookup — `with/with-get-unscopables-once` counts
14210 /// the calls.
14211 fn with_has_binding(&mut self, object: &Value, name: &str) -> JsResult<bool> {
14212 let key = PropertyKey::from(name);
14213 if !self.has_property_value(object, &key)? {
14214 return Ok(false);
14215 }
14216 let unscopables_key = self.realm.well_known_key(WellKnown::Unscopables);
14217 let unscopables = self.read_field_key(object, &unscopables_key)?;
14218 let Value::Object(_) = unscopables else {
14219 // `undefined` (the usual case) or a primitive: nothing is excluded.
14220 return Ok(true);
14221 };
14222 let excluded = self.read_field_key(&unscopables, &key)?;
14223 Ok(!excluded.to_boolean())
14224 }
14225
14226 /// `GetBindingValue(N, S)` for an Object Environment Record: §9.1.1.2.4.
14227 ///
14228 /// `HasProperty` is asked a **second** time — the guard already asked it — because the
14229 /// object may have changed in between: `GetBindingValue` step 2 is a fresh lookup, and
14230 /// a proxy sees two `has` traps plus the `get`. The `unscopables` step is *not*
14231 /// repeated: that belongs to `HasBinding`, not to `GetBindingValue`.
14232 ///
14233 /// When the property has gone, strict code throws and sloppy code reads `undefined`
14234 /// from the environment (step 2's `S` is the strictness of the *running* code, not of
14235 /// the declaration).
14236 fn with_get_binding(&mut self, object: &Value, name: &str) -> JsResult<Value> {
14237 let key = PropertyKey::from(name);
14238 if !self.has_property_value(object, &key)? {
14239 if self.frame().code.code.strict {
14240 return Err(self.throw_reference(name));
14241 }
14242 return Ok(Value::Undefined);
14243 }
14244 self.read_field_key(object, &key)
14245 }
14246
14247 /// `SetMutableBinding(N, V, S)` for an Object Environment Record: §9.1.1.2.5.
14248 ///
14249 /// Same second `HasProperty`, and the same strict-mode `ReferenceError` when the
14250 /// property is gone — before the store, which is what makes
14251 /// `set-mutable-binding-binding-deleted-with-typed-array-in-proto-chain-strict-mode`
14252 /// a `ReferenceError` rather than whatever the failed store would have thrown.
14253 fn with_put_binding(&mut self, object: &Value, name: &str, value: Value) -> JsResult<()> {
14254 let key = PropertyKey::from(name);
14255 if !self.has_property_value(object, &key)? && self.frame().code.code.strict {
14256 return Err(self.throw_reference(name));
14257 }
14258 self.write_field_key(object, &key, value)
14259 }
14260
14261 /// `HasProperty(O, P)` on a `Value`, without the `in`-operator error for a primitive.
14262 fn has_property_value(&mut self, object: &Value, key: &PropertyKey) -> JsResult<bool> {
14263 match object {
14264 Value::Object(target) => self.has_property_key(target, key),
14265 // `with` boxes its object when the statement is entered (`to_object`), so a
14266 // primitive cannot arrive here; `false` is the honest answer rather than a
14267 // panic if it ever does.
14268 _ => Ok(false),
14269 }
14270 }
14271
14272 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
14273 let Value::Object(object) = object else {
14274 return Err(Signal::Throw(
14275 self.make_error("TypeError", "cannot use 'in' on a non-object"),
14276 ));
14277 };
14278 let key = self.propkey(key)?;
14279 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
14280 // trap. One implementation, so an array's derived `length` and its inherited holes
14281 // cannot be right in one caller and wrong in another.
14282 self.has_own_or_inherited(object, &key)
14283 }
14284
14285 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
14286 ///
14287 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
14288 /// whole reason the operator is a hook rather than a prototype walk.
14289 ///
14290 /// §13.10.2 `InstanceofOperator(O, C)`, which is stricter than
14291 /// [`Interp::ordinary_instance_of`]: step 1 throws when `C` is not an object at all
14292 /// (`true instanceof true`) and step 4 throws when it is an object but not callable
14293 /// (`1 instanceof Math`). Both used to answer `false`, which is `OrdinaryHasInstance`'s
14294 /// rule (its step 2) and not this operator's — so nine `expressions/instanceof` cases
14295 /// expected a `TypeError` and got a value.
14296 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14297 // Step 1, before any method lookup.
14298 if constructor.as_object().is_none() {
14299 return Err(Signal::Throw(self.make_error(
14300 "TypeError",
14301 "right-hand side of 'instanceof' is not an object",
14302 )));
14303 }
14304 let Value::Object(function) = constructor else {
14305 unreachable!("just checked");
14306 };
14307 // Step 2. A primitive `C` cannot reach here, so `get_property_key` on the object is
14308 // the whole of it.
14309 let key = self.realm.well_known_key(WellKnown::HasInstance);
14310 let method = self.get_property_key(function, &key)?;
14311 if let Some(method) = method
14312 && !matches!(method, Value::Undefined)
14313 {
14314 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
14315 return Ok(answer.to_boolean());
14316 }
14317 // Step 4.
14318 if !function.is_callable() {
14319 return Err(Signal::Throw(self.make_error(
14320 "TypeError",
14321 "right-hand side of 'instanceof' is not callable",
14322 )));
14323 }
14324 // Step 5.
14325 self.instance_of(object, constructor)
14326 }
14327
14328 /// `OrdinaryHasInstance`: the prototype walk on its own.
14329 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14330 self.instance_of(object, constructor)
14331 }
14332
14333 /// `IsArray`: an array, or a proxy whose target is one.
14334 ///
14335 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
14336 /// makes `Array.isArray(new Proxy([], {}))` true.
14337 pub fn is_array_value(&self, value: &Value) -> bool {
14338 match value {
14339 Value::Object(object) => {
14340 if let Some(state) = object.proxy_state() {
14341 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
14342 }
14343 object.is_array()
14344 }
14345 _ => false,
14346 }
14347 }
14348
14349 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
14350 ///
14351 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
14352 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
14353 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
14354 /// see [`Interp::enqueue_job_function`].
14355 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
14356 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
14357 // the handler is reported rather than lost — the same reason a `then` reaction needs a
14358 // promise to settle.
14359 let promise = self.new_promise();
14360 self.fulfill_promise(&promise, Value::Undefined);
14361 self.jobs.push_back(Job::Reaction {
14362 handler: Some(function),
14363 argument: Value::Undefined,
14364 rejected: false,
14365 promise,
14366 });
14367 Ok(())
14368 }
14369
14370 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
14371 ///
14372 /// Four of its steps were missing or wrong, and each one is a test262 case in
14373 /// `Function/prototype/Symbol.hasInstance/`:
14374 ///
14375 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
14376 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
14377 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
14378 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
14379 /// `prototype` of its own, so without this step the walk below gives `false`;
14380 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
14381 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
14382 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14383 let Value::Object(function) = constructor else {
14384 return Ok(false);
14385 };
14386 if !function.is_callable() {
14387 return Ok(false);
14388 }
14389 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
14390 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
14391 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
14392 if let Some((target, this)) = function.bound_target_and_this() {
14393 let object = if this.as_object().is_some() {
14394 this
14395 } else {
14396 object.clone()
14397 };
14398 return self.instance_of(&object, &target);
14399 }
14400 let Value::Object(target) = object else {
14401 return Ok(false);
14402 };
14403 let prototype = self.get_property(function, "prototype")?;
14404 let Some(Value::Object(prototype)) = prototype else {
14405 return Err(Signal::Throw(self.make_error(
14406 "TypeError",
14407 "function has non-object prototype in instanceof check",
14408 )));
14409 };
14410 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
14411 // which is also what makes `proxyOfInstance instanceof C` work.
14412 let mut current = Some(target.clone());
14413 while let Some(object) = current {
14414 if object.ptr_eq(&prototype) {
14415 return Ok(true);
14416 }
14417 current = self.object_prototype_of(&object)?;
14418 }
14419 Ok(false)
14420 }
14421
14422 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
14423 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
14424 if let Some(proto) = self.proxy_get_prototype_of(object)? {
14425 return Ok(proto);
14426 }
14427 if let Some(exotic) = object.exotic()
14428 && let Some(proto) = exotic.get_prototype(self, object)?
14429 {
14430 return Ok(proto);
14431 }
14432 Ok(object.proto())
14433 }
14434
14435 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
14436 pub fn object_set_prototype_of(
14437 &mut self,
14438 object: &Gc<JsObject>,
14439 proto: Option<Gc<JsObject>>,
14440 ) -> JsResult<bool> {
14441 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
14442 return Ok(answer);
14443 }
14444 if let Some(exotic) = object.exotic()
14445 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
14446 {
14447 return Ok(answer);
14448 }
14449 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
14450 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
14451 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
14452 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
14453 if self
14454 .internal_get(object, "_immutable_proto")
14455 .is_some_and(|flag| flag.to_boolean())
14456 && !same_proto(object.proto().as_ref(), proto.as_ref())
14457 {
14458 return Ok(false);
14459 }
14460 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
14461 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
14462 // inheriting from itself, which every later prototype walk then had to defend
14463 // against — and `Reflect.setPrototypeOf` reported success for an operation the
14464 // language says is impossible.
14465 if let Some(proto) = &proto {
14466 let mut current = Some(proto.clone());
14467 let mut guard = 0;
14468 while let Some(node) = current {
14469 if node.ptr_eq(object) {
14470 // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
14471 // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
14472 // while `Reflect.setPrototypeOf` reports it
14473 // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
14474 return Ok(false);
14475 }
14476 guard += 1;
14477 if guard > 1000 {
14478 break;
14479 }
14480 current = node.proto();
14481 }
14482 }
14483 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14484 // re-setting it to the *same* one is a no-op `true`. Missing this made
14485 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14486 // actually reparent the object — and it is what
14487 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14488 // forwarding path has nothing else left to refuse it.
14489 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14490 return Ok(false);
14491 }
14492 object.set_proto(proto);
14493 Ok(true)
14494 }
14495
14496 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14497 ///
14498 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14499 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14500 /// already one.
14501 /// `HasProperty(O, P)`.
14502 ///
14503 /// One implementation, shared with the `in` operator. It used to be a second copy that
14504 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14505 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14506 /// proxy ran the wrong hook and could even disagree with `in`. The
14507 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14508 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14509 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14510 self.has_own_or_inherited(object, key)
14511 }
14512
14513 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14514 ///
14515 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14516 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14517 /// boolean as well, and it needs the receiver to be the one the caller named.
14518 pub fn set_property_with_key_receiver(
14519 &mut self,
14520 object: &Gc<JsObject>,
14521 key: &PropertyKey,
14522 value: Value,
14523 receiver: Option<&Value>,
14524 on_failure: DeleteFailure,
14525 ) -> JsResult<bool> {
14526 let receiver = receiver
14527 .cloned()
14528 .unwrap_or_else(|| Value::Object(object.clone()));
14529 if object.proxy_state().is_some() {
14530 return match self.proxy_set(object, key, value, &receiver)? {
14531 Some(accepted) => Ok(accepted),
14532 None => Ok(true),
14533 };
14534 }
14535 // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14536 // receiver. This has to be answered here as well as in the storing path below,
14537 // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14538 if object.module_namespace_marker() {
14539 return Ok(false);
14540 }
14541 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14542 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14543 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14544 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14545 //
14546 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14547 //
14548 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14549 // * an *invalid* index with a different receiver answers `true` and does nothing,
14550 // not even converting `V` (`valueOfCalls` stays 0);
14551 // * a valid index with a different receiver falls through to
14552 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14553 // value lands on the **receiver**, unconverted, and can be refused by a
14554 // non-extensible receiver, an accessor, or a read-only index there.
14555 //
14556 // The last one used to write into the view itself, which left `target[0]` changed
14557 // and `receiver[0]` untouched — backwards.
14558 if object.typed_array_element_type().is_some()
14559 && let Some(numeric) = canonical_numeric_index(key)
14560 {
14561 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14562 if same {
14563 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14564 return Ok(true);
14565 }
14566 if !typed_array_index_is_valid(object, numeric) {
14567 return Ok(true);
14568 }
14569 let Some(receiver) = receiver.as_object().cloned() else {
14570 return Ok(false);
14571 };
14572 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
14573 if existing.is_accessor() || !existing.writable {
14574 return Ok(false);
14575 }
14576 let property = Property {
14577 value: Some(value),
14578 ..existing
14579 };
14580 return self.object_define_own_property(&receiver, key, property);
14581 }
14582 return self.object_define_own_property(&receiver, key, Property::data(value));
14583 }
14584 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
14585 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
14586 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
14587 // `Reflect.set` to *report* the refusal instead of raising.
14588 //
14589 // A receiver that is not the object turns the whole operation into
14590 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
14591 // `[[Set]]` rather than a lookup — that is what makes
14592 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
14593 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
14594 // writes to `object`, so it cannot express that and is only used when the two are
14595 // the same.
14596 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14597 if !same {
14598 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14599 }
14600 // Same receiver: the plain path below writes into `object`, which is right, but it
14601 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14602 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
14603 if let Some(existing) = self.object_get_own_property(object, key)? {
14604 if existing.is_accessor() {
14605 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
14606 Some(setter) => {
14607 self.call_value(setter, receiver, vec![value])?;
14608 Ok(true)
14609 }
14610 None => Ok(false),
14611 };
14612 }
14613 if !existing.writable {
14614 return Ok(false);
14615 }
14616 }
14617 // Otherwise it is an ordinary create-or-write into `object` itself.
14618 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14619 Ok(true)
14620 }
14621
14622 /// `[[IsExtensible]]`, with the proxy trap when there is one.
14623 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14624 if let Some(answer) = self.proxy_is_extensible(object)? {
14625 return Ok(answer);
14626 }
14627 if let Some(exotic) = object.exotic()
14628 && let Some(answer) = exotic.is_extensible(self, object)?
14629 {
14630 return Ok(answer);
14631 }
14632 Ok(object.is_extensible())
14633 }
14634
14635 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
14636 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14637 if let Some(answer) = self.proxy_prevent_extensions(object)? {
14638 return Ok(answer);
14639 }
14640 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
14641 //
14642 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
14643 //
14644 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
14645 // created with an explicit length, because the buffer can still move it. That is
14646 // what makes `Object.freeze` refuse every such view, including a zero-length one
14647 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14648 // plain buffer is allowed.
14649 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14650 && buffer
14651 .array_buffer_storage()
14652 .is_some_and(|storage| storage.borrow().is_resizable())
14653 {
14654 return Err(
14655 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14656 );
14657 }
14658 if let Some(exotic) = object.exotic()
14659 && let Some(answer) = exotic.prevent_extensions(self, object)?
14660 {
14661 return Ok(answer);
14662 }
14663 object.set_extensible(false);
14664 Ok(true)
14665 }
14666
14667 fn copy_properties(
14668 &mut self,
14669 target: &Value,
14670 source: &Value,
14671 exclusion: &Value,
14672 ) -> JsResult<()> {
14673 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14674 // does contribute: its index properties are own, enumerable and writable, which
14675 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14676 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14677 // is a no-op.
14678 let Some(target) = target.as_object() else {
14679 return Ok(());
14680 };
14681 let source_object = match source {
14682 Value::Object(object) => object.clone(),
14683 Value::String(text) => {
14684 // Untaken keys are the string's indices, which are code units.
14685 for index in 0..text.utf16_len() {
14686 if let Some(unit) = text.wtf8().unit_at(index) {
14687 target.define_data(&index.to_string(), self.string_wtf8(unit));
14688 }
14689 }
14690 return Ok(());
14691 }
14692 _ => return Ok(()),
14693 };
14694 // An object *rest* element passes the keys already taken by the literal part as
14695 // an array of **key values**; a spread passes `null`, which excludes nothing. The
14696 // array is read by its elements rather than by its own property names, and the
14697 // values stay `PropertyKey`s: a computed key can be a symbol, and
14698 // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
14699 // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
14700 // strings made a symbol exclusion a no-op.
14701 let mut excluded: Vec<PropertyKey> = Vec::new();
14702 if let Value::Object(list) = exclusion
14703 && let Some(length) = list.array_length()
14704 {
14705 for index in 0..length {
14706 if let Some(value) = list.array_get(index) {
14707 excluded.push(self.propkey(&value)?);
14708 }
14709 }
14710 }
14711 let source = &source_object;
14712 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
14713 // Reading the property table directly made every spread of a proxy empty.
14714 let keys = self.object_own_property_keys(source)?;
14715 for as_key in keys {
14716 // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
14717 // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
14718 // Skipping them silently lost every symbol on every spread and every object
14719 // rest element (`obj-rest-order`).
14720 //
14721 if excluded.contains(&as_key) {
14722 continue;
14723 }
14724 let enumerable = self
14725 .object_get_own_property(source, &as_key)?
14726 .is_some_and(|property| property.enumerable);
14727 if !enumerable {
14728 continue;
14729 }
14730 let value = self
14731 .get_property_key(source, &as_key)?
14732 .unwrap_or(Value::Undefined);
14733 target.define_data_key(&as_key, value);
14734 }
14735 Ok(())
14736 }
14737
14738 // -- iteration ---------------------------------------------------------
14739
14740 /// One object's own keys in enumeration order: array indices ascending, then the
14741 /// rest in insertion order.
14742 ///
14743 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
14744 /// whether the key is enumerable, which the caller resolves per key because an
14745 /// array's elements are not in the same store as its named properties.
14746 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
14747 // An index can arrive twice, once from the array's element store and once from
14748 // its property map, so the numeric keys go through a map that keeps the
14749 // enumerable answer if either source gave one.
14750 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
14751 for (key, enumerable) in &own {
14752 if let Some(index) = key.as_str().and_then(array_index) {
14753 let entry = numeric.entry(index).or_insert(false);
14754 *entry = *entry || *enumerable;
14755 }
14756 }
14757 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
14758 .into_iter()
14759 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
14760 .collect();
14761 ordered.extend(
14762 own.into_iter()
14763 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
14764 );
14765 ordered
14766 }
14767
14768 /// Build the key list a `for-in` loop walks.
14769 ///
14770 /// The order is the specification's: own properties before inherited ones, and
14771 /// within one object the integer-like keys in ascending numeric order ahead of the
14772 /// string keys in insertion order. A shadowed key only appears once, and a key that
14773 /// is a non-enumerable own property anywhere nearer is skipped entirely.
14774 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14775 let record = self.new_object(None);
14776 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
14777 // A proxy supplies its own key list, and — the reason this is not just another
14778 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
14779 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
14780 // descriptor there.
14781 if let Value::Object(object) = value
14782 && object.proxy_state().is_some()
14783 {
14784 let own = self
14785 .proxy_own_keys(object)?
14786 .unwrap_or_else(|| object.own_property_keys());
14787 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
14788 let mut numeric: Vec<u32> = Vec::new();
14789 let mut rest: Vec<PropertyKey> = Vec::new();
14790 for key in own {
14791 match key.as_str().and_then(array_index) {
14792 Some(index) => numeric.push(index),
14793 None => rest.push(key),
14794 }
14795 }
14796 numeric.sort_unstable();
14797 ordered.extend(
14798 numeric
14799 .into_iter()
14800 .map(|index| PropertyKey::from(index.to_string())),
14801 );
14802 ordered.extend(rest);
14803 for (index, key) in ordered.into_iter().enumerate() {
14804 record.define_data(&index.to_string(), self.key_value(&key));
14805 }
14806 record.define_data("__index", Value::Int(0));
14807 // The mark that makes `for_in_advance` re-ask the proxy per key.
14808 record.define_data("__proxy", Value::Object(object.clone()));
14809 return Ok(record);
14810 }
14811 if let Value::Object(object) = value {
14812 let mut chain = vec![object.clone()];
14813 chain.extend(object.chain());
14814 // Every own string key the walk has seen, enumerable or not. A
14815 // non-enumerable own property still hides a same-named enumerable one
14816 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
14817 // keeps `x` out of the loop even when the prototype has one.
14818 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
14819 for object in chain {
14820 // A namespace's bindings are materialised by `[[GetOwnProperty]]`, and a
14821 // binding still in its dead zone throws there (§10.4.6.8). Enumerating
14822 // through the raw table skipped that, so `for (var k in ns)` on a namespace
14823 // whose module was still evaluating saw the keys and read `undefined`
14824 // (`namespace/internals/enumerate-binding-uninit`).
14825 if object.module_namespace_marker() {
14826 for key in object.own_property_keys() {
14827 self.object_get_own_property(&object, &key)?;
14828 }
14829 }
14830 let mut own: Vec<(crate::value::Wtf8, bool)> = object
14831 .own_property_keys()
14832 .iter()
14833 .filter_map(|key| key.as_wtf8().cloned())
14834 .map(|key| {
14835 let enumerable = object
14836 .own_property(&key.to_string_lossy())
14837 .map(|property| property.enumerable)
14838 .unwrap_or(false);
14839 (key, enumerable)
14840 })
14841 .collect();
14842 if let Some(length) = object.array_length() {
14843 own.retain(|(key, _)| key.as_str() != Some("length"));
14844 for index in 0..length {
14845 // A dense element is enumerable; a **hole** is not there at all —
14846 // and a hole is also what an index with a recorded descriptor
14847 // leaves behind, in which case the table entry above already
14848 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
14849 // defines index 0 non-enumerable and `for…in` must skip it).
14850 if let Some(value) = object.array_get(index)
14851 && !matches!(value, Value::Hole)
14852 {
14853 own.push((crate::value::Wtf8::new(index.to_string()), true));
14854 }
14855 }
14856 }
14857 // Integer-like keys come first in ascending order, then the rest in
14858 // insertion order — and the ordering is *per object*, not for the chain
14859 // as a whole: one pass over every collected key lifted a prototype's
14860 // `"4"` above the target's own `x`/`y`, which is not the order
14861 // `for…in` reports.
14862 for (key, enumerable) in Self::order_own_keys(own) {
14863 if visited.contains(&key) {
14864 continue;
14865 }
14866 visited.push(key.clone());
14867 if enumerable {
14868 keys.push(key);
14869 }
14870 }
14871 }
14872 }
14873 for (index, key) in keys.into_iter().enumerate() {
14874 record.define_data(&index.to_string(), self.string_wtf8(key));
14875 }
14876 record.define_data("__index", Value::Int(0));
14877 Ok(record)
14878 }
14879
14880 /// The next key of a `for…in` record, `None` when the loop is done.
14881 ///
14882 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
14883 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
14884 /// the loop reaches it, so a handler that stops reporting a key partway through drops
14885 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
14886 /// key the handler had already withdrawn.
14887 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
14888 let Value::Object(record) = record else {
14889 return Ok(None);
14890 };
14891 let proxy = record
14892 .own_property("__proxy")
14893 .and_then(|property| property.value);
14894 loop {
14895 let index = record
14896 .own_property("__index")
14897 .and_then(|property| property.value)
14898 .map(|value| value.to_int32())
14899 .unwrap_or(0);
14900 let Some(candidate) = record
14901 .own_property(&index.to_string())
14902 .and_then(|property| property.value)
14903 else {
14904 return Ok(None);
14905 };
14906 record.define_data("__index", Value::Int(index + 1));
14907 let text = candidate.to_js_string();
14908 let Some(Value::Object(proxy)) = &proxy else {
14909 return Ok(Some(text));
14910 };
14911 // The candidate is already a key string here, so the lookup does not need a
14912 // second `ToPropertyKey` conversion.
14913 let key = PropertyKey::from(text.as_str());
14914 let live = match self.proxy_get_own_property(proxy, &key)? {
14915 Some(descriptor) => descriptor,
14916 // Not a proxy after all, or it lost its state: fall back to the target.
14917 None => proxy.own_property_key(&key),
14918 };
14919 if live.is_some_and(|property| property.enumerable) {
14920 return Ok(Some(text));
14921 }
14922 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
14923 // next one.
14924 }
14925 }
14926
14927 /// The iterator for `for-of`: the object and its `next` method.
14928 ///
14929 /// An object that already carries a `next` method is used as it is — that is what
14930 /// `arr.values()` returns — and only arrays and strings get the built-in
14931 /// sequence iterator.
14932 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
14933 ///
14934 /// Callers that must choose between the iterable and the array-like protocol — the
14935 /// typed-array constructor is the main one — need to ask *before* committing to one.
14936 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
14937 let key = self.realm.well_known_key(WellKnown::Iterator);
14938 let method = self.read_field_key(value, &key)?;
14939 if matches!(method, Value::Undefined | Value::Null) {
14940 return Ok(false);
14941 }
14942 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14943 return Err(Signal::Throw(
14944 self.make_error("TypeError", "Symbol.iterator is not callable"),
14945 ));
14946 }
14947 Ok(true)
14948 }
14949
14950 /// Collect everything an iterable yields.
14951 ///
14952 /// The cap is a guard against a generator that never ends: an unbounded collect would
14953 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
14954 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
14955 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
14956 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
14957 const MAX_ITEMS: usize = 1 << 24;
14958 let iterator = self.get_iterator(value)?;
14959 let mut out = Vec::new();
14960 loop {
14961 let (element, done) = self.iterator_step(&iterator)?;
14962 if done {
14963 return Ok(out);
14964 }
14965 out.push(element);
14966 if out.len() > MAX_ITEMS {
14967 // Close before refusing: the walk is being abandoned, so the iterator's
14968 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14969 // unrun and a locked resource unreleased.
14970 self.close_iterator_after_throw(&iterator)?;
14971 return Err(self.range_error("iterable is too long to collect"));
14972 }
14973 }
14974 }
14975
14976 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14977 ///
14978 /// A native constructor calls this once it has validated its arguments, which is the
14979 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14980 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14981 /// never reached. The prototype comes from `new.target` when it is an object, and from
14982 /// `default_proto` otherwise.
14983 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14984 let proto = self.ctor_prototype(default_proto)?;
14985 Ok(self.new_object(Some(proto)))
14986 }
14987
14988 /// An **array** whose prototype comes from `new.target`.
14989 ///
14990 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14991 /// instance from `new.target.prototype`, and building a plain array instead made every
14992 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14993 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14994 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14995 Ok(JsObject::array(self.heap, Some(proto), 0))
14996 }
14997
14998 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14999 ///
15000 /// The `Option` form is for the constructors that build their instance in a helper which
15001 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
15002 /// from `await`'s internal promise, and only the first has a `new.target`.
15003 fn ctor_prototype_opt(
15004 &mut self,
15005 default_proto: Option<Gc<JsObject>>,
15006 ) -> JsResult<Option<Gc<JsObject>>> {
15007 // `active_new_target`: by the time a native constructor runs, `call_value` has
15008 // already consumed the parked value.
15009 let Some(target) = self
15010 .active_new_target
15011 .as_object()
15012 .cloned()
15013 .map(Value::Object)
15014 else {
15015 return Ok(default_proto);
15016 };
15017 let Some(target) = target.as_object().cloned() else {
15018 return Ok(default_proto);
15019 };
15020 match self.get_property(&target, "prototype")? {
15021 Some(Value::Object(proto)) => Ok(Some(proto)),
15022 _ => Ok(default_proto),
15023 }
15024 }
15025
15026 /// `new.target.prototype`, or `default_proto` when this is a plain call.
15027 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
15028 let Some(target) = self.active_new_target.as_object().cloned() else {
15029 return Ok(default_proto);
15030 };
15031 match self.get_property(&target, "prototype")? {
15032 Some(Value::Object(proto)) => Ok(proto),
15033 _ => Ok(default_proto),
15034 }
15035 }
15036
15037 /// `CreateDataPropertyOrThrow(O, key, value)`.
15038 ///
15039 /// A *definition*, not an assignment. The difference is visible the moment the target
15040 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
15041 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
15042 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
15043 /// refused (`configurable: false`).
15044 ///
15045 /// The fast path exists because this is called once per element by `map`, `filter`,
15046 /// `slice` and friends: a plain array with no custom element descriptors and a writable
15047 /// `length` can store straight into its element vector.
15048 pub fn create_data_property_or_throw(
15049 &mut self,
15050 object: &Gc<JsObject>,
15051 index: usize,
15052 value: Value,
15053 ) -> JsResult<()> {
15054 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
15055 // an array (that is what `Array.isArray` must say), so the element fast path would
15056 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
15057 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
15058 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
15059 // records the exact trap sequence.
15060 if object.proxy_state().is_none()
15061 && object.is_array()
15062 && object.elements_writable()
15063 && !object.has_element_descriptors()
15064 && object.is_extensible()
15065 && object.array_set(self.heap, index, value.clone())
15066 {
15067 return Ok(());
15068 }
15069 let key = PropertyKey::from(index.to_string());
15070 let property = Property {
15071 value: Some(value),
15072 writable: true,
15073 enumerable: true,
15074 configurable: true,
15075 ..Property::default()
15076 };
15077 // `CreateDataProperty` always asks for the default attributes, so it can only ever
15078 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
15079 // the rest. Checking here rather than inside `object_define_own_property` is
15080 // deliberate: that function receives a fully-populated `Property` and cannot tell
15081 // an omitted attribute from an explicit `false`, so the generic check it would need
15082 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
15083 // writable property (that cost eight `Object/defineProperty` tests).
15084 if object.proxy_state().is_none()
15085 && let Some(existing) = self.object_get_own_property(object, &key)?
15086 && !existing.configurable
15087 {
15088 return Err(self.type_error("cannot create the property"));
15089 }
15090 if self.object_define_own_property(object, &key, property)? {
15091 return Ok(());
15092 }
15093 Err(self.type_error("cannot create the property"))
15094 }
15095
15096 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
15097 ///
15098 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
15099 /// its callers have; this is the same operation for the named properties a built-in
15100 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
15101 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
15102 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
15103 pub fn create_named_data_property_or_throw(
15104 &mut self,
15105 object: &Gc<JsObject>,
15106 key: &str,
15107 value: Value,
15108 ) -> JsResult<()> {
15109 let key = PropertyKey::from(key);
15110 let property = Property {
15111 value: Some(value),
15112 writable: true,
15113 enumerable: true,
15114 configurable: true,
15115 ..Property::default()
15116 };
15117 if object.proxy_state().is_none()
15118 && let Some(existing) = self.object_get_own_property(object, &key)?
15119 && !existing.configurable
15120 {
15121 return Err(self.type_error("cannot create the property"));
15122 }
15123 if self.object_define_own_property(object, &key, property)? {
15124 return Ok(());
15125 }
15126 Err(self.type_error("cannot create the property"))
15127 }
15128
15129 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
15130 ///
15131 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
15132 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
15133 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
15134 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
15135 /// run user code and both can throw.
15136 pub fn species_constructor(
15137 &mut self,
15138 object: &Gc<JsObject>,
15139 default: Value,
15140 ) -> JsResult<Value> {
15141 let Some(constructor) = self.get_property(object, "constructor")? else {
15142 return Ok(default);
15143 };
15144 let constructor = match constructor {
15145 Value::Undefined => return Ok(default),
15146 Value::Object(constructor) => constructor,
15147 _ => return Err(self.type_error("constructor is not an object")),
15148 };
15149 let key = self.realm.well_known_key(WellKnown::Species);
15150 let species = self.get_property_key(&constructor, &key)?;
15151 match species {
15152 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
15153 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
15154 Some(_) => Err(self.type_error("species is not a constructor")),
15155 }
15156 }
15157
15158 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
15159 ///
15160 /// The result is an array of `length` holes whose prototype comes from
15161 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
15162 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
15163 /// is why the `IsArray` check is the first step and not an optimisation.
15164 pub fn array_species_create(
15165 &mut self,
15166 original: &Value,
15167 length: usize,
15168 ) -> JsResult<Gc<JsObject>> {
15169 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
15170 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
15171 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
15172 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
15173 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
15174 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
15175 // realm** — the species may be a user function that ignores the length entirely, and
15176 // then `2**53 - 1` is not its problem
15177 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
15178 // a short proxy and expects the copy loop to run).
15179 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
15180 if length > ARRAY_CREATE_LIMIT {
15181 return Err(interp.range_error("invalid array length"));
15182 }
15183 Ok(interp.new_array_of_length(length))
15184 };
15185 let Some(object) = original.as_object().cloned() else {
15186 return default(self);
15187 };
15188 if !object.is_array() {
15189 return default(self);
15190 }
15191 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
15192 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
15193 let Some(constructor) = self.get_property(&object, "constructor")? else {
15194 return default(self);
15195 };
15196 let species = match constructor {
15197 Value::Undefined => return Ok(self.new_array_of_length(length)),
15198 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
15199 return default(self);
15200 }
15201 Value::Object(constructor) => {
15202 let key = self.realm.well_known_key(WellKnown::Species);
15203 match self.get_property_key(&constructor, &key)? {
15204 None | Some(Value::Undefined) | Some(Value::Null) => {
15205 return default(self);
15206 }
15207 Some(species) => species,
15208 }
15209 }
15210 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
15211 // is a `TypeError`, not "the default". Treating it as the default made
15212 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
15213 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
15214 // `concat/create-ctor-non-object` are the same rule three times.
15215 _ => return Err(self.type_error("constructor is not an object")),
15216 };
15217 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
15218 // that is merely callable is the `create-species-non-ctor` case.
15219 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
15220 return Err(self.type_error("species is not a constructor"));
15221 }
15222 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
15223 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
15224 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
15225 let created = self.construct(
15226 species.clone(),
15227 species,
15228 vec![crate::object::length_value(length)],
15229 )?;
15230 let Some(created) = created.as_object().cloned() else {
15231 return Err(self.type_error("species constructor did not answer an object"));
15232 };
15233 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
15234 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
15235 // object, and `create-species-with-non-writable-property` asserts exactly that.
15236 // The length is set for the array case; the generic case is the caller's
15237 // `Set(A, "length", …)`.
15238 if created.is_array() {
15239 created.array_set_length(self.heap, length);
15240 }
15241 Ok(created)
15242 }
15243
15244 /// Whether `object` is this realm's `%Array%`.
15245 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
15246 self.realm
15247 .array_constructor
15248 .as_ref()
15249 .is_some_and(|array| array.ptr_eq(object))
15250 }
15251
15252 /// A fresh `length`-hole array with the intrinsic prototype.
15253 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
15254 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
15255 array.array_set_length(self.heap, length);
15256 array
15257 }
15258
15259 /// Whether this call is a construction, i.e. `new.target` is defined.
15260 ///
15261 /// A native constructor receives `this = undefined` (it builds its own instance), so it
15262 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
15263 /// The native function currently executing, if any.
15264 pub fn current_native(&self) -> Option<Gc<JsObject>> {
15265 self.current_native.clone()
15266 }
15267
15268 /// Whether this call is a construction, i.e. `new.target` is defined.
15269 pub fn is_constructing(&self) -> bool {
15270 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
15271 // `call_value` before a native runs, so by the time a constructor body asks, the
15272 // answer is only in the active slot.
15273 matches!(self.active_new_target, Value::Object(_))
15274 }
15275
15276 /// The `TypeError` a constructor too primitive to have a wrapper raises.
15277 ///
15278 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
15279 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
15280 /// happens inside the native function, which is why the trace carries an
15281 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
15282 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
15283 /// constructor`, and an unnamed one reports the leading space of `" is not a
15284 /// constructor"` because the reference formats the empty name as it is.
15285 ///
15286 /// It is also the answer for a `new.target` that cannot be named at all — not a
15287 /// function, or a throwing `name` getter — where the reference falls back to the bare
15288 /// `not a constructor`.
15289 pub fn not_a_constructor_error(&mut self) -> Signal {
15290 let target = self.active_new_target.clone();
15291 self.not_a_constructor_error_for(target)
15292 }
15293
15294 /// The same `TypeError` for an explicit target, for the callers that check
15295 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
15296 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
15297 let target = match target {
15298 Value::Object(target) if target.is_callable() => target,
15299 _ => return self.type_error("not a constructor"),
15300 };
15301 let name = match self.get_property(&target, "name") {
15302 Ok(Some(value)) => value.to_js_string(),
15303 _ => return self.type_error("not a constructor"),
15304 };
15305 self.type_error(format!("{name} is not a constructor"))
15306 }
15307
15308 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
15309 ///
15310 /// True whenever `new.target` is not the callee itself, or when it has no usable
15311 /// `prototype` — the cases where reading the property is observable at all.
15312 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
15313 match &self.active_new_target {
15314 Value::Object(target) => !target.ptr_eq(callee),
15315 Value::Undefined => false,
15316 _ => true,
15317 }
15318 }
15319
15320 /// The symbol key for one of the engine's own hidden slots.
15321 ///
15322 /// Cached on the realm, so every object of a kind shares one key and a slot can be
15323 /// read back by name.
15324 /// Whether any object on `object`'s **prototype chain** owns an array index.
15325 ///
15326 /// The one question the array methods' dense fast paths have to ask before touching the
15327 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
15328 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
15329 /// vector an unreliable answer. Walking the chain once per call is cheap because a
15330 /// prototype almost never holds an index.
15331 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
15332 let mut current = object.proto();
15333 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
15334 for _ in 0..10_000 {
15335 let Some(proto) = current else {
15336 return false;
15337 };
15338 if proto.has_indexed_own_property() {
15339 return true;
15340 }
15341 current = proto.proto();
15342 }
15343 false
15344 }
15345
15346 /// The hidden symbol a named internal slot is keyed by, created on first use.
15347 ///
15348 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
15349 /// either keeping a table of its own.
15350 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
15351 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
15352 return PropertyKey::Symbol(symbol.clone());
15353 }
15354 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
15355 self.realm
15356 .internal_slots
15357 .borrow_mut()
15358 .insert(name, Value::Symbol(symbol.clone()));
15359 PropertyKey::Symbol(symbol)
15360 }
15361
15362 /// Read a hidden slot, or `None` when the object has none of that name.
15363 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
15364 let slots = self.realm.internal_slots.borrow();
15365 let Value::Symbol(symbol) = slots.get(name)? else {
15366 return None;
15367 };
15368 object
15369 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
15370 .and_then(|property| property.value)
15371 }
15372
15373 /// Define a hidden slot.
15374 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
15375 let key = self.internal_slot(name);
15376 object.define_key(&key, Property::with_attributes(value, false, false));
15377 }
15378
15379 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
15380 ///
15381 /// The method is looked up on the value (through its prototype), called with no
15382 /// arguments, and its result becomes the iterator. A generator gets here through
15383 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
15384 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
15385 ///
15386 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
15387 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
15388 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
15389 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
15390 /// does, and a user-defined iterable works without a special case.
15391 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
15392 /// `Symbol.iterator`.
15393 ///
15394 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
15395 /// iterable is legal there, and each value it produces is simply already settled by
15396 /// the time the `await` around it runs.
15397 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15398 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
15399 let method = self.read_field_key(value, &async_key)?;
15400 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
15401 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
15402 // is *present but not callable* is a TypeError — it does not mean "try the other
15403 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
15404 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
15405 // guard is there to catch.
15406 let absent = matches!(method, Value::Undefined | Value::Null);
15407 if !absent {
15408 let Value::Object(object) = &method else {
15409 return Err(Signal::Throw(
15410 self.make_error("TypeError", "value is not iterable"),
15411 ));
15412 };
15413 if !object.is_callable() {
15414 return Err(Signal::Throw(
15415 self.make_error("TypeError", "value is not iterable"),
15416 ));
15417 }
15418 }
15419 if absent {
15420 // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
15421 // generator's `yield*` both reach here, and the wrapper is what puts
15422 // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
15423 // caller — a poisoned `constructor` on that value rejects instead of being
15424 // yielded, and a rejection closes the synchronous iterator first.
15425 let sync = self.get_iterator(value)?;
15426 return self.async_from_sync_iterator(sync);
15427 }
15428 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15429 if !matches!(iterator, Value::Object(_)) {
15430 return Err(Signal::Throw(
15431 self.make_error("TypeError", "iterator is not an object"),
15432 ));
15433 }
15434 let next = self.read_field(&iterator, "next")?;
15435 Ok(Iterator {
15436 object: iterator,
15437 next,
15438 })
15439 }
15440
15441 /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
15442 ///
15443 /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
15444 /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
15445 /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
15446 fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
15447 let Some(factory) = self.realm.async_from_sync.clone() else {
15448 // No wrapper installed (a realm whose heap refused to hold it): fall back to the
15449 // raw synchronous iterator rather than refusing to iterate at all.
15450 return Ok(sync);
15451 };
15452 let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
15453 let next = self.read_field(&wrapper, "next")?;
15454 Ok(Iterator {
15455 object: wrapper,
15456 next,
15457 })
15458 }
15459
15460 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
15461 /// read — `@@iterator` is **not** consulted.
15462 ///
15463 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
15464 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
15465 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
15466 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
15467 /// refused it with "[object Object] is not iterable".
15468 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
15469 if !matches!(value, Value::Object(_)) {
15470 return Err(self.type_error("iterator is not an object"));
15471 }
15472 let next = self.read_field(&value, "next")?;
15473 Ok(Iterator {
15474 object: value,
15475 next,
15476 })
15477 }
15478
15479 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15480 let key = self.realm.well_known_key(WellKnown::Iterator);
15481 let method = self.read_field_key(value, &key)?;
15482 let Value::Object(function) = &method else {
15483 return Err(Signal::Throw(self.make_error(
15484 "TypeError",
15485 &format!("{} is not iterable", value.to_js_string()),
15486 )));
15487 };
15488 if !function.is_callable() {
15489 return Err(Signal::Throw(self.make_error(
15490 "TypeError",
15491 &format!("{} is not iterable", value.to_js_string()),
15492 )));
15493 }
15494 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15495 // The spec requires an object here; a primitive iterator has no `next` to call
15496 // and would fail one step later with a confusing message.
15497 if !matches!(iterator, Value::Object(_)) {
15498 return Err(Signal::Throw(
15499 self.make_error("TypeError", "iterator is not an object"),
15500 ));
15501 }
15502 let next = self.read_field(&iterator, "next")?;
15503 Ok(Iterator {
15504 object: iterator,
15505 next,
15506 })
15507 }
15508
15509 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15510 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15511 /// exception from `return` propagates normally instead of being swallowed. That is the
15512 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15513 /// because confusing them is exactly the bug both exist to avoid.
15514 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15515 let method = self.read_field(&iterator.object, "return")?;
15516 if matches!(method, Value::Undefined | Value::Null) {
15517 return Ok(());
15518 }
15519 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15520 return Err(self.type_error("iterator return is not a function"));
15521 }
15522 self.call_value(method, iterator.object.clone(), Vec::new())?;
15523 Ok(())
15524 }
15525
15526 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15527 /// cannot replace it.
15528 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15529 let method = self.read_field(&iterator.object, "return")?;
15530 if matches!(method, Value::Undefined | Value::Null) {
15531 return Ok(());
15532 }
15533 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15534 return Err(self.type_error("iterator return is not a function"));
15535 }
15536 self.call_value(method, iterator.object.clone(), Vec::new())?;
15537 Ok(())
15538 }
15539
15540 /// One step of an internal iterator: the value and whether it is exhausted.
15541 /// Replace the iterator slot of an iteration record with `undefined`.
15542 ///
15543 /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15544 /// `undefined` record is what every close path already treats as "nothing to close", so
15545 /// one store both records "this iterator must not be closed" and keeps
15546 /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15547 fn clear_iterator_slot(&mut self, slot: usize) {
15548 let frame = self.frame_mut();
15549 let depth = frame.stack.len();
15550 if depth > slot {
15551 frame.stack[depth - 1 - slot] = Value::Undefined;
15552 }
15553 }
15554
15555 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
15556 // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
15557 // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
15558 // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
15559 // before the first step, so an iterator with no `next` still gets its `return`
15560 // called by `it.return()` instead of failing up front
15561 // (`array-rest-iter-rtrn-close-err`).
15562 if let Value::Object(object) = &iterator.next
15563 && object.is_callable()
15564 {
15565 let result =
15566 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
15567 let Some(result) = result.as_object().cloned() else {
15568 return Err(self.type_error("iterator result is not an object"));
15569 };
15570 let done = self
15571 .get_property(&result, "done")?
15572 .is_some_and(|value| value.to_boolean());
15573 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
15574 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
15575 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
15576 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
15577 // made an unrelated `value` getter observable after the loop was over.
15578 if done {
15579 return Ok((Value::Undefined, true));
15580 }
15581 let value = self
15582 .get_property(&result, "value")?
15583 .unwrap_or(Value::Undefined);
15584 return Ok((value, false));
15585 }
15586 // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
15587 // tested at the call. Treating a non-callable `next` as "exhausted" instead made
15588 // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
15589 // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
15590 Err(Signal::Throw(self.make_error(
15591 "TypeError",
15592 "iterator's next method is not callable",
15593 )))
15594 }
15595
15596 /// `[...iterable]`: append everything the iterator yields, and answer the next
15597 /// index.
15598 ///
15599 /// This goes through the same iterator machinery `for-of` uses rather than copying
15600 /// an array's elements, because a spread source is any iterable: a string spreads
15601 /// into its characters and an array iterator spreads into its results. Handling
15602 /// only arrays made `[..."ab"]` come out empty with no error at all.
15603 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
15604 let Some(target) = array.as_object().cloned() else {
15605 return Ok(0);
15606 };
15607 let start = target.array_length().unwrap_or(0);
15608 let mut added = 0;
15609 let iterator = self.get_iterator(iterable)?;
15610 loop {
15611 let (value, done) = self.iterator_step(&iterator)?;
15612 if done {
15613 break;
15614 }
15615 target.array_set(self.heap, start + added, value);
15616 added += 1;
15617 }
15618 Ok((start + added) as i32)
15619 }
15620
15621 /// How an uncaught exception is reported.
15622 ///
15623 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
15624 /// with `ToString` — `js_std_dump_error` is three lines that end in
15625 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
15626 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
15627 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
15628 ///
15629 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
15630 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
15631 /// `toString`"; it does call it, but only for objects of a class it does not know how
15632 /// to walk, and never for errors, arrays or plain objects.
15633 ///
15634 /// A printer that fails must not take the reporter down with it, so that case falls
15635 /// back to the `ToString` rendering.
15636 pub fn describe_exception(&mut self, value: &Value) -> String {
15637 match crate::print::sprint(self, value) {
15638 Ok(text) => text,
15639 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
15640 }
15641 }
15642
15643 /// The file name of whatever is running, innermost frame first.
15644 ///
15645 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
15646 /// innermost frame's file name, without distinguishing a module body from a plain
15647 /// script. `import()` uses it as the base for a relative specifier, which is why
15648 /// `import('./x.js')` inside a script resolves next to the script and not next to the
15649 /// process's working directory.
15650 pub fn script_or_module_name(&self) -> Option<String> {
15651 self.script_or_module_name_at(0)
15652 }
15653
15654 /// [`Interp::script_or_module_name`] `level` frames further out.
15655 ///
15656 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
15657 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
15658 /// frame without a file name is skipped rather than counted, because a native call
15659 /// pushes no frame of its own and so cannot be a level.
15660 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
15661 self.frames
15662 .iter()
15663 .rev()
15664 .filter_map(|frame| frame.code.code.filename.clone())
15665 .nth(level)
15666 }
15667
15668 /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15669 ///
15670 /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15671 /// because that is what a stack trace should print, but §19.2.1.1's
15672 /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15673 /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15674 /// produced the bare specifier `x.js`, which the loader then looked for in the working
15675 /// directory instead of beside the file that called `eval`.
15676 pub fn script_or_module_file_name(&self) -> Option<String> {
15677 self.frames.iter().rev().find_map(|frame| {
15678 let name = frame.code.code.filename.as_deref()?;
15679 (!name.starts_with('<')).then(|| name.to_string())
15680 })
15681 }
15682
15683 /// The current call stack, formatted the way `qjs` prints `error.stack`.
15684 ///
15685 /// One ` at name (file:line:col)` line per active frame, innermost first. The
15686 /// position is the one recorded for the instruction each frame is stopped on, which
15687 /// is why the compiler builds a pc-to-position table per function: without it a
15688 /// trace could only name the function, not the line inside it.
15689 ///
15690 /// A frame whose code has no positions prints just `(file)`, matching the
15691 /// reference's output for stripped bytecode.
15692 pub fn stack_trace(&self) -> String {
15693 self.stack_trace_skipping(0)
15694 }
15695
15696 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15697 fn stack_trace_skipping(&self, skip: usize) -> String {
15698 // One ordered list, innermost first, so `skip` counts the same thing whether the
15699 // frames it leaves out are native or bytecode. Indices rather than references: a
15700 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
15701 let depth = self.frames.len();
15702 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
15703 // A native entered while `at` bytecode frames were live was called *from* the
15704 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
15705 // entered at the current depth are therefore innermost of all.
15706 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
15707 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
15708 if *at == wanted {
15709 order.push((true, index));
15710 }
15711 }
15712 };
15713 push_natives(&mut order, depth);
15714 for index in (0..depth).rev() {
15715 order.push((false, index));
15716 push_natives(&mut order, index);
15717 }
15718 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
15719 // barrier. Natives entered at exactly the barrier depth are the eval entry point
15720 // itself (`evalScript (native)`), and the reference leaves those out too.
15721 if let Some(barrier) = self.trace_barriers.last().copied() {
15722 order.retain(|(is_native, index)| match is_native {
15723 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
15724 false => *index >= barrier,
15725 });
15726 }
15727
15728 let mut out = String::new();
15729 for (is_native, index) in order.into_iter().skip(skip) {
15730 match is_native {
15731 true => {
15732 out.push_str(" at ");
15733 let (native, _) = &self.native_frames[index];
15734 let name = native
15735 .own_property("name")
15736 .and_then(|property| property.value)
15737 .map(|value| value.to_js_string())
15738 .unwrap_or_default();
15739 out.push_str(&name);
15740 out.push_str(" (native)\n");
15741 }
15742 false => {
15743 let frame = &self.frames[index];
15744 let code = &frame.code.code;
15745 let file = code.filename.as_deref().unwrap_or("<input>");
15746 // The name comes from the function *object*, not from the compiled code:
15747 // an anonymous function expression is named by the property it is stored
15748 // in (`{valueOf: function(){}}`), which only the object knows.
15749 let bound_name = match &frame.callee {
15750 Value::Object(object) => {
15751 object
15752 .own_property("name")
15753 .and_then(|property| match property.value {
15754 Some(Value::String(text)) if !text.wtf8().is_empty() => {
15755 Some(text.to_string_lossy().into_owned())
15756 }
15757 _ => None,
15758 })
15759 }
15760 _ => None,
15761 };
15762 // No callee object means the body was entered by the host, so the
15763 // name has to come from the compiled code. Two cases differ:
15764 //
15765 // * an *unnamed* function of any kind — the reference reads the
15766 // `name` property, finds it empty, and prints `<anonymous>`;
15767 // * a *module* body, which has no `name` property at all: the
15768 // reference builds that function object with `js_closure2` and
15769 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
15770 // so a trace reaching it also prints `<anonymous>` — while a
15771 // *script* body prints `<eval>`, its `name`.
15772 let unnamed = code.name.is_empty() || code.module.is_some();
15773 out.push_str(" at ");
15774 match bound_name.as_deref() {
15775 Some(name) => out.push_str(name),
15776 None if unnamed => out.push_str("<anonymous>"),
15777 None => out.push_str(&code.name),
15778 }
15779 match code.position_at(frame.at as u32) {
15780 Some((line, column)) => {
15781 out.push_str(&format!(" ({file}:{line}:{column})\n"));
15782 }
15783 None => out.push_str(&format!(" ({file})\n")),
15784 }
15785 }
15786 }
15787 }
15788 out
15789 }
15790
15791 /// Give an anonymous function the name of the property it is stored in.
15792 ///
15793 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
15794 /// enumerable and not configurable, and a function that already has a real name
15795 /// keeps it.
15796 ///
15797 /// "Already named" means a *non-empty* name: every function object is created with
15798 /// a `name` of `""` so the property exists on all of them, and treating that empty
15799 /// string as a name left every anonymous function nameless — which is how a stack
15800 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
15801 /// `SetFunctionName`, for a name that came from source text.
15802 fn set_function_name(&mut self, function: &Value, name: &str) {
15803 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
15804 }
15805
15806 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
15807 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
15808 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
15809 let Value::Object(object) = function else {
15810 return;
15811 };
15812 // `SetFunctionName` applies to *functions* and classes only, and only when they are
15813 // anonymous. Without the callability guard, `{value: someObject}` renamed
15814 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
15815 // on the right-hand side of a property. That is how a `zipKeyed` result object
15816 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
15817 // has no `NamedEvaluation` at all.
15818 if !object.is_callable() {
15819 return;
15820 }
15821 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
15822 && !existing.wtf8().is_empty()
15823 {
15824 return;
15825 }
15826 let text = self.string_wtf8(name.clone());
15827 object.define("name", Property::name_or_length(text));
15828 }
15829
15830 // -- global declarations -----------------------------------------------
15831
15832 /// Declare a global binding, creating its reference cell.
15833 /// Declare a `var` or function global, whose home is the global object.
15834 ///
15835 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
15836 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
15837 /// such as `print`, or a redeclaration — is left alone.
15838 pub fn declare_var_global(&mut self, name: &str) {
15839 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
15840 // global object is exactly the leak `typeof my_var === "undefined"` after
15841 // `eval("var my_var=2")` rules out.
15842 if let Some(scope) = self.eval_scope.as_mut() {
15843 scope.entry(name.to_string()).or_insert(Value::Undefined);
15844 return;
15845 }
15846 // A sloppy direct eval declares into its *caller's* variable environment. Doing
15847 // this on the global object instead made `eval("var c = 1")` inside a parameter
15848 // list overwrite a global `c`, and made two calls to the same function share one
15849 // binding.
15850 if let Some(cell) = self.declare_eval_local(name) {
15851 cell.set(Value::Undefined);
15852 return;
15853 }
15854 let global = self.realm.global.clone();
15855 if global.own_property(name).is_some() {
15856 return;
15857 }
15858 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
15859 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
15860 // whole point of that trick and what lets `Object.defineProperty` reshape it
15861 // afterwards. `eval_scope` is `Some` while an eval is running.
15862 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
15863 global.define(
15864 name,
15865 Property {
15866 value: Some(Value::Undefined),
15867 writable: true,
15868 enumerable: true,
15869 configurable: from_eval,
15870 ..Property::default()
15871 },
15872 );
15873 }
15874
15875 /// Declare a *lexical* global binding, which starts in its dead zone.
15876 ///
15877 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
15878 /// global object and is created when its initialiser runs.
15879 pub fn declare_global(&mut self, name: &str, is_const: bool) {
15880 if is_const {
15881 self.realm.lexical_consts.insert(name.to_string());
15882 }
15883 if !self.realm.globals.contains_key(name) {
15884 // `Uninitialized` rather than `Undefined`: the binding exists but is not
15885 // readable until its initialiser runs, and that is what `let x` before
15886 // `x = 1` has to observe.
15887 let cell = self.new_cell(Value::Uninitialized);
15888 self.realm.globals.insert(name.to_string(), cell);
15889 self.realm.declared.push(name.to_string());
15890 }
15891 }
15892}
15893
15894/// The bytecode and environment of a function object, if it is a bytecode function.
15895///
15896/// Extracted before a call so no borrow of the object is held across it.
15897fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
15898 function.with(|data| match &data.kind {
15899 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
15900 _ => None,
15901 })
15902}
15903
15904/// A native call target, extracted before the call so no borrow is held.
15905enum NativeCall {
15906 Native(NativeFn),
15907 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
15908 /// not hold that object's `RefCell` borrow.
15909 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
15910 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
15911 Bound {
15912 target: Value,
15913 this: Value,
15914 leading: Vec<Value>,
15915 },
15916 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
15917 Revoker(crate::object::ProxyRef),
15918 /// A promise's `resolve`.
15919 PromiseResolve(Gc<JsObject>),
15920 /// A promise's `reject`.
15921 PromiseReject(Gc<JsObject>),
15922 /// The executor `NewPromiseCapability(C)` hands a user constructor.
15923 CapabilityExecutor {
15924 state: Gc<JsObject>,
15925 },
15926 /// One leg of a `then` that settles through a user capability.
15927 ThenShim {
15928 handler: Option<Value>,
15929 resolve: Value,
15930 reject: Value,
15931 fulfilled: bool,
15932 },
15933 /// One continuation of an `await`.
15934 AwaitResume {
15935 coroutine: Gc<JsObject>,
15936 promise: Gc<JsObject>,
15937 kind: ResumeKind,
15938 },
15939 /// One element of a `Promise` combinator settling.
15940 CombinatorSettle {
15941 state: Gc<JsObject>,
15942 index: usize,
15943 fulfilled: bool,
15944 },
15945 /// One of `Promise.prototype.finally`'s two shims.
15946 FinallyShim {
15947 callback: Option<Value>,
15948 fulfilled: bool,
15949 constructor: Value,
15950 },
15951 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
15952 ReturnValue(Value),
15953 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
15954 ThrowValue(Value),
15955 /// Settle a promise with a fixed outcome.
15956 SettlePromise {
15957 promise: Gc<JsObject>,
15958 value: Value,
15959 rejected: bool,
15960 },
15961 /// Continue an async generator after its `await` settled.
15962 GeneratorResume {
15963 generator: Gc<JsObject>,
15964 promise: Gc<JsObject>,
15965 kind: ResumeKind,
15966 },
15967 /// Read a module namespace's binding out of its cell.
15968 ModuleBinding(Gc<Cell>),
15969 /// Finish a completed async generator's `return(v)` once `v` has settled.
15970 CompletedReturn {
15971 generator: Gc<JsObject>,
15972 promise: Gc<JsObject>,
15973 rejected: bool,
15974 },
15975 /// Answer a pending async-generator method with `{value, done}`.
15976 YieldResult {
15977 generator: Gc<JsObject>,
15978 promise: Gc<JsObject>,
15979 done: bool,
15980 },
15981 /// One step of `AsyncDisposableStack.disposeAsync`.
15982 DisposeStep {
15983 remaining: Gc<JsObject>,
15984 promise: Gc<JsObject>,
15985 error: Value,
15986 rejected: bool,
15987 awaited: bool,
15988 needs_await: bool,
15989 },
15990}
15991
15992/// What a store does when the object refuses the write.
15993#[derive(Clone, Copy, PartialEq, Eq)]
15994pub enum DeleteFailure {
15995 /// Raise a `TypeError`, which is what strict mode and every built-in does.
15996 Throw,
15997 /// Ignore the write, which is what a sloppy-mode assignment does.
15998 Ignore,
15999}
16000
16001/// Whether `object` is a `Date` instance, by the class tag it carries.
16002///
16003/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
16004/// builtins module depending on the interpreter's conversion order.
16005fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
16006 interp
16007 .internal_get(object, "_class")
16008 .is_some_and(|value| value.to_js_string() == "Date")
16009}
16010
16011/// Which type `ToPrimitive` prefers when it converts an object.
16012#[derive(Clone, Copy, PartialEq, Eq)]
16013pub enum Hint {
16014 /// The default hint, which behaves like [`Hint::Number`].
16015 Default,
16016 /// `Number(obj)` and the arithmetic operators.
16017 Number,
16018 /// `String(obj)` and `ToPropertyKey`.
16019 String,
16020}
16021
16022/// Which table a binding slot indexes, for the messages that name it.
16023#[derive(Clone, Copy)]
16024enum VarSlot {
16025 Loc,
16026 Closure,
16027}
16028
16029/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
16030fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
16031 Ok(this)
16032}
16033
16034/// An internal iterator: the sequence plus a cursor.
16035pub(crate) struct Iterator {
16036 pub(crate) object: Value,
16037 pub(crate) next: Value,
16038}
16039
16040/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
16041/// and plain `a` for a method.
16042///
16043/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
16044/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
16045/// reads `at get a (file:1:2)`.
16046/// The same prefixing, for a name that may hold an unpaired surrogate.
16047fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
16048 let prefix = match flags & 3 {
16049 1 => "get ",
16050 2 => "set ",
16051 _ => return key.clone(),
16052 };
16053 let mut units: Vec<u16> = prefix.encode_utf16().collect();
16054 units.extend_from_slice(&key.to_units());
16055 crate::value::Wtf8::from_units(&units)
16056}
16057
16058/// `SetFunctionName`'s name for a symbol property key: `[description]`, or `""`.
16059///
16060/// §7.3.24 step 1. A symbol without a description names the function the empty string, not
16061/// `Symbol()` — the two are different and test262 checks both.
16062fn symbol_key_name(key: &PropertyKey) -> crate::value::Wtf8 {
16063 let PropertyKey::Symbol(symbol) = key else {
16064 return crate::value::Wtf8::default();
16065 };
16066 match symbol.description() {
16067 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
16068 None => crate::value::Wtf8::default(),
16069 }
16070}
16071
16072/// Define a method or accessor property, per the `define_method` flag byte.
16073///
16074/// The low two bits pick value/getter/setter and bit 2 marks the property
16075/// enumerable.
16076///
16077/// A getter and a setter arrive as two separate `define_method` instructions, and the
16078/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
16079/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
16080/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
16081/// `JS_DefineProperty`, which leaves the other half alone.
16082fn define_function_property(
16083 object: &Gc<JsObject>,
16084 key: &PropertyKey,
16085 function: Value,
16086 flags: u32,
16087) -> bool {
16088 let enumerable = flags & 4 != 0;
16089 let kind = flags & 3;
16090 let existing = object.own_property_key(key);
16091 let property = match kind {
16092 1 => Property {
16093 getter: Some(function),
16094 // The setter half, if this literal already defined one.
16095 setter: existing
16096 .filter(Property::is_accessor)
16097 .and_then(|p| p.setter),
16098 enumerable,
16099 configurable: true,
16100 ..Property::default()
16101 },
16102 2 => Property {
16103 getter: existing
16104 .filter(Property::is_accessor)
16105 .and_then(|p| p.getter),
16106 setter: Some(function),
16107 enumerable,
16108 configurable: true,
16109 ..Property::default()
16110 },
16111 _ => Property {
16112 value: Some(function),
16113 writable: true,
16114 enumerable,
16115 configurable: true,
16116 ..Property::default()
16117 },
16118 };
16119 object.create_data_property_key(key, property)
16120}
16121
16122// ---------------------------------------------------------------------------
16123// Operand decoding
16124// ---------------------------------------------------------------------------
16125
16126/// How `print` renders a value: the reference's `JS_PrintValue`.
16127///
16128/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
16129/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
16130/// The format is reproduced closely because the test suite compares output text:
16131///
16132/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
16133/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
16134/// * a cycle prints `[circular N]` with `N` the stack index of the object;
16135/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
16136/// end print as `<N empty item(s)>`;
16137/// * a string is quoted inside a container but raw at the top level, which is why
16138/// `print("x")` and `print(["x"])` differ.
16139pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
16140 // A string argument is printed raw: `js_print` converts it with `ToString`
16141 // instead of dumping it, and the quoting only appears inside a container.
16142 if let Value::String(text) = value {
16143 return text.to_string_lossy().into_owned();
16144 }
16145 let mut printer = Printer {
16146 interp,
16147 out: String::new(),
16148 stack: Vec::new(),
16149 };
16150 printer.value(value, 0);
16151 printer.out
16152}
16153
16154/// The internal class name an object carries, when it has one.
16155fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
16156 interp
16157 .internal_get(object, "_class")
16158 .map(|value| value.to_js_string())
16159}
16160
16161/// A string property, looked up the way `GetProperty` does: own first, then the
16162/// prototype chain. Needed because the print formatter holds the interpreter
16163/// immutably and so cannot run getters.
16164fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
16165 let mut current = Some(object.clone());
16166 // Bounded, because a prototype cycle would otherwise loop forever.
16167 for _ in 0..100 {
16168 let node = current?;
16169 if let Some(property) = node.own_property(name)
16170 && let Some(value) = property.value
16171 {
16172 return Some(value.to_js_string());
16173 }
16174 current = node.with(|data| data.proto.clone());
16175 }
16176 None
16177}
16178
16179/// The `JS_PrintValue` state: output, and the objects currently being printed.
16180struct Printer<'a, 'rt> {
16181 /// Kept for the class-name lookups that typed arrays and `Date` will need.
16182 #[allow(dead_code)]
16183 interp: &'a Interp<'rt>,
16184 out: String,
16185 stack: Vec<Gc<JsObject>>,
16186}
16187
16188impl Printer<'_, '_> {
16189 /// Depth past which a container is summarised by its class name.
16190 const MAX_DEPTH: usize = 2;
16191
16192 fn value(&mut self, value: &Value, level: usize) {
16193 match value {
16194 Value::Undefined
16195 | Value::Uninitialized
16196 | Value::Hole
16197 | Value::CatchOffset(_)
16198 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
16199 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
16200 // The printer writes a bigint the way the language spells one, so a dump is
16201 // unambiguous about which kind of number it is showing.
16202 Value::BigInt(big) => {
16203 self.out.push_str(&big.to_decimal_string());
16204 self.out.push('n');
16205 }
16206 Value::Null => self.out.push_str("null"),
16207 Value::Bool(true) => self.out.push_str("true"),
16208 Value::Bool(false) => self.out.push_str("false"),
16209 Value::Int(number) => self.out.push_str(&number.to_string()),
16210 Value::Float(number) => {
16211 self.out
16212 .push_str(&crate::value::number_to_string_for_print(*number));
16213 }
16214 Value::String(text) => self.print_string(&text.to_string_lossy()),
16215 Value::Object(object) => self.object(object, level),
16216 }
16217 }
16218
16219 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
16220 // A cycle is reported rather than followed; the index is where the object
16221 // already sits in the print stack, which is what the reference shows.
16222 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
16223 self.out.push_str(&format!("[circular {index}]"));
16224 return;
16225 }
16226 if object.is_callable() {
16227 let name = object
16228 .own_property("name")
16229 .and_then(|property| property.value)
16230 .map(|value| value.to_js_string())
16231 .unwrap_or_default();
16232 if name.is_empty() {
16233 self.out.push_str("[Function (anonymous)]");
16234 } else {
16235 self.out.push_str(&format!("[Function {name}]"));
16236 }
16237 return;
16238 }
16239 if level >= Self::MAX_DEPTH {
16240 let class = if object.is_array() { "Array" } else { "Object" };
16241 self.out.push_str(&format!("[{class}]"));
16242 return;
16243 }
16244 // A `RegExp` prints as its own literal, `js_print_regexp`'s `/%s/%s`. Without this
16245 // it fell through to the plain-object form and `print(/x/)` answered `{ }` — no
16246 // properties, so nothing to show, and the value's identity lost.
16247 if let Some(data) = object.regexp() {
16248 let source = crate::builtins::regexp::escaped_source(&data.source);
16249 self.out.push('/');
16250 self.out.push_str(&source.to_string_lossy());
16251 self.out.push('/');
16252 self.out.push_str(&data.flags);
16253 return;
16254 }
16255 // `Date` and `Error` print as themselves rather than as bags of properties:
16256 // the ISO string, and `Name: message` followed by the trace.
16257 if let Some(class) = class_of(self.interp, object) {
16258 if class == "Date" {
16259 self.date(object);
16260 return;
16261 }
16262 if class == "Error" {
16263 self.error(object);
16264 return;
16265 }
16266 }
16267 self.stack.push(object.clone());
16268 if object.is_array() {
16269 self.array(object, level);
16270 } else {
16271 self.plain_object(object, level);
16272 }
16273 self.stack.pop();
16274 }
16275
16276 /// A Date prints as its ISO string; an invalid one falls through to the plain
16277 /// object form, the way the reference falls back when `toISOString` throws.
16278 fn date(&mut self, object: &Gc<JsObject>) {
16279 let value = self
16280 .interp
16281 .internal_get(object, "_date_value")
16282 .map(|value| value.to_number());
16283 match value.and_then(crate::builtins::date::iso_string) {
16284 Some(text) => self.out.push_str(&text),
16285 None => self.plain_object(object, 0),
16286 }
16287 }
16288
16289 /// `Name: message`, then the trace with its trailing newline removed.
16290 fn error(&mut self, object: &Gc<JsObject>) {
16291 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
16292 self.out.push_str(&name);
16293 if let Some(message) = inherited(object, "message")
16294 && !message.is_empty()
16295 {
16296 self.out.push_str(": ");
16297 self.out.push_str(&message);
16298 }
16299 if let Some(stack) = inherited(object, "stack") {
16300 self.out.push('\n');
16301 self.out.push_str(stack.trim_end_matches('\n'));
16302 }
16303 }
16304
16305 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
16306 let elements = object.array_elements().unwrap_or_default();
16307 self.out.push_str("[ ");
16308 // An interior hole means the array is "sparse": the reference prints those
16309 // as `index: value` pairs and says nothing about the holes themselves, while
16310 // a hole run at the end becomes a single `<N empty items>` note.
16311 let last_present = elements
16312 .iter()
16313 .rposition(|value| !matches!(value, Value::Hole));
16314 let has_interior_hole = match last_present {
16315 Some(last) => elements[..last]
16316 .iter()
16317 .any(|value| matches!(value, Value::Hole)),
16318 None => false,
16319 };
16320 let mut first = true;
16321 if has_interior_hole {
16322 let mut index = 0;
16323 while index < elements.len() {
16324 let value = &elements[index];
16325 if matches!(value, Value::Hole) {
16326 index += 1;
16327 continue;
16328 }
16329 if !first {
16330 self.out.push_str(", ");
16331 }
16332 first = false;
16333 self.out.push_str(&format!("{index}: "));
16334 self.value(value, level + 1);
16335 index += 1;
16336 }
16337 } else {
16338 for (index, value) in elements.iter().enumerate() {
16339 if matches!(value, Value::Hole) {
16340 continue;
16341 }
16342 if !first {
16343 self.out.push_str(", ");
16344 }
16345 first = false;
16346 let _ = index;
16347 self.value(value, level + 1);
16348 }
16349 if let Some(last) = last_present {
16350 let trailing = elements.len() - last - 1;
16351 if trailing > 0 {
16352 if !first {
16353 self.out.push_str(", ");
16354 }
16355 self.out.push_str(&format!(
16356 "<{trailing} empty item{}>",
16357 if trailing > 1 { "s" } else { "" }
16358 ));
16359 }
16360 } else if !elements.is_empty() {
16361 let count = elements.len();
16362 self.out.push_str(&format!(
16363 "<{count} empty item{}>",
16364 if count > 1 { "s" } else { "" }
16365 ));
16366 }
16367 }
16368 self.out.push_str(" ]");
16369 }
16370
16371 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
16372 self.out.push_str("{ ");
16373 let mut first = true;
16374 for key in object.own_keys() {
16375 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
16376 continue;
16377 };
16378 if !property.enumerable {
16379 continue;
16380 }
16381 if !first {
16382 self.out.push_str(", ");
16383 }
16384 first = false;
16385 self.out
16386 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
16387 &key.to_string_lossy(),
16388 )));
16389 self.out.push_str(": ");
16390 // An accessor has no value to dump; the reference names the half that
16391 // exists instead of calling it.
16392 if property.is_accessor() {
16393 let text = match (property.getter.is_some(), property.setter.is_some()) {
16394 (true, true) => "[Getter/Setter]",
16395 (false, true) => "[Setter]",
16396 _ => "[Getter]",
16397 };
16398 self.out.push_str(text);
16399 } else {
16400 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
16401 }
16402 }
16403 self.out.push_str(" }");
16404 }
16405
16406 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
16407 fn print_string(&mut self, text: &str) {
16408 self.out.push('"');
16409 for character in text.chars() {
16410 match character {
16411 '"' => self.out.push_str("\\\""),
16412 '\\' => self.out.push_str("\\\\"),
16413 '\n' => self.out.push_str("\\n"),
16414 '\r' => self.out.push_str("\\r"),
16415 '\t' => self.out.push_str("\\t"),
16416 c if (c as u32) < 0x20 => {
16417 self.out.push_str(&format!("\\u{:04x}", c as u32));
16418 }
16419 c => self.out.push(c),
16420 }
16421 }
16422 self.out.push('"');
16423 }
16424}
16425
16426/// How `print` renders a value.
16427///
16428/// `ToString`, except that negative zero keeps its sign — the reference's host
16429/// printer does that while `String(-0)` is `"0"`.
16430pub fn display(value: &Value) -> String {
16431 match value {
16432 Value::Float(number) => crate::value::number_to_string_for_print(*number),
16433 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
16434 "undefined".to_string()
16435 }
16436 other => other.to_js_string(),
16437 }
16438}
16439
16440// ---------------------------------------------------------------------------
16441// Numeric operators
16442// ---------------------------------------------------------------------------
16443
16444/// `a + b` keeping the `Int` representation when it fits.
16445fn add_numbers(left: Value, right: Value) -> Value {
16446 match (&left, &right) {
16447 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
16448 Some(sum) => Value::Int(sum),
16449 None => Value::Float(*a as f64 + *b as f64),
16450 },
16451 _ => Value::Float(left.to_number() + right.to_number()),
16452 }
16453}
16454
16455/// The arithmetic operators other than `+`, which needs string concatenation.
16456fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16457 use Opcode::*;
16458 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
16459 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
16460 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
16461 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
16462 return Ok(match op {
16463 And => Value::Int(x & y),
16464 Or => Value::Int(x | y),
16465 Xor => Value::Int(x ^ y),
16466 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
16467 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
16468 Shr => match (*x as u32) >> ((*y as u32) & 31) {
16469 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
16470 shifted => Value::Float(shifted as f64),
16471 },
16472 Sub => match x.checked_sub(*y) {
16473 Some(value) => Value::Int(value),
16474 None => Value::Float(*x as f64 - *y as f64),
16475 },
16476 _ => return arithmetic_slow(op, left, right),
16477 });
16478 }
16479 arithmetic_slow(op, left, right)
16480}
16481
16482/// [`arithmetic`] for everything the integer fast path above does not take.
16483fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16484 use Opcode::*;
16485 let (a, b) = (left.to_number(), right.to_number());
16486 Ok(match op {
16487 Sub => match (&left, &right) {
16488 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
16489 Some(value) => Value::Int(value),
16490 None => Value::Float(a - b),
16491 },
16492 _ => Value::Float(a - b),
16493 },
16494 Mul => Value::Float(a * b),
16495 Div => Value::Float(a / b),
16496 Mod => Value::Float(js_mod(a, b)),
16497 Pow => Value::Float(a.powf(b)),
16498 And => Value::Int(left.to_int32() & right.to_int32()),
16499 Or => Value::Int(left.to_int32() | right.to_int32()),
16500 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
16501 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
16502 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
16503 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
16504 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
16505 // fits the small-integer representation stays an `Int`; the rest become a
16506 // float, which is how the reference keeps `n >>> 0` non-negative.
16507 Shr => {
16508 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
16509 match i32::try_from(shifted) {
16510 Ok(value) => Value::Int(value),
16511 Err(_) => Value::Float(shifted as f64),
16512 }
16513 }
16514 _ => Value::Float(a),
16515 })
16516}
16517
16518/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16519///
16520/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16521/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16522/// slow path where the rules live.
16523fn is_number(value: &Value) -> bool {
16524 matches!(value, Value::Int(_) | Value::Float(_))
16525}
16526
16527/// The `Value::Bool` a comparison operator answers for `ordering`.
16528///
16529/// `None` is the unordered case — a `NaN` on either side — and every operator answers
16530/// false for it, including `<=` and `>=`.
16531fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
16532 use Opcode::*;
16533 let answer = match (op, ordering) {
16534 (_, None) => false,
16535 (Lt, Some(ordering)) => ordering.is_lt(),
16536 (Lte, Some(ordering)) => ordering.is_le(),
16537 (Gt, Some(ordering)) => ordering.is_gt(),
16538 (Gte, Some(ordering)) => ordering.is_ge(),
16539 _ => false,
16540 };
16541 Value::Bool(answer)
16542}
16543
16544/// `%`, which follows the sign of the dividend rather than Rust's.
16545fn js_mod(left: f64, right: f64) -> f64 {
16546 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
16547 return f64::NAN;
16548 }
16549 if right.is_infinite() {
16550 return left;
16551 }
16552 let remainder = left % right;
16553 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
16554 // the spec makes the sign match the dividend.
16555 if remainder == 0.0 {
16556 0.0f64.copysign(left)
16557 } else {
16558 remainder
16559 }
16560}
16561
16562fn negate(value: Value) -> Value {
16563 match value {
16564 Value::Int(0) => Value::Float(-0.0),
16565 Value::Int(i) => Value::Int(-i),
16566 other => Value::Float(-other.to_number()),
16567 }
16568}
16569
16570fn increment(value: Value) -> Value {
16571 match value {
16572 Value::Int(i) => match i.checked_add(1) {
16573 Some(next) => Value::Int(next),
16574 None => Value::Float(i as f64 + 1.0),
16575 },
16576 other => Value::Float(other.to_number() + 1.0),
16577 }
16578}
16579
16580fn decrement(value: Value) -> Value {
16581 match value {
16582 Value::Int(i) => match i.checked_sub(1) {
16583 Some(next) => Value::Int(next),
16584 None => Value::Float(i as f64 - 1.0),
16585 },
16586 other => Value::Float(other.to_number() - 1.0),
16587 }
16588}
16589
16590/// Compare a `BigInt` with an `f64` on their mathematical values.
16591///
16592/// Neither side is rounded to the other's precision: the number is split into its integer
16593/// part (compared as an exact bigint) and its fraction, which is what decides the answer
16594/// when the integer parts are equal. An infinite value is larger than every bigint.
16595fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
16596 use std::cmp::Ordering;
16597 if number.is_nan() {
16598 return None;
16599 }
16600 if number.is_infinite() {
16601 return Some(if number > 0.0 {
16602 Ordering::Less
16603 } else {
16604 Ordering::Greater
16605 });
16606 }
16607 // The comparison is **exact**, because rounding it is observable: an f64 is
16608 // `m * 2^e` with `m` a 53-bit integer, so scaling the bigint by the same power of two
16609 // turns this into an integer comparison at any width. Converting the *bigint* to f64
16610 // instead — which is what this used to do once the number was wider than `i128` —
16611 // rounds it to the nearest double, and `0xfffffffffffff7ff…n < Number.MAX_VALUE` is
16612 // decided by a difference of one bit at 2^971, which rounding erases
16613 // (`less-than/bigint-and-number-extremes`).
16614 // Both branches answer `big.cmp(number)`; which side gets scaled depends on the sign of
16615 // the exponent, because scaling the smaller one keeps the shift bounded by the f64's own
16616 // range (at most 1074 bits) instead of by the bigint's width.
16617 let (mantissa, exponent) = decompose_f64(number);
16618 let product = crate::bigint::BigInt::from_i64(mantissa);
16619 Some(if exponent >= 0 {
16620 // `number = mantissa * 2^exponent`, and that product is the exact f64 value.
16621 big.cmp(&product.shl(exponent as u64))
16622 } else {
16623 // `number = mantissa / 2^-exponent`; scale the *bigint* up instead so both sides stay
16624 // integers.
16625 big.shl((-exponent) as u64).cmp(&product)
16626 })
16627}
16628
16629/// `value` as `(mantissa, exponent)` with `value == mantissa * 2^exponent` exactly.
16630///
16631/// `mantissa` carries the sign and is the f64's significand with its implicit bit made
16632/// explicit, so `|mantissa| <= 2^53` and the `i64` conversion is exact. `value` must be
16633/// finite.
16634fn decompose_f64(value: f64) -> (i64, i32) {
16635 let bits = value.abs().to_bits();
16636 let raw_exponent = ((bits >> 52) & 0x7ff) as i32;
16637 let fraction = bits & ((1u64 << 52) - 1);
16638 // A subnormal has no implicit bit and an exponent of `1 - 1023`; a normal one carries a
16639 // leading 1 at bit 52, and the `-1075` folds in the bias and the 52 fraction bits.
16640 let (significand, exponent) = if raw_exponent == 0 {
16641 (fraction, -1074)
16642 } else {
16643 (fraction | (1u64 << 52), raw_exponent - 1075)
16644 };
16645 let significand = significand as i64;
16646 let mantissa = if value < 0.0 {
16647 -significand
16648 } else {
16649 significand
16650 };
16651 (mantissa, exponent)
16652}
16653
16654/// The UTF-16 code unit ordering of two strings, which is what `<` compares.
16655///
16656/// `JsString` caches its code units on first access, so the first `code_unit_at` builds the
16657/// cache and the rest are O(1) — no allocation here, and no decoding in the loop.
16658fn compare_code_units(
16659 a: &crate::value::JsString,
16660 b: &crate::value::JsString,
16661) -> std::cmp::Ordering {
16662 let (left, right) = (a.utf16_len(), b.utf16_len());
16663 for index in 0..left.min(right) {
16664 let (x, y) = (
16665 a.code_unit_at(index).unwrap_or(0),
16666 b.code_unit_at(index).unwrap_or(0),
16667 );
16668 if x != y {
16669 return x.cmp(&y);
16670 }
16671 }
16672 // A proper prefix sorts first, which is what the length comparison gives.
16673 left.cmp(&right)
16674}
16675
16676/// `StringToBigInt(argument)` (§7.1.14): the string read as an **integer** literal.
16677///
16678/// `undefined` — `None` here — for anything that is only a *number* literal: `"0."`,
16679/// `".0"`, `"0e0"` and `"Infinity"` all fail, which is why `1n > "0."` is `false` rather
16680/// than `true` (`greater-than/bigint-and-incomparable-string`). Leading zeros are outside
16681/// the grammar too (`"007"`), and so is whitespace between the sign and the digits.
16682///
16683/// The empty string *is* `0n`: §7.1.14 turns a whitespace-only literal into `0`.
16684fn string_to_bigint(text: &str) -> Option<crate::bigint::BigInt> {
16685 let trimmed = text.trim();
16686 let body = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
16687 let signed = body.len() != trimmed.len();
16688 // A radix prefix admits no sign, and the digits must follow immediately.
16689 let (radix, digits) = if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
16690 (16, rest)
16691 } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
16692 (8, rest)
16693 } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
16694 (2, rest)
16695 } else {
16696 (10, body)
16697 };
16698 if signed && radix != 10 && signed {
16699 // `StrNonDecimalIntegerLiteral` has no sign.
16700 return None;
16701 }
16702 if radix == 10 && digits.len() > 1 && digits.starts_with('0') {
16703 // `StrUnsignedDecimalLiteral : 0 | NonZeroDigit DecimalDigits?`.
16704 return None;
16705 }
16706 crate::bigint::BigInt::from_string(trimmed)
16707}
16708
16709/// `CanonicalNumericIndexString(argument)` (§7.1.21).
16710///
16711/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
16712/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
16713/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
16714/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
16715/// rather than treating it as `0`.
16716fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
16717 let PropertyKey::String(text) = key else {
16718 // A symbol is never an index.
16719 return None;
16720 };
16721 let text = text.to_string_lossy();
16722 if text == "-0" {
16723 return Some(-0.0);
16724 }
16725 let number: f64 = text.parse().ok()?;
16726 // The round-trip test *is* the definition: only the canonical spelling qualifies.
16727 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
16728 // `"0.10"` does not.
16729 let rendered = Value::Float(number).to_js_string();
16730 (rendered == text).then_some(number)
16731}
16732
16733/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
16734///
16735/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
16736/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
16737/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
16738/// numeric and invalid, which is why they stop the prototype chain instead of falling
16739/// through it.
16740///
16741/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
16742/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
16743/// `in`, `delete` and `defineProperty` separately to make sure it does not.
16744fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
16745 numeric.is_finite()
16746 && numeric.fract() == 0.0
16747 && !(numeric == 0.0 && numeric.is_sign_negative())
16748 && numeric >= 0.0
16749 && object
16750 .typed_array_length()
16751 .is_some_and(|length| (numeric as usize) < length)
16752}
16753
16754/// `ArrayCreate`'s length bound, `2**32 - 1`.
16755///
16756/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
16757/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
16758/// through — can enforce it without depending on a builtin module.
16759const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;