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, RefTarget, array_index, has_own,
27 lookup_key, 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 /// Which phase `import`/`import.defer`/`import.source` asked for.
598 phase: js_parse::ast::ImportPhase,
599 },
600 /// An async generator resuming after the value it awaited settled.
601 GeneratorResume {
602 /// The async generator to continue.
603 generator: Gc<JsObject>,
604 /// The promise the pending method returned.
605 promise: Gc<JsObject>,
606 /// Whether this delivers the value or raises the reason.
607 kind: ResumeKind,
608 /// The settled value, or the rejection reason.
609 value: Value,
610 },
611 /// An async function resuming after the value it awaited settled.
612 Resume {
613 /// The body, parked in a coroutine.
614 coroutine: Gc<JsObject>,
615 /// The promise the async function handed its caller.
616 promise: Gc<JsObject>,
617 /// Whether this resumption delivers a value or raises one.
618 kind: ResumeKind,
619 /// The settled value, or the rejection reason.
620 value: Value,
621 },
622}
623
624/// One macro-task: work the event loop owes the script but has not run yet.
625///
626/// The microtask queue ([`Job`]) is different: those run before the host regains control.
627/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
628/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
629/// logic: the engine decides *what* is due, the host decides *how to wait*.
630///
631/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
632/// reference counting even though nothing else references it — the same rule the `HostFn`
633/// documentation states from the other side (a host closure must not hold a `Gc`, so the
634/// `Gc` lives here instead).
635pub enum Task {
636 /// A `setTimeout` that is due at `due_at`.
637 ///
638 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
639 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
640 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
641 /// would give this engine a timer the reference cannot produce, with nothing to
642 /// compare it against.
643 Timer {
644 /// The id `setTimeout` returned, for `clearTimeout`.
645 id: i32,
646 /// What to call when it fires.
647 callback: Value,
648 /// When it becomes runnable, as a monotonic instant.
649 due_at: std::time::Instant,
650 },
651}
652
653/// A descriptor the host has to poll, and which directions have a handler.
654///
655/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
656/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
657/// blocks on it, and the host reports back through [`Interp::fire_fd`].
658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
659pub struct FdInterest {
660 /// The descriptor to watch.
661 pub fd: i32,
662 /// Whether `os.setReadHandler` registered a callback.
663 pub read: bool,
664 /// Whether `os.setWriteHandler` registered a callback.
665 pub write: bool,
666}
667
668/// The callbacks registered for one descriptor, per direction.
669#[derive(Default)]
670pub(crate) struct FdHandlers {
671 /// `os.setReadHandler`'s callback.
672 pub read: Option<Value>,
673 /// `os.setWriteHandler`'s callback.
674 pub write: Option<Value>,
675}
676
677/// The file name `eval` reports, which the reference does not inherit from the caller.
678///
679/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
680/// reference and the names show up in stack traces.
681/// The description of the private symbol a class brand is made from.
682///
683/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
684/// place no script can reach, since no expression can name a private symbol.
685const BRAND_DESCRIPTION: &str = "brand";
686
687/// One validated property lookup.
688///
689/// Covers both own-property hits and prototype hits. The second kind was deliberately left
690/// uncached at first ("a prototype hit depends on more than the object and the name"), and
691/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
692/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
693/// names on every iteration (measured: 100 ns per call over an empty loop).
694pub struct FieldCache {
695 /// The name, so two different properties of one object do not collide.
696 key: PropertyKey,
697 /// Where the value was found, relative to the chain below.
698 index: usize,
699 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
700 level: u8,
701 /// The receiver and every prototype down to (and including) the level that answered,
702 /// each with the length of its property table at the time.
703 ///
704 /// That length is the whole guard, and it is sufficient for the ways the answer can
705 /// change without a lookup: adding or deleting any property moves it, and a
706 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
707 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
708 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
709 /// the one that was cached.
710 ///
711 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
712 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
713 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
714}
715
716/// How many links of a prototype chain a [`FieldCache`] remembers.
717///
718/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
719/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
720/// at three.
721const MAX_CACHED_CHAIN: usize = 3;
722
723/// A remembered global-variable lookup.
724///
725/// A `var` global is an ordinary property of the global object, so reading one walks the
726/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
727/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
728/// fixed by the bytecode, and the slot in the object's table only changes if the global
729/// object is mutated, which the index-and-name check below catches.
730pub struct GlobalCache {
731 /// The global object the lookup was resolved on, weakly.
732 object: js_gc::WeakGc<JsObject>,
733 /// Index of the data property in the global object's table.
734 index: usize,
735}
736
737/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
738const GLOBAL_CACHE_SLOTS: usize = 1024;
739
740/// How many property lookups are remembered.
741///
742/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
743/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
744/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
745/// lookup itself. Making it bigger stops helping: the working set of a real program's
746/// property sites is bounded by its code size.
747const FIELD_CACHE_SLOTS: usize = 4096;
748
749/// How much the heap may grow past the last `out of memory` before saying it again.
750///
751/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
752/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
753/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
754/// because it looks like it works. The reference gets this for free: it fails inside
755/// `js_malloc`, and its printing path happens not to allocate.
756///
757/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
758/// allocating is stopped within a rounding error of the limit) and far above what a
759/// handler needs.
760const OOM_HYSTERESIS: usize = 64 * 1024;
761
762/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
763pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
764
765/// How many instructions run between polls of [`Interp::interrupt`].
766///
767/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
768/// order of magnitude on both implementations — which is what lets a C driver compare its
769/// output byte for byte (see `scripts/m15-capi.sh --embed`).
770pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
771
772/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
773///
774/// Chosen so that the byte budget is what actually decides for every ordinary
775/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
776/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
777/// millions of frames.
778pub const MAX_FRAMES: usize = 200_000;
779
780const EVAL_FILE: &str = "<input>";
781
782/// The file name `std.evalScript` reports.
783const EVAL_SCRIPT_FILE: &str = "<evalScript>";
784
785/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
786///
787/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
788/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
789fn clamp_delay(delay_ms: f64) -> std::time::Duration {
790 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
791 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
792 // non-positive delay mean "due now".
793 if delay_ms.is_nan() || delay_ms <= 0.0 {
794 return std::time::Duration::ZERO;
795 }
796 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
797}
798
799impl js_gc::Trace for Task {
800 fn trace(&self, tracer: &mut js_gc::Tracer) {
801 let Task::Timer { callback, .. } = self;
802 callback.trace(tracer);
803 }
804}
805
806/// What one turn of the event loop did, so the caller cannot spin by accident.
807///
808/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
809/// core until the timer is due. Naming the three cases makes the wait explicit.
810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
811pub enum Turn {
812 /// Something ran. Call again immediately — there may be more ready work.
813 Ran,
814 /// Nothing is runnable, but descriptors are registered: the host must poll
815 /// [`Interp::pending_fds`] for at most this long, then report readiness with
816 /// [`Interp::fire_fd`].
817 ///
818 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
819 /// the failure this project treats as worst — a handler that silently never fires —
820 /// so the two cannot be confused by accident.
821 Poll(std::time::Duration),
822 /// Nothing is runnable yet, but something is pending. Block at most this long, then
823 /// call again.
824 Wait(std::time::Duration),
825 /// Nothing is pending at all: the loop is done.
826 Done,
827}
828
829impl js_gc::Trace for Job {
830 fn trace(&self, tracer: &mut js_gc::Tracer) {
831 match self {
832 Job::Reaction {
833 handler,
834 argument,
835 promise,
836 ..
837 } => {
838 if let Some(handler) = handler {
839 handler.trace(tracer);
840 }
841 argument.trace(tracer);
842 tracer.visit(promise);
843 }
844 Job::Thenable {
845 then,
846 value,
847 promise,
848 } => {
849 then.trace(tracer);
850 value.trace(tracer);
851 tracer.visit(promise);
852 }
853 Job::Resume {
854 coroutine,
855 promise,
856 value,
857 ..
858 } => {
859 tracer.visit(coroutine);
860 tracer.visit(promise);
861 value.trace(tracer);
862 }
863 Job::Import { promise, .. } => tracer.visit(promise),
864 Job::GeneratorResume {
865 generator,
866 promise,
867 value,
868 ..
869 } => {
870 tracer.visit(generator);
871 tracer.visit(promise);
872 value.trace(tracer);
873 }
874 }
875 }
876}
877
878/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
879#[derive(Debug, Clone, Copy, PartialEq, Eq)]
880pub enum ResumeKind {
881 /// The generator was just created and is being run to its first suspension.
882 Start,
883 /// `next(v)`.
884 Next,
885 /// `return(v)`.
886 Return,
887 /// `throw(e)`.
888 Throw,
889}
890
891/// A generator object's saved execution.
892///
893/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
894/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
895/// separately allocated buffers.
896pub struct GeneratorState {
897 /// The detached frame, or `None` once the generator has finished or while it runs.
898 frame: Option<Frame>,
899 /// How far it got.
900 phase: GeneratorPhase,
901 /// Whether the last suspension was an `await` rather than a `yield`.
902 ///
903 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
904 /// value and a magic number, because the emitted code branches on which method
905 /// resumed it, while an `await` simply continues with its value. Getting this wrong
906 /// leaves an extra value on the operand stack that the next instruction then
907 /// consumes — a wrong answer rather than a crash.
908 parked_on_await: bool,
909 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
910 ///
911 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
912 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
913 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
914 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
915 /// delegating. Tracking it as part of the phase, the way the reference splits
916 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
917 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
918 /// exception and never reached `xs.throw`.
919 parked_on_yield_star: bool,
920 /// Pending `next`/`return`/`throw` calls, oldest first.
921 ///
922 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
923 /// called back to back must answer in that order, with the second call's value
924 /// arriving at the *second* `yield`. Running each call straight into the body — which
925 /// is what this engine did before — delivered the last queued value to whichever
926 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
927 /// `a === b ===` the final argument.
928 ///
929 /// The front entry is the one being served; it stays there (with `async_busy` set)
930 /// until its promise settles, because an `await` inside the body is a suspension of
931 /// the *driver*, not the end of the request.
932 requests: std::collections::VecDeque<AsyncRequest>,
933 /// Whether the front request is in flight.
934 async_busy: bool,
935 /// Whether this came from an `async function*`.
936 ///
937 /// A sync generator and an async one share `ObjectKind::Generator`, so without this
938 /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
939 /// `AsyncGeneratorValidate` has to tell them apart
940 /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
941 pub is_async: bool,
942}
943
944/// How one async-generator request ended.
945enum AsyncOutcome {
946 /// The method answered this `{value, done}`.
947 Value(Value),
948 /// The body threw.
949 Error(Value),
950}
951
952/// One queued `next`/`return`/`throw` on an async generator: the reference's
953/// `JSAsyncGeneratorRequest`.
954pub struct AsyncRequest {
955 /// Which method was called.
956 kind: ResumeKind,
957 /// Its argument.
958 value: Value,
959 /// The promise the method answered.
960 promise: Gc<JsObject>,
961}
962
963/// Which of §27.5.3.3's states a generator is in.
964#[derive(Debug, Clone, Copy, PartialEq, Eq)]
965enum GeneratorPhase {
966 /// Created, `initial_yield` reached, body not entered.
967 SuspendedStart,
968 /// Parked at a `yield`.
969 SuspendedYield,
970 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
971 Executing,
972 /// Finished; the frame is gone.
973 Completed,
974}
975
976impl js_gc::Trace for GeneratorState {
977 fn trace(&self, tracer: &mut js_gc::Tracer) {
978 if let Some(frame) = &self.frame {
979 frame.trace(tracer);
980 }
981 for request in &self.requests {
982 request.value.trace(tracer);
983 tracer.visit(&request.promise);
984 }
985 }
986}
987
988/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
989/// them in.
990///
991/// Each is a field rather than a map entry because the runtime reads them on hot paths
992/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
993/// failure — reaching a default here means the builtin did not install, and every
994/// accessor panics rather than silently answering `undefined`.
995///
996/// [`builtins::symbol`]: crate::builtins::symbol
997#[derive(Default)]
998pub struct WellKnownSymbols {
999 /// The symbol values, positionally. Empty until `Symbol` installs.
1000 symbols: Vec<Value>,
1001}
1002
1003/// Which well-known symbol a caller wants.
1004///
1005/// A typed accessor beats passing a name around: a typo is a compile error rather than
1006/// an `undefined` key that quietly matches nothing.
1007#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1008pub enum WellKnown {
1009 /// `Symbol.toPrimitive`.
1010 ToPrimitive,
1011 /// `Symbol.iterator`.
1012 Iterator,
1013 /// `Symbol.match`.
1014 Match,
1015 /// `Symbol.matchAll`.
1016 MatchAll,
1017 /// `Symbol.replace`.
1018 Replace,
1019 /// `Symbol.search`.
1020 Search,
1021 /// `Symbol.split`.
1022 Split,
1023 /// `Symbol.toStringTag`.
1024 ToStringTag,
1025 /// `Symbol.isConcatSpreadable`.
1026 IsConcatSpreadable,
1027 /// `Symbol.hasInstance`.
1028 HasInstance,
1029 /// `Symbol.species`.
1030 Species,
1031 /// `Symbol.unscopables`.
1032 Unscopables,
1033 /// `Symbol.asyncIterator`.
1034 AsyncIterator,
1035 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1036 Disposable,
1037 /// `Symbol.asyncDispose` — the awaited form.
1038 AsyncDisposable,
1039}
1040
1041impl WellKnown {
1042 /// The index `Symbol`'s installer creates this symbol at.
1043 fn index(self) -> usize {
1044 match self {
1045 WellKnown::ToPrimitive => 0,
1046 WellKnown::Iterator => 1,
1047 WellKnown::Match => 2,
1048 WellKnown::MatchAll => 3,
1049 WellKnown::Replace => 4,
1050 WellKnown::Search => 5,
1051 WellKnown::Split => 6,
1052 WellKnown::ToStringTag => 7,
1053 WellKnown::IsConcatSpreadable => 8,
1054 WellKnown::HasInstance => 9,
1055 WellKnown::Species => 10,
1056 WellKnown::Unscopables => 11,
1057 WellKnown::AsyncIterator => 12,
1058 WellKnown::Disposable => 13,
1059 WellKnown::AsyncDisposable => 14,
1060 }
1061 }
1062}
1063
1064impl Realm {
1065 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1066 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1067 self.well_known_symbols.symbols = symbols;
1068 }
1069
1070 /// A well-known symbol.
1071 pub fn well_known(&self, which: WellKnown) -> Value {
1072 self.well_known_symbols
1073 .symbols
1074 .get(which.index())
1075 .cloned()
1076 .unwrap_or(Value::Undefined)
1077 }
1078
1079 /// The well-known symbol as a property key.
1080 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1081 match self.well_known(which) {
1082 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1083 // Unreachable once `Symbol` has installed; an empty string key matches
1084 // nothing, which degrades to "the object has no such method".
1085 _ => PropertyKey::from(String::new()),
1086 }
1087 }
1088}
1089
1090/// The interpreter: a realm plus a frame stack.
1091pub struct Interp<'a> {
1092 /// The heap everything is allocated on.
1093 pub heap: &'a Heap,
1094 /// The realm.
1095 pub realm: Realm,
1096 /// Active frames, outermost first.
1097 frames: Vec<Frame>,
1098 /// Value buffers from frames that have finished, reused by the next call.
1099 ///
1100 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1101 /// the locals and the operand stack — and free all four on return. `call:recursion`
1102 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1103 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1104 ///
1105 /// Bounded in both directions: a few buffers per kind, and none larger than
1106 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1107 /// and keeping its buffer would pin that memory for the rest of the run.
1108 free_values: Vec<Vec<Value>>,
1109 /// A strict-mode `eval`'s own variable scope, while its script runs.
1110 ///
1111 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1112 /// become a global. Name lookups still fall through to the realm, which is why
1113 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1114 /// A **stack**, innermost last, because evals nest: the inner eval of
1115 /// `eval("var a; eval('a')")` must still see the outer one's `a`, and each strict eval
1116 /// gets a fresh environment of its own layered over the previous.
1117 eval_scope: Vec<BTreeMap<String, Value>>,
1118 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1119 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1120 eval_depth: usize,
1121 /// Whether the program currently being compiled is an `eval` body rather than a
1122 /// global script. See [`Compiler::eval_body`].
1123 compiling_eval_body: bool,
1124 /// The calling frame's own bindings, which the running `eval` can read and write.
1125 ///
1126 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1127 /// come from the frame, and a write is applied back to the frame (or to the cell
1128 /// the frame captured) when the eval finishes. That is what makes
1129 /// `f("a = 3")` visible to the caller as `a === 3`.
1130 eval_bindings: Vec<EvalBinding>,
1131 /// The calling frame's `arguments`, while an `eval` runs.
1132 ///
1133 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1134 /// own yet still has to see the caller's `arguments`.
1135 eval_arguments: Option<Value>,
1136 /// The `with` objects live at the moment the running `eval` started, innermost first.
1137 ///
1138 /// `None` outside an eval, which is what keeps a finished block's object from
1139 /// shadowing ordinary bytecode reads.
1140 eval_with: Option<Vec<Gc<JsObject>>>,
1141 /// The bindings the running direct `eval` makes visible, as name → cell.
1142 ///
1143 /// Set for the duration of an eval and then restored, but every closure created
1144 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1145 /// `eval("f = () => i")` work after the eval has returned.
1146 active_eval_scope: Option<Gc<EvalScope>>,
1147 /// The frame that called the direct `eval` currently running, if any.
1148 ///
1149 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1150 /// on the global object, which is what keeps
1151 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1152 /// gives each call its own `x`.
1153 eval_caller: Option<Option<usize>>,
1154 /// The caller's `new.target`, while an `eval` runs.
1155 ///
1156 /// The eval'd code is a script with no constructor of its own, so it inherits the
1157 /// one the enclosing function was called with.
1158 eval_new_target: Option<Value>,
1159 /// `new.target` for the frame about to be pushed.
1160 ///
1161 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1162 /// value reaches the frame without threading a parameter through every call site.
1163 ///
1164 /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1165 /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1166 /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1167 /// value was parked for the outer call and never consumed.
1168 pending_new_target: Option<Value>,
1169 /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1170 ///
1171 /// `undefined` outside a `new` call.
1172 active_new_target: Value,
1173 /// Names of the native functions currently executing, outermost first.
1174 ///
1175 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1176 /// trace still names it with `(native)` instead of a position, so the names are
1177 /// tracked separately and stitched into [`Interp::stack_trace`].
1178 ///
1179 /// The third field is how many bytecode frames were live when the native was entered,
1180 /// which is what places it *among* them rather than before all of them. Native
1181 /// functions used to be emitted up front on the grounds that they never re-enter
1182 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1183 /// The natives currently running, innermost last: the function object and the
1184 /// depth it was entered at.
1185 ///
1186 /// The *name* is deliberately not stored. It used to be, read with
1187 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1188 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1189 /// benchmark. A stack trace is built rarely; it can read the name then.
1190 native_frames: Vec<(Gc<JsObject>, usize)>,
1191 /// The native function currently executing, for the ones that have to know *which*
1192 /// function they are — a typed-array constructor reads its element type off itself.
1193 ///
1194 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1195 /// reports whatever the enclosing bytecode frame was called with.
1196 current_native: Option<Gc<JsObject>>,
1197 /// Text written by `print` and friends, in order.
1198 ///
1199 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1200 /// once at the end, which is also when upstream's line buffering becomes
1201 /// visible for the cases compared here.
1202 pub output: String,
1203 /// Where `print` also writes, as it goes. `output` keeps the full log for
1204 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1205 ///
1206 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1207 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1208 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1209 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1210 /// would show a script's output all at once when it finished.
1211 pub output_sink: Option<Box<dyn std::io::Write>>,
1212 /// Where recent property reads found their value.
1213 ///
1214 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1215 /// table remembering *which object* and *which entry of its property table* answered a
1216 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1217 /// can move; the property can become an accessor), which is what makes a stale entry a
1218 /// miss rather than a wrong answer.
1219 ///
1220 /// The object is held weakly: a cache that held it strongly would keep up to
1221 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1222 /// program cannot see and cannot work around.
1223 pub field_cache: Vec<Option<FieldCache>>,
1224 /// Global lookups, by binding slot. See [`GlobalCache`].
1225 global_cache: Vec<Option<GlobalCache>>,
1226 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1227 /// under its limit. See [`Interp::check_memory`].
1228 pub oom_reported_at: usize,
1229 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1230 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1231 ///
1232 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1233 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1234 /// host that wants to stop a runaway script must not have to wait for it to return.
1235 ///
1236 /// Two things this cannot do, both of them differences a host can observe:
1237 ///
1238 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1239 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1240 /// needs a signal that the `catch` machinery does not see, which is a change to
1241 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1242 /// a host that stops the script itself.
1243 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1244 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1245 /// both, so the difference is when the counter hits zero, not whether it will.
1246 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1247 /// Instructions until the next [`Interp::interrupt`] poll.
1248 pub interrupt_counter: u32,
1249 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1250 ///
1251 /// A separate field from [`Interp::uncatchable`] because the two live for different
1252 /// spans. This one is the host's standing request; it survives the start of an
1253 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1254 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1255 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1256 /// cleared it before the script it was set for had a chance to throw.
1257 pub uncatchable_next: bool,
1258 /// Whether the exception now unwinding may be caught by a `catch`.
1259 ///
1260 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1261 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1262 /// a host stopping a runaway loop is not fought by the loop.
1263 ///
1264 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1265 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1266 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1267 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1268 pub uncatchable: bool,
1269 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1270 ///
1271 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1272 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1273 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1274 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1275 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1276 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1277 ///
1278 /// The numbers come out close for the same reason a C frame and a heap frame of this
1279 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1280 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1281 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1282 /// `crates/quickjs-cli/tests/limits.rs`.
1283 pub stack_limit: usize,
1284 /// The most frames that may be live at once, whatever the byte budget says.
1285 ///
1286 /// A second bound for a reason the reference does not have: our frames cost less than
1287 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1288 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1289 /// `--stack-size 1G` from being a memory bomb.
1290 pub max_frames: usize,
1291 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1292 ///
1293 /// Script execution does not return until this has drained, which is what makes
1294 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1295 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1296 /// not a `for`.
1297 pub(crate) jobs: std::collections::VecDeque<Job>,
1298 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1299 ///
1300 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1301 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1302 pub(crate) tasks: Vec<Task>,
1303 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1304 /// barrier'd evaluation started.
1305 ///
1306 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1307 /// lets a REPL report an error from the line it just evaluated without also reporting
1308 /// its own readline loop.
1309 trace_barriers: Vec<usize>,
1310 /// `os.signal` handlers, keyed by signal number.
1311 ///
1312 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1313 /// a handler cannot be freed while it is still registered.
1314 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1315 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1316 ///
1317 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1318 /// that is only reachable from a host closure could be freed while still registered.
1319 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1320 /// The next timer id.
1321 ///
1322 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1323 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1324 next_timer_id: i32,
1325 /// Errors thrown by timer callbacks, already rendered.
1326 ///
1327 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1328 /// that throws has no promise behind it. Both are reported by the host at the end of
1329 /// the loop, but only one is fixed up by a later `.catch`.
1330 timer_errors: Vec<String>,
1331 /// The module registry, keyed by canonical name.
1332 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1333 /// How the host turns a specifier into bytes.
1334 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1335 /// The module the host was asked to run, for `import.meta.main`.
1336 pub main_module_name: Option<String>,
1337 /// `[[ModuleAsyncEvaluationCount]]` — the next `[[AsyncEvaluationOrder]]` to hand out.
1338 ///
1339 /// Monotonic for the life of the interpreter and never reset: an engine *may* reset it
1340 /// when nothing is pending (the reset is unobservable), but a counter that only grows
1341 /// is unobservable for the same reason and cannot get the comparison backwards.
1342 pub next_module_async_evaluation_order: u64,
1343 /// The name to register the *entry* module under, when the host supplies one.
1344 ///
1345 /// The entry's bytes come from a path on disk; this is the name the module graph should
1346 /// know it by. They differ for a host that evaluates a file it did not write — a test
1347 /// runner that prepends a harness, a bundler, a REPL — and getting it wrong is visible:
1348 /// a module importing *itself* resolves the specifier against the real path, finds no
1349 /// record under that name, and loads a second copy with its own bindings.
1350 pub entry_module_name: Option<String>,
1351 /// Module bodies currently running, innermost last.
1352 ///
1353 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1354 /// this is the only place that knows which module that is.
1355 pub module_stack: Vec<String>,
1356 /// Rejections that no handler has claimed, with the promise they belong to.
1357 ///
1358 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1359 /// reason alone cannot say whether somebody eventually listened.
1360 unhandled: Vec<(Gc<JsObject>, Value)>,
1361}
1362
1363impl<'a> Interp<'a> {
1364 /// Build an interpreter over `heap`, with a fresh realm.
1365 pub fn new(heap: &'a Heap) -> Interp<'a> {
1366 let object_proto = JsObject::ordinary(heap, None);
1367 let function_proto = JsObject::function(
1368 heap,
1369 Some(object_proto.clone()),
1370 Callable::Native {
1371 func: |_, _, _| Ok(Value::Undefined),
1372 own_instance: false,
1373 },
1374 );
1375 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1376 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1377 let mut interp = Interp {
1378 heap,
1379 realm: Realm {
1380 global,
1381 object_proto,
1382 function_proto,
1383 array_proto,
1384 array_constructor: None,
1385 promise_constructor: None,
1386 object_proto_to_string: None,
1387 globals: BTreeMap::new(),
1388 declared: Vec::new(),
1389 lexical_consts: BTreeSet::new(),
1390 errors: BTreeMap::new(),
1391 string_proto: None,
1392 number_proto: None,
1393 boolean_proto: None,
1394 bigint_proto: None,
1395 error_proto: JsObject::ordinary(heap, None),
1396 date_proto: JsObject::ordinary(heap, None),
1397 throw_type_error: None,
1398 generator_proto: JsObject::ordinary(heap, None),
1399 promise_proto: None,
1400 async_generator_proto: None,
1401 async_iterator_proto: None,
1402 symbol_proto: None,
1403 symbol_registry: BTreeMap::new(),
1404 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1405 regexp_proto: None,
1406 regexp_ctor: None,
1407 suppressed_error_proto: None,
1408 disposable_stack_proto: None,
1409 map_proto: None,
1410 set_proto: None,
1411 finalization_registries: Vec::new(),
1412 array_buffer_proto: None,
1413 typed_array_proto: None,
1414 typed_array_protos: Vec::new(),
1415 data_view_proto: None,
1416 async_disposable_stack_proto: None,
1417 async_from_sync: None,
1418 iterator_proto: None,
1419 iterator_ctor: None,
1420 iterator_helper_proto: None,
1421 iterator_wrap_proto: None,
1422 generator_function_proto: None,
1423 async_function_proto: None,
1424 async_generator_function_proto: None,
1425 iterator_protos: std::collections::BTreeMap::new(),
1426 well_known_symbols: WellKnownSymbols::default(),
1427 host_classes: HostClasses::new(),
1428 template_map: std::collections::HashMap::new(),
1429 },
1430 frames: Vec::new(),
1431 free_values: Vec::new(),
1432 global_cache: {
1433 let mut cache = Vec::new();
1434 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1435 cache
1436 },
1437 eval_scope: Vec::new(),
1438 eval_depth: 0,
1439 compiling_eval_body: false,
1440 eval_bindings: Vec::new(),
1441 eval_arguments: None,
1442 eval_with: None,
1443 active_eval_scope: None,
1444 eval_caller: None,
1445 pending_new_target: None,
1446 active_new_target: Value::Undefined,
1447 eval_new_target: None,
1448 native_frames: Vec::new(),
1449 current_native: None,
1450 output: String::new(),
1451 output_sink: None,
1452 field_cache: {
1453 let mut cache = Vec::new();
1454 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1455 cache
1456 },
1457 oom_reported_at: 0,
1458 interrupt: None,
1459 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1460 uncatchable_next: false,
1461 uncatchable: false,
1462 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1463 // absent.
1464 stack_limit: DEFAULT_STACK_SIZE,
1465 max_frames: MAX_FRAMES,
1466 jobs: std::collections::VecDeque::new(),
1467 tasks: Vec::new(),
1468 trace_barriers: Vec::new(),
1469 signal_handlers: std::collections::BTreeMap::new(),
1470 fd_handlers: std::collections::BTreeMap::new(),
1471 next_timer_id: 1,
1472 timer_errors: Vec::new(),
1473 modules: std::collections::BTreeMap::new(),
1474 module_loader: None,
1475 main_module_name: None,
1476 next_module_async_evaluation_order: 0,
1477 entry_module_name: None,
1478 module_stack: Vec::new(),
1479 unhandled: Vec::new(),
1480 };
1481 crate::builtins::install(&mut interp);
1482 interp
1483 }
1484
1485 // -- allocation helpers -------------------------------------------------
1486
1487 /// A new string value.
1488 /// A `BigInt` value from a computed big integer.
1489 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1490 Value::BigInt(Gc::new(self.heap, value))
1491 }
1492
1493 /// A string value from bytes that are already WTF-8, which is how a string with an
1494 /// unpaired surrogate reaches a `Value`.
1495 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1496 Value::string_wtf8(self.heap, text)
1497 }
1498
1499 /// A new string value, from text that is valid UTF-8.
1500 pub fn string(&self, text: impl Into<String>) -> Value {
1501 Value::string(self.heap, text)
1502 }
1503
1504 /// A new ordinary object with the given prototype.
1505 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1506 JsObject::ordinary(self.heap, proto)
1507 }
1508
1509 // -- host classes -------------------------------------------------------
1510
1511 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1512 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1513 self.realm.host_classes.register(def)
1514 }
1515
1516 /// Register `def` under an id the host already holds (`JS_NewClass`).
1517 ///
1518 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1519 /// `JS_NewClass`.
1520 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1521 self.realm.host_classes.define(id, def)
1522 }
1523
1524 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1525 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1526 self.realm.host_classes.set_proto(id, proto);
1527 }
1528
1529 /// The prototype installed for `id`, if any.
1530 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1531 self.realm.host_classes.proto(id)
1532 }
1533
1534 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1535 ///
1536 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1537 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1538 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1539 /// host installed none.
1540 ///
1541 /// Answers `None` for an id that was never registered: the C API would return an
1542 /// exception, and silently making an ordinary object instead would move the failure to
1543 /// the first `JS_GetOpaque` that no longer matches.
1544 pub fn new_host_object(
1545 &mut self,
1546 proto: Option<Gc<JsObject>>,
1547 class_id: ClassId,
1548 ) -> Option<Gc<JsObject>> {
1549 let class = self.realm.host_classes.def(class_id)?;
1550 let proto = proto
1551 .or_else(|| self.realm.host_classes.proto(class_id))
1552 .or_else(|| Some(self.realm.object_proto.clone()));
1553 Some(JsObject::host_object(self.heap, proto, class_id, class))
1554 }
1555
1556 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1557 ///
1558 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1559 /// object, it is an object of another class, or the class never got a payload. A host
1560 /// that has to tell them apart uses [`JsObject::host_class_id`].
1561 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1562 let object = value.as_object()?;
1563 if object.host_class_id()? != class_id {
1564 return None;
1565 }
1566 object.host_opaque()
1567 }
1568
1569 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1570 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1571 match value.as_object() {
1572 Some(object) => object.set_host_opaque(opaque),
1573 None => false,
1574 }
1575 }
1576
1577 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1578 ///
1579 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1580 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1581 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1582 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1583 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1584 /// said `[object Object]` instead of `[object Array Iterator]`.
1585 ///
1586 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1587 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1588 /// its own.
1589 pub fn new_iterator_prototype(
1590 &mut self,
1591 tag: &str,
1592 next: crate::object::NativeFn,
1593 ) -> Gc<JsObject> {
1594 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1595 return existing.clone();
1596 }
1597 let parent = self.realm.iterator_proto.clone();
1598 let proto = self.new_object(parent);
1599 let next = self.new_native("next", 0, next);
1600 proto.define(
1601 "next",
1602 Property::with_attributes(Value::Object(next), true, false),
1603 );
1604 let key = self.realm.well_known_key(WellKnown::Iterator);
1605 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1606 proto.define_key(
1607 &key,
1608 Property::with_attributes(Value::Object(identity), true, false),
1609 );
1610 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1611 let tag_value = self.string(tag);
1612 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1613 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1614 // checks it.
1615 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1616 self.realm
1617 .iterator_protos
1618 .insert(tag.to_string(), proto.clone());
1619 proto
1620 }
1621
1622 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1623 ///
1624 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1625 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1626 /// produced. That is why the two branches are not merged.
1627 pub fn object_own_property_keys(
1628 &mut self,
1629 object: &Gc<JsObject>,
1630 ) -> JsResult<Vec<PropertyKey>> {
1631 if let Some(keys) = self.proxy_own_keys(object)? {
1632 return Ok(keys);
1633 }
1634 // §10.4.6.10 `[[OwnPropertyKeys]]`: the list of a namespace's exports is only
1635 // available once the module is evaluated, so a deferred namespace evaluates here —
1636 // with no symbol-like exemption, because this operation has no key to exempt.
1637 if object.module_namespace_marker() {
1638 self.trigger_deferred_namespace(object)?;
1639 }
1640 // Integer-like keys ascending, then the string keys in insertion order, then the
1641 // symbols — the order every schema that walks an object expects.
1642 let entries = object.property_entries();
1643 let mut numeric: Vec<u32> = Vec::new();
1644 // An integer-indexed exotic object reports its indices as own keys even though they
1645 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1646 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1647 // order). The length is asked per call, so a resizable buffer's view reports the
1648 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1649 if object.typed_array_parts().is_some() {
1650 for index in 0..object.typed_array_length().unwrap_or(0) {
1651 // `u32::try_from` cannot fail for a real length, but the length is a
1652 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1653 // as an array index and one element beyond is not.
1654 match u32::try_from(index) {
1655 Ok(index) => numeric.push(index),
1656 Err(_) => break,
1657 }
1658 }
1659 }
1660 let mut strings: Vec<PropertyKey> = Vec::new();
1661 let mut symbols: Vec<PropertyKey> = Vec::new();
1662 for (key, _) in entries {
1663 match &key {
1664 // A class-private name is never reported by any enumeration: that is the
1665 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1666 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1667 // symbol skip, `Object.assign`) therefore cannot see it.
1668 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1669 PropertyKey::Symbol(_) => symbols.push(key),
1670 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1671 Some(index) => {
1672 if !numeric.contains(&index) {
1673 numeric.push(index);
1674 }
1675 }
1676 None => strings.push(key),
1677 },
1678 }
1679 }
1680 // An array's `length` is an own property from the moment the array exists, so it
1681 // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1682 // as `["length", "a"]`, not `["a", "length"]`
1683 // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1684 // than stored in the property table, which is why it has to be placed here.
1685 if object.is_array() && object.proxy_state().is_none() {
1686 // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1687 // the property table, at whatever position the *define* happened, but the key
1688 // lists it as the array's oldest string property because that is what it is.
1689 if let Some(position) = strings
1690 .iter()
1691 .position(|key| key.as_str() == Some("length"))
1692 {
1693 strings.remove(position);
1694 }
1695 strings.insert(0, PropertyKey::from("length"));
1696 }
1697 numeric.sort_unstable();
1698 let mut keys: Vec<PropertyKey> = numeric
1699 .into_iter()
1700 .map(|index| PropertyKey::from(index.to_string()))
1701 .collect();
1702 keys.extend(strings);
1703 keys.extend(symbols);
1704 Ok(keys)
1705 }
1706
1707 /// The state behind a promise object, or `None` when `object` is not one.
1708 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1709 object.with(|data| match &data.kind {
1710 ObjectKind::Promise(state) => Some(state.clone()),
1711 _ => None,
1712 })
1713 }
1714
1715 /// A new pending promise.
1716 pub fn new_promise(&mut self) -> Gc<JsObject> {
1717 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1718 // the one place every promise is built, and a subclass that builds its instances
1719 // somewhere else would be invisible to `instanceof`.
1720 let default = self.realm.promise_proto.clone();
1721 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1722 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1723 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1724 // `prototype` getter therefore still gets a working promise; the alternative is a
1725 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1726 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1727 Self::make_promise_object(self.heap, proto)
1728 }
1729
1730 /// A promise object with an explicit prototype, and nothing else.
1731 ///
1732 /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1733 /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1734 /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1735 /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1736 pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1737 let promise = JsObject::ordinary(heap, proto);
1738 promise.with_mut(|data| {
1739 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1740 crate::object::PromiseState::default(),
1741 )));
1742 });
1743 promise
1744 }
1745
1746 /// Fulfil `promise`, unless it has already settled.
1747 ///
1748 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1749 /// after `reject`, changes nothing.
1750 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1751 let Some(state) = self.promise_state(promise) else {
1752 return;
1753 };
1754 let reactions = {
1755 let mut state = state.borrow_mut();
1756 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1757 return;
1758 }
1759 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1760 std::mem::take(&mut state.reactions)
1761 };
1762 self.queue_reactions(reactions, value, false);
1763 }
1764
1765 /// Reject `promise`, unless it has already settled.
1766 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1767 let Some(state) = self.promise_state(promise) else {
1768 return;
1769 };
1770 let reactions = {
1771 let mut state = state.borrow_mut();
1772 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1773 return;
1774 }
1775 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1776 std::mem::take(&mut state.reactions)
1777 };
1778 // Remember it only when nothing is listening *now*; a `then` registered later
1779 // prunes the entry in `perform_then`.
1780 if reactions.is_empty() {
1781 self.unhandled.push((promise.clone(), reason.clone()));
1782 }
1783 self.queue_reactions(reactions, reason, true);
1784 }
1785
1786 /// Queue one job per reaction.
1787 ///
1788 /// This is what makes `then` asynchronous even on an already-settled promise:
1789 /// `p.then(f); g()` calls `g` first.
1790 fn queue_reactions(
1791 &mut self,
1792 reactions: Vec<crate::object::PromiseReaction>,
1793 argument: Value,
1794 rejected: bool,
1795 ) {
1796 for reaction in reactions {
1797 let handler = if rejected {
1798 reaction.on_rejected.clone()
1799 } else {
1800 reaction.on_fulfilled.clone()
1801 };
1802 self.jobs.push_back(Job::Reaction {
1803 handler,
1804 argument: argument.clone(),
1805 rejected,
1806 promise: reaction.promise,
1807 });
1808 }
1809 }
1810
1811 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1812 /// resolve/reject pair.
1813 ///
1814 /// The pair are callable objects rather than Rust closures, because the script gets
1815 /// them and may stash them for later.
1816 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1817 let promise = self.new_promise();
1818 // Both handlers are built-ins with an empty name and length 1, in
1819 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1820 // off `Object.getOwnPropertyNames`.
1821 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1822 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1823 (promise, Value::Object(resolve), Value::Object(reject))
1824 }
1825
1826 /// §27.2.1.5 `NewPromiseCapability(C)`.
1827 ///
1828 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1829 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1830 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1831 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1832 /// silently ignored argument.
1833 ///
1834 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1835 /// the engine's own executor is exactly what `new_promise_capability` builds.
1836 pub fn new_promise_capability_for(
1837 &mut self,
1838 constructor: &Value,
1839 ) -> JsResult<(Value, Value, Value)> {
1840 let Some(object) = constructor.as_object().cloned() else {
1841 return Err(self.type_error("promise constructor is not a constructor"));
1842 };
1843 if !object.is_constructor() {
1844 return Err(self.type_error("promise constructor is not a constructor"));
1845 }
1846 if self
1847 .realm
1848 .promise_constructor
1849 .as_ref()
1850 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1851 {
1852 let (promise, resolve, reject) = self.new_promise_capability();
1853 return Ok((Value::Object(promise), resolve, reject));
1854 }
1855 let state = self.new_object(Some(self.realm.object_proto.clone()));
1856 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1857 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1858 // which only a *custom* constructor can observe, and none of the combinator tests
1859 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1860 let executor = self.builtin_function(
1861 "",
1862 2,
1863 Callable::CapabilityExecutor {
1864 state: state.clone(),
1865 },
1866 );
1867 let promise = self.construct(
1868 Value::Object(object.clone()),
1869 Value::Object(object),
1870 vec![Value::Object(executor)],
1871 )?;
1872 // The pair is read *after* the constructor returns, so a constructor that never
1873 // called its executor, or called it with non-callables, is the spec's step 11
1874 // `TypeError` — not something the engine can paper over.
1875 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1876 return Err(self.type_error("promise executor never ran"));
1877 };
1878 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1879 return Err(self.type_error("promise executor never ran"));
1880 };
1881 for handler in [&resolve, &reject] {
1882 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1883 return Err(self.type_error("promise capability handler is not callable"));
1884 }
1885 }
1886 Ok((promise, resolve, reject))
1887 }
1888
1889 /// §27.2.3.1 `PromiseResolve(C, x)`.
1890 ///
1891 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1892 /// an `x` that is already a promise of exactly this constructor is handed back
1893 /// unchanged, and anything else gets a fresh capability from `C`.
1894 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1895 if let Value::Object(object) = &value
1896 && self.promise_state(object).is_some()
1897 {
1898 // `x.constructor === C` means "already the right kind", so no capability is
1899 // built — which is observable through a `resolve` that counts its calls.
1900 let x_constructor = self.get_property(object, "constructor")?;
1901 let same = match (
1902 x_constructor.as_ref().and_then(Value::as_object),
1903 constructor.as_object(),
1904 ) {
1905 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1906 _ => false,
1907 };
1908 if same {
1909 return Ok(value);
1910 }
1911 }
1912 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1913 // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1914 // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1915 // the intrinsic one swallows its own self-resolution error.
1916 self.call_value(resolve, Value::Undefined, vec![value])?;
1917 Ok(promise)
1918 }
1919
1920 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1921 /// promise, as `{ value: completion }`.
1922 ///
1923 /// The three cases are the reference's, and they differ on purpose:
1924 ///
1925 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1926 /// exception before any promise exists;
1927 /// * a **runtime** error rejects the returned promise;
1928 /// * success resolves it with `{ value }`, where the value is the script's completion
1929 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1930 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1931 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1932 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1933 ///
1934 /// # What this does not do
1935 ///
1936 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1937 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1938 /// the parser and the suspension machinery to accept a suspended top-level script, and
1939 /// is not implemented — such source is a syntax error here. Everything else about the
1940 /// flag is reproduced.
1941 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1942 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1943 // too, and the reference truncates that one at the same place as a runtime failure.
1944 if barrier {
1945 let depth = self.frames.len();
1946 self.trace_barriers.push(depth);
1947 }
1948 // Compiled before the promise exists, so a parse failure propagates as a throw
1949 // instead of being folded into a rejection.
1950 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1951 Ok(compiled) => compiled,
1952 Err(error) => {
1953 if barrier {
1954 self.trace_barriers.pop();
1955 }
1956 return Err(error);
1957 }
1958 };
1959 // An async body answers its own promise, and that promise is what the reference
1960 // hands back — the same object, not a wrapper around it. Its resolution value is
1961 // the `{value}` object the compiled epilogue built.
1962 if compiled.kind.is_async() {
1963 let strict = compiled.strict;
1964 let promise = self.run_eval_script(compiled, strict)?;
1965 if barrier {
1966 self.trace_barriers.pop();
1967 }
1968 return Ok(promise);
1969 }
1970 let (promise, resolve, reject) = self.new_promise_capability();
1971 let strict = compiled.strict;
1972 match self.run_eval_script(compiled, strict) {
1973 Ok(value) => {
1974 // `{ value }` is a plain object, so resolving with it adopts nothing even
1975 // when the completion value is itself a promise.
1976 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1977 self.set_property(&wrapped, "value", value)?;
1978 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1979 }
1980 Err(Signal::Throw(error)) => {
1981 self.call_value(reject, Value::Undefined, vec![error])?;
1982 }
1983 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1984 }
1985 if barrier {
1986 self.trace_barriers.pop();
1987 }
1988 Ok(Value::Object(promise))
1989 }
1990
1991 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1992 ///
1993 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1994 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1995 /// timer table, where the collector already scans it.
1996 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1997 let (promise, resolve, _reject) = self.new_promise_capability();
1998 let resolve = self.new_host_function(
1999 "resolve",
2000 1,
2001 Box::new(
2002 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
2003 let value = args.first().cloned().unwrap_or(Value::Undefined);
2004 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
2005 },
2006 ),
2007 );
2008 // The timer keeps the resolver alive: it is a property of the timer entry, and the
2009 // timer table is part of what the collector walks.
2010 self.schedule_timer(Value::Object(resolve), delay_ms);
2011 Ok(Value::Object(promise))
2012 }
2013
2014 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
2015 /// new promise resolved with it.
2016 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
2017 if let Value::Object(object) = &value
2018 && self.promise_state(object).is_some()
2019 {
2020 return Ok(value);
2021 }
2022 let promise = self.new_promise();
2023 self.resolve_promise_with(&promise, value)?;
2024 Ok(Value::Object(promise))
2025 }
2026
2027 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
2028 ///
2029 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
2030 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
2031 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
2032 /// therefore observable — which is exactly what
2033 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
2034 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
2035 /// shortcut.
2036 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
2037 if let Value::Object(object) = &value
2038 && self.promise_state(object).is_some()
2039 {
2040 let constructor = self.get_property(object, "constructor")?;
2041 let same = match (&constructor, &self.realm.promise_constructor) {
2042 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2043 _ => false,
2044 };
2045 if same {
2046 return Ok(value);
2047 }
2048 }
2049 let promise = self.new_promise();
2050 self.resolve_promise_with(&promise, value)?;
2051 Ok(Value::Object(promise))
2052 }
2053
2054 /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2055 ///
2056 /// The pair of resolving functions a promise hands to its executor shares this record, so
2057 /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2058 /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2059 pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2060 let Some(state) = self.promise_state(promise) else {
2061 return true;
2062 };
2063 let mut state = state.borrow_mut();
2064 if state.resolved {
2065 return false;
2066 }
2067 state.resolved = true;
2068 true
2069 }
2070
2071 /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2072 fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2073 let Some(state) = self.promise_state(promise) else {
2074 return;
2075 };
2076 state.borrow_mut().resolved = false;
2077 }
2078
2079 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2080 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2081 // Resolving a promise with itself is a `TypeError`. The check exists because the
2082 // alternative is a chain of self-reactions that never settles.
2083 if let Value::Object(object) = &value
2084 && object.ptr_eq(promise)
2085 {
2086 // The spec rejects *and* throws, so both the promise and the caller see it.
2087 let thrown = self.type_error("cannot resolve a promise with itself");
2088 let Signal::Throw(error) = thrown.clone() else {
2089 unreachable!("type_error always throws")
2090 };
2091 self.reject_promise(promise, error);
2092 return Err(thrown);
2093 }
2094 // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2095 // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2096 // whoever resolved it — a poisoned `then` getter is the case every
2097 // `*-poisoned-then` test is written against.
2098 let then = match &value {
2099 Value::Object(object) => match self.get_property(object, "then") {
2100 Ok(then) => then,
2101 Err(signal) => {
2102 if let Signal::Throw(reason) = signal {
2103 self.reject_promise(promise, reason);
2104 return Ok(());
2105 }
2106 return Err(signal);
2107 }
2108 },
2109 _ => None,
2110 };
2111 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2112 if !callable_then {
2113 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2114 self.fulfill_promise(promise, value);
2115 return Ok(());
2116 }
2117 // Adopting a thenable is asynchronous — `then` is called from a job, never from
2118 // inside `resolve`, so a script cannot make a promise settle synchronously.
2119 self.jobs.push_back(Job::Thenable {
2120 then: then.expect("checked callable"),
2121 value,
2122 promise: promise.clone(),
2123 });
2124 Ok(())
2125 }
2126
2127 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2128 ///
2129 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2130 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2131 ///
2132 /// The property read is **not** short-circuitable even for a real promise: the spec says
2133 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2134 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2135 /// the combinator's loop infinite — the test's iterator never sets `done`.
2136 pub fn invoke_then(
2137 &mut self,
2138 thenable: Value,
2139 on_fulfilled: Value,
2140 on_rejected: Value,
2141 ) -> JsResult<()> {
2142 let then = match &thenable {
2143 Value::Object(object) => self.get_property(object, "then")?,
2144 primitive => {
2145 let boxed = self.object_from(primitive)?;
2146 self.get_property(&boxed, "then")?
2147 }
2148 };
2149 let Some(then) = then else {
2150 return Err(self.type_error("thenable has no then method"));
2151 };
2152 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2153 return Err(self.type_error("then is not a function"));
2154 }
2155 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2156 Ok(())
2157 }
2158
2159 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2160 ///
2161 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2162 /// promise.
2163 pub fn perform_then(
2164 &mut self,
2165 promise: &Gc<JsObject>,
2166 on_fulfilled: Option<Value>,
2167 on_rejected: Option<Value>,
2168 ) -> JsResult<Value> {
2169 let Some(state) = self.promise_state(promise) else {
2170 return Err(self.type_error("not a promise"));
2171 };
2172 // Whether a rejection handler is being attached decides whether a recorded
2173 // rejection stops being unhandled, so it is read before the values are moved.
2174 let has_rejection_handler = on_rejected.is_some();
2175 let derived = self.new_promise();
2176 let reaction = crate::object::PromiseReaction {
2177 on_fulfilled,
2178 on_rejected,
2179 promise: derived.clone(),
2180 };
2181 let settled = {
2182 let mut state = state.borrow_mut();
2183 // A rejection somebody reacts to is no longer unhandled.
2184 state.handled = true;
2185 match &state.status {
2186 crate::object::PromiseStatus::Pending => {
2187 state.reactions.push(reaction.clone());
2188 None
2189 }
2190 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2191 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2192 }
2193 };
2194 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2195 // later, means somebody is listening after all.
2196 if has_rejection_handler {
2197 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2198 }
2199 if let Some((argument, rejected)) = settled {
2200 let handler = if rejected {
2201 reaction.on_rejected
2202 } else {
2203 reaction.on_fulfilled
2204 };
2205 self.jobs.push_back(Job::Reaction {
2206 handler,
2207 argument,
2208 rejected,
2209 promise: reaction.promise,
2210 });
2211 }
2212 Ok(Value::Object(derived))
2213 }
2214
2215 /// The rejections nobody listened to, formatted the way the reference reports them.
2216 ///
2217 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2218 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2219 /// unhandled at the point the queue drains, because a `then` may still be attached
2220 /// before the host acts on it.
2221 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2222 let entries = std::mem::take(&mut self.unhandled);
2223 // Somebody may have attached a handler after the rejection was recorded, so the
2224 // promise is the authority rather than the list.
2225 let still_unhandled: Vec<Value> = entries
2226 .into_iter()
2227 .filter_map(|(promise, reason)| {
2228 let handled = self
2229 .promise_state(&promise)
2230 .map(|state| state.borrow().handled)
2231 .unwrap_or(true);
2232 (!handled).then_some(reason)
2233 })
2234 .collect();
2235 still_unhandled
2236 .into_iter()
2237 .map(|reason| {
2238 let text = self.describe_exception(&reason);
2239 let stack = match &reason {
2240 Value::Object(object) => self
2241 .get_property(object, "stack")
2242 .ok()
2243 .flatten()
2244 .map(|value| value.to_js_string())
2245 // `stack` carries a trailing newline of its own, which would leave
2246 // a blank line between two reported rejections.
2247 .map(|text| text.trim_end().to_string())
2248 .unwrap_or_default(),
2249 _ => String::new(),
2250 };
2251 if stack.is_empty() {
2252 format!("Possibly unhandled promise rejection: {text}")
2253 } else {
2254 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2255 }
2256 })
2257 .collect()
2258 }
2259
2260 /// Run the microtask queue to exhaustion.
2261 ///
2262 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2263 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2264 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2265 ///
2266 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2267 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2268 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2269 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2270 crate::builtins::json::parse_text(self, text, true)
2271 }
2272
2273 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2274 ///
2275 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2276 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2277 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2278 ///
2279 /// The callback is called with **no arguments**. The reference stores only the function
2280 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2281 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2282 /// extra arguments arrive as `undefined`.
2283 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2284 let id = self.next_timer_id;
2285 // Wrap rather than grow: the id reaches the script as an `Int32`.
2286 self.next_timer_id = if self.next_timer_id == i32::MAX {
2287 1
2288 } else {
2289 self.next_timer_id + 1
2290 };
2291 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2292 self.tasks.push(Task::Timer {
2293 id,
2294 callback,
2295 due_at,
2296 });
2297 id
2298 }
2299
2300 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2301 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2302 pub fn cancel_timer(&mut self, id: i32) -> bool {
2303 let before = self.tasks.len();
2304 self.tasks.retain(|task| match task {
2305 Task::Timer { id: task_id, .. } => *task_id != id,
2306 });
2307 self.tasks.len() != before
2308 }
2309
2310 /// How long until the earliest pending timer, or `None` when none is pending.
2311 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2312 let now = std::time::Instant::now();
2313 self.tasks
2314 .iter()
2315 .map(|task| match task {
2316 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2317 })
2318 .min()
2319 }
2320
2321 /// Run one turn of the event loop.
2322 ///
2323 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2324 /// run at most one due timer, then drain again. The blocking belongs to the caller
2325 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2326 /// is how it asks.
2327 ///
2328 /// One timer per turn rather than all of them: a timer callback may schedule another
2329 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2330 /// starve the microtask queue.
2331 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2332 self.drain_jobs()?;
2333 let now = std::time::Instant::now();
2334 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2335 // followed by `setTimeout(g, 1)` must run `g` first.
2336 let due = self
2337 .tasks
2338 .iter()
2339 .enumerate()
2340 .filter(|(_, task)| match task {
2341 Task::Timer { due_at, .. } => *due_at <= now,
2342 })
2343 .min_by_key(|(_, task)| match task {
2344 Task::Timer { due_at, .. } => *due_at,
2345 })
2346 .map(|(index, _)| index);
2347 let Some(index) = due else {
2348 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2349 // descriptor is registered but no timer is closer, so a script that never
2350 // touches the descriptor still gets control back. Without a cap a handler on a
2351 // descriptor that is never ready would block for as long as the host allows.
2352 let timeout = self
2353 .next_timeout()
2354 .unwrap_or(std::time::Duration::from_secs(10))
2355 .min(std::time::Duration::from_secs(10));
2356 if !self.fd_handlers.is_empty() {
2357 // Blocking on a timer while descriptors are registered would starve them,
2358 // and blocking on the descriptors while a timer is due would delay it; the
2359 // host polls with the earlier of the two deadlines, which this timeout is.
2360 return Ok(Turn::Poll(timeout));
2361 }
2362 return Ok(match self.next_timeout() {
2363 Some(wait) => Turn::Wait(wait),
2364 None => Turn::Done,
2365 });
2366 };
2367 let Task::Timer { callback, .. } = self.tasks.remove(index);
2368 let this = Value::Undefined;
2369 // A throwing timer callback must not stop the loop: the reference reports it and
2370 // keeps going, because the alternative is that one bad timer silently stops every
2371 // later one.
2372 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2373 match self.call_value(callback, this, Vec::new()) {
2374 Ok(_) => {}
2375 Err(Signal::Throw(value)) => {
2376 let text = self.describe_exception(&value);
2377 self.timer_errors.push(text);
2378 }
2379 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2380 }
2381 self.drain_jobs()?;
2382 Ok(Turn::Ran)
2383 }
2384
2385 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2386 ///
2387 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2388 /// left is removed — the reference does the same, so a script can rely on
2389 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2390 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2391 let entry = self.fd_handlers.entry(fd).or_default();
2392 if readable {
2393 entry.read = callback;
2394 } else {
2395 entry.write = callback;
2396 }
2397 if entry.read.is_none() && entry.write.is_none() {
2398 self.fd_handlers.remove(&fd);
2399 }
2400 }
2401
2402 /// Register or clear an `os.signal` handler.
2403 ///
2404 /// `None` removes it; the host separately restores the default disposition or sets
2405 /// ignore, because which of those happened is the script's choice (`null` versus
2406 /// `undefined`) and not something this table can express.
2407 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2408 match handler {
2409 Some(handler) => {
2410 self.signal_handlers.insert(signal, handler);
2411 }
2412 None => {
2413 self.signal_handlers.remove(&signal);
2414 }
2415 }
2416 }
2417
2418 /// Run the handler for `signal`, reporting whether one ran.
2419 ///
2420 /// A throwing handler is reported and the loop continues, like a timer's.
2421 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2422 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2423 return Ok(false);
2424 };
2425 match self.call_value(handler, Value::Undefined, Vec::new()) {
2426 Ok(_) => {}
2427 Err(Signal::Throw(value)) => {
2428 let text = self.describe_exception(&value);
2429 self.timer_errors.push(text);
2430 }
2431 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2432 }
2433 self.drain_jobs()?;
2434 Ok(true)
2435 }
2436
2437 /// The descriptors the host has to poll, and in which direction.
2438 ///
2439 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2440 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2441 /// `os_poll` asks for.
2442 pub fn pending_fds(&self) -> Vec<FdInterest> {
2443 self.fd_handlers
2444 .iter()
2445 .map(|(fd, entry)| FdInterest {
2446 fd: *fd,
2447 read: entry.read.is_some(),
2448 write: entry.write.is_some(),
2449 })
2450 .collect()
2451 }
2452
2453 /// Call the handler registered for `fd`, reporting whether one ran.
2454 ///
2455 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2456 /// poll iteration and then restarts the loop, because the handler may have changed the
2457 /// registration list underneath it; doing the same here keeps a handler that
2458 /// unregisters itself from being called with stale state.
2459 ///
2460 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2461 /// every later one, exactly as with timers.
2462 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2463 let Some(entry) = self.fd_handlers.get(&fd) else {
2464 return Ok(false);
2465 };
2466 let callback = if readable {
2467 entry.read.clone()
2468 } else if writable {
2469 entry.write.clone()
2470 } else {
2471 None
2472 };
2473 let Some(callback) = callback else {
2474 return Ok(false);
2475 };
2476 self.drain_jobs()?;
2477 match self.call_value(callback, Value::Undefined, Vec::new()) {
2478 Ok(_) => {}
2479 Err(Signal::Throw(value)) => {
2480 let text = self.describe_exception(&value);
2481 self.timer_errors.push(text);
2482 }
2483 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2484 }
2485 self.drain_jobs()?;
2486 Ok(true)
2487 }
2488
2489 /// Take the errors timer callbacks threw, leaving the list empty.
2490 pub fn take_timer_errors(&mut self) -> Vec<String> {
2491 std::mem::take(&mut self.timer_errors)
2492 }
2493
2494 /// Whether anything is still pending: a microtask or a timer.
2495 pub fn has_pending_work(&self) -> bool {
2496 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2497 }
2498
2499 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2500 pub fn has_pending_timers_or_jobs(&self) -> bool {
2501 !self.jobs.is_empty() || !self.tasks.is_empty()
2502 }
2503
2504 /// Run every queued microtask, including ones queued while draining.
2505 pub fn drain_jobs(&mut self) -> JsResult<()> {
2506 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2507 // would spin forever, so the drain is bounded the way the call stack is.
2508 let mut budget = 1_000_000usize;
2509 while let Some(job) = self.jobs.pop_front() {
2510 if budget == 0 {
2511 return Err(Signal::Throw(
2512 self.make_error("InternalError", "promise job queue did not drain"),
2513 ));
2514 }
2515 budget -= 1;
2516 self.run_job(job)?;
2517 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2518 // engine may run script that the script itself did not ask for. Doing it here
2519 // rather than from a drop hook is what keeps the callback out of arbitrary
2520 // engine bookkeeping — see `builtins::weak`'s header.
2521 crate::builtins::weak::drain_finalizers(self)?;
2522 }
2523 // A script that queued no jobs may still have dropped targets, so the checkpoint
2524 // runs once more after the queue empties.
2525 crate::builtins::weak::drain_finalizers(self)?;
2526 Ok(())
2527 }
2528
2529 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2530 ///
2531 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2532 /// `None` and is swept out here. This is also where the realm learns that a registry
2533 /// died, which is why it is a mutation rather than a read.
2534 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2535 let handles = std::mem::take(&mut self.realm.finalization_registries);
2536 let mut live = Vec::with_capacity(handles.len());
2537 for handle in handles {
2538 let Some(object) = handle.upgrade() else {
2539 continue;
2540 };
2541 let Some(state) = object.finalization_state() else {
2542 continue;
2543 };
2544 live.push((object.clone(), *state));
2545 self.realm.finalization_registries.push(object.downgrade());
2546 }
2547 live
2548 }
2549
2550 /// Run one microtask.
2551 fn run_job(&mut self, job: Job) -> JsResult<()> {
2552 match job {
2553 Job::Reaction {
2554 handler: None,
2555 argument,
2556 rejected,
2557 promise,
2558 } => {
2559 // No handler: the settlement passes straight through to the derived
2560 // promise, which is why `p.catch(f)` ignores fulfilments.
2561 if rejected {
2562 self.reject_promise(&promise, argument);
2563 } else {
2564 self.fulfill_promise(&promise, argument);
2565 }
2566 Ok(())
2567 }
2568 Job::Reaction {
2569 handler: Some(handler),
2570 argument,
2571 promise,
2572 ..
2573 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2574 Ok(answer) => {
2575 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2576 self.reject_promise(&promise, error);
2577 }
2578 Ok(())
2579 }
2580 Err(Signal::Throw(reason)) => {
2581 self.reject_promise(&promise, reason);
2582 Ok(())
2583 }
2584 Err(other) => Err(other),
2585 },
2586 Job::Thenable {
2587 then,
2588 value,
2589 promise,
2590 } => {
2591 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2592 // the value it produces settles `promise`.
2593 // The thenable's `then` gets this promise's own pair, so whatever it
2594 // produces settles `promise`.
2595 // `length: 1`, `name: ""` — a resolve/reject function is a
2596 // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2597 // with `JsObject::function` left `length` at 0, which a test reads straight
2598 // off the function (`finally/resolved-observable-then-calls-argument`
2599 // requires `resolve.length === 1` for the pair handed to a thenable).
2600 let resolve =
2601 self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2602 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2603 // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2604 // so the one-shot record starts over. Without the reset the pair above was
2605 // already spent by the `resolve` that queued this job, and a thenable that
2606 // calls `reject` left the promise pending forever
2607 // (`Promise/all/reject-immed`).
2608 self.forget_resolution(&promise);
2609 let reject = Value::Object(reject);
2610 match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2611 Ok(_) => Ok(()),
2612 // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2613 // reject function, whose one-shot record makes this a no-op once `then`
2614 // has already resolved the promise
2615 // (`exception-after-resolve-in-thenable-job`).
2616 Err(Signal::Throw(reason)) => {
2617 self.call_value(reject, Value::Undefined, vec![reason])?;
2618 Ok(())
2619 }
2620 Err(other) => Err(other),
2621 }
2622 }
2623 Job::Resume {
2624 coroutine,
2625 promise,
2626 kind,
2627 value,
2628 } => self.drive_async(&coroutine, &promise, kind, value),
2629 Job::GeneratorResume {
2630 generator,
2631 promise,
2632 kind,
2633 value,
2634 } => self.step_async_generator(&generator, &promise, kind, value),
2635 Job::Import {
2636 specifier,
2637 referrer,
2638 promise,
2639 phase,
2640 } => {
2641 self.run_dynamic_import(&specifier, &referrer, &promise, phase);
2642 Ok(())
2643 }
2644 }
2645 }
2646
2647 /// One element of a `Promise` combinator settled.
2648 ///
2649 /// The shared state object holds the result array, the number still outstanding, and
2650 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2651 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2652 /// to settle, only whatever `Sub` said a capability is.
2653 ///
2654 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2655 /// and `any` must ignore every later settlement, and `all` must not report a second
2656 /// rejection after the first.
2657 fn settle_combinator(
2658 &mut self,
2659 state: &Gc<JsObject>,
2660 index: usize,
2661 fulfilled: bool,
2662 value: Value,
2663 ) -> JsResult<()> {
2664 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2665 // Each element settles at most once: a thenable may call `onFulfilled` twice
2666 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2667 // call a no-op. Without it the second call decremented `remaining` again and settled
2668 // `all` with a short values array (`call-resolve-element-items`).
2669 let done = field("done");
2670 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2671 let settled = field("settled").is_some_and(|value| value.to_boolean());
2672 if settled {
2673 return Ok(());
2674 }
2675 if let Some(Value::Object(done)) = &done {
2676 if done
2677 .array_get(index)
2678 .is_some_and(|value| value.to_boolean())
2679 {
2680 return Ok(());
2681 }
2682 done.array_set(self.heap, index, Value::Bool(true));
2683 }
2684 let resolve = field("resolve");
2685 let reject = field("reject");
2686 let keys = field("keys");
2687 let results = field("results").and_then(|value| value.as_object().cloned());
2688 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2689 // promise: the handler is a plain function the constructor chose.
2690 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2691 if let Some(handler) = handler {
2692 interp.call_value(handler, Value::Undefined, vec![value])?;
2693 }
2694 Ok(())
2695 };
2696 match kind {
2697 // `race`: the first settlement wins and stops the rest.
2698 3 => {
2699 state.define_data("settled", Value::Bool(true));
2700 let handler = if fulfilled { resolve } else { reject };
2701 settle_with(self, handler, value)?;
2702 return Ok(());
2703 }
2704 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2705 // the first rejection wins outright.
2706 0 | 4 if !fulfilled => {
2707 state.define_data("settled", Value::Bool(true));
2708 settle_with(self, reject, value)?;
2709 return Ok(());
2710 }
2711 // `any`: the first fulfilment wins.
2712 2 if fulfilled => {
2713 state.define_data("settled", Value::Bool(true));
2714 settle_with(self, resolve, value)?;
2715 return Ok(());
2716 }
2717 _ => {}
2718 }
2719 let Some(results) = &results else {
2720 return Ok(());
2721 };
2722 match kind {
2723 4 => {
2724 results.array_set(self.heap, index, value);
2725 }
2726 0 => {
2727 results.array_set(self.heap, index, value);
2728 }
2729 // `allSettled` (and its keyed twin) never rejects; each slot records what
2730 // happened.
2731 1 | 5 => {
2732 let record = self.new_object(Some(self.realm.object_proto.clone()));
2733 if fulfilled {
2734 record.define_data("status", self.string("fulfilled"));
2735 record.define_data("value", value);
2736 } else {
2737 record.define_data("status", self.string("rejected"));
2738 record.define_data("reason", value);
2739 }
2740 results.array_set(self.heap, index, Value::Object(record));
2741 }
2742 // `any`: a rejection is parked in the errors array and the sweep continues.
2743 2 => {
2744 results.array_set(self.heap, index, value);
2745 }
2746 _ => {}
2747 }
2748 let remaining = field("remaining")
2749 .map(|value| value.to_int32())
2750 .unwrap_or(0);
2751 let left = remaining - 1;
2752 state.define_data("remaining", Value::Int(left));
2753 if left != 0 {
2754 return Ok(());
2755 }
2756 state.define_data("settled", Value::Bool(true));
2757 match kind {
2758 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2759 // The keyed result: an ordinary object with a **null** prototype, holding the
2760 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2761 4 | 5 => {
2762 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2763 settle_with(self, resolve, keyed)?;
2764 }
2765 2 => {
2766 // The rejection is an `AggregateError` whose `errors` is the results array
2767 // itself — the slots are the reasons, in input order.
2768 let errors = results.array_elements().unwrap_or_default();
2769 let error = self.aggregate_error(errors, "all promises were rejected");
2770 settle_with(self, reject, error)?;
2771 }
2772 _ => {}
2773 }
2774 Ok(())
2775 }
2776
2777 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2778 ///
2779 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2780 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2781 /// prototype is load-bearing in both directions: a key called `toString` must not
2782 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2783 /// (`resolves-empty-object.js`).
2784 pub(crate) fn keyed_result_object(
2785 &mut self,
2786 keys: Option<&Value>,
2787 values: &Gc<JsObject>,
2788 ) -> JsResult<Value> {
2789 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2790 return Ok(Value::Object(self.new_object(None)));
2791 };
2792 let result = self.new_object(None);
2793 let count = values.array_length().unwrap_or(0);
2794 for index in 0..count {
2795 let Some(key) = keys.array_get(index) else {
2796 continue;
2797 };
2798 let Some(value) = values.array_get(index) else {
2799 continue;
2800 };
2801 let property = Property::with_attributes(value, true, true);
2802 match &key {
2803 Value::Symbol(symbol) => {
2804 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2805 }
2806 other => {
2807 let text = self.to_js_string(other)?;
2808 result.define_key(&PropertyKey::from(text.as_str()), property);
2809 }
2810 }
2811 }
2812 Ok(Value::Object(result))
2813 }
2814
2815 /// Build an async function's result: a promise whose body runs as a coroutine.
2816 pub fn new_async_function(
2817 &mut self,
2818 function: Value,
2819 this: Value,
2820 args: Vec<Value>,
2821 ) -> JsResult<Value> {
2822 let promise = self.new_promise();
2823 let coroutine = self.new_coroutine(function, this, args)?;
2824 if let Err(Signal::Throw(reason)) =
2825 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2826 {
2827 self.reject_promise(&promise, reason);
2828 }
2829 Ok(Value::Object(promise))
2830 }
2831
2832 /// The coroutine an async body runs in.
2833 ///
2834 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2835 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2836 /// than growing a second state machine. The difference is only in the ending — a
2837 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2838 /// Run `code` as an async function body, answering the promise it settles.
2839 ///
2840 /// Used for a module with top-level `await`: its body is an async function whose
2841 /// caller is the host, so there is no function object to pass through
2842 /// [`Interp::new_async_function`].
2843 pub fn run_async_body(
2844 &mut self,
2845 code: Gc<CompiledCode>,
2846 env: Gc<ClosureEnv>,
2847 this: Value,
2848 ) -> JsResult<Value> {
2849 let promise = self.new_promise();
2850 let coroutine = self.new_coroutine_from(code, env, this, Vec::new(), Value::Undefined)?;
2851 if let Err(Signal::Throw(reason)) =
2852 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2853 {
2854 self.reject_promise(&promise, reason);
2855 }
2856 Ok(Value::Object(promise))
2857 }
2858
2859 fn new_coroutine(
2860 &mut self,
2861 function: Value,
2862 this: Value,
2863 args: Vec<Value>,
2864 ) -> JsResult<Gc<JsObject>> {
2865 let Some(object) = function.as_object().cloned() else {
2866 return Err(self.type_error("not a function"));
2867 };
2868 let Some((code, env)) = bytecode_of(&object) else {
2869 return Err(self.type_error("not a function"));
2870 };
2871 self.new_coroutine_from(code, env, this, args, function)
2872 }
2873
2874 /// Build a coroutine over an already-resolved body.
2875 ///
2876 /// `callee` is the function object the body belongs to, or `undefined` when there is
2877 /// none — a module with top-level `await`. It has to be handed over rather than
2878 /// defaulted: the frame's callee is what `special_object 2` answers, and an async
2879 /// function's body uses that to initialise its own-name binding. Passing `undefined`
2880 /// made `var f = async function Binding(){ return typeof Binding }` answer
2881 /// `"undefined"`, so a named async function expression could not see its own name and
2882 /// `Binding = 1` inside it silently succeeded (`named-reassign-fn-name-in-body`).
2883 fn new_coroutine_from(
2884 &mut self,
2885 code: Gc<CompiledCode>,
2886 env: Gc<ClosureEnv>,
2887 this: Value,
2888 args: Vec<Value>,
2889 callee: Value,
2890 ) -> JsResult<Gc<JsObject>> {
2891 self.push_frame(code, env, this, args, callee)?;
2892 let frame = self.frames.pop().expect("push_frame just pushed it");
2893 let state = GeneratorState {
2894 frame: Some(frame),
2895 phase: GeneratorPhase::SuspendedStart,
2896 parked_on_await: false,
2897 parked_on_yield_star: false,
2898 requests: std::collections::VecDeque::new(),
2899 async_busy: false,
2900 // An `async function` body is driven by `drive_async`, never by the generator
2901 // protocol, and the object is not reachable from script.
2902 is_async: false,
2903 };
2904 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2905 coroutine.with_mut(|data| {
2906 data.kind = ObjectKind::Generator(Box::new(state));
2907 });
2908 Ok(coroutine)
2909 }
2910
2911 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2912 /// `await` and `value` is what it awaited.
2913 fn resume_coroutine(
2914 &mut self,
2915 coroutine: &Gc<JsObject>,
2916 kind: ResumeKind,
2917 value: Value,
2918 ) -> JsResult<(Value, bool)> {
2919 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2920 ObjectKind::Generator(state) => {
2921 let is_async = state.is_async;
2922 Some(std::mem::replace(
2923 state.as_mut(),
2924 GeneratorState {
2925 frame: None,
2926 phase: GeneratorPhase::Executing,
2927 parked_on_await: false,
2928 parked_on_yield_star: false,
2929 requests: std::collections::VecDeque::new(),
2930 async_busy: false,
2931 is_async,
2932 },
2933 ))
2934 }
2935 _ => None,
2936 }) else {
2937 return Err(self.type_error("not a coroutine"));
2938 };
2939 let result = self.step_generator(&mut state, kind, value);
2940 coroutine.with_mut(|data| {
2941 data.kind = ObjectKind::Generator(Box::new(state));
2942 });
2943 let (value, done, _ready, _reason) = result?;
2944 Ok((value, done))
2945 }
2946
2947 /// Advance an async body and settle its promise with the outcome.
2948 fn drive_async(
2949 &mut self,
2950 coroutine: &Gc<JsObject>,
2951 promise: &Gc<JsObject>,
2952 kind: ResumeKind,
2953 value: Value,
2954 ) -> JsResult<()> {
2955 match self.resume_coroutine(coroutine, kind, value) {
2956 Ok((value, true)) => {
2957 // `Ok` with `done` means the body finished *normally*, even when it was
2958 // resumed by a `throw` — `try { await p } catch {}` completes by
2959 // returning. Only the `Err` arm below is a rejection.
2960 //
2961 // Resolving rather than fulfilling matters: `return promise` in an async
2962 // body adopts the inner promise, so `async function f(){ return
2963 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2964 // promise.
2965 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2966 self.reject_promise(promise, reason);
2967 }
2968 Ok(())
2969 }
2970 Ok((value, false)) => {
2971 // Parked on `await`: follow what it awaited and resume with the outcome.
2972 let awaited = match self.promise_resolve_value(value) {
2973 Ok(awaited) => awaited,
2974 Err(Signal::Throw(error)) => {
2975 self.reject_promise(promise, error);
2976 return Ok(());
2977 }
2978 Err(other) => return Err(other),
2979 };
2980 self.hook_await(awaited, coroutine, promise)
2981 }
2982 Err(Signal::Throw(reason)) => {
2983 self.reject_promise(promise, reason);
2984 Ok(())
2985 }
2986 Err(other) => Err(other),
2987 }
2988 }
2989
2990 /// Arrange for `coroutine` to resume when `awaited` settles.
2991 fn hook_await(
2992 &mut self,
2993 awaited: Value,
2994 coroutine: &Gc<JsObject>,
2995 promise: &Gc<JsObject>,
2996 ) -> JsResult<()> {
2997 let resumed = JsObject::function(
2998 self.heap,
2999 Some(self.realm.function_proto.clone()),
3000 Callable::AwaitResume {
3001 coroutine: coroutine.clone(),
3002 promise: promise.clone(),
3003 kind: ResumeKind::Next,
3004 },
3005 );
3006 let raised = JsObject::function(
3007 self.heap,
3008 Some(self.realm.function_proto.clone()),
3009 Callable::AwaitResume {
3010 coroutine: coroutine.clone(),
3011 promise: promise.clone(),
3012 kind: ResumeKind::Throw,
3013 },
3014 );
3015 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
3016 // guarantees one; the fallback keeps a mis-shaped value from panicking.
3017 let Value::Object(awaited) = &awaited else {
3018 self.jobs.push_back(Job::Resume {
3019 coroutine: coroutine.clone(),
3020 promise: promise.clone(),
3021 kind: ResumeKind::Next,
3022 value: awaited,
3023 });
3024 return Ok(());
3025 };
3026 self.perform_then(
3027 awaited,
3028 Some(Value::Object(resumed)),
3029 Some(Value::Object(raised)),
3030 )?;
3031 Ok(())
3032 }
3033
3034 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
3035 /// things an engine keeps outside it — array elements and an array's `length`.
3036 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3037 if let Some(property) = object.own_property_key(key) {
3038 return Some(property);
3039 }
3040 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3041 // be synthesized too — and every one of them is a plain writable, enumerable,
3042 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3043 // `undefined` before this, which made `key-is-numericindex` fail on its own
3044 // side effect check.
3045 //
3046 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3047 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3048 // likewise not elements however numeric they look.
3049 if object.typed_array_element_type().is_some()
3050 && let Some(numeric) = canonical_numeric_index(key)
3051 && numeric.is_finite()
3052 && numeric.fract() == 0.0
3053 && !(numeric == 0.0 && numeric.is_sign_negative())
3054 && numeric >= 0.0
3055 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3056 {
3057 let value = object.typed_array_element(numeric as usize)?;
3058 return Some(Property::data(value));
3059 }
3060 // An array's elements live in their own vector rather than the property table, so
3061 // a descriptor for one has to be synthesized — with the attributes an element has.
3062 if let Some(index) = key.as_str().and_then(array_index)
3063 && let Some(value) = object.array_get(index as usize)
3064 && !matches!(value, Value::Hole)
3065 {
3066 return Some(Property::data(value));
3067 }
3068 // `length` is an own property of an array that is not in its property table
3069 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3070 // and non-enumerable.
3071 if key.as_str() == Some("length")
3072 && let Some(length) = object.array_length()
3073 {
3074 return Some(Property {
3075 value: Some(crate::object::length_value(length)),
3076 writable: object.length_writable(),
3077 enumerable: false,
3078 configurable: false,
3079 getter: None,
3080 setter: None,
3081 descriptor_fields: None,
3082 });
3083 }
3084 None
3085 }
3086
3087 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3088 pub fn object_get_own_property(
3089 &mut self,
3090 object: &Gc<JsObject>,
3091 key: &PropertyKey,
3092 ) -> JsResult<Option<Property>> {
3093 if let Some(answer) = self.proxy_get_own_property(object, key)? {
3094 return Ok(answer);
3095 }
3096 if let Some(exotic) = object.exotic()
3097 && let Some(answer) = exotic.get_own_property(self, object, key)?
3098 {
3099 return Ok(answer);
3100 }
3101 // A module namespace's bindings are accessors internally and data properties to
3102 // script; see `namespace_own_property`.
3103 //
3104 // This is also where a *deferred* namespace evaluates its module, and it is the one
3105 // place that has to be: §10.4.6 answers `[[Get]]`, `[[GetOwnProperty]]` and
3106 // `[[HasProperty]]` all through `GetModuleExportsList`, and in this engine all three
3107 // arrive here. `@@…` keys and `"then"` are exempt — see `is_symbol_like_namespace_key`.
3108 if object.module_namespace_marker() {
3109 self.trigger_deferred_namespace_for_key(object, key)?;
3110 return self.namespace_own_property(object, key);
3111 }
3112 // A mapped `arguments` index is a data property as far as script can see: the
3113 // accessor pair that aliases the parameter is plumbing, and exposing it would
3114 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3115 // report a `get` where the spec has a `[[Value]]`.
3116 if let Some(index) = key.as_str().and_then(crate::object::array_index)
3117 && let Some(cell) = object.mapped_argument_cell(index as usize)
3118 {
3119 // Non-configurable is *not* the default: an ordinary mapped index is
3120 // configurable, and only becomes non-configurable once something
3121 // redefines it. Preserve whatever the property table currently says.
3122 // The attributes come from whatever the property table holds, because they
3123 // can be changed independently of the mapping; only the *value* and the
3124 // data-property *kind* are the accessor's secret.
3125 let flags = Self::ordinary_own_property(object, key);
3126 if let Some(existing) = &flags
3127 && !existing.is_accessor()
3128 {
3129 // Already demapped: the table entry is the answer, not the cell.
3130 return Ok(flags);
3131 }
3132 return Ok(Some(Property {
3133 value: Some(cell.get()),
3134 writable: true,
3135 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3136 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3137 ..Property::default()
3138 }));
3139 }
3140 Ok(Self::ordinary_own_property(object, key))
3141 }
3142
3143 /// Whether `object` is a module namespace exotic object (§10.4.6).
3144 ///
3145 /// Recognised by shape rather than by a flag: a namespace is the only object whose
3146 /// properties are all accessors over a `ModuleBinding` cell. That is the same
3147 /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3148 /// distinction in one place instead of adding a boolean every constructor has to
3149 /// remember to set.
3150 pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3151 object.module_namespace_marker()
3152 }
3153
3154 /// `IsSymbolLikeNamespaceKey` — the keys a deferred namespace never evaluates for.
3155 ///
3156 /// A symbol never triggers, because the namespace machinery itself walks symbols:
3157 /// `Object.prototype.toString.call(ns)` reads `@@toStringTag` through this very
3158 /// function, and triggering there would make a mere type inspection run a module.
3159 ///
3160 /// `"then"` never triggers when the object is deferred, and that is the subtle half:
3161 /// the namespace is about to be handed to a promise as a resolution value, and the
3162 /// promise machinery reads `then` to decide whether it is a thenable. Evaluating a
3163 /// module as a side effect of *ignoring* a `then` that is not exported would evaluate
3164 /// it in the middle of `await import.defer(…)`.
3165 pub(crate) fn is_symbol_like_namespace_key(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
3166 if key.is_symbol() {
3167 return true;
3168 }
3169 match key.as_str() {
3170 Some("then") => object.deferred_namespace_module().is_some(),
3171 _ => false,
3172 }
3173 }
3174
3175 /// Evaluate a deferred namespace before the operation that asked for its exports.
3176 ///
3177 /// Every MOP entry point that §10.4.6 sends through `GetModuleExportsList` calls this
3178 /// with the key it was given, so the symbol-like exemption is applied once rather than
3179 /// at each site. An ordinary object — a namespace that is not deferred included — costs
3180 /// one marker test.
3181 pub(crate) fn trigger_deferred_namespace_for_key(
3182 &mut self,
3183 object: &Gc<JsObject>,
3184 key: &PropertyKey,
3185 ) -> JsResult<()> {
3186 if object.module_namespace_marker() && !Self::is_symbol_like_namespace_key(object, key) {
3187 self.trigger_deferred_namespace(object)?;
3188 }
3189 Ok(())
3190 }
3191
3192 /// `[[GetOwnProperty]]` for a module namespace exotic object.
3193 ///
3194 /// The bindings are stored as getters — that is the only way a live binding can be read
3195 /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3196 /// descriptor:
3197 ///
3198 /// ```text
3199 /// { [[Value]]: current value, [[Writable]]: true,
3200 /// [[Enumerable]]: true, [[Configurable]]: false }
3201 /// ```
3202 ///
3203 /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3204 /// `undefined`. Reporting the accessor instead — which is what the property table holds
3205 /// — made every one of test262's namespace descriptor assertions fail, in both the
3206 /// `await-ns-*` and `promise-then-ns-*` families.
3207 ///
3208 /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3209 /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3210 /// property`); the ordinary descriptor machinery derives that from these attributes.
3211 pub fn namespace_own_property(
3212 &mut self,
3213 object: &Gc<JsObject>,
3214 key: &PropertyKey,
3215 ) -> JsResult<Option<Property>> {
3216 let Some(stored) = Self::ordinary_own_property(object, key) else {
3217 return Ok(None);
3218 };
3219 let Some(Property {
3220 getter: Some(getter),
3221 ..
3222 }) = Some(&stored)
3223 else {
3224 return Ok(Some(stored));
3225 };
3226 // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3227 // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3228 // rather than stored.
3229 let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3230 Ok(Some(Property {
3231 value: Some(value),
3232 writable: true,
3233 enumerable: true,
3234 configurable: false,
3235 ..Property::default()
3236 }))
3237 }
3238
3239 /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3240 ///
3241 /// Modelled as "does this descriptor describe the property that is already there?",
3242 /// because a namespace property's attributes are fixed and its value cannot be changed
3243 /// through the namespace. The three ways to succeed:
3244 ///
3245 /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3246 /// * one whose `[[Value]]` is `SameValue` the current binding value;
3247 /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3248 /// configurable: false}`.
3249 ///
3250 /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3251 /// false), so it goes through the same check against its stored value — which is what
3252 /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3253 /// answer `true` while `{value: "Other"}` answers `false`.
3254 fn namespace_define_own_property(
3255 &mut self,
3256 object: &Gc<JsObject>,
3257 key: &PropertyKey,
3258 property: &Property,
3259 ) -> JsResult<bool> {
3260 let Some(current) = self.namespace_own_property(object, key)? else {
3261 // A name the namespace does not export cannot be added to it.
3262 return Ok(false);
3263 };
3264 if let Some(value) = &property.value {
3265 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3266 if !self.same_value(value, current_value)? {
3267 return Ok(false);
3268 }
3269 }
3270 Ok(true)
3271 }
3272
3273 /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3274 ///
3275 /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3276 /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3277 /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3278 /// descriptor with no fields at all therefore succeeds, which is what
3279 /// `Reflect.defineProperty(ns, k, {})` checks.
3280 ///
3281 /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3282 /// stored property, and a namespace stores its bindings as accessors, so every
3283 /// definition looked like "accessor → data kind changed" or carried `writable: false`
3284 /// from the accessor's own entry. Presence is only available here, before the merge.
3285 pub fn namespace_define_from_descriptor(
3286 &mut self,
3287 object: &Gc<JsObject>,
3288 key: &PropertyKey,
3289 descriptor: &Gc<JsObject>,
3290 ) -> JsResult<bool> {
3291 let Some(current) = self.namespace_own_property(object, key)? else {
3292 return Ok(false);
3293 };
3294 // An accessor descriptor can never describe a namespace binding.
3295 if self.get_property(descriptor, "get")?.is_some()
3296 || self.get_property(descriptor, "set")?.is_some()
3297 {
3298 return Ok(false);
3299 }
3300 if let Some(value) = self.get_property(descriptor, "value")? {
3301 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3302 if !self.same_value(&value, current_value)? {
3303 return Ok(false);
3304 }
3305 }
3306 // The three attribute fields, when named, must restate what the property already
3307 // has. Not a fixed shape: an exported binding reports
3308 // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3309 // is a real own data property with `{false, false, false}`, and both are namespace
3310 // properties. Comparing against `current` is what makes one rule cover both.
3311 for (name, have) in [
3312 ("writable", current.writable),
3313 ("enumerable", current.enumerable),
3314 ("configurable", current.configurable),
3315 ] {
3316 if let Some(named) = self.get_property(descriptor, name)?
3317 && named.to_boolean() != have
3318 {
3319 return Ok(false);
3320 }
3321 }
3322 Ok(true)
3323 }
3324
3325 /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3326 /// compare a requested value against a live binding.
3327 pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3328 Ok(a.same_value(b))
3329 }
3330
3331 ///
3332 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3333 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3334 /// abstract operation here rather than a private helper in `error.rs`.
3335 ///
3336 /// The name is the whole point: the setter must behave as if the prototype were not
3337 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3338 /// the accessor for every error object in the realm. Everything below follows from that:
3339 ///
3340 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3341 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3342 /// accessor's own home an error rather than a self-shadow.
3343 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3344 /// either has a string or has made a mistake.
3345 /// 4. An existing *own* property decides the path — an own setter is called, an own
3346 /// non-writable data property is a `TypeError` — and only a missing own property
3347 /// falls through to defining one.
3348 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3349 /// traps and a non-extensible receiver is a `TypeError`.
3350 ///
3351 /// The installed shape is writable + configurable, not enumerable.
3352 pub fn setter_that_ignores_prototype_properties(
3353 &mut self,
3354 this_value: Value,
3355 home: &Gc<JsObject>,
3356 property_key: &str,
3357 args: &[Value],
3358 ) -> JsResult<Value> {
3359 self.setter_that_ignores_prototype_properties_key(
3360 this_value,
3361 home,
3362 &PropertyKey::from(property_key),
3363 args,
3364 )
3365 }
3366
3367 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3368 ///
3369 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3370 pub fn setter_that_ignores_prototype_properties_key(
3371 &mut self,
3372 this_value: Value,
3373 home: &Gc<JsObject>,
3374 key: &PropertyKey,
3375 args: &[Value],
3376 ) -> JsResult<Value> {
3377 let Some(receiver) = this_value.as_object().cloned() else {
3378 return Err(self.type_error("setter called on a non-object"));
3379 };
3380 if Gc::ptr_eq(&receiver, home) {
3381 return Err(self.type_error("cannot assign to the accessor's own home object"));
3382 }
3383 // No type check here: §7.3.40 takes an arbitrary `v`, and
3384 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3385 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3386 // before calling this.
3387 let value = args.first().cloned().unwrap_or(Value::Undefined);
3388 // Step 4: an own property on the receiver changes what happens, and there are three
3389 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3390 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3391 // `Set` with `throw = true`, and a test exists for each.
3392 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3393 if existing.is_accessor() && existing.setter.is_none() {
3394 // A getter-only own accessor cannot be written through.
3395 return Err(self.type_error("no setter for the own property"));
3396 }
3397 // Everything else — an own data property, or an own accessor *with* a setter —
3398 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3399 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3400 // an own user setter receives the value (`setter-own-accessor`), because
3401 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3402 // setter directly is the difference between one code path and two that can
3403 // disagree.
3404 self.set_property_with_key(
3405 &receiver,
3406 key,
3407 value.clone(),
3408 crate::interp::DeleteFailure::Throw,
3409 )?;
3410 return Ok(Value::Undefined);
3411 }
3412 let property = Property {
3413 value: Some(value.clone()),
3414 writable: true,
3415 // Enumerable, despite the accessor it shadows not being. The reference installs
3416 // it that way and six cases check it (`setter-creates-own-property` and friends).
3417 enumerable: true,
3418 configurable: true,
3419 ..Property::default()
3420 };
3421 if !self.object_define_own_property(&receiver, key, property)? {
3422 return Err(self.type_error("the receiver refused the definition"));
3423 }
3424 Ok(Value::Undefined)
3425 }
3426
3427 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3428 ///
3429 /// The indices of a typed array are not properties at all — they are bytes in the
3430 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3431 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3432 /// enumerable and configurable, so a definition can only ever change the *value*, and
3433 /// every other descriptor is refused rather than applied.
3434 ///
3435 /// The order of the checks is the spec's, and two of them are load-bearing:
3436 ///
3437 /// * the index is validated **before** the value is converted, because the conversion
3438 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3439 /// detaches from a `valueOf` and still expects `true` with no store, which only
3440 /// happens when the index was valid on the way in;
3441 /// * the store is attempted even when the index has gone out of bounds by the time the
3442 /// conversion finishes, because the store is a silent no-op rather than a failure —
3443 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3444 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3445 ///
3446 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3447 /// the existing element, which is harmless here: every valid index is already
3448 /// writable, enumerable and configurable, so a `false` in the merged property can only
3449 /// have come from the descriptor having named `false`.
3450 fn integer_indexed_define_own_property(
3451 &mut self,
3452 object: &Gc<JsObject>,
3453 numeric: f64,
3454 property: &Property,
3455 ) -> JsResult<bool> {
3456 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3457 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3458 if !typed_array_index_is_valid(object, numeric) {
3459 return Ok(false);
3460 }
3461 // Step 6: the indices are data properties, so an accessor descriptor is refused
3462 // rather than converted. `Object.defineProperty` turns the `false` into a
3463 // `TypeError`; `Reflect.defineProperty` reports it.
3464 if property.is_accessor() {
3465 return Ok(false);
3466 }
3467 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3468 // definition that asks for anything else cannot be honoured.
3469 if !property.writable || !property.enumerable || !property.configurable {
3470 return Ok(false);
3471 }
3472 // Step 10: only a descriptor that names a value stores anything.
3473 let Some(value) = property.value.clone() else {
3474 return Ok(true);
3475 };
3476 let Some(element) = object.typed_array_element_type() else {
3477 return Ok(false);
3478 };
3479 let stored = self.element_value(element, value)?;
3480 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3481 return Err(self.type_error(reason));
3482 }
3483 Ok(true)
3484 }
3485
3486 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3487 pub fn object_define_own_property(
3488 &mut self,
3489 object: &Gc<JsObject>,
3490 key: &PropertyKey,
3491 property: Property,
3492 ) -> JsResult<bool> {
3493 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3494 return Ok(accepted);
3495 }
3496 // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3497 //
3498 // The only definitions that can succeed are ones describing the property the
3499 // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3500 // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3501 // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3502 // `writable: false`, `configurable: true`, or any name the namespace does not
3503 // export is `false`.
3504 //
3505 // The ordinary path gets the no-change case right by accident — it compares against
3506 // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3507 // is an accessor internally while the definition script writes is a data descriptor.
3508 // Answering here is what makes that attribute-only definition a no-op rather than a
3509 // refusal (`namespace/await-ns-define-own-property`).
3510 if object.module_namespace_marker() {
3511 self.trigger_deferred_namespace_for_key(object, key)?;
3512 return self.namespace_define_own_property(object, key, &property);
3513 }
3514 // A proxy always answers above — with `Some` from its trap, or with `None` when
3515 // the trap is absent, and then the definition belongs to the **target**
3516 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3517 // when there is no trap). Falling through to the ordinary path here defined the
3518 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3519 // property the target never saw.
3520 if object.proxy_state().is_some() {
3521 let Some((target, _handler)) = self.proxy_parts(object)? else {
3522 return Err(self.type_error("cannot use a proxy that has been revoked"));
3523 };
3524 return self.object_define_own_property(&target, key, property);
3525 }
3526 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3527 // they accept exactly one descriptor shape. This has to happen before the
3528 // ordinary path, which would happily store a data property next to the buffer —
3529 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3530 // and `TypedArray/prototype/set` are about this section.
3531 if object.typed_array_element_type().is_some()
3532 && let Some(index) = canonical_numeric_index(key)
3533 {
3534 return self.integer_indexed_define_own_property(object, index, &property);
3535 }
3536 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3537 // non-extensible object. The check lives here rather than in the callers because
3538 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3539 // `Array.prototype.filter` uses to store its result, and a species object made
3540 // non-extensible by its own constructor must make that a `TypeError`
3541 // (`target-array-non-extensible`).
3542 // Note the `is_none()`: an already-present property may still be **redefined** on a
3543 // non-extensible object, and only *adding* one is refused (as Distinct from
3544 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3545 // properties — testing extensibility before looking for the property made every
3546 // `Object.freeze` of an ordinary object refuse its own second step).
3547 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3548 return Ok(false);
3549 }
3550 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3551 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3552 // an omitted field is left alone). Merging here rather than at each call site is
3553 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3554 // the value and `enumerable` in place.
3555 //
3556 // The merge is a no-op when the property is absent: there is nothing to keep.
3557 let was_partial = property.descriptor_fields.is_some();
3558 let property = match property.descriptor_fields {
3559 None => property,
3560 Some(fields) => {
3561 let base = self.object_get_own_property(object, key)?;
3562 let mut merged = base.clone().unwrap_or_default();
3563 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3564 // descriptor names, and switching kind discards the other half —
3565 // `{set: f}` on a data property is an accessor with no getter, not a data
3566 // property whose `get` happens to be absent.
3567 let wants_accessor = fields.get || fields.set;
3568 let wants_data = fields.value || fields.writable;
3569 if wants_accessor {
3570 merged.value = None;
3571 merged.writable = false;
3572 merged.getter = property.getter.clone();
3573 merged.setter = property.setter.clone();
3574 } else if wants_data {
3575 merged.getter = None;
3576 merged.setter = None;
3577 if fields.value {
3578 merged.value = property.value.clone();
3579 }
3580 if fields.writable {
3581 merged.writable = property.writable;
3582 }
3583 }
3584 if fields.enumerable {
3585 merged.enumerable = property.enumerable;
3586 }
3587 if fields.configurable {
3588 merged.configurable = property.configurable;
3589 }
3590 merged.descriptor_fields = None;
3591 merged
3592 }
3593 };
3594 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3595 // descriptor. `define_property_on` runs the same check before it calls here, so an
3596 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3597 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3598 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3599 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3600 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3601 // own define would have refused.
3602 //
3603 // Only partial descriptors are validated here. A whole `Property` passed by an
3604 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3605 // what the descriptor "named", and those callers rely on the write landing.
3606 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3607 // Every branch below is gated on `!existing.configurable`: a *configurable*
3608 // property may be reshaped however the descriptor likes, which is why an
3609 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3610 // must succeed. Testing only `writable` refused that and broke
3611 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3612 let same_kind = existing.is_accessor() == property.is_accessor();
3613 if !same_kind {
3614 // Step 4: a non-configurable property may not change kind.
3615 if !existing.configurable {
3616 return Ok(false);
3617 }
3618 } else if existing.is_accessor() {
3619 // Step 6: an accessor's halves are its value.
3620 if !existing.configurable
3621 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3622 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3623 {
3624 return Ok(false);
3625 }
3626 } else if !existing.configurable && !existing.writable {
3627 // Step 7: a non-configurable *and* non-writable data property's value is
3628 // fixed, and it may not become writable again.
3629 if property.writable {
3630 return Ok(false);
3631 }
3632 let current = existing.value.clone().unwrap_or(Value::Undefined);
3633 let requested = property.value.clone().unwrap_or(Value::Undefined);
3634 if !current.same_value(&requested) {
3635 return Ok(false);
3636 }
3637 }
3638 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3639 // is frozen with it.
3640 if !existing.configurable
3641 && (property.configurable || property.enumerable != existing.enumerable)
3642 {
3643 return Ok(false);
3644 }
3645 }
3646 // A host class that intercepts definitions owns the attributes of the properties it
3647 // defines: `_class`-style storage on the native side is the usual reason.
3648 if let Some(exotic) = object.exotic()
3649 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3650 {
3651 return Ok(accepted);
3652 }
3653 // An array index is stored in the element vector, which can hold a plain value and
3654 // nothing else. An accessor — or a data property with non-default attributes —
3655 // therefore has to live in the property table, and the element slot is blanked so
3656 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3657 // {get})` stored the accessor where no read ever looked, and the array kept
3658 // answering its old value.
3659 // An array's `length` is not stored in the property table, so defining it has to
3660 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3661 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3662 // {value: 1})` reported success and changed nothing.
3663 if key.as_str() == Some("length") && object.is_array() {
3664 // `{writable: false}` on `length` does not change the length, but it does make
3665 // it read-only — after which neither a later `{writable: true}` nor a store
3666 // past the end may succeed.
3667 if property.value.is_none() {
3668 if !object.length_writable() && property.writable {
3669 return Ok(false);
3670 }
3671 object.set_length_writable(property.writable);
3672 return Ok(true);
3673 }
3674 if !object.length_writable() {
3675 return Ok(false);
3676 }
3677 }
3678 if key.as_str() == Some("length")
3679 && object.is_array()
3680 && let Some(value) = property.value.clone()
3681 {
3682 let requested = value.to_number();
3683 let valid = requested.is_finite()
3684 && requested >= 0.0
3685 && requested.fract() == 0.0
3686 && requested <= u32::MAX as f64;
3687 if !valid {
3688 return Err(self.range_error("invalid array length"));
3689 }
3690 // Truncating deletes the elements above the new length, and a non-configurable
3691 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3692 // makes `a.length = 2` fail rather than quietly drop it.
3693 let current = object.array_length().unwrap_or(0);
3694 let requested = requested as usize;
3695 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3696 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3697 // `[[Writable]]: false` when the descriptor asked for it — the length is
3698 // left at its old value but locked. Returning `false` alone left it
3699 // writable, which `verifyProperty` catches
3700 // (`defineProperties/15.2.3.7-6-a-164`).
3701 if property
3702 .descriptor_fields
3703 .is_some_and(|fields| fields.writable)
3704 && !property.writable
3705 && object.length_writable()
3706 {
3707 object.set_length_writable(false);
3708 }
3709 return Ok(false);
3710 }
3711 object.array_set_length(self.heap, requested);
3712 return Ok(true);
3713 }
3714 let plain = property.writable
3715 && property.enumerable
3716 && property.configurable
3717 && !property.is_accessor();
3718 if let Some(index) = key.as_str().and_then(array_index)
3719 && object.is_array()
3720 {
3721 // Growing the array needs a writable `length`: after
3722 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3723 // be added.
3724 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3725 return Ok(false);
3726 }
3727 if plain && property.value.is_some() {
3728 // An ordinary element: the vector is where a read looks first, so it has
3729 // to be the vector that changes — unless the index is too far out to be
3730 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3731 // one property, because past its own limit it stores the index as an
3732 // ordinary key. Falling through to `define_key` below is the same choice,
3733 // and the alternative was worse: the store used to be *dropped* and the
3734 // length left at 0, which is a silent wrong answer.
3735 let value = property.value.clone().unwrap_or(Value::Undefined);
3736 object.delete_key(key);
3737 if object.array_set(self.heap, index as usize, value) {
3738 return Ok(true);
3739 }
3740 // Past the dense limit the element lives in the table like any property.
3741 object.note_element_descriptor();
3742 object.define_key(key, property);
3743 // A sparse store past the dense limit still extends `length`, which is what
3744 // `a[a.length] = v` relies on — but only extends: shortening would delete
3745 // the sparse properties above the index, including this one.
3746 if index as usize + 1 > object.array_length().unwrap_or(0) {
3747 object.array_set_length(self.heap, index as usize + 1);
3748 }
3749 return Ok(true);
3750 }
3751 // A non-plain element — an accessor, or an attribute that is not the default —
3752 // lives in the table while the slot becomes a hole. Recording it keeps every
3753 // later `a[i] = v` off the dense path, where the write would have shadowed the
3754 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3755 // replace the accessor with a plain data property.
3756 object.note_element_descriptor();
3757 object.define_key(key, property);
3758 // The slot stays, so `length` does not shrink; a hole is not an element, so
3759 // the table entry is now what a read finds.
3760 object.array_set(self.heap, index as usize, Value::Hole);
3761 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3762 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3763 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3764 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3765 if index as usize + 1 > object.array_length().unwrap_or(0) {
3766 object.array_set_length(self.heap, index as usize + 1);
3767 }
3768 return Ok(true);
3769 }
3770 object.define_key(key, property);
3771 Ok(true)
3772 }
3773
3774 /// Build a proxy object over `target`, with its traps read from `handler`.
3775 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3776 JsObject::proxy(self.heap, target, handler)
3777 }
3778
3779 /// The `revoke` function for a proxy's slots.
3780 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3781 let revoke = JsObject::function(
3782 self.heap,
3783 Some(self.realm.function_proto.clone()),
3784 Callable::Revoker(slots),
3785 );
3786 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3787 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3788 // inherited from `Function.prototype` reads the same but fails the three cases that
3789 // check the own-property list (`revocation-function-{length,name,property-order}`).
3790 revoke.define("length", Property::name_or_length(Value::Int(0)));
3791 revoke.define("name", Property::name_or_length(self.string("")));
3792 revoke
3793 }
3794
3795 /// A new array.
3796 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3797 let array = JsObject::array(
3798 self.heap,
3799 Some(self.realm.array_proto.clone()),
3800 elements.len(),
3801 );
3802 for (index, element) in elements.into_iter().enumerate() {
3803 array.array_set(self.heap, index, element);
3804 }
3805 array
3806 }
3807
3808 /// A new native function object.
3809 ///
3810 /// The observable `name` and `length` are installed as properties here, which is
3811 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3812 /// so `f.name = "x"` behaves like the writable property it is.
3813 /// A native constructor that builds its own instance after validating its arguments.
3814 ///
3815 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3816 /// check runs before `new.target.prototype` is read.
3817 pub fn new_native_ctor(
3818 &self,
3819 name: impl Into<String>,
3820 length: u32,
3821 func: NativeFn,
3822 ) -> Gc<JsObject> {
3823 let function = JsObject::function(
3824 self.heap,
3825 Some(self.realm.function_proto.clone()),
3826 Callable::Native {
3827 func,
3828 own_instance: true,
3829 },
3830 );
3831 function.set_constructible(true);
3832 function.define(
3833 "length",
3834 Property::name_or_length(Value::Int(length as i32)),
3835 );
3836 function.define("name", Property::name_or_length(self.string(name)));
3837 function
3838 }
3839
3840 /// A native constructor that lets `new` build the instance first.
3841 ///
3842 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3843 /// validation that must precede reading `new.target.prototype`, so the object can be
3844 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3845 /// which makes a *method* and therefore not a constructor at all.
3846 pub fn new_native_constructor(
3847 &self,
3848 name: impl Into<String>,
3849 length: u32,
3850 func: NativeFn,
3851 ) -> Gc<JsObject> {
3852 let function = self.new_native(name, length, func);
3853 function.set_constructible(true);
3854 function
3855 }
3856
3857 /// A new host function object: a native closure that carries its own state.
3858 ///
3859 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3860 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3861 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3862 /// this safe: the closure must not capture a `Gc`.
3863 pub fn new_host_function(
3864 &self,
3865 name: impl Into<String>,
3866 length: u32,
3867 func: crate::object::HostFn,
3868 ) -> Gc<JsObject> {
3869 self.new_host_inner(name.into(), length, func, false)
3870 }
3871
3872 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3873 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3874 pub fn new_host_ctor(
3875 &self,
3876 name: impl Into<String>,
3877 length: u32,
3878 func: crate::object::HostFn,
3879 ) -> Gc<JsObject> {
3880 let function = self.new_host_inner(name.into(), length, func, true);
3881 function.set_constructible(true);
3882 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3883 // installs its own methods on it, so it starts as a plain object.
3884 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3885 function.define(
3886 "prototype",
3887 Property {
3888 value: Some(Value::Object(proto)),
3889 writable: true,
3890 enumerable: false,
3891 configurable: false,
3892 ..Property::default()
3893 },
3894 );
3895 function
3896 }
3897
3898 fn new_host_inner(
3899 &self,
3900 name: String,
3901 length: u32,
3902 func: crate::object::HostFn,
3903 own_instance: bool,
3904 ) -> Gc<JsObject> {
3905 let function = JsObject::function(
3906 self.heap,
3907 Some(self.realm.function_proto.clone()),
3908 Callable::Host {
3909 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3910 own_instance,
3911 },
3912 );
3913 function.define(
3914 "length",
3915 Property::name_or_length(Value::Int(length as i32)),
3916 );
3917 function.define("name", Property::name_or_length(self.string(name)));
3918 function
3919 }
3920
3921 /// A callable object with the `length`/`name` a built-in function has, in that order.
3922 ///
3923 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3924 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3925 /// [`JsObject::function`] defines neither, which is why every capability helper built
3926 /// with it reported no own `length` and no own `name` at all.
3927 ///
3928 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3929 /// configurable.
3930 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3931 let function =
3932 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3933 function.define(
3934 "length",
3935 Property::name_or_length(Value::Int(length as i32)),
3936 );
3937 function.define("name", Property::name_or_length(self.string(name)));
3938 function
3939 }
3940
3941 /// A new native function object.
3942 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3943 let function = JsObject::function(
3944 self.heap,
3945 Some(self.realm.function_proto.clone()),
3946 Callable::Native {
3947 func,
3948 own_instance: false,
3949 },
3950 );
3951 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3952 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3953 // `length,name` and this listed `name,length`. A bytecode function already gets it
3954 // the right way round; only native ones were built backwards.
3955 function.define(
3956 "length",
3957 Property::name_or_length(Value::Int(length as i32)),
3958 );
3959 function.define("name", Property::name_or_length(self.string(name)));
3960 function
3961 }
3962
3963 /// A new bound function.
3964 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3965 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3966 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3967 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3968 let constructible = target
3969 .as_object()
3970 .is_some_and(|target| target.is_constructor());
3971 let bound = JsObject::function(
3972 self.heap,
3973 Some(self.realm.function_proto.clone()),
3974 Callable::Bound { target, this, args },
3975 );
3976 bound.set_constructible(constructible);
3977 bound
3978 }
3979
3980 /// A new reference cell.
3981 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3982 Gc::new(self.heap, Cell::new(value))
3983 }
3984
3985 // -- running ------------------------------------------------------------
3986
3987 /// Evaluate `code` as a script body and return its completion value.
3988 /// Compile and run `source` for the engine's own use, returning its completion value.
3989 ///
3990 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3991 /// needs to be a real async function, and the engine already runs those as coroutines,
3992 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3993 ///
3994 /// Differences from [`Self::eval_in_global`], both deliberate:
3995 ///
3996 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3997 /// being built, and the source is an IIFE that only constructs a closure, so there
3998 /// is nothing to drain — and draining here would run script-queued jobs in the
3999 /// middle of `install`.
4000 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
4001 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
4002 /// and it should not look like the user wrote something wrong.
4003 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
4004 let program = match js_parse::parse_script(source) {
4005 Ok(program) => program,
4006 Err(error) => {
4007 let message = format!("builtin source does not parse: {error}");
4008 return Err(Signal::Throw(self.make_error("InternalError", &message)));
4009 }
4010 };
4011 let mut code = match js_compile::compile_script_with_source(&program, source) {
4012 Ok(code) => code,
4013 Err(error) => {
4014 let message = format!("builtin source does not compile: {}", error.message);
4015 return Err(Signal::Throw(self.make_error("InternalError", &message)));
4016 }
4017 };
4018 // The frame has to name something, and `<builtin>` is what a stack trace through
4019 // this code should say.
4020 code.set_filename("<builtin>");
4021 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4022 let closure_vars = compiled.code.closure_vars.clone();
4023 let env = self.global_env(&closure_vars);
4024 let this = Value::Object(self.realm.global.clone());
4025 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
4026 }
4027
4028 /// Run an already-parsed script and drain the microtasks it queued.
4029 ///
4030 /// The drain is what lets an `async` function's body advance past its first `await`
4031 /// before the host sees the result: nothing else pumps the job queue.
4032 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
4033 let this = Value::Object(self.realm.global.clone());
4034 self.run_script_with_this(code, this)
4035 }
4036
4037 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
4038 ///
4039 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
4040 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
4041 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
4042 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
4043 /// state the next script evaluation tripped over.
4044 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
4045 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4046 let closure_vars = compiled.code.closure_vars.clone();
4047 let env = self.global_env(&closure_vars);
4048 let callee = Value::Undefined;
4049 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
4050 // The script is done, so the microtasks it queued run before the host sees the
4051 // result. Without this an `async` function's body would never advance past its
4052 // first `await`, because nothing else drains the queue.
4053 self.drain_jobs()?;
4054 Ok(result)
4055 }
4056
4057 /// Compile and run `source` in global scope, returning its completion value.
4058 ///
4059 /// This is what `eval` and `new Function` use. Running it as a script means it
4060 /// sees the global object and nothing else, which is right for `eval("1+1")` and
4061 /// for a `Function` body; a *direct* eval that reads a local variable would need
4062 /// the compiler to hand its variable environment over, which is not implemented.
4063 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
4064 self.eval_in_global_named(source, EVAL_FILE, false, true)
4065 }
4066
4067 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
4068 ///
4069 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
4070 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
4071 /// through the code, so they cannot share one constant.
4072 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
4073 // *Not* an eval body: `evalScript` evaluates a global script, so its top-level
4074 // `let`/`const`/`class` are global lexical bindings that outlive the call — which
4075 // is exactly what `global-code/script-decl-lex*` assert.
4076 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier, false)
4077 }
4078
4079 /// Evaluate `source` as a global script, reported under `file`.
4080 ///
4081 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
4082 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
4083 /// from inside a C callback, where the interpreter is the running one rather than a
4084 /// context's own.
4085 pub fn eval_in_global_named(
4086 &mut self,
4087 source: &str,
4088 file: &str,
4089 barrier: bool,
4090 is_eval: bool,
4091 ) -> JsResult<Value> {
4092 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4093 // eval-created global binding — configurable, unlike a script's own `var`.
4094 self.eval_depth += 1;
4095 if barrier {
4096 let depth = self.frames.len();
4097 self.trace_barriers.push(depth);
4098 }
4099 let result = self.eval_in_global_inner(source, file, is_eval);
4100 if barrier {
4101 self.trace_barriers.pop();
4102 }
4103 self.eval_depth -= 1;
4104 result
4105 }
4106
4107 fn eval_in_global_inner(&mut self, source: &str, file: &str, is_eval: bool) -> JsResult<Value> {
4108 self.compiling_eval_body = is_eval;
4109 let compiled = self.compile_global_script(source, file, false);
4110 self.compiling_eval_body = false;
4111 let compiled = compiled?;
4112 let strict = compiled.strict;
4113 self.run_eval_script(compiled, strict)
4114 }
4115
4116 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4117 ///
4118 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4119 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4120 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4121 /// direct eval's is.
4122 pub fn eval_script_with_this(
4123 &mut self,
4124 source: &str,
4125 file: &str,
4126 this: Value,
4127 ) -> JsResult<Value> {
4128 let program = match js_parse::parse_script(source) {
4129 Ok(program) => program,
4130 Err(error) => {
4131 return Err(Signal::Throw(self.syntax_error_at(
4132 file,
4133 error.span.start.line,
4134 error.span.start.column,
4135 &error.message,
4136 )));
4137 }
4138 };
4139 let mut compiled = match js_compile::compile_script(&program) {
4140 Ok(compiled) => compiled,
4141 Err(error) => {
4142 return Err(Signal::Throw(self.syntax_error_at(
4143 file,
4144 error.span.start.line,
4145 error.span.start.column,
4146 &error.message,
4147 )));
4148 }
4149 };
4150 compiled.set_filename(file);
4151 self.run_script_with_this(compiled, this)
4152 }
4153
4154 /// Parse and compile `source` as a global script, without running it.
4155 ///
4156 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4157 /// before a promise exists to reject — while still evaluating in the same eval context
4158 /// (direct-eval strictness, `new.target`, `super`).
4159 fn compile_global_script(
4160 &mut self,
4161 source: &str,
4162 file: &str,
4163 async_body: bool,
4164 ) -> JsResult<CompiledFunction> {
4165 // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4166 // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4167 // context at all. The site is what tells the two apart — an indirect call leaves no
4168 // site behind, since only a bare `eval(...)` is recorded.
4169 let site = self.eval_site_at_cursor();
4170 // Strictness follows the same rule, and it is *not* a detail: §19.2.1.1 step 4
4171 // makes the eval code strict when the caller is strict **and the call is direct**.
4172 // So `var s = eval; s("var eval;")` called from strict code is sloppy — legal —
4173 // while `eval("var eval;")` there is a `SyntaxError`
4174 // (`statements/variable/12.2.1-*-s`). Inheriting unconditionally rejected the
4175 // indirect form. A `"use strict"` prologue in the source still works either way:
4176 // the parser reads the directive itself, which is how a script becomes strict.
4177 let strict = site.is_some() && self.current_strict();
4178 // `eval` runs in the caller's function context, so `new.target` is legal here
4179 // even though the source is a bare script — and so is `super.x` when the caller
4180 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4181 // caller's, which is what `special_object 4` already does.
4182 let private = site
4183 .map(|site| site.private_names.clone())
4184 .unwrap_or_default();
4185 let context = js_parse::EvalContext {
4186 in_method: site.is_some() && self.enclosing_home_object().is_some(),
4187 // `super()` belongs to a derived constructor, and an eval'd body is not a
4188 // constructor at all: the caller frame's `this` is already built.
4189 in_derived_constructor: false,
4190 // Private names are lexically scoped, so a direct `eval` inside a class body
4191 // can see them; see `Interp::eval_private_names`.
4192 private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4193 arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4194 // §19.2.1.1 asks the *caller's* function for `new.target`, and a script or
4195 // module body is not one: at the top level `eval('new.target')` is a
4196 // `SyntaxError`, not `undefined` (`eval-code/direct/new.target`).
4197 // The *nearest non-arrow* frame, because an arrow has no `new.target` of its
4198 // own and `() => eval("new.target")` at the top level is still a
4199 // `SyntaxError` (`new.target-arrow`).
4200 new_target_allowed: site.is_some()
4201 && !self
4202 .frames
4203 .iter()
4204 .rposition(|frame| !frame.code.code.is_arrow)
4205 .map(|index| self.frames[index].code.code.is_script_body)
4206 .unwrap_or(true),
4207 };
4208 // A *global* eval is not a function body: `new.target` and `super` are out of
4209 // reach there. Its `{async: true}` form differs in the other direction — the body
4210 // may `await` — so the two flags are independent and the reference sets both from
4211 // the eval type rather than from the caller.
4212 let parsed = if async_body {
4213 js_parse::parse_suspensible_global_eval(source, strict)
4214 } else {
4215 js_parse::parse_eval_script_in(source, strict, context)
4216 };
4217 let program = match parsed {
4218 Ok(program) => program,
4219 Err(error) => {
4220 // The message is bare: the position lives in `fileName`,
4221 // `lineNumber`, `columnNumber` and the stack frame above, which is where
4222 // the reference puts it. An `invalid source: L:C: ` prefix made
4223 // `e.message` differ from the reference while the stack already agreed.
4224 return Err(Signal::Throw(self.syntax_error_at(
4225 file,
4226 error.span.start.line,
4227 error.span.start.column,
4228 &error.message,
4229 )));
4230 }
4231 };
4232 let is_eval_body = self.compiling_eval_body;
4233 let mut compiled = match if async_body {
4234 js_compile::compile_eval_with_private(&program, &private, true, is_eval_body)
4235 } else {
4236 js_compile::compile_eval_with_private(&program, &private, false, is_eval_body)
4237 } {
4238 Ok(compiled) => compiled,
4239 // A construct the compiler does not handle yet is reported the same way a
4240 // parse error is: it happens before anything runs, so the trace is the
4241 // position in the source followed by the caller.
4242 Err(error) => {
4243 return Err(Signal::Throw(self.syntax_error_at(
4244 file,
4245 error.span.start.line,
4246 error.span.start.column,
4247 &error.message,
4248 )));
4249 }
4250 };
4251 compiled.set_filename(file);
4252 Ok(compiled)
4253 }
4254
4255 /// The private names the code at the current position can see, innermost first.
4256 ///
4257 /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4258 /// direct `eval` runs inside its caller's scope, so
4259 /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4260 /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4261 /// here rather than being derivable from the eval'd source.
4262 ///
4263 /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4264 /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4265 /// [`Interp::run_eval_script`] uses for "direct".
4266 fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4267 let frame = self.frames.last()?;
4268 let (line, column) = frame
4269 .code
4270 .code
4271 .position_at(frame.at as u32)
4272 .unwrap_or_default();
4273 // The nearest site at or before the current position: the recorded position of the
4274 // `call` instruction is the callee's, which sits a few columns inside the call
4275 // expression the compiler recorded, so an exact match would never be found.
4276 frame
4277 .code
4278 .code
4279 .eval_sites
4280 .iter()
4281 .filter(|site| (site.line, site.column) <= (line, column))
4282 .max_by_key(|site| (site.line, site.column))
4283 }
4284
4285 /// Run an `eval`'d script in the caller's scope.
4286 ///
4287 /// Three things have to come from the calling frame, because the eval'd code is a
4288 /// script and would otherwise see only the global object:
4289 ///
4290 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4291 /// * `arguments`, exposed as a binding of the eval's own scope, so
4292 /// `f("arguments.length", 1)` sees the caller's arguments;
4293 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4294 /// `eval("var v = 1")` into the global object.
4295 ///
4296 /// Locals of the calling function are *not* reachable: that needs the compiler to
4297 /// hand its variable environment over, which this milestone does not do.
4298 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4299 // `this` and `arguments` come from the innermost frame only — those are not
4300 // lexical — while the name bindings come from the whole chain of frames, part
4301 // of it being ordinary scope resolution.
4302 // An arrow has no `this` of its own, so an `eval` inside one inherits the
4303 // enclosing function's receiver — the lexical `this` the arrow was compiled to
4304 // read from its closure.
4305 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4306 // variable environment is the innermost frame of all: an arrow's own body is where
4307 // `var`s declared by an `eval` inside it belong.
4308 let caller_index = self
4309 .frames
4310 .iter()
4311 .rposition(|frame| !frame.code.code.is_arrow)
4312 .or_else(|| self.frames.len().checked_sub(1));
4313 let env_index = self.frames.len().checked_sub(1);
4314 let caller = caller_index.and_then(|index| self.frames.get(index));
4315 let (this, passed) = match caller {
4316 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4317 // No frame at all: the eval is running at the top level, so there is
4318 // nothing to inherit and the global receiver is right.
4319 None => (Value::Object(self.realm.global.clone()), Vec::new()),
4320 };
4321 // Innermost frame first, so the first binding found for a name is the one that
4322 // shadows the rest. A script frame (`<eval>`) contributes nothing.
4323 let mut bindings: Vec<EvalBinding> = Vec::new();
4324 // The calling function's own bindings, resolved by the compiler at the call
4325 // site. That table is the only reliable answer when a name is declared twice in
4326 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4327 // body means, and guessing by declaration order picks the wrong one as soon as
4328 // two loops in a row use the same name.
4329 // Only a *direct* eval sees the caller's scope. The compiler records a site for
4330 // every direct call — a bare `eval(...)` callee — so finding one at the current
4331 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4332 // callee to a value first and leave no site behind.
4333 let mut direct = false;
4334 let mut resolved_here = false;
4335 if let Some(frame) = self.frames.last() {
4336 let (line, column) = frame
4337 .code
4338 .code
4339 .position_at(frame.at as u32)
4340 .unwrap_or_default();
4341 // The nearest site at or before the current position, not an exact match:
4342 // the recorded position of the `call` instruction is the callee's, which
4343 // sits a few columns inside the call expression the compiler recorded. A
4344 // site is unique per call, so "the closest one behind us" identifies it.
4345 if let Some(site) = frame
4346 .code
4347 .code
4348 .eval_sites
4349 .iter()
4350 .filter(|site| (site.line, site.column) <= (line, column))
4351 .max_by_key(|site| (site.line, site.column))
4352 {
4353 direct = true;
4354 resolved_here = true;
4355 for binding in &site.bindings {
4356 // An enclosing function's frame sits `owner` levels below the one
4357 // running the call.
4358 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4359 else {
4360 continue;
4361 };
4362 bindings.push(EvalBinding {
4363 name: binding.name.clone(),
4364 frame,
4365 slot: if binding.is_arg {
4366 EvalSlot::Arg
4367 } else {
4368 EvalSlot::Local
4369 },
4370 index: binding.index as usize,
4371 });
4372 }
4373 }
4374 }
4375 for frame_index in (0..self.frames.len()).rev() {
4376 // Skip the innermost frame's flat scan when the compiler already answered
4377 // for it; an enclosing frame still needs one, because the eval resolves
4378 // those names dynamically.
4379 if resolved_here && frame_index == self.frames.len() - 1 {
4380 continue;
4381 }
4382 let frame = &self.frames[frame_index];
4383 for (index, arg) in frame.code.code.args.iter().enumerate() {
4384 bindings.push(EvalBinding {
4385 name: arg.name.clone(),
4386 frame: frame_index,
4387 slot: EvalSlot::Arg,
4388 index,
4389 });
4390 }
4391 for (index, local) in frame.code.code.vars.iter().enumerate() {
4392 bindings.push(EvalBinding {
4393 name: local.name.clone(),
4394 frame: frame_index,
4395 slot: EvalSlot::Local,
4396 index,
4397 });
4398 }
4399 }
4400 let mut seen = BTreeSet::new();
4401 bindings.retain(|binding| seen.insert(binding.name.clone()));
4402
4403 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4404 // elements is all the spec's ordinary uses need.
4405 //
4406 // Known divergence: this is bound for a *global* eval too, where there is no
4407 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4408 // needs "does the calling frame have an `arguments` of its own", which is not
4409 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4410 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4411 // the call-site detection does not answer it. Modelled as a binding in the caller's
4412 // variable environment, this would fall out; that is a larger change than the one
4413 // this comment is attached to.
4414 let arguments = Value::Object(self.new_array(passed));
4415
4416 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4417 // declares its `var`s in the caller's — which for a top-level eval is the global
4418 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4419 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4420 // vanish into a scope nobody reads back from.
4421 if code_strict {
4422 self.eval_scope.push(BTreeMap::new());
4423 }
4424 // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4425 // in global scope, where `arguments` means whatever the global object says — which
4426 // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4427 // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4428 // answer the array instead.
4429 let previous_arguments = if direct {
4430 self.eval_arguments.replace(arguments)
4431 } else {
4432 None
4433 };
4434 let previous_with = self.eval_with.replace(self.with_objects());
4435 let inherited_new_target = self
4436 .frames
4437 .iter()
4438 .rev()
4439 .find(|frame| !frame.code.code.is_arrow)
4440 .map(|frame| frame.new_target.clone());
4441 let previous_new_target = self
4442 .eval_new_target
4443 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4444 let eval_cells = self.eval_cells_for(&bindings);
4445 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4446 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4447 // `declare_eval_local` needs to know which frame that is.
4448 // An indirect eval gets the global environment, so nothing of the caller's is
4449 // recorded as the place its `var`s belong.
4450 let previous_caller = self
4451 .eval_caller
4452 .replace(if direct { env_index } else { None });
4453 // The cell-based view of the same bindings, which is what a closure created
4454 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4455 // whose compiler did not put a binding in a cell simply does not appear here —
4456 // reads and writes still work through `eval_bindings`, they just cannot outlive
4457 // the eval.
4458 let previous_eval_scope = self
4459 .active_eval_scope
4460 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4461 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4462 let closure_vars = compiled.code.closure_vars.clone();
4463 // Declaration instantiation is where this belongs: the check needs the caller frame
4464 // (recorded just above) and the eval's own var names, and it raises before any of
4465 // the eval's code runs.
4466 self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4467 let env = self.global_env(&closure_vars);
4468 let callee = Value::Undefined;
4469 // An async body does not run here: it becomes a coroutine and answers a promise,
4470 // which is what makes `await` legal in it. `this` still has to be the caller's
4471 // (for a global eval, the global object), because `this` is not part of `await`.
4472 let result = if compiled.code.kind.is_async() {
4473 self.run_async_body(compiled, env, this)
4474 } else {
4475 self.execute(compiled, env, this, Vec::new(), callee)
4476 };
4477 if code_strict {
4478 self.eval_scope.pop();
4479 }
4480 self.eval_arguments = previous_arguments;
4481 self.eval_with = previous_with;
4482 self.eval_new_target = previous_new_target;
4483 self.eval_bindings = previous_bindings;
4484 self.eval_caller = previous_caller;
4485 self.active_eval_scope = previous_eval_scope;
4486 result
4487 }
4488
4489 /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4490 /// rather than bindings.
4491 ///
4492 /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4493 /// declaration that cannot exist:
4494 ///
4495 /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4496 /// parameter expressions a separate parameter environment, and `arguments` is bound
4497 /// implicitly there, so a `var` of that name collides. An arrow that binds no
4498 /// `arguments` of its own has nothing to collide with and is allowed — see the table in
4499 /// [`Interp::check_eval_var_named_arguments`].
4500 /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4501 /// false; the operation is a `TypeError`, and `eval("var x")` with
4502 /// `Object.preventExtensions(this)` must raise rather than quietly do nothing
4503 /// (`non-definable-global-var` and its four siblings).
4504 fn check_eval_var_named_arguments(
4505 &self,
4506 closure_vars: &[js_compile::bytecode::ClosureVar],
4507 strict: bool,
4508 ) -> JsResult<()> {
4509 if strict {
4510 // A strict eval declares nothing outside itself, so none of the checks below
4511 // apply — they are all about the environment the declarations land in.
4512 return Ok(());
4513 }
4514 // §19.2.1.3 step 5.a: a `var` name that the *caller's* lexical environment already
4515 // binds is a `SyntaxError`, because the declaration would have to go into a
4516 // variable environment that sits inside that binding. `{ let x; eval("var x") }`
4517 // and a top-level `let x; eval("var x")` are both refused
4518 // (`var-env-lower-lex-non-strict`, `var-env-global-lex-non-strict`).
4519 //
4520 // The realm's `let`/`const`/`class` table is the global case; a caller frame's
4521 // lexical local is the nested one. `EvalSlot::Local` covers both, so the check has
4522 // to ask each binding whether it is lexical — which the *compiled code* knows.
4523 // A **declaration**, not a mention: the closure table carries an entry for every
4524 // global name the body touches, and only `GlobalDecl` means the eval itself would
4525 // create the binding. Without this, `for (let a …) eval("() => a")` looked like an
4526 // eval declaring `a` and was refused.
4527 let var_names = closure_vars.iter().filter(|var| {
4528 !var.is_lexical
4529 // `arguments` is not a lexical declaration wherever it appears: the
4530 // implicit one is var-like, and a *parameter* named `arguments` is handled
4531 // by the parameter-scope rule further down. Treating it as lexical made
4532 // every `eval("var arguments")` inside a nested arrow a `SyntaxError`.
4533 && var.name != "*default*"
4534 && var.name != "arguments"
4535 && matches!(
4536 var.closure_type,
4537 js_compile::bytecode::ClosureType::GlobalDecl
4538 )
4539 });
4540 for var in var_names {
4541 if self.realm.globals.contains_key(&var.name) {
4542 return Err(Signal::Throw(self.make_error(
4543 "SyntaxError",
4544 &format!(
4545 "eval declares '{}', which an enclosing lexical binding also names",
4546 var.name
4547 ),
4548 )));
4549 }
4550 // Only a *direct* eval has a caller environment to collide with. An indirect
4551 // one declares into the global environment, whose `thisLex` is already
4552 // `varEnv`, so the walk in §19.2.1.3 step 5.d has nothing to traverse —
4553 // `{ let x; (0, eval)("var x") }` is legal
4554 // (`eval-code/indirect/var-env-lower-lex-non-strict`).
4555 let lexical = self.eval_caller.flatten().is_some()
4556 && self.eval_bindings.iter().any(|binding| {
4557 binding.name == var.name
4558 && matches!(binding.slot, EvalSlot::Local)
4559 && self
4560 .frames
4561 .get(binding.frame)
4562 .and_then(|frame| frame.code.code.vars.get(binding.index))
4563 .is_some_and(|local| local.is_lexical)
4564 });
4565 if lexical {
4566 return Err(Signal::Throw(self.make_error(
4567 "SyntaxError",
4568 &format!(
4569 "eval declares '{}', which an enclosing lexical binding also names",
4570 var.name
4571 ),
4572 )));
4573 }
4574 }
4575 // A `var` this eval would declare on the global object, where there is no room for it.
4576 //
4577 // Two different rules, and the difference is the whole reason `ClosureVar` carries
4578 // `is_function_decl`:
4579 //
4580 // * `CanDeclareGlobalVar` — `var` — only asks that the global object be extensible
4581 // when the property does not exist at all, so `eval("var NaN")` is fine.
4582 // * `CanDeclareGlobalFunction` also refuses an existing property that is
4583 // non-configurable unless it is a writable, enumerable data property, so
4584 // `eval("function NaN(){}")` is a `TypeError`
4585 // (`non-definable-global-function`).
4586 let global = &self.realm.global;
4587 for var in closure_vars {
4588 if var.is_lexical || var.name == "*default*" {
4589 continue;
4590 }
4591 if !matches!(
4592 var.closure_type,
4593 js_compile::bytecode::ClosureType::GlobalDecl
4594 ) {
4595 continue;
4596 }
4597 match global.own_property(&var.name) {
4598 None => {
4599 if !global.is_extensible() {
4600 return Err(Signal::Throw(self.make_error(
4601 "TypeError",
4602 "cannot declare a global in a non-extensible global object",
4603 )));
4604 }
4605 }
4606 Some(existing) => {
4607 if var.is_function_decl
4608 && !existing.configurable
4609 && !(!existing.is_accessor() && existing.writable && existing.enumerable)
4610 {
4611 return Err(Signal::Throw(self.make_error(
4612 "TypeError",
4613 &format!("cannot declare global function '{}'", var.name),
4614 )));
4615 }
4616 }
4617 }
4618 }
4619 // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4620 // global environment, where `var arguments` is an ordinary global.
4621 let Some(caller) = self.eval_caller.flatten() else {
4622 return Ok(());
4623 };
4624 // §19.2.1.1 step 8: in a sloppy eval, a `var` name that the *running lexical
4625 // environment* already binds is a `SyntaxError`. While a default expression is being
4626 // evaluated that environment is the **parameter** scope, so
4627 // `function(a = eval("var a = 42")){}` throws rather than writing to the parameter —
4628 // the eval would otherwise declare into an environment that is about to be copied
4629 // into the body. A *different* name is fine, and so is the same name in a function
4630 // with a simple parameter list, where there is no separate parameter environment and
4631 // the `var` belongs to the function's own.
4632 //
4633 // The names come from `args`, which is exactly the plain-identifier parameters. A
4634 // pattern parameter's bindings are also in that scope but are not recoverable from
4635 // the bytecode, so `function([a] = eval("var a")){}` is still accepted; that gap is
4636 // narrower than the one this closes and needs the parameter scope published in the
4637 // compiled function to fix.
4638 if self.in_parameter_list_at(caller) {
4639 let parameter_names: Vec<String> = self
4640 .frames
4641 .get(caller)
4642 .map(|frame| {
4643 frame
4644 .code
4645 .code
4646 .args
4647 .iter()
4648 .map(|arg| arg.name.clone())
4649 .collect()
4650 })
4651 .unwrap_or_default();
4652 let collides = closure_vars.iter().any(|var| {
4653 !var.is_lexical && var.name != "*default*" && parameter_names.contains(&var.name)
4654 });
4655 if collides {
4656 return Err(Signal::Throw(self.make_error(
4657 "SyntaxError",
4658 "eval declares a var that the parameter scope already binds",
4659 )));
4660 }
4661 }
4662 if !closure_vars
4663 .iter()
4664 .any(|var| var.name == "arguments" && !var.is_lexical)
4665 {
4666 return Ok(());
4667 }
4668 // The body of a function is a different environment from its parameter list, and only
4669 // the parameter list is separate from `arguments`.
4670 if !self.in_parameter_list_at(caller) {
4671 return Ok(());
4672 }
4673 let caller_is_arrow = self
4674 .frames
4675 .get(caller)
4676 .is_some_and(|frame| frame.code.code.is_arrow);
4677 // A *parameter* named `arguments`, not merely a binding of that name: a body
4678 // `let arguments` is in the body's environment, which is the one that is separate and
4679 // therefore cannot collide. The slot tells them apart — an argument lives in
4680 // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4681 let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4682 binding.frame == caller
4683 && binding.name == "arguments"
4684 && matches!(binding.slot, EvalSlot::Arg)
4685 });
4686 if caller_is_arrow && !parameter_scope_binds_arguments {
4687 return Ok(());
4688 }
4689 Err(Signal::Throw(self.make_error(
4690 "SyntaxError",
4691 "eval declares 'arguments' in a function's parameter scope",
4692 )))
4693 }
4694
4695 /// The cell-backed subset of `bindings`, in the same priority order.
4696 ///
4697 /// Both lookup routes have to agree — the eval's own reads go through
4698 /// [`Interp::eval_binding_value`] and the closures it builds go through
4699 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4700 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4701 /// is not in a cell simply does not appear: reads and writes still work, they just
4702 /// cannot be handed to a closure that outlives the eval.
4703 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4704 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4705 for binding in bindings {
4706 let Some(frame) = self.frames.get(binding.frame) else {
4707 continue;
4708 };
4709 let cell = match binding.slot {
4710 EvalSlot::Arg => frame
4711 .code
4712 .arg_cell
4713 .get(binding.index)
4714 .copied()
4715 .unwrap_or(-1),
4716 EvalSlot::Local => frame
4717 .code
4718 .loc_cell
4719 .get(binding.index)
4720 .copied()
4721 .unwrap_or(-1),
4722 };
4723 if cell < 0 {
4724 continue;
4725 }
4726 if let Some(cell) = frame.cells.get(cell as usize) {
4727 names.push((binding.name.clone(), cell.clone()));
4728 }
4729 }
4730 names
4731 }
4732
4733 /// A `SyntaxError` that reports where in the source it happened.
4734 ///
4735 /// Compile-time failures never run, so they have no frame of their own; the
4736 /// reference still puts the position first in the trace, with no function name and
4737 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4738 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4739 /// reference borrows), which is how a script reads the position without parsing
4740 /// the trace.
4741 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4742 ///
4743 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4744 /// `columnNumber`, which is how the reference prints one. A positionless error
4745 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4746 /// the reference raises it from `js_resolve_module`, where there is no position.
4747 pub(crate) fn syntax_error_plain(
4748 &mut self,
4749 error: &js_parse::SyntaxError,
4750 file: &str,
4751 ) -> Value {
4752 if error.positionless {
4753 return self.make_error("SyntaxError", &error.message);
4754 }
4755 self.syntax_error_at(
4756 file,
4757 error.span.start.line,
4758 error.span.start.column,
4759 &error.message,
4760 )
4761 }
4762
4763 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4764 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4765 let value = self.make_error("SyntaxError", message);
4766 if let Value::Object(object) = &value {
4767 let text = self.string(blamed);
4768 // `stack` is an own data property, and the reference keeps it
4769 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4770 object.define("stack", Property::with_attributes(text, true, false));
4771 let name = self.string(file);
4772 object.define("fileName", Property::with_attributes(name, true, true));
4773 object.define(
4774 "lineNumber",
4775 Property::with_attributes(Value::Int(line as i32), true, true),
4776 );
4777 object.define(
4778 "columnNumber",
4779 Property::with_attributes(Value::Int(column as i32), true, true),
4780 );
4781 }
4782 value
4783 }
4784
4785 /// Run a compiled script whose completion value is a function, returning it.
4786 ///
4787 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4788 /// get the closure out, which keeps the constant-pool plumbing in one place.
4789 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4790 self.run_script(code)
4791 }
4792
4793 /// The environment of a script or of any function compiled at global scope:
4794 /// every entry is a global binding, so each one resolves to the realm's cell.
4795 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4796 let mut cells = Vec::with_capacity(closure_vars.len());
4797 for closure_var in closure_vars {
4798 let cell = match closure_var.closure_type {
4799 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4800 if closure_var.is_lexical =>
4801 {
4802 // A lexical declaration: the cell is created here holding the
4803 // dead-zone marker, which is what makes the binding exist and
4804 // unreadable before its initialiser runs.
4805 self.declare_global(&closure_var.name, closure_var.is_const);
4806 self.realm.globals[&closure_var.name].clone()
4807 }
4808 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4809 // A `var` or function declaration becomes a property of the global
4810 // object, and it exists from here on — which is why
4811 // `print(v); var v = 1` prints `undefined` instead of raising.
4812 // Declaring it at instantiation time (rather than at the
4813 // initialiser) is also what makes it non-configurable: the store
4814 // then lands on an existing property instead of creating one.
4815 self.declare_var_global(&closure_var.name);
4816 // The cell is a placeholder that nothing indexes; it cannot be
4817 // omitted because the slot has to hold something.
4818 self.new_cell(Value::Undefined)
4819 }
4820 _ => {
4821 // An undeclared global is read by name; the cell is a
4822 // placeholder that nothing indexes.
4823 self.new_cell(Value::Undefined)
4824 }
4825 };
4826 cells.push(cell);
4827 }
4828 Gc::new(
4829 self.heap,
4830 ClosureEnv {
4831 cells,
4832 eval_scope: None,
4833 local_vars: None,
4834 local_phase: 1,
4835 },
4836 )
4837 }
4838
4839 /// Push a frame and run until it returns.
4840 pub(crate) fn execute(
4841 &mut self,
4842 code: Gc<CompiledCode>,
4843 env: Gc<ClosureEnv>,
4844 this: Value,
4845 args: Vec<Value>,
4846 callee: Value,
4847 ) -> JsResult<Value> {
4848 let depth = self.frames.len();
4849 if depth == 0 {
4850 // A throw that reached the host ends the *active* mode: the next one is catchable
4851 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4852 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4853 // for the throw that evaluation will raise.
4854 self.uncatchable = false;
4855 }
4856 self.push_frame(code, env, this, args, callee)?;
4857 loop {
4858 // The fast loop first: it runs whole runs of records with `pc` in a register.
4859 //
4860 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4861 // reads it again — a store, a load and two bounds checks that a loop body does
4862 // not need, because nothing outside the loop can run in between. This is the
4863 // classic split: advance a register, and only spill it when leaving.
4864 //
4865 // `Some(value)` means the function ended by running off the end of its
4866 // instruction array, which is a normal return.
4867 let step = match self.run_fast() {
4868 Ok(Some(value)) => Ok(Step::Return(value)),
4869 Ok(None) => self.step(),
4870 Err(signal) => Err(signal),
4871 };
4872 match step {
4873 Ok(Step::Continue) => {}
4874 Ok(Step::Return(value)) => {
4875 self.pop_frame();
4876 // A frame that ended in a `tail_call` hands its value straight to
4877 // its caller: nothing after the call can run, so every frame above
4878 // the callee unwinds with the same value. See [`Frame::tail`] —
4879 // the reference does not reuse frames either, so recursion depth
4880 // and the stack-overflow limit behave the same way.
4881 while self.frames.len() > depth && self.frame().tail {
4882 self.pop_frame();
4883 }
4884 if self.frames.len() == depth {
4885 return Ok(value);
4886 }
4887 // The caller resumes with the value on its stack.
4888 self.frames
4889 .last_mut()
4890 .expect("a caller is live")
4891 .stack
4892 .push(value);
4893 }
4894 Err(Signal::Throw(value)) => {
4895 // The host's standing request becomes the active mode for this unwind,
4896 // and is consumed here so it does not leak into the next throw.
4897 if self.uncatchable_next {
4898 self.uncatchable_next = false;
4899 self.uncatchable = true;
4900 }
4901 // An uncatchable throw walks past every `catch` on the way out. The
4902 // frames are still popped, because the values they hold have to be
4903 // dropped — only the search for a handler is skipped.
4904 if self.uncatchable {
4905 while self.frames.len() > depth {
4906 self.frames.pop();
4907 }
4908 return Err(Signal::Throw(value));
4909 }
4910 // A handler lives on the stack of the frame that is throwing —
4911 // `catch` pushed it there — so this frame gets the first chance
4912 // to catch before it is popped.
4913 let mut value = value;
4914 loop {
4915 if self.frames.len() <= depth {
4916 return Err(Signal::Throw(value));
4917 }
4918 if self.catch_here(&mut value).is_some() {
4919 break;
4920 }
4921 self.frames.pop();
4922 }
4923 }
4924 // A `yield` in a frame that `execute` is running directly means a
4925 // generator body was entered as an ordinary call, which only happens if
4926 // the generator check in `call_or_push` was bypassed.
4927 Ok(Step::Suspend(_)) => {
4928 return Err(Signal::Throw(self.make_error(
4929 "InternalError",
4930 "a generator body ran as an ordinary call",
4931 )));
4932 }
4933 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4934 }
4935 }
4936 }
4937
4938 /// Install a handler for `value` if this frame has one, resuming at it.
4939 ///
4940 /// The scan is the reference's: walk the frame's stack downwards looking for the
4941 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4942 /// enumerator marker rather than a handler — `for of` keeps one under its record so
4943 /// that `break` and `return` can find the iterator — and an exception reaching one
4944 /// **closes that iterator** before the unwinding continues.
4945 ///
4946 /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4947 /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4948 /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4949 /// close the iterator while the reference to store into is being worked out.
4950 ///
4951 /// `value` is `&mut` because closing the iterator may replace it: see
4952 /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4953 fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4954 loop {
4955 // Popped one at a time so no frame borrow is held across the close below.
4956 let top = self.frames.last_mut()?.stack.pop()?;
4957 let Value::CatchOffset(offset) = top else {
4958 continue;
4959 };
4960 if offset != 0 {
4961 let frame = self.frames.last_mut().expect("the frame was just read");
4962 frame.stack.push(value.clone());
4963 frame.pc = offset as usize;
4964 return Some(());
4965 }
4966 // The record's `iter` and `next` sit directly below the marker.
4967 let close = {
4968 let frame = self.frames.last_mut().expect("the frame was just read");
4969 let next = frame.stack.pop();
4970 let iterator = frame.stack.pop();
4971 match (iterator, next) {
4972 (Some(iterator), Some(_next)) => Some(iterator),
4973 // A malformed record cannot be closed, but unwinding still has to go
4974 // on: this is not a handler, so there is nothing to resume at.
4975 _ => None,
4976 }
4977 };
4978 if let Some(iterator) = close {
4979 self.close_iterator_on_throw(iterator);
4980 }
4981 }
4982 }
4983
4984 /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4985 ///
4986 /// Two things differ from the ordinary close, both from the spec's step ordering:
4987 ///
4988 /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4989 /// return ? completion`) comes before step 5, so an exception raised by `return()`
4990 /// itself — or by reading it — is discarded;
4991 /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4992 ///
4993 /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4994 /// it saves the pending exception, clears the slot, and re-throws the saved one from
4995 /// `done:` no matter what happened in between.
4996 fn close_iterator_on_throw(&mut self, iterator: Value) {
4997 if matches!(iterator, Value::Undefined) {
4998 return;
4999 }
5000 let Ok(method) = self.read_field(&iterator, "return") else {
5001 return;
5002 };
5003 if matches!(method, Value::Undefined | Value::Null) {
5004 return;
5005 }
5006 // A throw from `return()` replaces nothing: the exception already being unwound is
5007 // the one that propagates.
5008 let _ = self.call_value(method, iterator, Vec::new());
5009 }
5010
5011 fn push_frame(
5012 &mut self,
5013 code: Gc<CompiledCode>,
5014 env: Gc<ClosureEnv>,
5015 this: Value,
5016 mut args: Vec<Value>,
5017 callee: Value,
5018 ) -> JsResult<()> {
5019 // Two bounds, and the byte budget is the one that decides in practice. The
5020 // reference's message is `stack overflow` on an `InternalError`, not V8's
5021 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
5022 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
5023 let frame_cost = Self::frame_cost(&code);
5024 let stack_base = self.stack_used();
5025 if self.frames.len() >= self.max_frames
5026 || stack_base.saturating_add(frame_cost) > self.stack_limit
5027 {
5028 return Err(Signal::Throw(
5029 self.make_error("InternalError", "stack overflow"),
5030 ));
5031 }
5032 let arg_count = code.code.args.len();
5033 // How many were actually passed, which `arguments.length` reports and
5034 // `assert(x)` depends on: a call with one argument must not look like a call
5035 // with one argument and an explicit `undefined`.
5036 let passed = args.len();
5037 // Missing arguments are `undefined` in their slots; extra ones are dropped
5038 // from the slots but still reachable through `arguments`.
5039 //
5040 // A call that passes no more than the declared parameters needs **no** copy:
5041 // after the resize below, `args[..passed]` *is* the passed values. Only the
5042 // extra ones — which `truncate` is about to drop — have to be kept, and they are
5043 // the rare case. This used to copy every call: one `Value` clone per argument
5044 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
5045 let passed_overflow = (passed > arg_count).then(|| {
5046 let mut values = self.take_values(passed, Value::Undefined);
5047 values[..passed].clone_from_slice(&args[..passed]);
5048 values
5049 });
5050 // Only when the counts differ, which for the overwhelmingly common call — as many
5051 // arguments as parameters — is never. `resize` followed by `truncate` on equal
5052 // lengths is two length compares and nothing else, but this is the hottest few
5053 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
5054 if passed != arg_count {
5055 args.resize(arg_count, Value::Undefined);
5056 args.truncate(arg_count);
5057 }
5058 let cell_count = code.code.var_ref_count as usize;
5059 let mut cells = Vec::with_capacity(cell_count);
5060 for _ in 0..cell_count {
5061 cells.push(self.new_cell(Value::Undefined));
5062 }
5063 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
5064 // A captured argument lives in its cell, not in the argument slot, so the
5065 // incoming value has to be moved there before the body runs.
5066 for (slot, cell) in code.arg_cell.iter().enumerate() {
5067 if *cell >= 0
5068 && let Some(value) = args.get(slot).cloned()
5069 {
5070 cells[*cell as usize].set(value);
5071 }
5072 }
5073 // Sloppy mode substitutes the global object for a missing receiver and boxes a
5074 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
5075 // reports `object`. Strict mode passes the value through untouched.
5076 let this = if code.code.strict {
5077 this
5078 } else if this.is_nullish() {
5079 Value::Object(self.realm.global.clone())
5080 } else if matches!(this, Value::Object(_)) {
5081 this
5082 } else {
5083 match crate::builtins::this_object(self, &this) {
5084 Ok(boxed) => Value::Object(boxed),
5085 Err(_) => this,
5086 }
5087 };
5088 let stack_depth = code.code.stack_size as usize + 1;
5089 // Taken before the `push` borrows `self.frames`, because the operand stack comes
5090 // out of the same recycle pool the locals did.
5091 let stack = self.take_values(stack_depth, Value::Undefined);
5092 self.frames.push(Frame {
5093 code,
5094 env,
5095 this,
5096 args,
5097 passed_count: passed,
5098 passed_overflow: passed_overflow.map(Box::new),
5099 locals,
5100 cells,
5101 local_vars: None,
5102 // Exactly the depth the compiler computed, so the operand stack never
5103 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
5104 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
5105 // the buffer between calls, so "exactly" costs nothing after the first one.
5106 stack,
5107 pc: 0,
5108 at: 0,
5109 callee,
5110 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
5111 cost: frame_cost,
5112 stack_base,
5113 tail: false,
5114 });
5115 Ok(())
5116 }
5117
5118 /// A value buffer of `len` slots, from the recycle pool when there is one.
5119 ///
5120 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
5121 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
5122 // A frame with no locals asks for nothing, and that is most frames: taking a
5123 // buffer out of the pool, clearing it and resizing it to zero is four operations
5124 // and a pool pop for an empty `Vec`, which is free to construct.
5125 if len == 0 {
5126 return Vec::new();
5127 }
5128 let mut buffer = self.free_values.pop().unwrap_or_default();
5129 buffer.clear();
5130 buffer.resize(len, fill);
5131 buffer
5132 }
5133
5134 /// Return a finished frame's value buffers for the next call to reuse.
5135 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
5136 for mut buffer in [
5137 std::mem::take(&mut frame.locals),
5138 frame
5139 .passed_overflow
5140 .take()
5141 .map(|buffer| *buffer)
5142 .unwrap_or_default(),
5143 std::mem::take(&mut frame.stack),
5144 ] {
5145 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
5146 // GC root: it kept every value the frame held reachable, which is invisible
5147 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
5148 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
5149 // exactly that within one run — the target `{}` of a finished IIFE was still
5150 // in its operand stack, in the pool.
5151 buffer.clear();
5152 // A buffer with no capacity is what `Vec::new` is; putting it back would just
5153 // fill the pool with nothing to offer.
5154 if free_values.len() < RECYCLE_SLOTS
5155 && buffer.capacity() > 0
5156 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
5157 {
5158 free_values.push(buffer);
5159 }
5160 }
5161 }
5162
5163 /// Pop a finished frame and keep its buffers.
5164 ///
5165 /// Every place that drops a frame goes through here: a recycled buffer is also where
5166 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
5167 /// nothing but the reuse.
5168 fn pop_frame(&mut self) -> Option<()> {
5169 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
5170 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
5171 let last = self.frames.len().checked_sub(1)?;
5172 Self::recycle(&mut self.free_values, &mut self.frames[last]);
5173 self.frames.truncate(last);
5174 Some(())
5175 }
5176
5177 /// Poll the host's interrupt handler, if one is installed.
5178 ///
5179 /// The counter is what keeps this off the hot path when nobody asked: the early return is
5180 /// one `Option` test, and with no handler installed the whole function is that test —
5181 /// `check_memory` next door already costs more, so this cannot be what shows up in a
5182 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
5183 #[inline]
5184 fn check_interrupt(&mut self) -> JsResult<()> {
5185 if self.interrupt.is_none() {
5186 return Ok(());
5187 }
5188 if self.interrupt_counter > 0 {
5189 self.interrupt_counter -= 1;
5190 return Ok(());
5191 }
5192 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
5193 // The closure is taken out for the duration so that a handler which re-enters the
5194 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
5195 let mut handler = self.interrupt.take().expect("checked above");
5196 let abort = handler();
5197 self.interrupt = Some(handler);
5198 if abort {
5199 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
5200 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
5201 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
5202 // documentation says.
5203 self.uncatchable = true;
5204 return Err(Signal::Throw(
5205 self.make_error("InternalError", "interrupted"),
5206 ));
5207 }
5208 Ok(())
5209 }
5210
5211 /// A memory checkpoint: does the heap still fit under its limit?
5212 ///
5213 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
5214 /// a `Cell` read and a predictable branch, and the point of asking that often is that
5215 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
5216 /// only at calls would let it run until the machine died, which is the exact failure
5217 /// `--memory-limit` exists to prevent.
5218 ///
5219 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
5220 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
5221 /// script that catches it, drops the reference and carries on is legitimate: measured
5222 /// on `qjs --memory-limit 1M`, the engine recovers.
5223 fn check_memory(&mut self) -> JsResult<()> {
5224 // One `Cell` read and a predictable branch when no limit is set, and an integer
5225 // compare when one is. Containers report their own growth as it happens
5226 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
5227 // walking it here was the first version and it was O(live) per 256 instructions,
5228 // which turned a 100k-element push loop into a five-minute one.
5229 let Some(limit) = self.heap.memory_limit() else {
5230 return Ok(());
5231 };
5232 let used = self.heap.used_bytes();
5233 if used <= limit {
5234 // Back under the limit — a collection or a dropped reference did it. The next
5235 // time it goes over is a new failure, not a repeat of this one.
5236 self.oom_reported_at = 0;
5237 return Ok(());
5238 }
5239 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5240 // block runs normally after `out of memory` — it allocates nothing, so nothing
5241 // fails. A check that re-fired on every instruction made the handler itself throw,
5242 // which is a dead end: the error became unobservable from script.
5243 //
5244 // Comparing against the total at the last report gives the same behaviour: the
5245 // handler runs while the total is unchanged, and the very next allocation over the
5246 // limit fails.
5247 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5248 {
5249 return Ok(());
5250 }
5251 self.oom_reported_at = used;
5252 Err(Signal::Throw(
5253 self.make_error("InternalError", "out of memory"),
5254 ))
5255 }
5256
5257 /// Fail before allocating `payload` bytes, if they would not fit.
5258 ///
5259 /// For the allocations whose size comes from script data — `new Array(n)`,
5260 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5261 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5262 /// answering NULL for the one big request.
5263 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5264 if self.heap.fits(payload) {
5265 return Ok(());
5266 }
5267 Err(Signal::Throw(
5268 self.make_error("InternalError", "out of memory"),
5269 ))
5270 }
5271
5272 /// Bytes of frame state the live call chain accounts for.
5273 pub fn stack_used(&self) -> usize {
5274 match self.frames.last() {
5275 Some(frame) => frame.stack_base + frame.cost,
5276 None => 0,
5277 }
5278 }
5279
5280 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5281 ///
5282 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5283 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5284 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5285 /// instead. That is the whole difference between the two models: it rations C stack, we
5286 /// ration frame state, and both quantities are dominated by the value slots — which is
5287 /// why the two depths come out comparable rather than merely proportional.
5288 fn frame_cost(code: &CompiledCode) -> usize {
5289 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5290 std::mem::size_of::<Frame>()
5291 + std::mem::size_of::<Value>() * slots
5292 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5293 }
5294
5295 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5296 ///
5297 /// Only names the eval created are here: a name the frame already declared statically
5298 /// is written through to its own slot instead, so this cannot shadow a real local.
5299 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5300 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5301 let (local_vars, phase) = self.visible_local_vars()?;
5302 if !local_vars.contains(name) {
5303 return None;
5304 }
5305 local_vars.get(name, phase)
5306 }
5307
5308 /// The variables a direct `eval` declared, as the code currently running sees them.
5309 ///
5310 /// Inside an eval that is the *caller's* set — the eval's own variable environment
5311 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5312 /// else it is the current frame's, falling back to the frame the closure was created
5313 /// in.
5314 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5315 ///
5316 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5317 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5318 /// refcount operations (the clone out of the frame, the drop at the end of the match)
5319 /// just to be asked `is_none`.
5320 fn has_visible_local_vars(&self) -> bool {
5321 let index = match self.eval_caller.flatten() {
5322 Some(caller) => caller,
5323 None => match self.frames.len().checked_sub(1) {
5324 Some(top) => top,
5325 None => return false,
5326 },
5327 };
5328 match self.frames.get(index) {
5329 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5330 None => false,
5331 }
5332 }
5333
5334 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5335 // While an `eval` runs, its own frame is on top but its variable environment is
5336 // the *caller's* — so the caller is what the lookup has to start from.
5337 let (index, phase) = match self.eval_caller.flatten() {
5338 Some(caller) => (
5339 caller,
5340 if self.in_parameter_list_at(caller) {
5341 0
5342 } else {
5343 1
5344 },
5345 ),
5346 None => (
5347 self.frames.len().checked_sub(1)?,
5348 if self.in_parameter_list() { 0 } else { 1 },
5349 ),
5350 };
5351 let frame = self.frames.get(index)?;
5352 // The frame's own variables, or — for an arrow, which has no variable environment
5353 // of its own — the one it was created in, which `ClosureEnv` carries.
5354 if let Some(local_vars) = frame.local_vars.clone() {
5355 return Some((local_vars, phase));
5356 }
5357 frame
5358 .env
5359 .local_vars
5360 .clone()
5361 .map(|local_vars| (local_vars, frame.env.local_phase))
5362 }
5363
5364 /// Whether the innermost frame is still evaluating its parameter list.
5365 ///
5366 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5367 /// and a closure created there may only see that much of [`LocalVars`].
5368 fn in_parameter_list(&self) -> bool {
5369 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5370 }
5371
5372 /// [`Interp::in_parameter_list`] for a specific frame.
5373 fn in_parameter_list_at(&self, frame: usize) -> bool {
5374 let Some(frame) = self.frames.get(frame) else {
5375 return false;
5376 };
5377 let code = &frame.code.code;
5378 if !code.has_parameter_expressions {
5379 return false;
5380 }
5381 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5382 // function as its body and let a direct `eval` act accordingly.
5383 if code.body_start == (0, 0) {
5384 return false;
5385 }
5386 match code.position_at(frame.at as u32) {
5387 Some(position) => position < code.body_start,
5388 None => false,
5389 }
5390 }
5391
5392 fn frame(&self) -> &Frame {
5393 self.frames.last().expect("a frame is live")
5394 }
5395
5396 fn frame_mut(&mut self) -> &mut Frame {
5397 self.frames.last_mut().expect("a frame is live")
5398 }
5399
5400 // -- slot access --------------------------------------------------------
5401
5402 /// Move a local's value out, leaving `undefined` in the slot.
5403 ///
5404 /// `None` for a captured slot: its value lives in a cell shared with every closure
5405 /// that closed over it, so it can never be exclusively ours and must not be taken.
5406 ///
5407 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5408 /// for every read and fatal for this one — a clone is exactly the second handle that
5409 /// rules out growing the string in place.
5410 fn take_loc(&mut self, slot: usize) -> Option<Value> {
5411 let frame = self.frames.last_mut()?;
5412 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5413 return None;
5414 }
5415 frame
5416 .locals
5417 .get_mut(slot)
5418 .map(|value| std::mem::replace(value, Value::Undefined))
5419 }
5420
5421 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5422 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5423 ///
5424 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5425 /// it** — the value is put back before the general path runs — so a `valueOf` that
5426 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5427 /// error as it would have without the fusion. This is why the in-place attempt is a
5428 /// `take` and not a `get`: an optimisation that changes what an exception observes is
5429 /// a wrong answer with a good excuse.
5430 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5431 // The take is `matches!`-guarded on the *right* operand only, and the taken value
5432 // is put back on every path that does not append. An earlier version wrote the two
5433 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5434 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5435 // through with its value already taken and dropped: the general path below then
5436 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5437 // A wrong answer, from an optimisation, with every test green.
5438 if matches!(right, Value::String(_))
5439 && let Some(taken) = self.take_loc(slot)
5440 {
5441 if let Value::String(mut left) = taken {
5442 let appended = match left.get_mut() {
5443 Some(string) => string.append_in_place(
5444 // The pattern is the one `matches!` just checked.
5445 match &right {
5446 Value::String(text) => text,
5447 _ => unreachable!("guarded above"),
5448 },
5449 ),
5450 None => None,
5451 };
5452 self.put_loc(slot, Value::String(left));
5453 if let Some(added) = appended {
5454 // The buffer grew where it stood, so the heap's running total has to
5455 // be told: `measure_used` would report the new length, and the two must
5456 // agree or the subtraction at free time leaves the counter wrong.
5457 self.heap.adjust_payload(added as isize);
5458 return Ok(());
5459 }
5460 } else {
5461 self.put_loc(slot, taken);
5462 }
5463 }
5464 // The two-number case, without an operand stack round trip. Everything below
5465 // this point is the *general* path: push both, call `binary_add`, pop the answer,
5466 // store it — five operations and two `Value` clones for what is one integer add.
5467 // `AddImmLoc` already answers this shape that way; the fusion above it was written
5468 // for string append and never got the numeric half, so `t += i` — a counting loop
5469 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5470 let left = self.get_loc(slot);
5471 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5472 self.put_loc(
5473 slot,
5474 match a.checked_add(*b) {
5475 Some(sum) => Value::Int(sum),
5476 None => Value::Float(*a as f64 + *b as f64),
5477 },
5478 );
5479 return Ok(());
5480 }
5481 self.push(left);
5482 self.push(right);
5483 self.binary_add()?;
5484 let value = self.pop();
5485 self.put_loc(slot, value);
5486 Ok(())
5487 }
5488
5489 fn get_arg(&self, slot: usize) -> Value {
5490 self.frame().read_arg(slot)
5491 }
5492
5493 fn put_arg(&mut self, slot: usize, value: Value) {
5494 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5495 if cell == -1 {
5496 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5497 *slot = value;
5498 }
5499 } else {
5500 self.frame().cells[cell as usize].set(value);
5501 }
5502 }
5503
5504 fn get_loc(&self, slot: usize) -> Value {
5505 // The cell mapping is `-1` for every slot that was not captured — which is all of
5506 // them in a function that creates no closure. `Frame::read_loc` tests that first,
5507 // so the common case is one array read and a clone: 20% of every loop iteration
5508 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5509 // sample of `dispatch:arith`).
5510 self.frame().read_loc(slot)
5511 }
5512
5513 fn put_loc(&mut self, slot: usize, value: Value) {
5514 // One borrow instead of three, and the cell check on the frame we already hold.
5515 let frame = self.frames.last_mut().expect("a frame is live");
5516 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5517 if cell < 0 {
5518 if let Some(slot) = frame.locals.get_mut(slot) {
5519 *slot = value;
5520 }
5521 } else if let Some(cell) = frame.cells.get(cell as usize) {
5522 cell.set(value);
5523 }
5524 }
5525
5526 // -- globals ------------------------------------------------------------
5527
5528 /// The name a global-slot operand refers to.
5529 fn global_name(&self, slot: usize) -> String {
5530 self.frame()
5531 .code
5532 .code
5533 .closure_vars
5534 .get(slot)
5535 .map(|c| c.name.clone())
5536 .unwrap_or_default()
5537 }
5538
5539 /// The facts about a global binding that decide where it lives.
5540 ///
5541 /// A script's globals split in two, and the split is observable: `var` and
5542 /// function declarations become properties of the global object (`globalThis.v`
5543 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5544 /// declarations live in the global *lexical* environment and are invisible there
5545 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5546 /// `is_lexical` flag means the answer is already in the bytecode.
5547 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5548 let name = self.global_name(slot);
5549 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5550 // while forwarding a reference through a nested function is built with the
5551 // flags cleared, so `const c` would look like an ordinary `var` from inside a
5552 // closure. Presence in the realm's lexical table is the same fact, recorded
5553 // once, and every slot sees it.
5554 let lexical = self.realm.globals.contains_key(&name);
5555 let is_const = self.realm.lexical_consts.contains(&name);
5556 (name, lexical, is_const)
5557 }
5558
5559 /// The value of `name` in the innermost active `with` object, if any.
5560 ///
5561 /// The active objects are the [`VarKind::With`] locals of every frame still running,
5562 /// innermost frame first and innermost block first within one. Walking frames rather
5563 /// than keeping a separate stack is what makes a closure called from inside a `with`
5564 /// see it, and what keeps the object alive only as long as the block is.
5565 /// The innermost active `with` object that has `name`, if any.
5566 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5567 let objects = self.eval_with.clone().unwrap_or_default();
5568 for object in objects {
5569 let key = self.string(name.to_string());
5570 if self
5571 .has_property(&key, &Value::Object(object.clone()))
5572 .ok()?
5573 {
5574 return Some(object);
5575 }
5576 }
5577 None
5578 }
5579
5580 /// Every active `with` object, innermost first.
5581 fn with_objects(&self) -> Vec<Gc<JsObject>> {
5582 let mut objects = Vec::new();
5583 for frame in self.frames.iter().rev() {
5584 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5585 if var.kind != js_compile::VarKind::With {
5586 continue;
5587 }
5588 // A captured binding lives in its cell and not in the slot list, so the
5589 // cell is consulted first — a closure created inside the block is exactly
5590 // what makes the object captured. Before the store runs the slot still
5591 // holds `undefined`, and a `with` object is always boxed, so a non-object
5592 // entry is simply not in scope yet.
5593 let value = frame
5594 .code
5595 .loc_cell
5596 .get(index)
5597 .copied()
5598 .filter(|cell| *cell >= 0)
5599 .and_then(|cell| frame.cells.get(cell as usize))
5600 .map(|cell| cell.get())
5601 .or_else(|| frame.locals.get(index).cloned());
5602 if let Some(Value::Object(object)) = value {
5603 objects.push(object);
5604 }
5605 }
5606 }
5607 objects
5608 }
5609
5610 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5611 for object in self.eval_with.clone().unwrap_or_default() {
5612 let key = self.string(name.to_string());
5613 if self.has_property(&key, &Value::Object(object.clone()))? {
5614 return Ok(Some(self.read_field(&Value::Object(object), name)?));
5615 }
5616 }
5617 Ok(None)
5618 }
5619
5620 /// Whether every scope between here and the global object is an ordinary one.
5621 ///
5622 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5623 /// bytecode resolved; when any is live the general path has to run in full order. When
5624 /// none is — every ordinary program — a global read is a property read and nothing
5625 /// else, and that is worth caching.
5626 fn scopes_are_plain(&self) -> bool {
5627 self.eval_caller.is_none()
5628 && self.eval_with.is_none()
5629 && self.eval_arguments.is_none()
5630 && self.eval_bindings.is_empty()
5631 && self.eval_scope.is_empty()
5632 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5633 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5634 // its `ClosureEnv`, so the test has to be the same one the general path makes.
5635 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5636 // upstream corpus caught and no unit test did.
5637 && !self.has_visible_local_vars()
5638 && self.frame().env.eval_scope.is_none()
5639 }
5640
5641 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5642 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5643 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5644 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5645 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5646 // borrow outlive the `&mut self` the lookup needs.
5647 //
5648 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5649 // forwarded through a nested function has its flags cleared, so the flag cannot
5650 // be believed.
5651 let code = self.frame().code.clone();
5652 let name = code
5653 .code
5654 .closure_vars
5655 .get(slot)
5656 .map(|c| c.name.as_str())
5657 .unwrap_or_default();
5658 let lexical = self.realm.globals.contains_key(name);
5659 // The common case, first: an ordinary global `var`, with a cache in front of the
5660 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5661 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5662 // cache hit and return without touching any of it.
5663 if !lexical && self.scopes_are_plain() {
5664 return self.get_plain_global(name, slot);
5665 }
5666 if name == "arguments"
5667 && let Some(arguments) = &self.eval_arguments
5668 {
5669 return Ok(arguments.clone());
5670 }
5671 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5672 // the objects live when the eval started are consulted before anything else. The
5673 // snapshot is taken at entry rather than scanning the frames on every read: a
5674 // block that has already finished still leaves its object in the slot, and a
5675 // bytecode read outside the block must not see it.
5676 if let Some(value) = self.with_lookup(name)? {
5677 return Ok(value);
5678 }
5679 // A name a **running** eval declared itself outranks the caller's bindings — that
5680 // is what makes a strict eval's `var` private to it. It has to come first here, and
5681 // first in `put_global`, or a nested eval would read the caller's variable while
5682 // writing its own: `eval("var o = 'str2'; eval('o')")` inside a function that also
5683 // has an `o`.
5684 for scope in self.eval_scope.iter().rev() {
5685 if let Some(value) = scope.get(name) {
5686 return Ok(value.clone());
5687 }
5688 }
5689 // A closure created by an `eval` resolves its free names against the bindings
5690 // that eval saw, even after the eval (and its frames) are gone.
5691 if let Some(cell) = self
5692 .frame()
5693 .env
5694 .eval_scope
5695 .as_ref()
5696 .and_then(|scope| scope.get(name))
5697 {
5698 let value = cell.get();
5699 if matches!(value, Value::Uninitialized) {
5700 return Err(self.throw_reference(name));
5701 }
5702 return Ok(value);
5703 }
5704 // A variable a direct `eval` declared shadows everything the compiler resolved,
5705 // including an enclosing function's binding: the eval put it in the caller's own
5706 // variable environment, which is nearer than any captured scope.
5707 if let Some((local_vars, phase)) = self.visible_local_vars()
5708 && let Some(cell) = local_vars.get(name, phase)
5709 {
5710 return Ok(cell.get());
5711 }
5712 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5713 // its local `a` wins over a global `a`.
5714 if let Some(value) = self.eval_binding_value(name) {
5715 return Ok(value);
5716 }
5717 // A binding declared by the strict `eval` currently running shadows anything
5718 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5719 if lexical {
5720 // A lexical global is a binding in a side table, so the dead zone is
5721 // visible and it is nowhere on the global object.
5722 if let Some(cell) = self.realm.globals.get(name) {
5723 let value = cell.get();
5724 if matches!(value, Value::Uninitialized) {
5725 return Err(self.throw_reference(name));
5726 }
5727 return Ok(value);
5728 }
5729 return Err(self.throw_reference(name));
5730 }
5731 // A `var` global is an ordinary property, so the prototype chain and the
5732 // global object's own builtins are all reachable through it.
5733 match self.get_property(&self.realm.global.clone(), name)? {
5734 Some(value) => Ok(value),
5735 None => Err(self.throw_reference(name)),
5736 }
5737 }
5738
5739 /// Read a plain global `var`: a cached own data property, or the full lookup.
5740 ///
5741 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5742 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5743 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5744 let object = self.realm.global.clone();
5745 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5746 if let Some(cached) = &self.global_cache[site]
5747 && object.upgrades_to(&cached.object)
5748 && let Some(value) = object.data_property_at(cached.index, name)
5749 {
5750 return Ok(value);
5751 }
5752 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5753 // chain exactly as before, then remember the answer if it is worth remembering.
5754 let Some(value) = self.get_property(&object, name)? else {
5755 return Err(self.throw_reference(name));
5756 };
5757 if let Some(index) = object.own_data_index(name) {
5758 self.global_cache[site] = Some(GlobalCache {
5759 object: object.downgrade(),
5760 index,
5761 });
5762 }
5763 Ok(value)
5764 }
5765
5766 /// Store to a global binding.
5767 ///
5768 /// Returns a signal when the store is refused: a `const` global may only be
5769 /// written by its initialiser, and a non-configurable `var` global may not be
5770 /// deleted but is always writable.
5771 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5772 let (name, lexical, is_const) = self.global_binding(slot);
5773
5774 // An assignment inside a `with` writes through to the object that supplies the
5775 // name, which for an `eval` means consulting the same chain `get_global` does.
5776 if let Some(owner) = self.with_owner(&name) {
5777 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5778 return Ok(());
5779 }
5780 // A *strict* eval has a variable environment of its own, so a name it declared
5781 // there shadows the caller's binding of the same name: in
5782 // `function f(){ "use strict"; var v = 0; eval("var v = 1") }` the outer `v` must
5783 // stay 0 (`eval-code/direct/var-env-var-strict-caller`). `eval_scope` is `Some`
5784 // only while such an eval runs, and holds only the names it declared, so this is
5785 // narrower than it looks.
5786 //
5787 // It sits ahead of the caller's bindings below on purpose: the *reads* take the
5788 // same order (`get_global`), and a store that disagreed with its own read would
5789 // write somewhere the eval cannot see.
5790 let closure_scope = self
5791 .frame()
5792 .env
5793 .eval_scope
5794 .as_ref()
5795 .and_then(|scope| scope.get(&name))
5796 .cloned();
5797 if let Some(cell) = closure_scope {
5798 cell.set(value);
5799 return Ok(());
5800 }
5801 for scope in self.eval_scope.iter_mut().rev() {
5802 if let Some(slot) = scope.get_mut(&name) {
5803 *slot = value;
5804 return Ok(());
5805 }
5806 }
5807 // A variable the running eval *declared* takes the write before any caller
5808 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5809 // environment even when an enclosing function has a `var c` of its own.
5810 if self.eval_caller.flatten().is_some()
5811 && let Some((local_vars, phase)) = self.visible_local_vars()
5812 && local_vars.contains(&name)
5813 && let Some(cell) = local_vars.get(&name, phase)
5814 {
5815 cell.set(value);
5816 return Ok(());
5817 }
5818 // A binding of the frame that called `eval` takes the write, which is what
5819 // makes `f("a = 3")` change the caller's `a`.
5820 if self.set_eval_binding(&name, &value)? {
5821 return Ok(());
5822 }
5823 // An *assignment* to a name nobody declared is not a declaration, so it falls
5824 // through to the global: strict mode raises `ReferenceError` for it, which is what
5825 // `eval("1 + (@not_def = 1)")` has to do.
5826 if lexical {
5827 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5828 // A lexical global starts out `Uninitialized` and only `init_global` ends
5829 // that, so a store reaching here is either a plain assignment to a slot
5830 // still in its dead zone — `x = 1; let x` at the top level, a
5831 // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5832 if matches!(cell.get(), Value::Uninitialized) {
5833 return Err(self.dead_zone_global(&name));
5834 }
5835 if is_const {
5836 return Err(self.read_only_global(&name));
5837 }
5838 cell.set(value);
5839 return Ok(());
5840 }
5841 // Writing an undeclared lexical global is a `ReferenceError` in strict
5842 // mode and a silent global creation otherwise; creating the cell here
5843 // keeps both paths from losing the value.
5844 let cell = self.new_cell(value);
5845 self.realm.globals.insert(name, cell);
5846 return Ok(());
5847 }
5848 // A variable a direct `eval` declared in this call shadows the global object, even
5849 // when the global already has a property of that name — `var c = "global"` at the
5850 // top level must not capture `eval("var c = 1")` inside a function.
5851 if let Some((local_vars, phase)) = self.visible_local_vars()
5852 && local_vars.contains(&name)
5853 && let Some(cell) = local_vars.get(&name, phase)
5854 {
5855 cell.set(value);
5856 return Ok(());
5857 }
5858 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5859 // remembered a global's slot index since M12b, but the *store* side never did: it
5860 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5861 // global object's whole table — which holds every builtin — on every assignment to
5862 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5863 // full global lookup per iteration; measured with a counter, `s` as a global made
5864 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5865 //
5866 // Re-validated exactly like the read: same object, same index, still the name, and
5867 // — the one extra check a store needs — still writable. A global that is an
5868 // accessor, non-writable, or inherited fails here and falls through to the full
5869 // path below, which reports the failure the way it always did.
5870 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5871 let global = self.realm.global.clone();
5872 if let Some(cached) = &self.global_cache[site]
5873 && global.upgrades_to(&cached.object)
5874 && global.write_data_at(cached.index, &name, value.clone())
5875 {
5876 return Ok(());
5877 }
5878 match global.own_property(&name) {
5879 // A `var` global is writable, so the store goes straight through — but
5880 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5881 // store (a non-writable or accessor-without-setter global) is a silent
5882 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5883 // split every other assignment has.
5884 Some(_) => {
5885 let on_failure = if self.current_strict() {
5886 DeleteFailure::Throw
5887 } else {
5888 DeleteFailure::Ignore
5889 };
5890 let result = self.set_property_with(&global, &name, value, on_failure);
5891 // Teach the cache the slot for a plain writable own data property, which is
5892 // what a declared `var` is. Without this the fast path above could never
5893 // fire for a global that is only ever *written* — its entry would have to
5894 // be put there by a read of the same slot, and a write-only loop has none.
5895 if result.is_ok()
5896 && let Some(index) = global.own_data_index(&name)
5897 {
5898 self.global_cache[site] = Some(GlobalCache {
5899 object: global.downgrade(),
5900 index,
5901 });
5902 }
5903 result
5904 }
5905 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5906 // declaration creates a *configurable* property, which is what makes it
5907 // deletable and is the one way a global differs from a declared `var`.
5908 // In strict mode the same store is a `ReferenceError` instead: that is the
5909 // whole point of strict mode, and creating the global silently meant
5910 // `"use strict"; x = 1` looked like it worked.
5911 None => {
5912 if self.current_strict() {
5913 return Err(self.throw_reference(&name));
5914 }
5915 // A direct eval declares here rather than on the global object: its
5916 // `var`s belong to the caller's variable environment. `declare_eval_local`
5917 // also covers a plain assignment to a variable an earlier eval made.
5918 if let Some(cell) = self.declare_eval_local(&name) {
5919 cell.set(value);
5920 return Ok(());
5921 }
5922 global.define_data(&name, value);
5923 Ok(())
5924 }
5925 }
5926 }
5927
5928 /// The value of a binding of the frame that called `eval`, if there is one.
5929 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5930 let binding = self
5931 .eval_bindings
5932 .iter()
5933 .find(|binding| binding.name == name)?;
5934 let owner = self.frames.get(binding.frame)?;
5935 let (slot, index) = (binding.slot, binding.index);
5936 Some(match slot {
5937 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5938 cell if cell >= 0 => owner
5939 .cells
5940 .get(cell as usize)
5941 .map(|cell| cell.get())
5942 .unwrap_or(Value::Undefined),
5943 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5944 },
5945 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5946 cell if cell >= 0 => owner
5947 .cells
5948 .get(cell as usize)
5949 .map(|cell| cell.get())
5950 .unwrap_or(Value::Undefined),
5951 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5952 },
5953 })
5954 }
5955
5956 /// Write to a binding of the frame that called `eval`.
5957 ///
5958 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5959 /// matched binding can still refuse the store, which is why this is fallible: a
5960 /// `const` is read-only everywhere, and a named function expression's own name is
5961 /// read-only in strict mode.
5962 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5963 let Some(binding) = self
5964 .eval_bindings
5965 .iter()
5966 .find(|binding| binding.name == name)
5967 else {
5968 return Ok(false);
5969 };
5970 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5971 let strict = self.current_strict();
5972 let Some(owner) = self.frames.get_mut(frame) else {
5973 return Ok(false);
5974 };
5975 match slot {
5976 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5977 cell if cell >= 0 => {
5978 if let Some(cell) = owner.cells.get(cell as usize) {
5979 cell.set(value.clone());
5980 }
5981 }
5982 _ => {
5983 if let Some(slot) = owner.args.get_mut(index) {
5984 *slot = value.clone();
5985 }
5986 }
5987 },
5988 EvalSlot::Local => {
5989 let declared = owner.code.code.vars.get(index);
5990 // A `const` is read-only even through `eval`. The realm records this for
5991 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5992 // the bytecode, so this is where it has to be enforced.
5993 if declared.is_some_and(|var| var.is_const) {
5994 return Err(self.read_only_local(name));
5995 }
5996 // The name of a named function expression is read-only too, but only
5997 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5998 // such a name is ignored, the same as a direct store would be.
5999 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
6000 return if strict {
6001 Err(self.read_only_local(name))
6002 } else {
6003 Ok(true)
6004 };
6005 }
6006 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
6007 cell if cell >= 0 => {
6008 if let Some(cell) = owner.cells.get(cell as usize) {
6009 cell.set(value.clone());
6010 }
6011 }
6012 _ => {
6013 if let Some(slot) = owner.locals.get_mut(index) {
6014 *slot = value.clone();
6015 }
6016 }
6017 }
6018 }
6019 }
6020 Ok(true)
6021 }
6022
6023 /// The `TypeError` an assignment to a read-only binding raises.
6024 fn read_only_local(&self, name: &str) -> Signal {
6025 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6026 }
6027
6028 /// Declare `name` as a variable of the frame that called the running `eval`.
6029 ///
6030 /// `None` when there is no direct eval in progress, or it was called from the top
6031 /// level — then the caller's variable environment *is* the global one and the
6032 /// existing path is right.
6033 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
6034 let caller = self.eval_caller.flatten()?;
6035 // The bottom frame is the top-level script, whose variable environment *is* the
6036 // global one — so `eval("var x = 1")` at the top level still creates a global.
6037 if caller == 0 {
6038 return None;
6039 }
6040 // A name the eval's *own* variable environment already binds is not a new
6041 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
6042 // `arguments`, and creating a second binding would leave the first — the one
6043 // closures read — untouched. A binding of an *outer* frame does not count: a
6044 // declaration shadows it rather than writing through.
6045 if self
6046 .eval_bindings
6047 .iter()
6048 .any(|binding| binding.name == name && binding.frame == caller)
6049 {
6050 return None;
6051 }
6052 let phase = if self.in_parameter_list_at(caller) {
6053 0
6054 } else {
6055 1
6056 };
6057 self.frame_local_vars(caller)?;
6058 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
6059 if let Some(cell) = local_vars.get(name, 1) {
6060 return Some(cell);
6061 }
6062 let cell = self.new_cell(Value::Undefined);
6063 // §19.2.1.3 `EvalDeclarationInstantiation` creates every binding it adds with
6064 // `deletable = *true*`. That is the whole of
6065 // `eval("var x; delete x; x")` being a `ReferenceError`.
6066 Some(local_vars.declare_deletable(name, phase, cell))
6067 }
6068
6069 /// Make sure `frame` has a `LocalVars`, creating it on demand.
6070 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
6071 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
6072 return Some(local_vars.clone());
6073 }
6074 let local_vars = Gc::new(self.heap, LocalVars::new());
6075 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
6076 Some(local_vars)
6077 }
6078
6079 /// Whether the realm already has a binding for `name`, lexically or as an *own*
6080 /// property of the global object. Used to decide whether a store inside an
6081 /// `eval` writes through to the realm or declares a binding of its own.
6082 ///
6083 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
6084 /// write to `Object.prototype.toString`, and must not shadow it either.
6085 fn global_knows(&mut self, name: &str) -> bool {
6086 if self.realm.globals.contains_key(name) {
6087 return true;
6088 }
6089 self.realm.global.own_property(name).is_some()
6090 }
6091
6092 /// Whether the code currently running is strict.
6093 ///
6094 /// Read off the frame's function, which is where the parser's answer ended up; a
6095 /// native function never runs strict-only checks, and there is no frame at all
6096 /// before the first script.
6097 pub fn current_strict(&self) -> bool {
6098 self.frames
6099 .last()
6100 .is_some_and(|frame| frame.code.code.strict)
6101 }
6102
6103 /// Initialise a declared global, which is what ends its dead zone.
6104 ///
6105 /// A `var` global becomes a property of the global object: writable, so a later
6106 /// assignment goes through, and non-configurable, so `delete` refuses.
6107 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
6108 let (name, lexical, _) = self.global_binding(slot);
6109 // A `var` declared by the strict `eval` currently running belongs to the
6110 // eval's scope, not to the global object: `eval("var v = 1")` must not make
6111 // `typeof v` answer `"number"` afterwards. A name the realm already has is
6112 // initialised in place, which is what a re-declaration inside eval does.
6113 if !self.eval_scope.is_empty() && !lexical && !self.global_knows(&name) {
6114 self.eval_scope
6115 .last_mut()
6116 .expect("checked above")
6117 .insert(name, value);
6118 return Ok(());
6119 }
6120 for scope in self.eval_scope.iter_mut().rev() {
6121 if let Some(slot) = scope.get_mut(&name) {
6122 *slot = value;
6123 return Ok(());
6124 }
6125 }
6126 if lexical {
6127 // The cell exists (created at declaration time) holding the dead-zone
6128 // marker; storing the value is what makes the binding readable.
6129 if let Some(cell) = self.realm.globals.get(&name).cloned() {
6130 cell.set(value);
6131 return Ok(());
6132 }
6133 let cell = self.new_cell(value);
6134 self.realm.globals.insert(name, cell);
6135 return Ok(());
6136 }
6137 let global = self.realm.global.clone();
6138 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
6139 // to answer `false` and leave the binding in place. `with_attributes` ties
6140 // `configurable` to `writable`, so the property is built field by field.
6141 global.define(
6142 &name,
6143 Property {
6144 value: Some(value),
6145 writable: true,
6146 enumerable: true,
6147 configurable: false,
6148 ..Property::default()
6149 },
6150 );
6151 Ok(())
6152 }
6153
6154 /// The `TypeError` a store to a `const` global raises.
6155 fn read_only_global(&self, name: &str) -> Signal {
6156 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6157 }
6158
6159 /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
6160 fn dead_zone_global(&self, name: &str) -> Signal {
6161 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
6162 }
6163
6164 // -- properties ---------------------------------------------------------
6165
6166 /// Read `object[key]`, following the prototype chain.
6167 ///
6168 /// An inherited accessor runs with the *receiver* as `this`, which is why the
6169 /// lookup returns the owner rather than just the value.
6170 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
6171 self.get_property_key(object, &PropertyKey::from(key))
6172 }
6173
6174 /// [`Interp::get_property`] with a key that may be a symbol.
6175 pub fn get_property_key(
6176 &mut self,
6177 object: &Gc<JsObject>,
6178 key: &PropertyKey,
6179 ) -> JsResult<Option<Value>> {
6180 self.get_property_key_for(object, None, key)
6181 }
6182
6183 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
6184 ///
6185 /// The receiver matters when the property is found on a *prototype*: a getter has to
6186 /// see the object the read started from. For a primitive that is the primitive
6187 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
6188 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
6189 /// the owner.
6190 pub fn get_property_key_for(
6191 &mut self,
6192 object: &Gc<JsObject>,
6193 receiver: Option<&Value>,
6194 key: &PropertyKey,
6195 ) -> JsResult<Option<Value>> {
6196 // A proxy answers for itself, before any of the shortcuts below: `new
6197 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
6198 // have.
6199 if object.proxy_state().is_some() {
6200 let receiver = receiver
6201 .cloned()
6202 .unwrap_or_else(|| Value::Object(object.clone()));
6203 return self.proxy_get(object, &receiver, key);
6204 }
6205 // A host class's `get_property` trap replaces the whole read, prototype walk
6206 // included — that is what makes a native accessor free rather than a JavaScript
6207 // getter call.
6208 if let Some(exotic) = object.exotic() {
6209 let receiver_value = receiver
6210 .cloned()
6211 .unwrap_or_else(|| Value::Object(object.clone()));
6212 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
6213 return Ok(Some(value));
6214 }
6215 // With no `get_property` trap, a `get_own_property` trap still answers for the
6216 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
6217 // and the hook lives exactly there. A key the trap reports as absent is still
6218 // looked for on the prototype, which is why the search resumes *above*.
6219 if let Some(property) = exotic.get_own_property(self, object, key)? {
6220 return match property {
6221 Some(property) => self.read_property(property, object, receiver),
6222 None => match lookup_key_above(object, key) {
6223 Some((_, property)) => self.read_property(property, object, receiver),
6224 None => Ok(None),
6225 },
6226 };
6227 }
6228 }
6229 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
6230 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
6231 // The `[[Get]]` short-circuit therefore belongs to this one arm.
6232 //
6233 // Constructibility is exactly the split the reference makes: `function f(){}` and
6234 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
6235 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
6236 // function" — it *is* the predicate, which is why no extra marker is needed.
6237 if let Some(text) = key.as_str()
6238 && (text == "caller" || text == "arguments")
6239 && object.is_constructor()
6240 && object.is_callable()
6241 && !object.is_bound_function()
6242 // …and only when the body is **sloppy**. A strict body reaches the
6243 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
6244 // whole `Function/15.3.5.4_2-*gs` family is written against
6245 // (`onlyStrict`, so every function in them is strict).
6246 && !object.function_is_strict()
6247 && object.own_property(text).is_none()
6248 {
6249 return Ok(Some(Value::Undefined));
6250 }
6251 // The element-vector and `length` shortcuts are string-only: an array index
6252 // has no symbol spelling.
6253 if let Some(text) = key.as_str() {
6254 if let Some(value) = self.own_element(object, text) {
6255 return Ok(Some(value));
6256 }
6257 // `length` is not stored as a property: an array's length is its element
6258 // count, and keeping one copy of it is what makes `push`/`pop` and
6259 // `a.length = n` agree.
6260 if let Some(length) = object.array_length()
6261 && text == "length"
6262 {
6263 // Not `Value::Int(length as i32)`: see [`length_value`].
6264 return Ok(Some(crate::object::length_value(length)));
6265 }
6266 }
6267 // A proxy or a hooked exotic object anywhere above `object` makes the static
6268 // table walk below wrong: a proxy's own table is *empty by design* (the properties
6269 // live on its target), so the walk skipped that link entirely and everything behind
6270 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6271 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6272 // -target-is-proxy.js` are the four.
6273 if Self::chain_needs_dispatch(object) {
6274 return self.walk_get(object, receiver, key);
6275 }
6276 match lookup_key(object, key) {
6277 Some((_, property)) => self.read_property(property, object, receiver),
6278 None => Ok(None),
6279 }
6280 }
6281
6282 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6283 /// answer for itself.
6284 ///
6285 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6286 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6287 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6288 /// an inherited getter the object the read started from.
6289 fn walk_get(
6290 &mut self,
6291 start: &Gc<JsObject>,
6292 receiver: Option<&Value>,
6293 key: &PropertyKey,
6294 ) -> JsResult<Option<Value>> {
6295 let receiver = receiver
6296 .cloned()
6297 .unwrap_or_else(|| Value::Object(start.clone()));
6298 let mut current = Some(start.clone());
6299 while let Some(holder) = current {
6300 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6301 // has to ask it, not read its (empty) own-property table. `Object.create(new
6302 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6303 // instead found nothing.
6304 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6305 return Ok(Some(value));
6306 }
6307 // A host class's `get_property` trap replaces the whole read for that holder,
6308 // prototype walk included — the same rule `get_property_key_for` applies to the
6309 // first object.
6310 if let Some(exotic) = holder.exotic()
6311 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6312 {
6313 return Ok(Some(value));
6314 }
6315 if let Some(property) = self.object_get_own_property(&holder, key)? {
6316 return self.read_property(property, &holder, Some(&receiver));
6317 }
6318 current = self.object_prototype_of(&holder)?;
6319 }
6320 Ok(None)
6321 }
6322
6323 /// Whether `object` or anything above it has properties that cannot be read out of a
6324 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6325 ///
6326 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6327 /// is the hot path for every property read; this is the check that decides whether it
6328 /// is safe to take it.
6329 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6330 // A module namespace answers through `[[GetOwnProperty]]` (§10.4.6), and a
6331 // *deferred* one evaluates its module there — so the static property-table walk is
6332 // the wrong shortcut for it. This is the receiver's own marker, checked first: a
6333 // namespace's `[[Prototype]]` is null, so `chain()` below is empty for it and the
6334 // loop would never see it. Non-deferred namespaces pay a walk instead of a table
6335 // lookup; there are never many of them and they are read by importers.
6336 if object.module_namespace_marker() {
6337 return true;
6338 }
6339 object.chain().iter().any(|ancestor| {
6340 ancestor.proxy_state().is_some()
6341 || ancestor.exotic().is_some()
6342 || ancestor.module_namespace_marker()
6343 })
6344 }
6345
6346 /// The value a property read answers.
6347 ///
6348 /// One place rather than three, because an accessor has to run with the *receiver* as
6349 /// `this` whether the descriptor came from the property table, an exotic
6350 /// `get_own_property` trap, or a prototype above one.
6351 fn read_property(
6352 &mut self,
6353 property: Property,
6354 object: &Gc<JsObject>,
6355 receiver: Option<&Value>,
6356 ) -> JsResult<Option<Value>> {
6357 if property.is_accessor() {
6358 match &property.getter {
6359 Some(getter) if !matches!(getter, Value::Undefined) => {
6360 let receiver = receiver
6361 .cloned()
6362 .unwrap_or_else(|| Value::Object(object.clone()));
6363 self.call_value(getter.clone(), receiver, Vec::new())
6364 .map(Some)
6365 }
6366 // An accessor with no getter reads as `undefined`.
6367 _ => Ok(Some(Value::Undefined)),
6368 }
6369 } else {
6370 Ok(property.value)
6371 }
6372 }
6373
6374 /// `super.key` — start the search at `proto`, but report to `receiver`.
6375 ///
6376 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6377 /// found on the prototype of a class has to see the *instance* as `this`, and a
6378 /// plain property read off `proto` would lose that.
6379 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6380 let start = self.require_object(proto)?;
6381 let key = self.propkey(key)?;
6382 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6383 if matches!(proto, Value::Null) {
6384 return Ok(Value::Undefined);
6385 }
6386 // `super.x` is `OrdinaryGet` with `startObject` as the base, so a namespace on the
6387 // way is asked for its exports list — and a deferred one evaluates there, for a
6388 // name the base does *not* have as much as for one it does.
6389 self.trigger_deferred_namespace_for_key(&start, &key)?;
6390 match lookup_key(&start, &key) {
6391 Some((_, property)) if property.is_accessor() => match &property.getter {
6392 Some(getter) if !matches!(getter, Value::Undefined) => {
6393 self.call_value(getter.clone(), receiver.clone(), Vec::new())
6394 }
6395 _ => Ok(Value::Undefined),
6396 },
6397 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6398 None => Ok(Value::Undefined),
6399 }
6400 }
6401
6402 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6403 ///
6404 /// A setter found on the prototype runs with `receiver` as `this`; a data property
6405 /// is shadowed by a new own property on the receiver, the same rule an ordinary
6406 /// assignment follows.
6407 fn super_write(
6408 &mut self,
6409 receiver: &Value,
6410 proto: &Value,
6411 key: &Value,
6412 value: Value,
6413 ) -> JsResult<()> {
6414 let target = self.require_object(receiver)?;
6415 let key = self.propkey(key)?;
6416 if !matches!(proto, Value::Null)
6417 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6418 {
6419 // §10.4.6.6 / `OrdinarySetWithOwnDescriptor`: the descriptor is fetched from the
6420 // prototype before the store, which is where a deferred namespace evaluates.
6421 self.trigger_deferred_namespace_for_key(&owner, &key)?;
6422 if property.is_accessor() {
6423 if let Some(setter) = &property.setter
6424 && !matches!(setter, Value::Undefined)
6425 {
6426 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6427 }
6428 return Ok(());
6429 }
6430 // A data property on the prototype is writable or not; reading `owner` at
6431 // all is only for the attribute check.
6432 if !property.writable {
6433 return Err(self.type_error(format!("'{key}' is read-only")));
6434 }
6435 let _ = owner;
6436 }
6437 // `OrdinarySetWithOwnDescriptor` reaches the store only after asking the *receiver*
6438 // for its own descriptor — which is where a deferred namespace evaluates, and the
6439 // only reason `super[key] = v` runs a module whose `[[Set]]` refuses everything.
6440 self.trigger_deferred_namespace_for_key(&target, &key)?;
6441 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6442 }
6443
6444 /// The object a `super` operation needs, or the `TypeError` the spec raises.
6445 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6446 match value.as_object() {
6447 Some(object) => Ok(object.clone()),
6448 None => Err(Signal::Throw(
6449 self.make_error("TypeError", "value is not an object"),
6450 )),
6451 }
6452 }
6453
6454 /// Build the class object `define_class` produces.
6455 ///
6456 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6457 /// whose prototype property is a fresh object inheriting from the parent's
6458 /// prototype, and whose own prototype is the parent constructor — which is what makes
6459 /// a static method inherited too.
6460 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6461 let ctor = self.pop();
6462 let parent = self.pop();
6463 let Value::Object(function) = &ctor else {
6464 return Err(Signal::Throw(
6465 self.make_error("TypeError", "class constructor must be a function"),
6466 ));
6467 };
6468 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6469 // but gives the instances no prototype at all.
6470 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6471 match &parent {
6472 Value::Null => (Some(self.realm.function_proto.clone()), None),
6473 Value::Object(parent_class) => {
6474 // `IsConstructor`, not `IsCallable`: §15.7.14 ClassDefinitionEvaluation
6475 // step 9 rejects a heritage without `[[Construct]]` *before* reading
6476 // `superclass.prototype`, so an arrow function and a generator — both
6477 // callable, neither constructible — are a `TypeError` and their
6478 // `prototype` getter must never run
6479 // (`subclass/superclass-arrow-function`, `…-generator-function`).
6480 if !parent_class.is_constructor() {
6481 return Err(Signal::Throw(
6482 self.make_error("TypeError", "parent class must be constructor"),
6483 ));
6484 }
6485 let proto = self.get_property(parent_class, "prototype")?;
6486 match proto {
6487 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6488 Some(Value::Null) => (Some(parent_class.clone()), None),
6489 _ => {
6490 return Err(Signal::Throw(self.make_error(
6491 "TypeError",
6492 "parent prototype must be an object or null",
6493 )));
6494 }
6495 }
6496 }
6497 _ => {
6498 return Err(Signal::Throw(
6499 self.make_error("TypeError", "parent class must be constructor"),
6500 ));
6501 }
6502 }
6503 } else {
6504 (
6505 Some(self.realm.function_proto.clone()),
6506 Some(self.realm.object_proto.clone()),
6507 )
6508 };
6509 let proto = self.new_object(parent_proto);
6510 function.set_proto(parent_ctor);
6511 // A class is not callable without `new`, and its `prototype` is not writable —
6512 // both follow from being a class and are what `class A {}; A()` throws on.
6513 function.set_class_constructor(true);
6514 function.set_home_object(None);
6515 self.set_function_name(&ctor, name);
6516 self.define_class_properties(function, &ctor, &proto)?;
6517 Ok((ctor, proto))
6518 }
6519
6520 /// Give the constructor its `prototype` and `length`, and the prototype its
6521 /// `constructor` back-pointer.
6522 fn define_class_properties(
6523 &mut self,
6524 function: &Gc<JsObject>,
6525 ctor: &Value,
6526 proto: &Gc<JsObject>,
6527 ) -> JsResult<()> {
6528 proto.define(
6529 "constructor",
6530 Property::with_attributes(ctor.clone(), true, false),
6531 );
6532 function.define(
6533 "prototype",
6534 Property::prototype_of(Value::Object(proto.clone()), false),
6535 );
6536 if let Some((code, _)) = bytecode_of(function) {
6537 let length = code.code.defined_args;
6538 function.define(
6539 "length",
6540 Property::name_or_length(Value::Int(length as i32)),
6541 );
6542 }
6543 Ok(())
6544 }
6545
6546 /// The own array element `key` names, if this object has one.
6547 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6548 // A typed array's elements live in its buffer, not in a property list: reading one
6549 // goes through the view's element type so a bounds check and a detached buffer are
6550 // both handled there.
6551 //
6552 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6553 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6554 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6555 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6556 // consulted. Testing with `array_index` rejected all three, which let a throwing
6557 // getter installed on `TypedArray.prototype["-1"]` run.
6558 if object.typed_array_parts().is_some() {
6559 let property_key = PropertyKey::from(key);
6560 let numeric = canonical_numeric_index(&property_key)?;
6561 if typed_array_index_is_valid(object, numeric) {
6562 return object.typed_array_element(numeric as usize);
6563 }
6564 // Canonical, but not a valid index: `undefined`, and *final*.
6565 return Some(Value::Undefined);
6566 }
6567 let index = array_index(key)?;
6568 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6569 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6570 // search early, which is why `Array.prototype[1] = 9` could not be seen through
6571 // `[1,,3][1]`.
6572 match object.array_get(index as usize) {
6573 Some(Value::Hole) | None => None,
6574 other => other,
6575 }
6576 }
6577
6578 /// Store `object[key] = value`, honouring setters and inherited properties.
6579 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6580 self.set_property_with(object, key, value, DeleteFailure::Throw)
6581 }
6582
6583 /// Store a property, choosing what to do when the object refuses.
6584 ///
6585 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6586 /// mode, which is the one place assignment differs by mode. Native code (the array
6587 /// methods, `JSON`) always asks for the throw.
6588 pub fn set_property_with(
6589 &mut self,
6590 object: &Gc<JsObject>,
6591 key: &str,
6592 value: Value,
6593 on_failure: DeleteFailure,
6594 ) -> JsResult<()> {
6595 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6596 }
6597
6598 /// [`Interp::set_property_with`] with a key that may be a symbol.
6599 pub fn set_property_with_key(
6600 &mut self,
6601 object: &Gc<JsObject>,
6602 key: &PropertyKey,
6603 value: Value,
6604 on_failure: DeleteFailure,
6605 ) -> JsResult<()> {
6606 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6607 }
6608
6609 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6610 ///
6611 /// The receiver split lives one level up, in
6612 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6613 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6614 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6615 /// stores into `object` itself, which is why the element branch below converts `V`
6616 /// before asking whether the index is valid: `V` may put it back in bounds
6617 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6618 fn set_property_with_key_receiver_aware(
6619 &mut self,
6620 object: &Gc<JsObject>,
6621 key: &PropertyKey,
6622 value: Value,
6623 on_failure: DeleteFailure,
6624 ) -> JsResult<()> {
6625 // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6626 // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6627 // Nothing about the receiver or the value changes that, so the whole operation is
6628 // one answer.
6629 //
6630 // Not implementing it explicitly left the ordinary algorithm in charge, and that
6631 // says "true" for names the namespace does not own as soon as the value matches or
6632 // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6633 // assignment stopped throwing (`await-ns-set-strict`).
6634 if object.module_namespace_marker() {
6635 return match on_failure {
6636 DeleteFailure::Ignore => Ok(()),
6637 DeleteFailure::Throw => Err(self.type_error(format!(
6638 "cannot assign to property '{key}' of a module namespace object"
6639 ))),
6640 };
6641 }
6642 // A proxy's `set` trap decides, and its `false` means the same thing an
6643 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6644 if object.proxy_state().is_some() {
6645 let receiver = Value::Object(object.clone());
6646 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6647 return match (accepted, on_failure) {
6648 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6649 (false, DeleteFailure::Throw) => {
6650 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6651 }
6652 };
6653 }
6654 }
6655 // A host class's `set_property` trap decides for itself. `Some(false)` is a
6656 // refusal and means exactly what a proxy's `false` means.
6657 if let Some(exotic) = object.exotic() {
6658 let receiver = Value::Object(object.clone());
6659 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6660 return match (accepted, on_failure) {
6661 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6662 (false, DeleteFailure::Throw) => {
6663 Err(self.type_error(format!("property '{key}' is read-only")))
6664 }
6665 };
6666 }
6667 }
6668 // The element and `length` shortcuts only exist for string keys: an array
6669 // index has no symbol spelling, and a symbol named `length` is an ordinary
6670 // property.
6671 let text = key.as_str();
6672 // A typed array's elements are a window onto its buffer: the store has to go
6673 // through the view's element type so the value is wrapped (or clamped) and so an
6674 // out-of-range or detached write is a silent no-op, as the spec says.
6675 //
6676 // The key test is `CanonicalNumericIndexString`, like every other index operation
6677 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6678 // does not exist, so they do nothing and leave no own property behind
6679 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6680 // path, which created a property named `"-0"`.
6681 //
6682 // The conversion comes **first**, before the index is checked at all, and that
6683 // order is observable twice over:
6684 //
6685 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6686 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6687 // then store the converted value;
6688 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6689 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6690 // run and its exception to escape.
6691 //
6692 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6693 // validity check, not a validity check that skips the conversion. The store itself
6694 // is a no-op when the index is invalid by then, which is why no extra guard is
6695 // needed around `typed_array_set`.
6696 if let Some(element) = object.typed_array_element_type()
6697 && let Some(numeric) = canonical_numeric_index(key)
6698 {
6699 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6700 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6701 // in `Interp`, because it is script-observable and the storage borrow inside
6702 // `typed_array_set` must not be held across it.
6703 let stored = self.element_value(element, value)?;
6704 if typed_array_index_is_valid(object, numeric)
6705 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6706 {
6707 return Err(self.type_error(reason));
6708 }
6709 return Ok(());
6710 }
6711 if let Some(text) = text
6712 && let Some(index) = array_index(text)
6713 && object.is_array()
6714 {
6715 // An accessor defined on an index lives in the property table while the
6716 // element slot is a hole, so the store has to go through the property first.
6717 // Writing the vector directly skipped the setter entirely.
6718 if let Some(existing) = object.own_property_key(key) {
6719 if existing.is_accessor() {
6720 return match existing.setter.clone() {
6721 Some(setter) if !matches!(setter, Value::Undefined) => {
6722 let receiver = Value::Object(object.clone());
6723 self.call_value(setter, receiver, vec![value]).map(|_| ())
6724 }
6725 _ => match on_failure {
6726 DeleteFailure::Throw => Err(self.type_error(format!(
6727 "cannot set property '{text}', it has only a getter"
6728 ))),
6729 DeleteFailure::Ignore => Ok(()),
6730 },
6731 };
6732 }
6733 if !existing.writable {
6734 return match on_failure {
6735 DeleteFailure::Throw => {
6736 Err(self.type_error(format!("'{text}' is read-only")))
6737 }
6738 DeleteFailure::Ignore => Ok(()),
6739 };
6740 }
6741 }
6742 {
6743 // Growing the array needs a writable `length`.
6744 if (index as usize) >= object.array_length().unwrap_or(0)
6745 && !object.length_writable()
6746 {
6747 return match on_failure {
6748 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6749 DeleteFailure::Ignore => Ok(()),
6750 };
6751 }
6752 // Adding an index past the end makes the array longer, which a
6753 // non-extensible array refuses.
6754 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6755 return match on_failure {
6756 DeleteFailure::Throw => Err(self.type_error(format!(
6757 "cannot add property '{key}', object is not extensible"
6758 ))),
6759 DeleteFailure::Ignore => Ok(()),
6760 };
6761 }
6762 if object.element_is_locked(index) {
6763 return match on_failure {
6764 DeleteFailure::Throw => {
6765 Err(self.type_error(format!("'{key}' is read-only")))
6766 }
6767 DeleteFailure::Ignore => Ok(()),
6768 };
6769 }
6770 // The element vector is only half of `[[Set]]` for an index: the
6771 // prototype chain is consulted first, and a setter there answers instead
6772 // of the element store. This branch used to write the element directly, so
6773 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6774 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6775 // the reference calls the setter and the array keeps no own index.
6776 //
6777 // An *exotic* prototype has no entry to find, because its indices live
6778 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6779 // then looked like "nothing on the chain" and the store created the
6780 // element, where the view's `[[Set]]` answers `true` and does nothing for
6781 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6782 // checks the array's `length` stays 0). So the dispatch comes first.
6783 if !object.has_own_key(key)
6784 && let Some(proto) = object.proto()
6785 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6786 {
6787 let receiver = Value::Object(object.clone());
6788 let accepted =
6789 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6790 return if accepted {
6791 Ok(())
6792 } else {
6793 match on_failure {
6794 DeleteFailure::Throw => {
6795 Err(self.type_error(format!("'{key}' is read-only")))
6796 }
6797 DeleteFailure::Ignore => Ok(()),
6798 }
6799 };
6800 }
6801 if let Some((owner, property)) = lookup_key(object, key)
6802 && !owner.ptr_eq(object)
6803 {
6804 match &property {
6805 property if property.is_accessor() => {
6806 match &property.setter {
6807 Some(setter) if !matches!(setter, Value::Undefined) => {
6808 let receiver = Value::Object(object.clone());
6809 self.call_value(setter.clone(), receiver, vec![value])?;
6810 }
6811 _ => {
6812 return match on_failure {
6813 DeleteFailure::Throw => Err(self.type_error(format!(
6814 "cannot set property '{text}', it has only a getter"
6815 ))),
6816 DeleteFailure::Ignore => Ok(()),
6817 };
6818 }
6819 }
6820 return Ok(());
6821 }
6822 property if !property.writable => {
6823 return match on_failure {
6824 DeleteFailure::Throw => {
6825 Err(self.type_error(format!("'{text}' is read-only")))
6826 }
6827 DeleteFailure::Ignore => Ok(()),
6828 };
6829 }
6830 _ => {}
6831 }
6832 }
6833 if object.array_set(self.heap, index as usize, value.clone()) {
6834 return Ok(());
6835 }
6836 // Past the dense limit the slot is too far out to be worth one `Value`
6837 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6838 // constant time by keeping the index as an ordinary property. The store
6839 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6840 // to a legal program.
6841 object.define_key(key, Property::with_attributes(value, true, true));
6842 // Extend, never shorten: the index may be *inside* the current length (a
6843 // huge `length` with a sparse store), and shortening would delete the
6844 // sparse properties above it — including the one just stored.
6845 if index as usize + 1 > object.array_length().unwrap_or(0) {
6846 object.array_set_length(self.heap, index as usize + 1);
6847 }
6848 return Ok(());
6849 }
6850 }
6851 if text == Some("length") && object.is_array() {
6852 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6853 // test. A `valueOf` that locks `length` on its second call therefore turns the
6854 // store into a refused write rather than a silent success
6855 // (`length/define-own-prop-length-coercion-order-set`).
6856 let rounded = self.coerce_array_length_twice(&value)?;
6857 if !object.length_writable() {
6858 return match on_failure {
6859 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6860 DeleteFailure::Ignore => Ok(()),
6861 };
6862 }
6863 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6864 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6865 // answered `NaN`, which left the assignment silently ignored
6866 // (`S15.4.5.2_A3_T2`).
6867 let _ = rounded;
6868 let length = self.to_js_number(&value)?;
6869 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6870 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6871 // `RangeError`s; the old code only tested "finite and non-negative" and then
6872 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6873 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6874 let valid = length.is_finite()
6875 && length >= 0.0
6876 && length.fract() == 0.0
6877 && length <= u32::MAX as f64;
6878 if !valid {
6879 return Err(self.range_error("invalid array length"));
6880 }
6881 {
6882 let length = length as usize;
6883 // `a.length = n` with `n` below a non-configurable element cannot
6884 // drop that element, so the whole assignment fails. The spec makes
6885 // this a `TypeError` rather than a silent no-op, in any mode.
6886 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6887 // Sloppy mode stops the truncation at the blocking element
6888 // instead of failing; strict mode raises.
6889 // Both modes stop at the blocking element; they differ in
6890 // whether that is reported. The reference truncates *then*
6891 // throws, so the array is left in the shortened state.
6892 object.array_truncate(self.heap, blocked + 1);
6893 return match on_failure {
6894 DeleteFailure::Throw => {
6895 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6896 }
6897 DeleteFailure::Ignore => Ok(()),
6898 };
6899 }
6900 object.array_set_length(self.heap, length);
6901 return Ok(());
6902 }
6903 }
6904 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6905 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6906 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6907 //
6908 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6909 // applying whatever came back is the same thing for an ordinary prototype and
6910 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6911 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6912 // answers "not mine, the receiver is not me" without touching the buffer. This
6913 // code used to find nothing owned by `o`, find no property on the view either,
6914 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6915 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6916 // `key-is-canonical-invalid-index-prototype-chain-set`).
6917 //
6918 // The read-only and accessor rules of step 1 are what make
6919 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6920 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6921 let own = match self.lookup_for_write(object, key)? {
6922 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6923 _ => None,
6924 };
6925 if let Some(property) = own {
6926 if property.is_accessor() {
6927 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6928 Some(setter) => {
6929 let receiver = Value::Object(object.clone());
6930 self.call_value(setter, receiver, vec![value])?;
6931 Ok(())
6932 }
6933 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6934 // Sloppy code swallows that refusal, strict code raises — the same
6935 // rule the read-only *data* property below follows, and skipping it
6936 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6937 // return silently. The reference answers `TypeError: 'x' is
6938 // read-only`.
6939 None => match on_failure {
6940 DeleteFailure::Throw => {
6941 Err(self.type_error(format!("'{key}' is read-only")))
6942 }
6943 DeleteFailure::Ignore => Ok(()),
6944 },
6945 };
6946 }
6947 // An own non-writable data property stops here: nothing may change it.
6948 if !property.writable {
6949 return match on_failure {
6950 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6951 DeleteFailure::Ignore => Ok(()),
6952 };
6953 }
6954 // An existing writable own property keeps its attributes: only the value
6955 // moves. Redefining instead would reset them, which is how a
6956 // non-configurable global `var` used to become deletable.
6957 if object.write_value_key(key, value.clone()) {
6958 return Ok(());
6959 }
6960 }
6961 // Step 2: hand the store to the prototype, with `object` as the receiver.
6962 if let Some(proto) = object.proto() {
6963 let receiver = Value::Object(object.clone());
6964 let accepted =
6965 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6966 return if accepted {
6967 Ok(())
6968 } else {
6969 match on_failure {
6970 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6971 DeleteFailure::Ignore => Ok(()),
6972 }
6973 };
6974 }
6975 // Step 3: create one, and a non-extensible object cannot.
6976 if !object.is_extensible() {
6977 return match on_failure {
6978 DeleteFailure::Throw => Err(self.type_error(format!(
6979 "cannot add property {key}, object is not extensible"
6980 ))),
6981 DeleteFailure::Ignore => Ok(()),
6982 };
6983 }
6984 object.define_data_key(key, value);
6985 Ok(())
6986 }
6987
6988 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6989 ///
6990 /// The distinction the fast path above does not need: it is called with the store's
6991 /// receiver already being the object it writes to. Here `object` is the one whose
6992 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6993 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6994 /// and not a write to `object`.
6995 ///
6996 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6997 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6998 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6999 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
7000 /// descriptor on the prototype refuses instead, which is the same rule that keeps
7001 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
7002 ///
7003 /// Answers `false` where the spec says `false`; the caller turns that into the
7004 /// strict-mode `TypeError` or the sloppy-mode silence.
7005 fn ordinary_set_with_receiver(
7006 &mut self,
7007 object: &Gc<JsObject>,
7008 receiver: &Value,
7009 key: &PropertyKey,
7010 value: Value,
7011 on_failure: DeleteFailure,
7012 ) -> JsResult<bool> {
7013 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
7014 if object.proxy_state().is_some() {
7015 return Ok(self
7016 .proxy_set(object, key, value, receiver)?
7017 .unwrap_or(true));
7018 }
7019 // A host class decides for itself, with the receiver the caller named.
7020 if let Some(exotic) = object.exotic()
7021 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
7022 {
7023 return Ok(accepted);
7024 }
7025 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
7026 // rather than the receiver, but the receiver may still *be* the view:
7027 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
7028 // itself as receiver, and then the first half applies — convert `V` once, store
7029 // if the index is valid, answer `true` either way. The conversion is the observable
7030 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
7031 //
7032 // Only the second half, a view that is *not* the receiver, skips the conversion
7033 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
7034 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
7035 // below with the value still unconverted.
7036 if object.typed_array_element_type().is_some()
7037 && let Some(numeric) = canonical_numeric_index(key)
7038 {
7039 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
7040 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
7041 return Ok(true);
7042 }
7043 if !typed_array_index_is_valid(object, numeric) {
7044 return Ok(true);
7045 }
7046 }
7047 let own = self.object_get_own_property(object, key)?;
7048 if let Some(own) = own {
7049 if own.is_accessor() {
7050 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
7051 Some(setter) => {
7052 self.call_value(setter, receiver.clone(), vec![value])?;
7053 Ok(true)
7054 }
7055 None => Ok(false),
7056 };
7057 }
7058 // A non-writable data descriptor refuses, own or inherited. Either way the
7059 // receiver must not gain a shadowing property.
7060 if !own.writable {
7061 return Ok(false);
7062 }
7063 // Step 1.d: the *receiver's* own descriptor decides whether it can be
7064 // created or written, and it is created as an ordinary data property.
7065 let Some(receiver_object) = receiver.as_object().cloned() else {
7066 return Ok(false);
7067 };
7068 return match self.object_get_own_property(&receiver_object, key)? {
7069 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
7070 Some(existing) => self.object_define_own_property(
7071 &receiver_object,
7072 key,
7073 Property {
7074 value: Some(value),
7075 ..existing
7076 },
7077 ),
7078 None => {
7079 self.object_define_own_property(&receiver_object, key, Property::data(value))
7080 }
7081 };
7082 }
7083 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
7084 if let Some(proto) = object.proto() {
7085 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
7086 }
7087 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
7088 // *default* data descriptor here, so control falls into step 2 exactly as if the
7089 // target had owned a writable property — which means the **receiver's** own
7090 // descriptor is asked for before the write. Skipping that question went straight to
7091 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
7092 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
7093 // exactly those calls).
7094 let Some(receiver_object) = receiver.as_object().cloned() else {
7095 return Ok(false);
7096 };
7097 match self.object_get_own_property(&receiver_object, key)? {
7098 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
7099 Some(existing) => self.object_define_own_property(
7100 &receiver_object,
7101 key,
7102 Property {
7103 value: Some(value),
7104 ..existing
7105 },
7106 ),
7107 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
7108 }
7109 }
7110
7111 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
7112 ///
7113 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
7114 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
7115 /// a virtual accessor gets its setter run without implementing `set_property` at all.
7116 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
7117 /// the prototype, so the walk resumes above the object.
7118 fn lookup_for_write(
7119 &mut self,
7120 object: &Gc<JsObject>,
7121 key: &PropertyKey,
7122 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
7123 let Some(exotic) = object.exotic() else {
7124 return Ok(lookup_key(object, key));
7125 };
7126 Ok(match exotic.get_own_property(self, object, key)? {
7127 Some(Some(property)) => Some((object.clone(), property)),
7128 Some(None) => lookup_key_above(object, key),
7129 None => lookup_key(object, key),
7130 })
7131 }
7132
7133 /// Delete `object[key]`.
7134 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
7135 self.delete_property_key(object, &PropertyKey::from(key))
7136 }
7137
7138 /// [`Interp::delete_property`] with a key that may be a symbol.
7139 pub fn delete_property_key(
7140 &mut self,
7141 object: &Gc<JsObject>,
7142 key: &PropertyKey,
7143 ) -> JsResult<bool> {
7144 // A proxy decides for itself, and may even throw; the invariant checks live in
7145 // `proxy_delete`.
7146 if let Some(answer) = self.proxy_delete(object, key)? {
7147 return Ok(answer);
7148 }
7149 // A host class's `delete_property` trap decides; `false` is a refusal, which the
7150 // caller reports as a failed delete.
7151 if let Some(exotic) = object.exotic()
7152 && let Some(answer) = exotic.delete_property(self, object, key)?
7153 {
7154 return Ok(answer);
7155 }
7156 // §10.4.6.9 `[[Delete]]` also asks for the exports list — every export is
7157 // non-configurable, so the answer is always `false`, but a deferred namespace
7158 // evaluates first and symbol-like keys are exempt.
7159 self.trigger_deferred_namespace_for_key(object, key)?;
7160 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
7161 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
7162 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
7163 // one answers `false` because the elements are non-configurable. The prototype
7164 // chain is not consulted either, which is what makes a throwing getter on
7165 // `TypedArray.prototype["-1"]` stay unrun.
7166 if object.typed_array_parts().is_some()
7167 && object.proxy_state().is_none()
7168 && let Some(numeric) = canonical_numeric_index(key)
7169 {
7170 return Ok(!typed_array_index_is_valid(object, numeric));
7171 }
7172 let mapped_index = key.as_str().and_then(array_index);
7173 if let Some(index) = mapped_index
7174 && let Some(length) = object.array_length()
7175 && (index as usize) < length
7176 {
7177 // An accessor defined on an index lives in the property table rather than the
7178 // element vector, so both have to be cleared: `delete` after
7179 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
7180 object.delete_key(key);
7181 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
7182 // index stops answering `in`.
7183 if object.element_is_undeletable(index) {
7184 return Ok(false);
7185 }
7186 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
7187 // so a later `defineProperty(arguments, "0", {value})` writes to the object
7188 // and no longer through to the parameter. A refused delete leaves the
7189 // mapping alone.
7190 object.drop_mapped_argument(index as usize);
7191 object.array_set(self.heap, index as usize, Value::Hole);
7192 return Ok(true);
7193 }
7194 // An array's `length` is a non-configurable own property that lives outside the
7195 // property table, so `delete_key` finds nothing and reports success — `Reflect
7196 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
7197 // §10.4.4.1 step 3 refuses it.
7198 if key.as_str() == Some("length") && object.array_length().is_some() {
7199 return Ok(false);
7200 }
7201 // The same for an object that is not an array: only a delete that actually
7202 // removed the property ends the alias.
7203 let deleted = object.delete_key(key);
7204 if deleted && let Some(index) = mapped_index {
7205 object.drop_mapped_argument(index as usize);
7206 }
7207 Ok(deleted)
7208 }
7209
7210 // -- proxy traps --------------------------------------------------------
7211 //
7212 // A proxy's internal methods all look the same: ask the handler for the trap, call it
7213 // with the target and the operation's own arguments, then check the answer against
7214 // the target. The checks are not decoration — they are what stops a proxy from
7215 // reporting a `non-configurable` property as missing, which would let a frozen object
7216 // be rewritten by standing in front of it.
7217
7218 /// The target and handler of `object`, or `None` when it is not a proxy.
7219 ///
7220 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
7221 /// one has to fail: the slots the traps would have been read from are gone.
7222 pub(crate) fn proxy_parts(
7223 &mut self,
7224 object: &Gc<JsObject>,
7225 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
7226 let Some(state) = object.proxy_state() else {
7227 return Ok(None);
7228 };
7229 let state = state.borrow();
7230 match (&state.target, &state.handler) {
7231 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
7232 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
7233 }
7234 }
7235
7236 /// Call `handler[name]`, or answer `None` when the trap is absent.
7237 ///
7238 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
7239 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
7240 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
7241 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
7242 /// one per trap plus the `target-is-proxy` variants.
7243 ///
7244 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
7245 /// this cannot simply be "any non-callable means no trap".
7246 fn proxy_trap(
7247 &mut self,
7248 handler: &Value,
7249 name: &str,
7250 args: Vec<Value>,
7251 ) -> JsResult<Option<Value>> {
7252 let Value::Object(table) = handler else {
7253 return Err(self.type_error("proxy handler is not an object"));
7254 };
7255 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
7256 match trap {
7257 Value::Undefined | Value::Null => Ok(None),
7258 Value::Object(function) if function.is_callable() => {
7259 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
7260 Ok(Some(answer))
7261 }
7262 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
7263 }
7264 }
7265
7266 /// Whether the target's own property `key` is one it refuses to lose.
7267 ///
7268 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
7269 /// its value behind the target's back.
7270 ///
7271 /// A **method**, not a free function, because §10.5.1's invariants say
7272 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
7273 /// property table directly finds nothing (a proxy's table is empty by design), so every
7274 /// invariant check silently passed for a proxy target. That is what
7275 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
7276 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
7277 /// where an array's elements and its `length` — both fixed, both outside the table —
7278 /// are covered.
7279 fn fixed_property(
7280 &mut self,
7281 target: &Gc<JsObject>,
7282 key: &PropertyKey,
7283 ) -> JsResult<Option<Property>> {
7284 Ok(self
7285 .object_get_own_property(target, key)?
7286 .filter(|property| !property.configurable))
7287 }
7288
7289 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7290 fn proxy_get(
7291 &mut self,
7292 object: &Gc<JsObject>,
7293 receiver: &Value,
7294 key: &PropertyKey,
7295 ) -> JsResult<Option<Value>> {
7296 let Some((target, handler)) = self.proxy_parts(object)? else {
7297 return Ok(None);
7298 };
7299 let key_value = self.key_value(key);
7300 let Some(result) = self.proxy_trap(
7301 &handler,
7302 "get",
7303 vec![Value::Object(target.clone()), key_value, receiver.clone()],
7304 )?
7305 else {
7306 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7307 // inherited getter still sees the proxy.
7308 return Ok(Some(
7309 self.get_property_key_for(&target, Some(receiver), key)?
7310 .unwrap_or(Value::Undefined),
7311 ));
7312 };
7313 if let Some(fixed) = self.fixed_property(&target, key)? {
7314 if fixed.is_accessor() {
7315 // A fixed accessor with no getter must read as `undefined`.
7316 let has_getter = fixed
7317 .getter
7318 .as_ref()
7319 .is_some_and(|getter| !matches!(getter, Value::Undefined));
7320 if !has_getter && !matches!(result, Value::Undefined) {
7321 return Err(self.type_error(format!(
7322 "proxy 'get' must report undefined for the non-configurable property '{key}'"
7323 )));
7324 }
7325 } else if !fixed.writable {
7326 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7327 if !fixed_value.same_value(&result) {
7328 return Err(self.type_error(format!(
7329 "proxy 'get' disagrees with the non-configurable property '{key}'"
7330 )));
7331 }
7332 }
7333 }
7334 Ok(Some(result))
7335 }
7336
7337 /// `[[Set]]` on a proxy.
7338 ///
7339 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7340 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7341 /// read-only store has.
7342 fn proxy_set(
7343 &mut self,
7344 object: &Gc<JsObject>,
7345 key: &PropertyKey,
7346 value: Value,
7347 receiver: &Value,
7348 ) -> JsResult<Option<bool>> {
7349 let Some((target, handler)) = self.proxy_parts(object)? else {
7350 return Ok(None);
7351 };
7352 let key_value = self.key_value(key);
7353 let Some(result) = self.proxy_trap(
7354 &handler,
7355 "set",
7356 vec![
7357 Value::Object(target.clone()),
7358 key_value,
7359 value.clone(),
7360 receiver.clone(),
7361 ],
7362 )?
7363 else {
7364 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7365 // given — not the target. `OrdinarySet` step 3 is
7366 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7367 // object whose prototype is a typed array has to reach the proxy's own
7368 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7369 // calls and expects exactly one. Storing on the target instead put the value
7370 // in the target and never consulted the trap.
7371 let accepted = self.ordinary_set_with_receiver(
7372 &target,
7373 receiver,
7374 key,
7375 value,
7376 DeleteFailure::Ignore,
7377 )?;
7378 return Ok(Some(accepted));
7379 };
7380 if !result.to_boolean() {
7381 return Ok(Some(false));
7382 }
7383 if let Some(fixed) = self.fixed_property(&target, key)? {
7384 if fixed.is_accessor() {
7385 let has_setter = fixed
7386 .setter
7387 .as_ref()
7388 .is_some_and(|setter| !matches!(setter, Value::Undefined));
7389 if !has_setter {
7390 return Err(self.type_error(format!(
7391 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7392 )));
7393 }
7394 } else if !fixed.writable {
7395 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7396 if !fixed_value.same_value(&value) {
7397 return Err(self.type_error(format!(
7398 "proxy 'set' changed the non-configurable property '{key}'"
7399 )));
7400 }
7401 }
7402 }
7403 // A new property cannot appear on a target that refuses new properties.
7404 if self.object_get_own_property(&target, key)?.is_none()
7405 && !self.object_is_extensible(&target)?
7406 {
7407 return Err(self.type_error(format!(
7408 "proxy 'set' added '{key}' to a non-extensible target"
7409 )));
7410 }
7411 Ok(Some(true))
7412 }
7413
7414 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7415 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7416 let Some((target, handler)) = self.proxy_parts(object)? else {
7417 return Ok(None);
7418 };
7419 let key_value = self.key_value(key);
7420 let Some(result) = self.proxy_trap(
7421 &handler,
7422 "has",
7423 vec![Value::Object(target.clone()), key_value],
7424 )?
7425 else {
7426 return Ok(Some(self.has_own_or_inherited(&target, key)?));
7427 };
7428 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7429 return Err(self.type_error(format!(
7430 "proxy 'has' denied the non-configurable property '{key}'"
7431 )));
7432 }
7433 // A non-extensible target cannot grow, so every own property it *has* is fixed.
7434 if !result.to_boolean()
7435 && !self.object_is_extensible(&target)?
7436 && self.object_get_own_property(&target, key)?.is_some()
7437 {
7438 return Err(self.type_error(format!(
7439 "proxy 'has' denied the own property '{key}' of a non-extensible target"
7440 )));
7441 }
7442 Ok(Some(result.to_boolean()))
7443 }
7444
7445 /// `[[Delete]]` on a proxy.
7446 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7447 let Some((target, handler)) = self.proxy_parts(object)? else {
7448 return Ok(None);
7449 };
7450 let key_value = self.key_value(key);
7451 let Some(result) = self.proxy_trap(
7452 &handler,
7453 "deleteProperty",
7454 vec![Value::Object(target.clone()), key_value],
7455 )?
7456 else {
7457 return Ok(Some(self.delete_property_key(&target, key)?));
7458 };
7459 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7460 return Err(self.type_error(format!(
7461 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7462 )));
7463 }
7464 if result.to_boolean()
7465 && !self.object_is_extensible(&target)?
7466 && self.object_get_own_property(&target, key)?.is_some()
7467 {
7468 return Err(self.type_error(format!(
7469 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7470 )));
7471 }
7472 Ok(Some(result.to_boolean()))
7473 }
7474
7475 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7476 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7477 let Some((target, handler)) = self.proxy_parts(object)? else {
7478 return Ok(None);
7479 };
7480 let Some(result) =
7481 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7482 else {
7483 // No trap: the target's own keys, already in the order an object reports.
7484 return Ok(Some(self.object_own_property_keys(&target)?));
7485 };
7486 // `CreateListFromArrayLike` with the string-or-symbol restriction.
7487 let list = self.list_from_array_like(&result, true)?;
7488 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7489 for value in list {
7490 let key = self.propkey(&value)?;
7491 if keys.contains(&key) {
7492 return Err(self.type_error(format!(
7493 "proxy 'ownKeys' returned the duplicate key '{key}'"
7494 )));
7495 }
7496 keys.push(key);
7497 }
7498 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7499 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7500 // table is empty, which made every check below vacuous.
7501 let target_keys = self.object_own_property_keys(&target)?;
7502 let extensible = self.object_is_extensible(&target)?;
7503 for key in &target_keys {
7504 if keys.contains(key) {
7505 continue;
7506 }
7507 if self.fixed_property(&target, key)?.is_some() {
7508 return Err(self.type_error(format!(
7509 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7510 )));
7511 }
7512 if !extensible {
7513 return Err(self.type_error(format!(
7514 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7515 )));
7516 }
7517 }
7518 if !extensible {
7519 // §10.5.11 step 12: the lists must match one for one, in any order.
7520 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7521 {
7522 return Err(
7523 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7524 );
7525 }
7526 }
7527 Ok(Some(keys))
7528 }
7529
7530 /// `[[GetOwnProperty]]` on a proxy.
7531 fn proxy_get_own_property(
7532 &mut self,
7533 object: &Gc<JsObject>,
7534 key: &PropertyKey,
7535 ) -> JsResult<Option<Option<Property>>> {
7536 let Some((target, handler)) = self.proxy_parts(object)? else {
7537 return Ok(None);
7538 };
7539 let key_value = self.key_value(key);
7540 let Some(result) = self.proxy_trap(
7541 &handler,
7542 "getOwnPropertyDescriptor",
7543 vec![Value::Object(target.clone()), key_value],
7544 )?
7545 else {
7546 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7547 // property table. Two things ride on that choice: a target that is itself a
7548 // proxy has to re-dispatch (its own table is empty, so reading it reported
7549 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7550 // indices and `length` live outside the table and need the ordinary synthesis.
7551 // `object_get_own_property` does both.
7552 return Ok(Some(self.object_get_own_property(&target, key)?));
7553 };
7554 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7555 // `ToPropertyDescriptor` runs, because that operation would box the primitive
7556 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7557 // empty descriptor instead of refusing.
7558 if !matches!(result, Value::Undefined | Value::Object(_)) {
7559 return Err(self.type_error(
7560 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7561 ));
7562 }
7563 let target_desc = self.object_get_own_property(&target, key)?;
7564 let extensible = self.object_is_extensible(&target)?;
7565 let Some(descriptor) = (match result {
7566 Value::Undefined => None,
7567 _ => Some(self.property_from_descriptor(&result)?),
7568 }) else {
7569 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7570 // descriptor is configurable *and* the target can still grow back.
7571 if let Some(target_desc) = &target_desc {
7572 if !target_desc.configurable {
7573 return Err(self.type_error(format!(
7574 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7575 )));
7576 }
7577 if !extensible {
7578 return Err(self.type_error(format!(
7579 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7580 )));
7581 }
7582 }
7583 return Ok(Some(None));
7584 };
7585 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7586 // which is a stronger requirement than "the target is not contradicting it" — the
7587 // four branches below are each one test262 case.
7588 if !descriptor.configurable {
7589 let Some(target_desc) = &target_desc else {
7590 return Err(self.type_error(format!(
7591 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7592 )));
7593 };
7594 if target_desc.configurable {
7595 return Err(self.type_error(format!(
7596 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7597 )));
7598 }
7599 let target_is_data = !target_desc.is_accessor();
7600 let result_is_data = !descriptor.is_accessor();
7601 if result_is_data && !target_is_data {
7602 return Err(self.type_error(format!(
7603 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7604 )));
7605 }
7606 if target_is_data && !target_desc.writable {
7607 if !result_is_data {
7608 return Err(self.type_error(format!(
7609 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7610 )));
7611 }
7612 if descriptor.writable {
7613 return Err(self.type_error(format!(
7614 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7615 )));
7616 }
7617 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7618 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7619 if !fixed_value.same_value(&reported) {
7620 return Err(self.type_error(format!(
7621 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7622 )));
7623 }
7624 }
7625 // Step 16.d: a reported *read-only* data property needs a real read-only data
7626 // property behind it. Missing this let a trap bolt a frozen property onto a
7627 // writable target intent (`resultdesc-is-not-configurable-not-writable-
7628 // targetdesc-is-writable`).
7629 if result_is_data && !descriptor.writable {
7630 if !target_is_data {
7631 return Err(self.type_error(format!(
7632 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7633 )));
7634 }
7635 if target_desc.writable {
7636 return Err(self.type_error(format!(
7637 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7638 )));
7639 }
7640 }
7641 if descriptor.is_accessor() {
7642 // Step 16.e: a getter the target does not have may not be invented, and
7643 // vice versa.
7644 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7645 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7646 (Some(a), Some(b)) => a.same_value(b),
7647 _ => false,
7648 };
7649 if !same(&target_desc.getter, &descriptor.getter)
7650 || !same(&target_desc.setter, &descriptor.setter)
7651 {
7652 return Err(self.type_error(format!(
7653 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7654 )));
7655 }
7656 }
7657 }
7658 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7659 // where the target's own is locked. Without it a handler could advertise
7660 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7661 // that believed it would try to redefine something it cannot.
7662 if descriptor.configurable
7663 && let Some(target_desc) = &target_desc
7664 && !target_desc.configurable
7665 {
7666 return Err(self.type_error(format!(
7667 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7668 )));
7669 }
7670 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7671 // through the trap either, however well-formed the descriptor is. This is the
7672 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7673 // the frozen target does not own.
7674 if !extensible {
7675 let Some(target_desc) = &target_desc else {
7676 return Err(self.type_error(format!(
7677 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7678 )));
7679 };
7680 if target_desc.is_accessor() == descriptor.is_accessor() {
7681 let target_is_data = !target_desc.is_accessor();
7682 let result_is_data = !descriptor.is_accessor();
7683 if target_is_data && !target_desc.writable && descriptor.writable {
7684 return Err(self.type_error(format!(
7685 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7686 )));
7687 }
7688 if !result_is_data && !target_is_data {
7689 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7690 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7691 (Some(a), Some(b)) => a.same_value(b),
7692 _ => false,
7693 };
7694 if !same(&target_desc.getter, &descriptor.getter)
7695 || !same(&target_desc.setter, &descriptor.setter)
7696 {
7697 return Err(self.type_error(format!(
7698 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7699 )));
7700 }
7701 }
7702 }
7703 }
7704 Ok(Some(Some(descriptor)))
7705 }
7706
7707 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7708 ///
7709 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7710 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7711 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7712 /// for a data property. `Property` cannot express "this field is absent", so the whole
7713 /// property path is skipped and the descriptor is assembled here field by field.
7714 ///
7715 /// `current` is the property the trap reported, used only to tell a data property from
7716 /// an accessor.
7717 pub fn proxy_seal_property(
7718 &mut self,
7719 object: &Gc<JsObject>,
7720 key: &PropertyKey,
7721 frozen: bool,
7722 current: &Property,
7723 ) -> JsResult<bool> {
7724 let Some((_target, handler)) = self.proxy_parts(object)? else {
7725 return Err(self.type_error("not a proxy"));
7726 };
7727 let descriptor = self.new_object(None);
7728 descriptor.define_data("configurable", Value::Bool(false));
7729 if frozen && !current.is_accessor() {
7730 descriptor.define_data("writable", Value::Bool(false));
7731 }
7732 let key_value = self.key_value(key);
7733 let target = object
7734 .proxy_state()
7735 .and_then(|state| state.borrow().target.clone());
7736 let Some(target) = target else {
7737 return Err(self.type_error("cannot use a proxy that has been revoked"));
7738 };
7739 let Some(result) = self.proxy_trap(
7740 &handler,
7741 "defineProperty",
7742 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7743 )?
7744 else {
7745 // No trap means the definition belongs to the target; `false` is its answer.
7746 return Ok(false);
7747 };
7748 Ok(result.to_boolean())
7749 }
7750
7751 /// `[[DefineOwnProperty]]` on a proxy.
7752 fn proxy_define_property(
7753 &mut self,
7754 object: &Gc<JsObject>,
7755 key: &PropertyKey,
7756 property: Property,
7757 ) -> JsResult<Option<bool>> {
7758 let Some((target, handler)) = self.proxy_parts(object)? else {
7759 return Ok(None);
7760 };
7761 let key_value = self.key_value(key);
7762 let descriptor = self.descriptor_from_property(&property);
7763 let Some(result) = self.proxy_trap(
7764 &handler,
7765 "defineProperty",
7766 vec![Value::Object(target.clone()), key_value, descriptor],
7767 )?
7768 else {
7769 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7770 // going" answer and `object_define_own_property` turns it into exactly that
7771 // forwarding — see the note there. (Reading it as "not a proxy" would define
7772 // the property on the proxy object itself, whose table is empty and which no
7773 // read ever consults.)
7774 return Ok(None);
7775 };
7776 if !result.to_boolean() {
7777 return Ok(Some(false));
7778 }
7779 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7780 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7781 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7782 // and treating them alike made four cases pass a descriptor the target contradicts.
7783 let target_desc = self.object_get_own_property(&target, key)?;
7784 let extensible = self.object_is_extensible(&target)?;
7785 let named = property
7786 .descriptor_fields
7787 .unwrap_or(crate::object::DescriptorFields {
7788 value: false,
7789 writable: false,
7790 enumerable: false,
7791 configurable: false,
7792 get: false,
7793 set: false,
7794 });
7795 if named.configurable && !property.configurable {
7796 let Some(target_desc) = &target_desc else {
7797 return Err(self.type_error(format!(
7798 "proxy 'defineProperty' invented the non-configurable '{key}'"
7799 )));
7800 };
7801 if target_desc.configurable {
7802 return Err(self.type_error(format!(
7803 "proxy 'defineProperty' made '{key}' non-configurable"
7804 )));
7805 }
7806 }
7807 // Step 11's other half: reporting that a property was made *configurable* needs a
7808 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7809 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7810 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7811 // target`).
7812 if named.configurable
7813 && property.configurable
7814 && let Some(target_desc) = &target_desc
7815 && !target_desc.configurable
7816 {
7817 return Err(
7818 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7819 );
7820 }
7821 // Step 12: a property cannot be reported *made writable* when the target's copy is
7822 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7823 // the trap is allowed to claim a definition it did not perform, as long as the
7824 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7825 // legal, and refusing it broke the commonest way to seed a proxy).
7826 if named.writable
7827 && property.writable
7828 && let Some(target_desc) = &target_desc
7829 && !target_desc.writable
7830 {
7831 return Err(self.type_error(format!(
7832 "proxy 'defineProperty' made the read-only '{key}' writable"
7833 )));
7834 }
7835 // Step 13: making a property read-only needs an existing read-only property.
7836 if named.writable
7837 && !property.writable
7838 && let Some(target_desc) = &target_desc
7839 && !target_desc.is_accessor()
7840 && target_desc.writable
7841 {
7842 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7843 }
7844 // Step 14: a non-writable, non-configurable property's value is fixed.
7845 if named.value
7846 && let Some(target_desc) = &target_desc
7847 && !target_desc.is_accessor()
7848 && !target_desc.writable
7849 && !target_desc.configurable
7850 {
7851 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7852 let reported = property.value.clone().unwrap_or(Value::Undefined);
7853 if !fixed_value.same_value(&reported) {
7854 return Err(self.type_error(format!(
7855 "proxy 'defineProperty' changed the value of '{key}'"
7856 )));
7857 }
7858 }
7859 // Step 15: a non-extensible target cannot grow.
7860 if target_desc.is_none() && !extensible {
7861 return Err(self.type_error(format!(
7862 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7863 )));
7864 }
7865 Ok(Some(true))
7866 }
7867
7868 /// `[[GetPrototypeOf]]` on a proxy.
7869 fn proxy_get_prototype_of(
7870 &mut self,
7871 object: &Gc<JsObject>,
7872 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7873 let Some((target, handler)) = self.proxy_parts(object)? else {
7874 return Ok(None);
7875 };
7876 let Some(result) = self.proxy_trap(
7877 &handler,
7878 "getPrototypeOf",
7879 vec![Value::Object(target.clone())],
7880 )?
7881 else {
7882 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7883 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7884 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7885 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7886 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7887 return Ok(Some(self.object_prototype_of(&target)?));
7888 };
7889 let proto = match &result {
7890 Value::Null => None,
7891 Value::Object(proto) => Some(proto.clone()),
7892 _ => {
7893 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7894 }
7895 };
7896 if !self.object_is_extensible(&target)? {
7897 let actual = self.object_prototype_of(&target)?;
7898 if !same_proto(proto.as_ref(), actual.as_ref()) {
7899 return Err(self.type_error(
7900 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7901 ));
7902 }
7903 }
7904 Ok(Some(proto))
7905 }
7906
7907 /// `[[SetPrototypeOf]]` on a proxy.
7908 fn proxy_set_prototype_of(
7909 &mut self,
7910 object: &Gc<JsObject>,
7911 proto: Option<Gc<JsObject>>,
7912 ) -> JsResult<Option<bool>> {
7913 let Some((target, handler)) = self.proxy_parts(object)? else {
7914 return Ok(None);
7915 };
7916 let proto_value = match &proto {
7917 Some(proto) => Value::Object(proto.clone()),
7918 None => Value::Null,
7919 };
7920 let Some(result) = self.proxy_trap(
7921 &handler,
7922 "setPrototypeOf",
7923 vec![Value::Object(target.clone()), proto_value],
7924 )?
7925 else {
7926 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7927 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7928 // its stored prototype overwritten behind its back.
7929 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7930 };
7931 if result.to_boolean()
7932 && !self.object_is_extensible(&target)?
7933 && !same_proto(
7934 Some(&proto).and_then(|p| p.clone()).as_ref(),
7935 self.object_prototype_of(&target)?.as_ref(),
7936 )
7937 {
7938 return Err(self.type_error(
7939 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7940 ));
7941 }
7942 Ok(Some(result.to_boolean()))
7943 }
7944
7945 /// `[[IsExtensible]]` on a proxy.
7946 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7947 let Some((target, handler)) = self.proxy_parts(object)? else {
7948 return Ok(None);
7949 };
7950 let Some(result) = self.proxy_trap(
7951 &handler,
7952 "isExtensible",
7953 vec![Value::Object(target.clone())],
7954 )?
7955 else {
7956 return Ok(Some(self.object_is_extensible(&target)?));
7957 };
7958 // The answer is not the proxy's to invent: it must agree with the target, or a
7959 // script could learn `false` while the target keeps accepting new properties.
7960 if result.to_boolean() != self.object_is_extensible(&target)? {
7961 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7962 }
7963 Ok(Some(result.to_boolean()))
7964 }
7965
7966 /// `[[PreventExtensions]]` on a proxy.
7967 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7968 let Some((target, handler)) = self.proxy_parts(object)? else {
7969 return Ok(None);
7970 };
7971 let Some(result) = self.proxy_trap(
7972 &handler,
7973 "preventExtensions",
7974 vec![Value::Object(target.clone())],
7975 )?
7976 else {
7977 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7978 // its answer can be `false`.
7979 return Ok(Some(self.object_prevent_extensions(&target)?));
7980 };
7981 if result.to_boolean() && self.object_is_extensible(&target)? {
7982 return Err(self.type_error(
7983 "proxy 'preventExtensions' reported success but the target is still extensible",
7984 ));
7985 }
7986 Ok(Some(result.to_boolean()))
7987 }
7988
7989 /// `[[Call]]` on a proxy, through the `apply` trap.
7990 fn proxy_apply(
7991 &mut self,
7992 object: &Gc<JsObject>,
7993 this: Value,
7994 args: Vec<Value>,
7995 ) -> JsResult<Option<Value>> {
7996 let Some((target, handler)) = self.proxy_parts(object)? else {
7997 return Ok(None);
7998 };
7999 // The trap gets the arguments as one array, which is the shape the spec passes
8000 // and the shape `apply` traps are written against (`args[0]` is the first one).
8001 let arguments = self.new_array(args.clone());
8002 let this_for_trap = this.clone();
8003 let Some(result) = self.proxy_trap(
8004 &handler,
8005 "apply",
8006 vec![
8007 Value::Object(target.clone()),
8008 this_for_trap,
8009 Value::Object(arguments),
8010 ],
8011 )?
8012 else {
8013 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
8014 };
8015 Ok(Some(result))
8016 }
8017
8018 /// `[[Construct]]` on a proxy, through the `construct` trap.
8019 fn proxy_construct(
8020 &mut self,
8021 object: &Gc<JsObject>,
8022 args: Vec<Value>,
8023 new_target: &Value,
8024 ) -> JsResult<Option<Value>> {
8025 let Some((target, handler)) = self.proxy_parts(object)? else {
8026 return Ok(None);
8027 };
8028 if !target.is_callable() {
8029 return Err(self.type_error("proxy target is not a constructor"));
8030 }
8031 let arguments = self.new_array(args.clone());
8032 let Some(result) = self.proxy_trap(
8033 &handler,
8034 "construct",
8035 vec![
8036 Value::Object(target.clone()),
8037 Value::Object(arguments),
8038 new_target.clone(),
8039 ],
8040 )?
8041 else {
8042 return Ok(Some(self.construct(
8043 Value::Object(target),
8044 new_target.clone(),
8045 args,
8046 )?));
8047 };
8048 if !matches!(result, Value::Object(_)) {
8049 return Err(self.type_error("proxy 'construct' must return an object"));
8050 }
8051 Ok(Some(result))
8052 }
8053
8054 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
8055 pub(crate) fn has_own_or_inherited(
8056 &mut self,
8057 object: &Gc<JsObject>,
8058 key: &PropertyKey,
8059 ) -> JsResult<bool> {
8060 // The object itself first: it may be a proxy, and then the answer is its trap's.
8061 if let Some(answer) = self.proxy_has(object, key)? {
8062 return Ok(answer);
8063 }
8064 // An integer-indexed exotic object answers a canonical numeric index from
8065 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
8066 // prototype chain. That is observable twice: a view the buffer has been resized
8067 // away from has no indices, so `2 in view` is `false` even when
8068 // `Object.getPrototypeOf(view)[2]` exists (what
8069 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
8070 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
8071 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
8072 // goes through here, which is why the same rule is repeated in `has_property_key`
8073 // rather than living only there.
8074 if object.typed_array_parts().is_some()
8075 && let Some(numeric) = canonical_numeric_index(key)
8076 {
8077 return Ok(typed_array_index_is_valid(object, numeric));
8078 }
8079 // §10.4.6.4 `[[HasProperty]]` asks for the exports list, so a deferred namespace
8080 // evaluates its module here — before the own-key test, because the list is what
8081 // decides the answer. Symbol-like keys are exempt, as everywhere else.
8082 if object.module_namespace_marker() && !Self::is_symbol_like_namespace_key(object, key) {
8083 self.trigger_deferred_namespace(object)?;
8084 }
8085 // A host class answers `in` for its own keys, which may live nowhere in a property
8086 // table — `"x" in point` is true because the class says so, not because a property
8087 // exists.
8088 if let Some(exotic) = object.exotic()
8089 && let Some(answer) = exotic.has_property(self, object, key)?
8090 {
8091 return Ok(answer);
8092 }
8093 // `has_own` rather than `own_property_key`: an array's elements and its derived
8094 // `length` are invisible to the property table, and `Array.prototype` is an array.
8095 // A host class's `get_own_property` counts too, because the reference's
8096 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
8097 // lives — a class with only `get_own_property` answers `in` through it.
8098 if self.exotic_has_own(object, key)? {
8099 return Ok(true);
8100 }
8101 // A hole is *not* the end of the search: the chain may still have the key, which
8102 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
8103 for ancestor in object.chain() {
8104 // A namespace further up the chain is still asked for its exports list, so a
8105 // deferred one evaluates here — `Object.create(ns); key in obj` is the case.
8106 self.trigger_deferred_namespace_for_key(&ancestor, key)?;
8107 // A proxy further up the chain answers for itself.
8108 if let Some(answer) = self.proxy_has(&ancestor, key)? {
8109 return Ok(answer);
8110 }
8111 // Same for a host class: a prototype may be one, and `in` reaches it.
8112 if let Some(exotic) = ancestor.exotic()
8113 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
8114 {
8115 return Ok(answer);
8116 }
8117 if self.exotic_has_own(&ancestor, key)? {
8118 return Ok(true);
8119 }
8120 }
8121 Ok(false)
8122 }
8123
8124 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
8125 /// trap included.
8126 ///
8127 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
8128 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
8129 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
8130 if let Some(exotic) = object.exotic()
8131 && let Some(answer) = exotic.get_own_property(self, object, key)?
8132 {
8133 return Ok(answer.is_some());
8134 }
8135 Ok(has_own(object, key))
8136 }
8137
8138 /// `CreateListFromArrayLike`, optionally restricted to property keys.
8139 ///
8140 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
8141 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
8142 /// `TypeError` instead of a property named `"1.5"`.
8143 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
8144 let object = self.object_from(value)?;
8145 let length = self
8146 .get_property(&object, "length")?
8147 .map(|value| value.to_number())
8148 .unwrap_or(0.0);
8149 if !length.is_finite() || length < 0.0 {
8150 return Err(self.type_error("invalid array-like length"));
8151 }
8152 let length = length as usize;
8153 let mut items = Vec::with_capacity(length.min(1024));
8154 for index in 0..length {
8155 let item = self
8156 .get_property(&object, &index.to_string())?
8157 .unwrap_or(Value::Undefined);
8158 if keys_only && matches!(&item, Value::Symbol(_)) {
8159 items.push(item);
8160 continue;
8161 }
8162 if keys_only && !matches!(&item, Value::String(_)) {
8163 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
8164 }
8165 items.push(item);
8166 }
8167 Ok(items)
8168 }
8169
8170 /// A `Property` from the descriptor object a trap returned.
8171 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
8172 let object = self.object_from(value)?;
8173 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
8174 interp.get_property(&object, name)
8175 };
8176 let getter = field(self, "get")?;
8177 let setter = field(self, "set")?;
8178 let accessor = getter.is_some() || setter.is_some();
8179 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
8180 Ok(interp
8181 .get_property(&object, name)?
8182 .is_some_and(|value| value.to_boolean()))
8183 };
8184 let enumerable = boolean(self, "enumerable")?;
8185 let configurable = boolean(self, "configurable")?;
8186 if accessor {
8187 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
8188 return Err(
8189 self.type_error("a descriptor cannot be both a data property and an accessor")
8190 );
8191 }
8192 Ok(Property {
8193 getter: getter.or(Some(Value::Undefined)),
8194 setter: setter.or(Some(Value::Undefined)),
8195 enumerable,
8196 configurable,
8197 writable: false,
8198 value: None,
8199 descriptor_fields: None,
8200 })
8201 } else {
8202 Ok(Property {
8203 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
8204 writable: boolean(self, "writable")?,
8205 enumerable,
8206 configurable,
8207 getter: None,
8208 setter: None,
8209 descriptor_fields: None,
8210 })
8211 }
8212 }
8213
8214 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
8215 fn descriptor_from_property(&mut self, property: &Property) -> Value {
8216 let object = self.new_object(None);
8217 // A partial descriptor names only some fields, and the trap must see exactly those:
8218 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
8219 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
8220 // case, where every field is present.
8221 let fields = property.descriptor_fields;
8222 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
8223 fields.is_none_or(|fields| field(&fields))
8224 };
8225 if property.is_accessor() {
8226 let getter = property.getter.clone().unwrap_or(Value::Undefined);
8227 let setter = property.setter.clone().unwrap_or(Value::Undefined);
8228 object.define_data("get", getter);
8229 object.define_data("set", setter);
8230 } else {
8231 if names(|fields| fields.value) {
8232 let value = property.value.clone().unwrap_or(Value::Undefined);
8233 object.define_data("value", value);
8234 }
8235 if names(|fields| fields.writable) {
8236 object.define_data("writable", Value::Bool(property.writable));
8237 }
8238 }
8239 if names(|fields| fields.enumerable) {
8240 object.define_data("enumerable", Value::Bool(property.enumerable));
8241 }
8242 if names(|fields| fields.configurable) {
8243 object.define_data("configurable", Value::Bool(property.configurable));
8244 }
8245 Value::Object(object)
8246 }
8247
8248 // -- calling ------------------------------------------------------------
8249
8250 /// Call `callee` with `this` and `args`.
8251 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
8252 let Value::Object(function) = &callee else {
8253 // `typeof x === "function"` is not enough to make `x()` legal: only a
8254 // callable object is. `null` and `undefined` need no special wording
8255 // here — their `ToString` already reads the way the reference's does.
8256 let what = format!("{} is not a function", callee.to_js_string());
8257 return Err(Signal::Throw(self.make_error("TypeError", &what)));
8258 };
8259 // A proxy of a function is called through its `apply` trap. It has no
8260 // `ObjectKind::Function` of its own, so this has to come before the dispatch
8261 // below, and a proxy of a non-function has nothing to forward to.
8262 if function.proxy_state().is_some() {
8263 return match self.proxy_apply(function, this, args)? {
8264 Some(result) => Ok(result),
8265 None => Err(Signal::Throw(
8266 self.make_error("TypeError", "proxy target is not callable"),
8267 )),
8268 };
8269 }
8270 let callable = function.with(|data| match &data.kind {
8271 ObjectKind::Function(callable) => match callable {
8272 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
8273 // The `Rc` is cloned out so the borrow of this object's data is released
8274 // before the closure runs: the closure may touch the same object.
8275 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
8276 Callable::Bound {
8277 target,
8278 this,
8279 args: leading,
8280 } => Some(NativeCall::Bound {
8281 target: target.clone(),
8282 this: this.clone(),
8283 leading: leading.clone(),
8284 }),
8285 Callable::Bytecode { code, env } => {
8286 Some(NativeCall::Bytecode(code.clone(), env.clone()))
8287 }
8288 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
8289 Callable::PromiseResolve(promise) => {
8290 Some(NativeCall::PromiseResolve(promise.clone()))
8291 }
8292 Callable::PromiseReject(promise) => {
8293 Some(NativeCall::PromiseReject(promise.clone()))
8294 }
8295 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8296 state: state.clone(),
8297 }),
8298 Callable::ThenShim {
8299 handler,
8300 resolve,
8301 reject,
8302 fulfilled,
8303 } => Some(NativeCall::ThenShim {
8304 handler: handler.clone(),
8305 resolve: resolve.clone(),
8306 reject: reject.clone(),
8307 fulfilled: *fulfilled,
8308 }),
8309 Callable::AwaitResume {
8310 coroutine,
8311 promise,
8312 kind,
8313 } => Some(NativeCall::AwaitResume {
8314 coroutine: coroutine.clone(),
8315 promise: promise.clone(),
8316 kind: *kind,
8317 }),
8318 Callable::CombinatorSettle {
8319 state,
8320 index,
8321 fulfilled,
8322 } => Some(NativeCall::CombinatorSettle {
8323 state: state.clone(),
8324 index: *index,
8325 fulfilled: *fulfilled,
8326 }),
8327 Callable::FinallyShim {
8328 callback,
8329 fulfilled,
8330 constructor,
8331 } => Some(NativeCall::FinallyShim {
8332 callback: callback.clone(),
8333 fulfilled: *fulfilled,
8334 constructor: constructor.clone(),
8335 }),
8336 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8337 Callable::CompletedReturn {
8338 generator,
8339 promise,
8340 rejected,
8341 } => Some(NativeCall::CompletedReturn {
8342 generator: generator.clone(),
8343 promise: promise.clone(),
8344 rejected: *rejected,
8345 }),
8346 Callable::YieldResult {
8347 generator,
8348 promise,
8349 done,
8350 } => Some(NativeCall::YieldResult {
8351 generator: generator.clone(),
8352 promise: promise.clone(),
8353 done: *done,
8354 }),
8355 Callable::DisposeStep {
8356 remaining,
8357 promise,
8358 error,
8359 rejected,
8360 awaited,
8361 needs_await,
8362 } => Some(NativeCall::DisposeStep {
8363 remaining: remaining.clone(),
8364 promise: promise.clone(),
8365 error: error.clone(),
8366 rejected: *rejected,
8367 awaited: *awaited,
8368 needs_await: *needs_await,
8369 }),
8370 Callable::GeneratorResume {
8371 generator,
8372 promise,
8373 kind,
8374 } => Some(NativeCall::GeneratorResume {
8375 generator: generator.clone(),
8376 promise: promise.clone(),
8377 kind: *kind,
8378 }),
8379 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8380 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8381 Callable::SettlePromise {
8382 promise,
8383 value,
8384 rejected,
8385 } => Some(NativeCall::SettlePromise {
8386 promise: promise.clone(),
8387 value: value.clone(),
8388 rejected: *rejected,
8389 }),
8390 Callable::ModuleEvaluationFulfilled { module } => {
8391 Some(NativeCall::ModuleEvaluationFulfilled {
8392 module: module.clone(),
8393 })
8394 }
8395 Callable::ModuleEvaluationRejected { module } => {
8396 Some(NativeCall::ModuleEvaluationRejected {
8397 module: module.clone(),
8398 })
8399 }
8400 Callable::ModuleNamespaceForImport { module, promise } => {
8401 Some(NativeCall::ModuleNamespaceForImport {
8402 module: module.clone(),
8403 promise: promise.clone(),
8404 })
8405 }
8406 },
8407 _ => None,
8408 });
8409 match callable {
8410 Some(NativeCall::Host(func)) => {
8411 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8412 // function by name rather than stopping at the caller.
8413 let frame_less = function
8414 .own_property("_frame_less")
8415 .and_then(|property| property.value)
8416 .is_some_and(|value| value.to_boolean());
8417 let outer = if frame_less {
8418 None
8419 } else {
8420 self.native_frames
8421 .push((function.clone(), self.frames.len()));
8422 Some(self.current_native.replace(function.clone()))
8423 };
8424 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8425 // constructor reads it through `current_new_target` because it is handed
8426 // `undefined` for `this`. Taking the parked value here is what stops a
8427 // *plain* call made from inside a constructor body from seeing the
8428 // enclosing `new.target`.
8429 let parked = self.pending_new_target.take();
8430 let result = {
8431 let outer_new_target = std::mem::replace(
8432 &mut self.active_new_target,
8433 parked.unwrap_or(Value::Undefined),
8434 );
8435 let result = {
8436 let mut body = func.borrow_mut();
8437 body(self, this, &args)
8438 };
8439 self.active_new_target = outer_new_target;
8440 result
8441 };
8442 if !frame_less {
8443 self.native_frames.pop();
8444 self.current_native = outer.flatten();
8445 }
8446 result
8447 }
8448 Some(NativeCall::Native(func)) => {
8449 // A function marked `_frame_less` is one the reference implements
8450 // without a call frame — `eval` is the only one so far.
8451 let frame_less = function
8452 .own_property("_frame_less")
8453 .and_then(|property| property.value)
8454 .is_some_and(|value| value.to_boolean());
8455 let outer = if frame_less {
8456 None
8457 } else {
8458 self.native_frames
8459 .push((function.clone(), self.frames.len()));
8460 Some(self.current_native.replace(function.clone()))
8461 };
8462 let parked = self.pending_new_target.take();
8463 let outer_new_target = std::mem::replace(
8464 &mut self.active_new_target,
8465 parked.unwrap_or(Value::Undefined),
8466 );
8467 let result = func(self, this, &args);
8468 self.active_new_target = outer_new_target;
8469 if !frame_less {
8470 self.native_frames.pop();
8471 self.current_native = outer.flatten();
8472 }
8473 result
8474 }
8475 Some(NativeCall::Revoker(slots)) => {
8476 // Idempotent: revoking twice answers `undefined` again rather than
8477 // complaining, which is what the spec says and what a `finally` block
8478 // relies on.
8479 let mut state = slots.borrow_mut();
8480 state.target = None;
8481 state.handler = None;
8482 Ok(Value::Undefined)
8483 }
8484 Some(NativeCall::PromiseResolve(promise)) => {
8485 // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8486 // else, so a resolve after a reject does nothing *and* a resolve after a
8487 // resolve-with-thenable does nothing — the promise is still `Pending` then,
8488 // because the adoption is a queued job.
8489 let value = args.first().cloned().unwrap_or(Value::Undefined);
8490 if !self.claim_resolution(&promise) {
8491 return Ok(Value::Undefined);
8492 }
8493 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8494 // the resolve function performs `RejectPromise` and returns `undefined`.
8495 // (`ResolvePromise` itself throws as well, so the engine's own callers see
8496 // it; only this wrapper swallows it.)
8497 let _ = self.resolve_promise_with(&promise, value);
8498 Ok(Value::Undefined)
8499 }
8500 Some(NativeCall::PromiseReject(promise)) => {
8501 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8502 // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8503 if !self.claim_resolution(&promise) {
8504 return Ok(Value::Undefined);
8505 }
8506 self.reject_promise(&promise, reason);
8507 Ok(Value::Undefined)
8508 }
8509 Some(NativeCall::ThenShim {
8510 handler,
8511 resolve,
8512 reject,
8513 fulfilled,
8514 }) => {
8515 // `PerformPromiseThen` with a capability: run the handler, then settle
8516 // through the capability's own pair. A throw from the handler is the
8517 // rejection, and a throw from the capability's `resolve` is not caught —
8518 // exactly the spec's `?`.
8519 let value = args.first().cloned().unwrap_or(Value::Undefined);
8520 match handler {
8521 Some(handler) => {
8522 match self.call_value(handler, Value::Undefined, vec![value]) {
8523 Ok(result) => {
8524 self.call_value(resolve, Value::Undefined, vec![result])?;
8525 }
8526 Err(Signal::Throw(reason)) => {
8527 self.call_value(reject, Value::Undefined, vec![reason])?;
8528 }
8529 Err(signal) => return Err(signal),
8530 }
8531 }
8532 None => {
8533 let handler = if fulfilled { resolve } else { reject };
8534 self.call_value(handler, Value::Undefined, vec![value])?;
8535 }
8536 }
8537 Ok(Value::Undefined)
8538 }
8539 Some(NativeCall::CapabilityExecutor { state }) => {
8540 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8541 // slot holds a value yet. The test is on the *values*, not on a call count —
8542 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8543 // called-twice`'s first case does exactly that), while a second call after a
8544 // real pair is the `TypeError`.
8545 let defined = |name: &str| {
8546 state
8547 .own_property(name)
8548 .and_then(|property| property.value)
8549 .is_some_and(|value| !matches!(value, Value::Undefined))
8550 };
8551 if defined("resolve") || defined("reject") {
8552 return Err(self.type_error("promise capability executor called twice"));
8553 }
8554 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8555 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8556 state.define_data("resolve", resolve);
8557 state.define_data("reject", reject);
8558 Ok(Value::Undefined)
8559 }
8560 Some(NativeCall::CombinatorSettle {
8561 state,
8562 index,
8563 fulfilled,
8564 }) => {
8565 let value = args.first().cloned().unwrap_or(Value::Undefined);
8566 self.settle_combinator(&state, index, fulfilled, value)?;
8567 Ok(Value::Undefined)
8568 }
8569 Some(NativeCall::AwaitResume {
8570 coroutine,
8571 promise,
8572 kind,
8573 }) => {
8574 // Resume *inline*, in the reaction that delivered the value. Deferring it
8575 // by another job inserts a tick between every `await` and its
8576 // continuation, which reorders `await` against unrelated `then` chains —
8577 // `f().then(g)` then runs before `f`'s own next statement.
8578 self.drive_async(
8579 &coroutine,
8580 &promise,
8581 kind,
8582 args.first().cloned().unwrap_or(Value::Undefined),
8583 )
8584 .map(|()| Value::Undefined)
8585 }
8586 Some(NativeCall::ReturnValue(value)) => Ok(value),
8587 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8588 Some(NativeCall::FinallyShim {
8589 callback,
8590 fulfilled,
8591 constructor,
8592 }) => {
8593 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8594 // own value is discarded; what the caller sees is the *original* outcome,
8595 // delayed until `PromiseResolve(C, result)` has settled.
8596 //
8597 // Two details are observable and both have a test:
8598 //
8599 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8600 // `PerformPromiseThen`. A callback that returns a thenable with its own
8601 // `then` must have that `then` called
8602 // (`resolved-observable-then-calls` counts it);
8603 // * only the **fulfil** handler is supplied. A returned promise that
8604 // *rejects* rejects the whole `finally`, rather than having its failure
8605 // swallowed and the original value passed through.
8606 let original = args.first().cloned().unwrap_or(Value::Undefined);
8607 let result = match &callback {
8608 Some(callback) => {
8609 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8610 }
8611 None => Value::Undefined,
8612 };
8613 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8614 // constructor is reused rather than rewrapped, which is what keeps
8615 // `mp1.finally(() => mp2)` from gaining a layer.
8616 let resolved = self.promise_resolve_for(&constructor, result)?;
8617 let thunk = if fulfilled {
8618 Callable::ReturnValue(original)
8619 } else {
8620 Callable::ThrowValue(original)
8621 };
8622 // `length: 0` and `name: ""`, and **not** a constructor — the three things
8623 // `resolved-observable-then-calls-argument` reads off the thunk while it has
8624 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8625 // function with no `length` at all.
8626 let thunk = self.builtin_function("", 0, thunk);
8627 let then = self.read_field(&resolved, "then")?;
8628 if !matches!(&then, Value::Object(object) if object.is_callable()) {
8629 return Err(self.type_error("then is not a function"));
8630 }
8631 self.call_value(then, resolved, vec![Value::Object(thunk)])
8632 }
8633 Some(NativeCall::DisposeStep {
8634 remaining,
8635 promise,
8636 error,
8637 rejected,
8638 awaited,
8639 needs_await,
8640 }) => {
8641 let error = if rejected {
8642 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8643 self.merge_dispose_error(reason, error)
8644 } else {
8645 error
8646 };
8647 self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8648 Ok(Value::Undefined)
8649 }
8650 Some(NativeCall::ModuleBinding(cell)) => {
8651 // §10.4.6.8 `[[Get]]` step 4: a binding that has not been initialised yet
8652 // throws rather than reading `undefined`. A namespace can be observed
8653 // before its module has finished evaluating — a cycle, or
8654 // `Object.freeze(ns)` in the importer — and every read of the still-dead
8655 // `let` must be a `ReferenceError`
8656 // (`module-code/namespace/internals/get-str-found-uninit` and seven
8657 // siblings).
8658 let value = cell.get();
8659 if matches!(value, Value::Uninitialized) {
8660 return Err(Signal::Throw(
8661 self.make_error("ReferenceError", "module binding is not initialized"),
8662 ));
8663 }
8664 Ok(value)
8665 }
8666 Some(NativeCall::CompletedReturn {
8667 generator,
8668 promise,
8669 rejected,
8670 }) => {
8671 let value = args.first().cloned().unwrap_or(Value::Undefined);
8672 let outcome = if rejected {
8673 AsyncOutcome::Error(value)
8674 } else {
8675 AsyncOutcome::Value(self.iterator_result(value, true)?)
8676 };
8677 self.settle_async_request(&generator, &promise, outcome)?;
8678 Ok(Value::Undefined)
8679 }
8680 Some(NativeCall::YieldResult {
8681 generator,
8682 promise,
8683 done,
8684 }) => {
8685 let value = args.first().cloned().unwrap_or(Value::Undefined);
8686 let result = self.iterator_result(value, done)?;
8687 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8688 Ok(Value::Undefined)
8689 }
8690 Some(NativeCall::GeneratorResume {
8691 generator,
8692 promise,
8693 kind,
8694 }) => {
8695 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8696 // tick and reorders the generator against other chains.
8697 self.step_async_generator(
8698 &generator,
8699 &promise,
8700 kind,
8701 args.first().cloned().unwrap_or(Value::Undefined),
8702 )
8703 .map(|()| Value::Undefined)
8704 }
8705 Some(NativeCall::SettlePromise {
8706 promise,
8707 value,
8708 rejected,
8709 }) => {
8710 if rejected {
8711 self.reject_promise(&promise, value);
8712 } else {
8713 self.fulfill_promise(&promise, value);
8714 }
8715 Ok(Value::Undefined)
8716 }
8717 Some(NativeCall::ModuleEvaluationFulfilled { module }) => {
8718 self.async_module_execution_fulfilled(&module)?;
8719 Ok(Value::Undefined)
8720 }
8721 Some(NativeCall::ModuleEvaluationRejected { module }) => {
8722 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8723 self.async_module_execution_rejected_public(&module, reason);
8724 Ok(Value::Undefined)
8725 }
8726 Some(NativeCall::ModuleNamespaceForImport { module, promise }) => {
8727 let namespace = self.module_namespace(&module)?;
8728 self.fulfill_promise(&promise, namespace);
8729 Ok(Value::Undefined)
8730 }
8731 Some(NativeCall::Bound {
8732 target,
8733 this: bound_this,
8734 leading,
8735 }) => {
8736 let mut all = leading;
8737 all.extend(args);
8738 self.call_value(target, bound_this, all)
8739 }
8740 Some(NativeCall::Bytecode(code, env)) => {
8741 if code.code.kind.is_generator() {
8742 return self.new_generator(callee, this, args);
8743 }
8744 if code.code.kind.is_async() {
8745 // Same coroutine machinery as a generator; the difference is only in
8746 // what the completion does — see `new_async_function`.
8747 return self.new_async_function(callee, this, args);
8748 }
8749 self.execute(code, env, this, args, callee)
8750 }
8751 None => Err(Signal::Throw(
8752 self.make_error("TypeError", "not a function"),
8753 )),
8754 }
8755 }
8756
8757 /// Give a freshly built function its own `prototype` object.
8758 ///
8759 /// Every function that can be used with `new` carries one, and its
8760 /// `constructor` points back at the function — a reference cycle, which is
8761 /// exactly what the collector's cycle pass exists to reclaim.
8762 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8763 self.install_function_prototype_with(function, None);
8764 }
8765
8766 /// [`Interp::install_function_prototype`] with an explicit parent for the new
8767 /// `prototype` object.
8768 ///
8769 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8770 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8771 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8772 /// `None` means `%Object.prototype%`.
8773 fn install_function_prototype_with(
8774 &mut self,
8775 function: &Gc<JsObject>,
8776 parent: Option<Gc<JsObject>>,
8777 ) {
8778 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8779 let prototype = self.new_object(Some(parent));
8780 let constructor = Value::Object(function.clone());
8781 prototype.define(
8782 "constructor",
8783 Property::with_attributes(constructor, true, false),
8784 );
8785 let value = Value::Object(prototype);
8786 function.define("prototype", Property::prototype_of(value, true));
8787 }
8788
8789 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8790 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8791 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8792 ///
8793 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8794 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8795 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8796 /// is `[]` there.
8797 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8798 let prototype = self.new_object(Some(parent));
8799 let value = Value::Object(prototype);
8800 function.define("prototype", Property::prototype_of(value, true));
8801 }
8802
8803 /// The `[[Prototype]]` a newly created generator object gets:
8804 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8805 ///
8806 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8807 /// function's `prototype` is writable, so a script can replace it with anything, and
8808 /// only an *object* is consulted.
8809 fn generator_instance_proto(
8810 &mut self,
8811 function: &Gc<JsObject>,
8812 default: Gc<JsObject>,
8813 ) -> JsResult<Gc<JsObject>> {
8814 match self.get_property(function, "prototype")? {
8815 Some(Value::Object(prototype)) => Ok(prototype),
8816 _ => Ok(default),
8817 }
8818 }
8819
8820 /// A getter or setter that reads or writes the reference cell behind a mapped
8821 /// `arguments` index.
8822 ///
8823 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8824 /// count — which is what the collector treats as "a reference from outside the
8825 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8826 /// accessor is reachable, which is the same lifetime the arguments object has.
8827 ///
8828 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8829 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8830 /// parameter value and the arguments object reaches the closure, never the other
8831 /// way round. Nothing the collector has to see is hidden.
8832 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8833 let name = if is_setter { "set" } else { "get" };
8834 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8835 if is_setter {
8836 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8837 Ok(Value::Undefined)
8838 } else {
8839 Ok(cell.get())
8840 }
8841 };
8842 self.new_host_function(name, 1, Box::new(func))
8843 }
8844
8845 /// The object `special_object` builds.
8846 ///
8847 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8848 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8849 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8850 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8851 /// write through `arguments` does not reach the parameter.
8852 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8853 match magic {
8854 0 | 1 => {
8855 let args = self.frame().passed().to_vec();
8856 let proto = self.realm.object_proto.clone();
8857 let object = self.new_object(Some(proto));
8858 // The marker `Object.prototype.toString` needs: an arguments object is an
8859 // ordinary object apart from reporting `[object Arguments]`, and that has
8860 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8861 // show up ahead of them in a key listing anyway — it is non-enumerable.
8862 self.internal_set(&object, "_class", self.string("Arguments"));
8863 // `length` is writable and configurable but neither enumerable nor a
8864 // plain data property: `Object.keys(arguments)` lists the indices only,
8865 // which is how `{...arguments}` copies them without the length.
8866 object.define(
8867 "length",
8868 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8869 );
8870 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8871 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8872 // change `a`, and assigning `a` has to change `arguments[0]`.
8873 //
8874 // The shared storage is the parameter's reference cell. The compiler
8875 // gives every parameter of such a function one (see
8876 // `provide_body_arguments`), and the cell outlives the frame, so this
8877 // keeps working after the arguments object escapes.
8878 //
8879 // The index becomes an accessor rather than a data property. A mapped
8880 // index reports as a plain writable/enumerable data property through
8881 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8882 // the getter/setter pair is only the plumbing underneath.
8883 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8884 let frame = self.frame();
8885 frame
8886 .code
8887 .arg_cell
8888 .iter()
8889 .map(|cell| {
8890 (*cell >= 0)
8891 .then(|| frame.cells.get(*cell as usize).cloned())
8892 .flatten()
8893 })
8894 .collect()
8895 } else {
8896 Vec::new()
8897 };
8898 // Tell the object which indices are mapped, so
8899 // `Object.getOwnPropertyDescriptor` can report them as the data
8900 // properties the spec describes instead of the accessors that
8901 // implement the aliasing.
8902 if magic == 1 {
8903 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8904 for cell in &mapped_cells {
8905 table.push(cell.clone());
8906 }
8907 object.set_mapped_arguments(table);
8908 }
8909 for (index, value) in args.into_iter().enumerate() {
8910 match mapped_cells.get(index).cloned().flatten() {
8911 Some(cell) => {
8912 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8913 let setter = self.new_mapped_arguments_accessor(cell, true);
8914 object.define(
8915 &index.to_string(),
8916 Property::accessor_with(
8917 Some(Value::Object(getter)),
8918 Some(Value::Object(setter)),
8919 true,
8920 ),
8921 );
8922 }
8923 None => object.define_data(&index.to_string(), value),
8924 }
8925 }
8926 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8927 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8928 // non-enumerable and non-configurable. It is not a nicety — it is the only
8929 // documented way to reach `%ThrowTypeError%`:
8930 //
8931 // Object.getOwnPropertyDescriptor(function(){"use strict";
8932 // return arguments;}(), "callee").get
8933 //
8934 // and the whole `ThrowTypeError/` directory is written against that
8935 // expression. Without it 13 cases failed with `cannot read property 'get'
8936 // of undefined`, which reads like a test harness bug rather than a missing
8937 // accessor.
8938 //
8939 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8940 // writable data property holding the function being called, and
8941 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8942 // `hasOwnProperty("callee")` hold there.
8943 if magic == 1 {
8944 let callee = self.frame().callee.clone();
8945 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8946 object.define("callee", Property::with_attributes(callee, true, false));
8947 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8948 && object.own_property("callee").is_none()
8949 {
8950 object.define(
8951 "callee",
8952 Property {
8953 getter: Some(Value::Object(thrower.clone())),
8954 setter: Some(Value::Object(thrower)),
8955 enumerable: false,
8956 configurable: false,
8957 ..Property::default()
8958 },
8959 );
8960 }
8961 // An arguments object is iterable: `[...arguments]` and
8962 // `for (const a of arguments)` both work, through the *array* iterator
8963 // because the object is array-like. Without this the whole spread form
8964 // reported "not iterable".
8965 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8966 let values = self
8967 .realm
8968 .array_proto
8969 .own_property("values")
8970 .and_then(|property| property.value);
8971 if let Some(values) = values {
8972 object.define_key(
8973 &iterator_key,
8974 Property::with_attributes(values, true, false),
8975 );
8976 }
8977 Ok(Value::Object(object))
8978 }
8979 // `this.active_func`: the constructor `super()` resolves against.
8980 //
8981 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8982 // own, so it inherits this from the function it was written in along with `this`
8983 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8984 // the constructor and is called back later (`iter.return = () => super()`) has
8985 // the constructor nowhere on the stack. The compiler therefore reads it out of
8986 // a closure variable of the enclosing function, exactly as the reference does
8987 // with its `this_active_func` local.
8988 2 => Ok(self
8989 .current_callee()
8990 .map_or(Value::Undefined, Value::Object)),
8991 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8992 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8993 // its own either, so the lookup walks out to the nearest non-arrow frame for
8994 // the same reason as `this.active_func` above — without that, `super()` inside
8995 // an arrow passed `undefined` as the new target and the parent constructor was
8996 // then rejected for being invoked without `new`.
8997 3 => Ok(self
8998 .eval_new_target
8999 .clone()
9000 .unwrap_or_else(|| self.frame().new_target.clone())),
9001 // `[[HomeObject]]` of the function being run: what `super` is relative to.
9002 // An arrow has none of its own, so the lookup walks out to the enclosing
9003 // method — which is why `super` works inside an arrow inside a method.
9004 4 => Ok(self
9005 .frames
9006 .iter()
9007 .rev()
9008 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
9009 .map_or(Value::Undefined, Value::Object)),
9010 // `import.meta`: the innermost module body's meta object. Outside a module
9011 // the compiler never emits this, so an empty fallback is unreachable rather
9012 // than permissive.
9013 6 => {
9014 let name = self.module_stack.last().cloned();
9015 let meta = name
9016 .and_then(|name| self.modules.get(&name).cloned())
9017 .and_then(|module| module.with(|r| r.import_meta.clone()));
9018 Ok(meta.map_or(Value::Undefined, Value::Object))
9019 }
9020 other => Err(Signal::Throw(self.make_error(
9021 "InternalError",
9022 &format!("special_object {other} is not implemented yet"),
9023 ))),
9024 }
9025 }
9026
9027 /// `[[HomeObject]]` of the innermost function that has one, if any.
9028 ///
9029 /// An arrow has none, so the search walks out to the enclosing method — the same
9030 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
9031 /// inside a method.
9032 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
9033 self.frames
9034 .iter()
9035 .rev()
9036 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
9037 }
9038
9039 /// The dispose method a `using` declaration should snapshot, or an error.
9040 ///
9041 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
9042 /// is what makes a resource that only knows the synchronous protocol usable in both
9043 /// forms.
9044 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
9045 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
9046 if value.is_nullish() {
9047 return Ok(Value::Undefined);
9048 }
9049 let Some(object) = value.as_object() else {
9050 return Err(self.type_error("not an object"));
9051 };
9052 let mut method = if await_form {
9053 let found = self.get_property_key(
9054 object,
9055 &self.realm.well_known_key(WellKnown::AsyncDisposable),
9056 )?;
9057 match found {
9058 Some(found) if !found.is_nullish() => Some(found),
9059 _ => self
9060 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
9061 }
9062 } else {
9063 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
9064 };
9065 let Some(found) = method.take() else {
9066 return Err(self.type_error("value is not disposable"));
9067 };
9068 if found.is_nullish() {
9069 return Err(self.type_error("value is not disposable"));
9070 }
9071 let callable = found.as_object().is_some_and(|object| object.is_callable());
9072 if !callable {
9073 return Err(self.type_error("dispose method is not a function"));
9074 }
9075 Ok(found)
9076 }
9077
9078 /// Call one resource's disposer, folding a failure into `error_state`.
9079 ///
9080 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
9081 /// because a captured `using` binding lives in its reference cell and the local slot is
9082 /// stale — a closure over the resource is legal and must not change what is disposed.
9083 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
9084 let value = self.get_loc(slot);
9085 let method = self.get_loc(slot + 1);
9086 // A resource that was never initialised — its declaration threw — or that is
9087 // `null`/`undefined` has nothing to dispose.
9088 if value.is_nullish() || matches!(value, Value::Uninitialized) {
9089 return Ok(error_state);
9090 }
9091 if matches!(method, Value::Undefined | Value::Uninitialized) {
9092 return Ok(error_state);
9093 }
9094 match self.call_value(method, value, Vec::new()) {
9095 Ok(_) => Ok(error_state),
9096 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
9097 Err(other) => Err(other),
9098 }
9099 }
9100
9101 /// Combine a disposal failure with whatever was already going wrong.
9102 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
9103 if matches!(error_state, Value::Uninitialized) {
9104 return new_error;
9105 }
9106 self.new_suppressed_error(new_error, error_state)
9107 }
9108
9109 /// A `SuppressedError` instance built straight from its prototype.
9110 ///
9111 /// Not through the constructor: a script that rewrites
9112 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
9113 /// error wrapping.
9114 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
9115 let proto = self
9116 .realm
9117 .suppressed_error_proto
9118 .clone()
9119 .unwrap_or_else(|| self.realm.error_proto.clone());
9120 let object = self.new_object(Some(proto));
9121 object.define("error", Property::with_attributes(error, true, true));
9122 object.define(
9123 "suppressed",
9124 Property::with_attributes(suppressed, true, true),
9125 );
9126 object.define(
9127 "message",
9128 Property::with_attributes(self.string("SuppressedError"), true, true),
9129 );
9130 self.internal_set(&object, "_class", self.string("Error"));
9131 self.add_stack(&object);
9132 Value::Object(object)
9133 }
9134
9135 /// Call `callee`, or push its frame and let the main loop run it.
9136 ///
9137 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
9138 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
9139 /// continues, so `function f(){ return f() }` costs heap and stops at
9140 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
9141 /// is entered directly, and natives do not re-enter JavaScript in this
9142 /// milestone.
9143 ///
9144 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
9145 /// because the returning frame will.
9146 /// The elements of an array-like value, as a call argument list.
9147 ///
9148 /// `apply` accepts any array-like, not only a real array: the reference reads
9149 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
9150 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
9151 ///
9152 /// Used by the paths that take a *length* from script data — the typed-array
9153 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
9154 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
9155 /// `RangeError` rather than a silently clamped count.
9156 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
9157 let number = self.to_js_number(value)?;
9158 if number.is_nan() {
9159 return Ok(0);
9160 }
9161 let number = number.trunc();
9162 if number < 0.0 || number > 9_007_199_254_740_991.0 {
9163 return Err(self.range_error("invalid length"));
9164 }
9165 Ok(number as usize)
9166 }
9167
9168 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
9169 /// other callers that take an argument list from script data.
9170 ///
9171 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
9172 /// constructor and `Array.from` need `ToIndex` instead (see
9173 /// [`Interp::to_index`]), which is why they do not go through here.
9174 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
9175 let Some(object) = value.as_object().cloned() else {
9176 if value.is_nullish() {
9177 // `f.apply(this, null)` passes no arguments at all.
9178 return Ok(Vec::new());
9179 }
9180 return Err(self.type_error("createListFromArrayLike called on non-object"));
9181 };
9182 let length = match self.get_property(&object, "length")? {
9183 Some(length) => length.to_number(),
9184 None => 0.0,
9185 };
9186 if !length.is_finite() || length <= 0.0 {
9187 return Ok(Vec::new());
9188 }
9189 let length = (length as usize).min(1_000_000);
9190 let mut args = Vec::with_capacity(length);
9191 for index in 0..length {
9192 let element = self.get_property(&object, &index.to_string())?;
9193 args.push(element.unwrap_or(Value::Undefined));
9194 }
9195 Ok(args)
9196 }
9197
9198 /// Turn a call to a generator function into a generator object.
9199 ///
9200 /// The frame is built exactly as an ordinary call would build it, then detached and
9201 /// stored in the generator before any body instruction runs — which is what makes
9202 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
9203 /// is `initial_yield`, the first instruction of every suspending body.
9204 pub fn new_generator(
9205 &mut self,
9206 function: Value,
9207 this: Value,
9208 args: Vec<Value>,
9209 ) -> JsResult<Value> {
9210 let Some(object) = function.as_object().cloned() else {
9211 return Err(self.type_error("not a generator function"));
9212 };
9213 let Some((code, env)) = bytecode_of(&object) else {
9214 return Err(self.type_error("not a generator function"));
9215 };
9216 let is_async = code.code.kind.is_async();
9217 self.push_frame(code, env, this, args, function)?;
9218 let frame = self.frames.pop().expect("push_frame just pushed it");
9219 // A fresh generator is *suspended at start*: the body has not run, so a
9220 // `return`/`throw` on it finishes without executing anything.
9221 let mut state = GeneratorState {
9222 frame: Some(frame),
9223 phase: GeneratorPhase::SuspendedStart,
9224 parked_on_await: false,
9225 parked_on_yield_star: false,
9226 requests: std::collections::VecDeque::new(),
9227 async_busy: false,
9228 is_async,
9229 };
9230 // Run to the first suspension. For a generator that is `initial_yield`, so no
9231 // body code runs; for a malformed body it would be the first `yield`.
9232 // An `async function*` answers an async generator: same coroutine, but its
9233 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
9234 let default_proto = if is_async {
9235 self.realm
9236 .async_generator_proto
9237 .clone()
9238 .unwrap_or_else(|| self.realm.generator_proto.clone())
9239 } else {
9240 self.realm.generator_proto.clone()
9241 };
9242 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
9243 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
9244 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
9245 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
9246 let proto = self.generator_instance_proto(&object, default_proto)?;
9247 let generator = self.new_object(Some(proto));
9248 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
9249 Ok(_) => {}
9250 Err(error) => return Err(error),
9251 }
9252 generator.with_mut(|data| {
9253 data.kind = ObjectKind::Generator(Box::new(state));
9254 });
9255 Ok(Value::Object(generator))
9256 }
9257
9258 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9259 ///
9260 /// Returns the `{value, done}` object itself rather than the pair, because a
9261 /// `yield*` suspension already has one — the inner iterator's own result — and the
9262 /// protocol says to hand that straight through rather than nest it.
9263 /// Advance a generator and report *why* it parked.
9264 ///
9265 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
9266 /// "hand this value to the caller" — but an async generator does: an `await` has to
9267 /// settle before it can answer, while a `yield` is the answer.
9268 fn resume_generator_detailed(
9269 &mut self,
9270 generator: &Gc<JsObject>,
9271 kind: ResumeKind,
9272 value: Value,
9273 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9274 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
9275 ObjectKind::Generator(state) => {
9276 let is_async = state.is_async;
9277 Some(std::mem::replace(
9278 state.as_mut(),
9279 GeneratorState {
9280 frame: None,
9281 phase: GeneratorPhase::Executing,
9282 parked_on_await: false,
9283 parked_on_yield_star: false,
9284 requests: std::collections::VecDeque::new(),
9285 // **Busy while the body runs**, so a `next()` called *from inside*
9286 // the body queues instead of being served. §27.6.3.7
9287 // `AsyncGeneratorResumeNext` returns immediately for the state
9288 // "executing", and the request is served once the body suspends;
9289 // with `false` here the re-entrant call found an empty frame and
9290 // rejected (`request-queue-order-state-executing`).
9291 async_busy: is_async,
9292 is_async,
9293 },
9294 ))
9295 }
9296 _ => None,
9297 }) else {
9298 return Err(self.type_error("not a generator"));
9299 };
9300 let result = self.step_generator(&mut state, kind, value);
9301 // Requests queued *while* the body ran live on the placeholder, because the real
9302 // state is out of the object for the duration. They have to be folded back in
9303 // before the placeholder is overwritten, or the promise they carry never settles.
9304 let queued = generator.with_mut(|data| match &mut data.kind {
9305 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
9306 _ => std::collections::VecDeque::new(),
9307 });
9308 state.requests.extend(queued);
9309 generator.with_mut(|data| {
9310 data.kind = ObjectKind::Generator(Box::new(state));
9311 });
9312 result
9313 }
9314
9315 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9316 ///
9317 /// Returns the `{value, done}` object itself rather than the pair, because a
9318 /// `yield*` suspension already has one — the inner iterator's own result — and the
9319 /// protocol says to hand that straight through rather than nest it.
9320 pub fn resume_generator(
9321 &mut self,
9322 generator: &Gc<JsObject>,
9323 kind: ResumeKind,
9324 value: Value,
9325 ) -> JsResult<Value> {
9326 let (value, done, ready, _reason) =
9327 self.resume_generator_detailed(generator, kind, value)?;
9328 if ready {
9329 return Ok(value);
9330 }
9331 self.iterator_result(value, done)
9332 }
9333
9334 /// `next`/`return`/`throw` on an async generator, which answer a promise.
9335 ///
9336 /// The body is the same coroutine a sync generator runs; what changes is that an
9337 /// `await` inside it has to settle before the method can answer, so the step is
9338 /// driven off the job queue rather than returning inline.
9339 pub fn resume_async_generator(
9340 &mut self,
9341 generator: &Gc<JsObject>,
9342 kind: ResumeKind,
9343 value: Value,
9344 ) -> JsResult<Value> {
9345 let promise = self.new_promise();
9346 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9347 // that order, and the second value must reach the *second* `yield`.
9348 let idle = generator.with_mut(|data| match &mut data.kind {
9349 ObjectKind::Generator(state) => {
9350 state.requests.push_back(AsyncRequest {
9351 kind,
9352 value,
9353 promise: promise.clone(),
9354 });
9355 !state.async_busy
9356 }
9357 _ => false,
9358 });
9359 if idle {
9360 self.next_async_request(generator)?;
9361 }
9362 Ok(Value::Object(promise))
9363 }
9364
9365 /// Serve the front queued request, if the generator is free to run one.
9366 ///
9367 /// A finished generator answers from the queue without running anything:
9368 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9369 /// first, and `throw(e)` rejects.
9370 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9371 enum Front {
9372 Idle,
9373 Run(ResumeKind, Value, Gc<JsObject>),
9374 Finished(ResumeKind, Value, Gc<JsObject>),
9375 }
9376 let front = generator.with_mut(|data| match &mut data.kind {
9377 ObjectKind::Generator(state) => {
9378 let Some(request) = state.requests.front() else {
9379 return Front::Idle;
9380 };
9381 // Busy means a request is still in flight — awaiting inside the body, not
9382 // finished. Serving another now would interleave two requests.
9383 if state.async_busy && state.phase != GeneratorPhase::Completed {
9384 return Front::Idle;
9385 }
9386 let kind = request.kind;
9387 let value = request.value.clone();
9388 let promise = request.promise.clone();
9389 state.async_busy = true;
9390 if state.phase == GeneratorPhase::Completed {
9391 Front::Finished(kind, value, promise)
9392 } else {
9393 Front::Run(kind, value, promise)
9394 }
9395 }
9396 _ => Front::Idle,
9397 });
9398 match front {
9399 Front::Idle => Ok(()),
9400 Front::Run(kind, value, promise) => {
9401 self.step_async_generator(generator, &promise, kind, value)
9402 }
9403 Front::Finished(kind, value, promise) => match kind {
9404 ResumeKind::Throw => {
9405 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9406 }
9407 ResumeKind::Next | ResumeKind::Start => {
9408 let result = self.iterator_result(Value::Undefined, true)?;
9409 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9410 }
9411 ResumeKind::Return => {
9412 // `js_async_generator_completed_return`: the value is awaited before it
9413 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9414 // finished generator answers `1`, not a promise.
9415 let resolved = match self.promise_resolve_intrinsic(value) {
9416 Ok(resolved) => resolved,
9417 Err(Signal::Throw(reason)) => {
9418 return self.settle_async_request(
9419 generator,
9420 &promise,
9421 AsyncOutcome::Error(reason),
9422 );
9423 }
9424 Err(other) => return Err(other),
9425 };
9426 let done = JsObject::function(
9427 self.heap,
9428 Some(self.realm.function_proto.clone()),
9429 Callable::CompletedReturn {
9430 generator: generator.clone(),
9431 promise: promise.clone(),
9432 rejected: false,
9433 },
9434 );
9435 let failed = JsObject::function(
9436 self.heap,
9437 Some(self.realm.function_proto.clone()),
9438 Callable::CompletedReturn {
9439 generator: generator.clone(),
9440 promise: promise.clone(),
9441 rejected: true,
9442 },
9443 );
9444 let Value::Object(resolved) = resolved else {
9445 return self.settle_async_request(
9446 generator,
9447 &promise,
9448 AsyncOutcome::Error(Value::Undefined),
9449 );
9450 };
9451 self.perform_then(
9452 &resolved,
9453 Some(Value::Object(done)),
9454 Some(Value::Object(failed)),
9455 )?;
9456 Ok(())
9457 }
9458 },
9459 }
9460 }
9461
9462 /// Settle the front request and start the next one.
9463 ///
9464 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9465 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9466 /// generator would strand every later request.
9467 fn settle_async_request(
9468 &mut self,
9469 generator: &Gc<JsObject>,
9470 promise: &Gc<JsObject>,
9471 outcome: AsyncOutcome,
9472 ) -> JsResult<()> {
9473 let settled = generator.with_mut(|data| match &mut data.kind {
9474 ObjectKind::Generator(state) => {
9475 let front = state.requests.front();
9476 debug_assert!(
9477 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9478 "a request settled outside its turn"
9479 );
9480 state.requests.pop_front();
9481 state.async_busy = false;
9482 true
9483 }
9484 _ => false,
9485 });
9486 if settled {
9487 match outcome {
9488 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9489 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9490 }
9491 }
9492 self.next_async_request(generator)
9493 }
9494
9495 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9496 ///
9497 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9498 /// disposer runs **synchronously** — the reference starts it before returning, which
9499 /// a test can observe by logging after the call — and the rest follow once their
9500 /// predecessor settles.
9501 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9502 let promise = self.new_promise();
9503 // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9504 // any resource at all, because every `await using` resource has the async-dispose
9505 // hint — including the null/undefined ones that have nothing to call. If none of them
9506 // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9507 // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9508 // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9509 let needs_await = !resources.is_empty();
9510 let mut pairs = Vec::with_capacity(resources.len());
9511 for (value, method) in resources {
9512 let pair = self.new_array(vec![value, method]);
9513 pairs.push(Value::Object(pair));
9514 }
9515 let remaining = self.new_array(pairs);
9516 self.dispose_step(
9517 &remaining,
9518 &promise,
9519 Value::Uninitialized,
9520 false,
9521 needs_await,
9522 )?;
9523 Ok(Value::Object(promise))
9524 }
9525
9526 /// One link of the `disposeAsync` chain.
9527 ///
9528 /// Loops while the disposers finish synchronously, and parks on the first thenable it
9529 /// meets — pushing itself back in as the continuation, with the accumulated error
9530 /// carried along so a later failure can still be folded into the `SuppressedError`.
9531 fn dispose_step(
9532 &mut self,
9533 remaining: &Gc<JsObject>,
9534 promise: &Gc<JsObject>,
9535 mut error: Value,
9536 awaited: bool,
9537 needs_await: bool,
9538 ) -> JsResult<()> {
9539 loop {
9540 let length = remaining.array_length().unwrap_or(0);
9541 if length == 0 {
9542 // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9543 // still has to happen. Re-entering this same step past an already-fulfilled
9544 // promise is exactly one tick, and it keeps the folding of `error` in one place.
9545 if needs_await && !awaited {
9546 let finished = self.new_array(Vec::new());
9547 let thunk = JsObject::function(
9548 self.heap,
9549 Some(self.realm.function_proto.clone()),
9550 Callable::DisposeStep {
9551 remaining: finished.clone(),
9552 promise: promise.clone(),
9553 error,
9554 rejected: false,
9555 awaited: true,
9556 needs_await: false,
9557 },
9558 );
9559 let tick = self.promise_resolve_value(Value::Undefined)?;
9560 if let Value::Object(tick) = tick {
9561 self.perform_then(
9562 &tick,
9563 Some(Value::Object(thunk.clone())),
9564 Some(Value::Object(thunk)),
9565 )?;
9566 }
9567 return Ok(());
9568 }
9569 if matches!(error, Value::Uninitialized) {
9570 self.fulfill_promise(promise, Value::Undefined);
9571 } else {
9572 self.reject_promise(promise, error);
9573 }
9574 return Ok(());
9575 }
9576 let Some(Value::Object(pair)) = remaining
9577 .array_get(length - 1)
9578 .filter(|v| !matches!(v, Value::Hole))
9579 else {
9580 remaining.array_truncate(self.heap, length - 1);
9581 continue;
9582 };
9583 remaining.array_truncate(self.heap, length - 1);
9584 let value = pair.array_get(0).unwrap_or(Value::Undefined);
9585 let Some(Value::Object(method)) = pair.array_get(1) else {
9586 continue;
9587 };
9588 if !method.is_callable() {
9589 continue;
9590 }
9591 match self.call_value(Value::Object(method), value, Vec::new()) {
9592 Ok(result) => {
9593 if !self.is_thenable(&result)? {
9594 // Finished synchronously; the next disposer is the next iteration.
9595 continue;
9596 }
9597 let awaited = match self.promise_resolve_value(result) {
9598 Ok(awaited) => awaited,
9599 Err(Signal::Throw(reason)) => {
9600 self.reject_promise(promise, reason);
9601 return Ok(());
9602 }
9603 Err(other) => return Err(other),
9604 };
9605 let Value::Object(awaited) = awaited else {
9606 continue;
9607 };
9608 let ok = JsObject::function(
9609 self.heap,
9610 Some(self.realm.function_proto.clone()),
9611 Callable::DisposeStep {
9612 remaining: remaining.clone(),
9613 promise: promise.clone(),
9614 error: error.clone(),
9615 rejected: false,
9616 awaited: true,
9617 needs_await,
9618 },
9619 );
9620 let failed = JsObject::function(
9621 self.heap,
9622 Some(self.realm.function_proto.clone()),
9623 Callable::DisposeStep {
9624 remaining: remaining.clone(),
9625 promise: promise.clone(),
9626 error,
9627 rejected: true,
9628 awaited: true,
9629 needs_await,
9630 },
9631 );
9632 self.perform_then(
9633 &awaited,
9634 Some(Value::Object(ok)),
9635 Some(Value::Object(failed)),
9636 )?;
9637 return Ok(());
9638 }
9639 Err(Signal::Throw(thrown)) => {
9640 error = self.merge_dispose_error(thrown, error);
9641 }
9642 Err(other) => return Err(other),
9643 }
9644 }
9645 }
9646
9647 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9648 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9649 let Value::Object(object) = value else {
9650 return Ok(false);
9651 };
9652 Ok(matches!(
9653 self.get_property(object, "then")?,
9654 Some(Value::Object(then)) if then.is_callable()
9655 ))
9656 }
9657
9658 /// One step of an async generator, settling `promise` with an `{value, done}` result.
9659 fn step_async_generator(
9660 &mut self,
9661 generator: &Gc<JsObject>,
9662 promise: &Gc<JsObject>,
9663 kind: ResumeKind,
9664 value: Value,
9665 ) -> JsResult<()> {
9666 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9667 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9668 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9669 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9670 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9671 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9672 // out of the same read, one as a rejection and one as a rethrow.
9673 //
9674 // Narrow on purpose: only a value that is *already a promise* is inspected, so
9675 // nothing changes for `return 1` and the extra read is a plain data-property
9676 // lookup on the intrinsic case.
9677 if kind == ResumeKind::Return
9678 && let Value::Object(object) = &value
9679 && self.promise_state(object).is_some()
9680 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9681 {
9682 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9683 }
9684 let stepped = self.resume_generator_detailed(generator, kind, value);
9685 let (value, done, ready, reason) = match stepped {
9686 Ok(stepped) => stepped,
9687 Err(Signal::Throw(reason)) => {
9688 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9689 }
9690 Err(other) => return Err(other),
9691 };
9692 // Only an `await` has to wait before the method can answer.
9693 if !done && reason == Some(SuspendKind::Await) {
9694 let awaited = match self.promise_resolve_value(value) {
9695 Ok(awaited) => awaited,
9696 Err(Signal::Throw(reason)) => {
9697 return self.settle_async_request(
9698 generator,
9699 promise,
9700 AsyncOutcome::Error(reason),
9701 );
9702 }
9703 Err(other) => return Err(other),
9704 };
9705 let Value::Object(awaited) = awaited else {
9706 return Ok(());
9707 };
9708 let resumed = JsObject::function(
9709 self.heap,
9710 Some(self.realm.function_proto.clone()),
9711 Callable::GeneratorResume {
9712 generator: generator.clone(),
9713 promise: promise.clone(),
9714 kind: ResumeKind::Next,
9715 },
9716 );
9717 let raised = JsObject::function(
9718 self.heap,
9719 Some(self.realm.function_proto.clone()),
9720 Callable::GeneratorResume {
9721 generator: generator.clone(),
9722 promise: promise.clone(),
9723 kind: ResumeKind::Throw,
9724 },
9725 );
9726 self.perform_then(
9727 &awaited,
9728 Some(Value::Object(resumed)),
9729 Some(Value::Object(raised)),
9730 )?;
9731 return Ok(());
9732 }
9733 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9734 // completes it — both arrive as the settled value rather than as the promise
9735 // object. A plain value skips the round trip, which is also what keeps `yield 1`
9736 // from costing an extra tick.
9737 let awaits_value = self.is_thenable(&value)?;
9738 if awaits_value {
9739 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9740 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9741 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9742 // no `PromiseResolve` appears, so that path keeps the shortcut.
9743 let awaited = match if done {
9744 self.promise_resolve_intrinsic(value)
9745 } else {
9746 self.promise_resolve_value(value)
9747 } {
9748 Ok(awaited) => awaited,
9749 Err(Signal::Throw(reason)) => {
9750 return self.settle_async_request(
9751 generator,
9752 promise,
9753 AsyncOutcome::Error(reason),
9754 );
9755 }
9756 Err(other) => return Err(other),
9757 };
9758 let Value::Object(awaited) = awaited else {
9759 return Ok(());
9760 };
9761 // A rejected yield throws *at the yield* inside the body, so the rejection
9762 // resumes the generator rather than the method's promise.
9763 let answer = JsObject::function(
9764 self.heap,
9765 Some(self.realm.function_proto.clone()),
9766 Callable::YieldResult {
9767 generator: generator.clone(),
9768 promise: promise.clone(),
9769 done,
9770 },
9771 );
9772 let raise = JsObject::function(
9773 self.heap,
9774 Some(self.realm.function_proto.clone()),
9775 Callable::GeneratorResume {
9776 generator: generator.clone(),
9777 promise: promise.clone(),
9778 kind: ResumeKind::Throw,
9779 },
9780 );
9781 self.perform_then(
9782 &awaited,
9783 Some(Value::Object(answer)),
9784 Some(Value::Object(raise)),
9785 )?;
9786 return Ok(());
9787 }
9788 let result = if ready {
9789 // `yield*` handed back the inner iterator's own result object.
9790 value
9791 } else {
9792 self.iterator_result(value, done)?
9793 };
9794 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9795 }
9796
9797 /// The `{value, done}` object an iterator method answers with.
9798 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9799 let result = self.new_object(Some(self.realm.object_proto.clone()));
9800 result.define_data("value", value);
9801 result.define_data("done", Value::Bool(done));
9802 Ok(Value::Object(result))
9803 }
9804
9805 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9806 fn step_generator(
9807 &mut self,
9808 state: &mut GeneratorState,
9809 kind: ResumeKind,
9810 value: Value,
9811 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9812 match state.phase {
9813 GeneratorPhase::Executing => {
9814 return Err(self.type_error("cannot invoke a running generator"));
9815 }
9816 GeneratorPhase::Completed => {
9817 // A finished generator answers every resumption without running.
9818 return Ok(match kind {
9819 ResumeKind::Throw => return Err(Signal::Throw(value)),
9820 ResumeKind::Return => (value, true, false, None),
9821 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9822 });
9823 }
9824 GeneratorPhase::SuspendedStart => {
9825 if kind != ResumeKind::Next && kind != ResumeKind::Start {
9826 // The body never started, so there is nothing to unwind or return
9827 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9828 state.frame = None;
9829 state.phase = GeneratorPhase::Completed;
9830 return Ok(match kind {
9831 ResumeKind::Throw => return Err(Signal::Throw(value)),
9832 _ => (value, true, false, None),
9833 });
9834 }
9835 }
9836 GeneratorPhase::SuspendedYield => {}
9837 }
9838
9839 let Some(mut frame) = state.frame.take() else {
9840 return Ok((Value::Undefined, true, false, None));
9841 };
9842 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9843 // number that says which method resumed it; the emitted `if_false` branches on
9844 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9845 let mut raised = None;
9846 match kind {
9847 ResumeKind::Next | ResumeKind::Start => {
9848 if state.phase == GeneratorPhase::SuspendedYield {
9849 frame.stack.push(value);
9850 // An `await` resumes with its value alone; only a `yield` gets the
9851 // magic number that says which of `next`/`return` resumed it.
9852 if !state.parked_on_await {
9853 frame.stack.push(Value::Int(RESUME_NEXT));
9854 }
9855 }
9856 }
9857 ResumeKind::Return => {
9858 // A `return` on a not-yet-started generator is handled above, so this is
9859 // always a real resumption.
9860 frame.stack.push(value);
9861 frame.stack.push(Value::Int(RESUME_RETURN));
9862 }
9863 ResumeKind::Throw => {
9864 // At a `yield*` the exception is *data* for the delegation: the compiled
9865 // code resumes with the value and magic `2` and calls the inner iterator's
9866 // `throw`. Everywhere else it is raised at the suspension point, so the
9867 // body's own handler sees it.
9868 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9869 frame.stack.push(value);
9870 frame.stack.push(Value::Int(RESUME_THROW));
9871 } else {
9872 raised = Some(value);
9873 }
9874 }
9875 }
9876 state.phase = GeneratorPhase::Executing;
9877
9878 let depth = self.frames.len();
9879 self.frames.push(frame);
9880 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9881 // happened at the `yield`.
9882 if let Some(mut exception) = raised {
9883 if self.catch_here(&mut exception).is_none() {
9884 self.pop_frame();
9885 state.phase = GeneratorPhase::Completed;
9886 return Err(Signal::Throw(exception));
9887 }
9888 }
9889
9890 // Only the generator's *own* frame ends the generator. The body may call ordinary
9891 // functions, and those push frames of their own: a `Step::Return` from one of them
9892 // is a nested call finishing, not the generator completing. Miscounting that is
9893 // silent — the generator reports the callee's value as its own result and marks
9894 // itself done — so the depth comparison is load-bearing, not defensive.
9895 let own_frame = depth + 1;
9896 loop {
9897 match self.step() {
9898 Ok(Step::Continue) => {}
9899 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9900 let mut frame = self.frames.pop().expect("a frame is live");
9901 // `yield` left the value on the stack; `initial_yield` left nothing.
9902 let yielded = if reason == SuspendKind::Initial {
9903 Value::Undefined
9904 } else {
9905 frame.stack.pop().unwrap_or(Value::Undefined)
9906 };
9907 state.frame = Some(frame);
9908 state.parked_on_await = reason == SuspendKind::Await;
9909 state.parked_on_yield_star =
9910 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9911 state.phase = if reason == SuspendKind::Initial {
9912 GeneratorPhase::SuspendedStart
9913 } else {
9914 GeneratorPhase::SuspendedYield
9915 };
9916 // `yield*` hands the inner iterator's own result object straight
9917 // back, so the caller sees one `{value, done}` rather than a nested
9918 // one — which is why the third field says "already a result".
9919 return Ok((
9920 yielded,
9921 false,
9922 reason == SuspendKind::YieldStar,
9923 Some(reason),
9924 ));
9925 }
9926 Ok(Step::Suspend(_)) => {
9927 // A `yield` in a frame other than the generator's would mean a
9928 // generator body entered as an ordinary call, which
9929 // `call_or_push` prevents.
9930 self.unwind_to(depth);
9931 state.phase = GeneratorPhase::Completed;
9932 return Err(Signal::Throw(self.make_error(
9933 "InternalError",
9934 "a generator body ran as an ordinary call",
9935 )));
9936 }
9937 Ok(Step::Return(value)) => {
9938 self.pop_frame();
9939 if self.frames.len() > depth {
9940 // A nested call finished: hand the value back to its caller and
9941 // keep running the generator body.
9942 self.frames
9943 .last_mut()
9944 .expect("a caller is live")
9945 .stack
9946 .push(value);
9947 continue;
9948 }
9949 state.phase = GeneratorPhase::Completed;
9950 // The reference closes the generator's closure variables here; ours
9951 // live in cells the frame owned, which the drop below releases.
9952 return Ok((value, true, false, None));
9953 }
9954 Err(Signal::Throw(exception)) => {
9955 // The frame that threw gets the first chance to catch, exactly as in
9956 // the ordinary call loop; a frame above the generator's is popped and
9957 // the exception carries on down.
9958 let mut exception = exception;
9959 loop {
9960 if self.frames.len() <= depth {
9961 // The generator's own frame is gone, so nothing here caught it.
9962 state.phase = GeneratorPhase::Completed;
9963 return Err(Signal::Throw(exception));
9964 }
9965 if self.catch_here(&mut exception).is_some() {
9966 break;
9967 }
9968 self.pop_frame();
9969 }
9970 }
9971 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9972 }
9973 }
9974 }
9975
9976 /// Pop frames until `depth` are left, keeping their buffers.
9977 fn unwind_to(&mut self, depth: usize) {
9978 while self.frames.len() > depth {
9979 self.pop_frame();
9980 }
9981 }
9982 fn call_or_push(
9983 &mut self,
9984 callee: Value,
9985 this: Value,
9986 args: Vec<Value>,
9987 ) -> JsResult<Option<Value>> {
9988 if let Value::Object(function) = &callee
9989 && let Some((code, env)) = bytecode_of(function)
9990 {
9991 // Calling a generator function does not run anything: it captures the
9992 // arguments in a frame and hands back the generator object.
9993 if code.code.kind.is_generator() {
9994 return self.new_generator(callee, this, args).map(Some);
9995 }
9996 // An async function answers a promise and runs its body as a coroutine, so it
9997 // takes the same path as a plain call into it.
9998 if code.code.kind.is_async() {
9999 return self.new_async_function(callee, this, args).map(Some);
10000 }
10001 self.push_frame(code, env, this, args, callee)?;
10002 return Ok(None);
10003 }
10004 self.call_value(callee, this, args).map(Some)
10005 }
10006
10007 /// `new callee(args)`.
10008 ///
10009 /// A constructor differs from a plain call in three ways: it gets a fresh object
10010 /// as `this` whose prototype is the constructor's `prototype` property, its
10011 /// return value is *replaced* by that object unless it returns an object itself,
10012 /// and a native constructor is expected to initialise the object it is given
10013 /// rather than build one.
10014 pub fn construct(
10015 &mut self,
10016 callee: Value,
10017 new_target: Value,
10018 args: Vec<Value>,
10019 ) -> JsResult<Value> {
10020 // `new` on a bound function constructs its *target*, prepending the arguments
10021 // the bind fixed and ignoring the bound `this` — a bound function is a
10022 // constructor only when its target is one, and `new` always makes a fresh
10023 // object of the target's prototype rather than reusing the bound receiver.
10024 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
10025 // ran the body with `this === null` and threw on `this.x = a`.
10026 let mut callee = callee;
10027 let mut new_target = new_target;
10028 let mut args = args;
10029 loop {
10030 let Some(object) = callee.as_object().cloned() else {
10031 return Err(Signal::Throw(
10032 self.make_error("TypeError", "not a constructor"),
10033 ));
10034 };
10035 // A proxy of a function constructs through its `construct` trap, and the
10036 // trap's answer is the result directly — no fresh object is made here.
10037 if object.proxy_state().is_some() {
10038 return match self.proxy_construct(&object, args, &new_target)? {
10039 Some(result) => Ok(result),
10040 None => Err(Signal::Throw(
10041 self.make_error("TypeError", "proxy target is not a constructor"),
10042 )),
10043 };
10044 }
10045 // A generator function has no `[[Construct]]`, and the reference names it in
10046 // the message: `new (function* G(){})()` reports "G is not a constructor".
10047 if object.with(|data| match &data.kind {
10048 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
10049 code.code.kind.is_generator()
10050 }
10051 _ => false,
10052 }) {
10053 let name = object
10054 .own_property("name")
10055 .and_then(|property| property.value)
10056 .map(|value| value.to_js_string())
10057 .unwrap_or_default();
10058 return Err(Signal::Throw(
10059 self.make_error("TypeError", &format!("{name} is not a constructor")),
10060 ));
10061 }
10062 let bound = object.with(|data| match &data.kind {
10063 ObjectKind::Function(Callable::Bound {
10064 target,
10065 args: leading,
10066 ..
10067 }) => Some((target.clone(), leading.clone())),
10068 _ => None,
10069 });
10070 let Some((target, leading)) = bound else {
10071 // Not a bound function, so this object is the callee. §7.2.4
10072 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
10073 // refusals above cover only the built-ins the reference also refuses by
10074 // name. Everything else — a method, an arrow, an async function — has no
10075 // `[[Construct]]` either, and answering "yes" here made
10076 // `new (Array.prototype.map)` build an object instead of throwing.
10077 if !object.is_constructor() {
10078 let name = object
10079 .own_property("name")
10080 .and_then(|property| property.value)
10081 .map(|value| value.to_js_string())
10082 .unwrap_or_default();
10083 return Err(Signal::Throw(
10084 self.make_error("TypeError", &format!("{name} is not a constructor")),
10085 ));
10086 }
10087 break;
10088 };
10089 let mut all = leading;
10090 all.extend(args);
10091 args = all;
10092 // A bound function that is its own `new.target` stands in for its target:
10093 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
10094 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
10095 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
10096 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
10097 _ => false,
10098 };
10099 if same_wrapper {
10100 new_target = target.clone();
10101 }
10102 callee = target;
10103 }
10104 let Value::Object(function) = &callee else {
10105 unreachable!("the loop above only breaks on an object");
10106 };
10107 // The fresh object's prototype comes from `new.target`, not from the callee: a
10108 // derived constructor reaches here through `super()`, and the instance must be a
10109 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
10110 // an object inheriting `D.prototype` rather than `C.prototype`.
10111 let prototype_source = match new_target.as_object() {
10112 Some(target) => target.clone(),
10113 None => function.clone(),
10114 };
10115 // A native constructor builds its own instance, through `new_ctor_instance`, once it
10116 // has validated its arguments. Pre-building one here would read
10117 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
10118 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
10119 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
10120 let is_native = function.native_creates_own_instance();
10121 let this = if is_native {
10122 Value::Undefined
10123 } else {
10124 let prototype = self.get_property(&prototype_source, "prototype")?;
10125 let prototype = match prototype {
10126 Some(Value::Object(proto)) => Some(proto),
10127 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
10128 // object, the answer is the realm's *intrinsic* prototype for this
10129 // constructor, not `%Object.prototype%`.
10130 _ => {
10131 // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
10132 // and that is a `TypeError` for a revoked proxy. Without it, `new
10133 // revokedProxy()` quietly produced an `%Object.prototype%` instance —
10134 // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
10135 // trap, so it is already revoked when this fallback runs.
10136 if prototype_source.proxy_state().is_some() {
10137 self.proxy_parts(&prototype_source)?;
10138 }
10139 let fallback = self.get_property(function, "prototype")?;
10140 match fallback {
10141 Some(Value::Object(proto)) => Some(proto),
10142 _ => Some(self.realm.object_proto.clone()),
10143 }
10144 }
10145 };
10146 Value::Object(self.new_object(prototype))
10147 };
10148 // `new.target` inside the body is the constructor that was written, so a bound
10149 // function's target sees itself rather than the bound wrapper.
10150 //
10151 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
10152 // `?`, so assigning `None` after the call would be skipped and the failed
10153 // `new.target` would stay visible to every later native call. The symptom was a
10154 // native constructor refusing a plain call — `var s = Symbol(); new
10155 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
10156 // "FinalizationRegistry is not a constructor".
10157 let outer_new_target = self.pending_new_target.replace(new_target);
10158 let callee = callee.clone();
10159 let result = self.call_value(callee, this.clone(), args);
10160 self.pending_new_target = outer_new_target;
10161 let result = result?;
10162 // A constructor that returns an object overrides `this`; any other return value
10163 // (including `undefined`) is ignored — **except** in a derived constructor, where
10164 // §15.7.1 step 12 makes a non-object return a `TypeError`
10165 // (`Function/internals/Construct/derived-return-val`).
10166 let derived = function.with(|data| match &data.kind {
10167 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
10168 code.code.is_derived_constructor
10169 }
10170 _ => false,
10171 });
10172 Ok(match result {
10173 Value::Object(_) => result,
10174 // A bare `return;` answers `undefined`, which is **legal** even in a derived
10175 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
10176 Value::Undefined => this,
10177 _ if derived => {
10178 return Err(Signal::Throw(self.make_error(
10179 "TypeError",
10180 "derived constructor may only return an object or undefined",
10181 )));
10182 }
10183 _ => this,
10184 })
10185 }
10186
10187 /// `new.target` for the call currently being made.
10188 ///
10189 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
10190 /// it as `this`), but a *host* constructor that builds its own instance is handed
10191 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
10192 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
10193 /// it here.
10194 ///
10195 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
10196 /// receives for a plain call.
10197 pub fn current_new_target(&self) -> Value {
10198 self.active_new_target.clone()
10199 }
10200
10201 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
10202 ///
10203 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
10204 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
10205 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
10206 let constructor = self.realm.errors.get("AggregateError").cloned();
10207 let Some(constructor) = constructor else {
10208 return self.make_error("AggregateError", message);
10209 };
10210 let list = self.new_array(errors);
10211 match self.construct(
10212 Value::Object(constructor.clone()),
10213 Value::Object(constructor),
10214 vec![Value::Object(list), self.string(message)],
10215 ) {
10216 Ok(value) => value,
10217 // A user could have replaced `AggregateError` with something that throws; the
10218 // engine still owes the caller a rejection, so it falls back rather than
10219 // turning `Promise.any`'s rejection into a throw.
10220 Err(_) => self.make_error("AggregateError", message),
10221 }
10222 }
10223
10224 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
10225 ///
10226 /// The error classes themselves arrive with the builtins milestone; what
10227 /// matters here is that the thrown value stringifies the way a script printing
10228 /// the caught value expects.
10229 ///
10230 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
10231 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
10232 /// rely on when they print a caught value.
10233 pub fn make_error(&self, name: &str, message: &str) -> Value {
10234 let proto = self
10235 .realm
10236 .errors
10237 .get(name)
10238 .map(|constructor| self.prototype_of(constructor))
10239 .unwrap_or_else(|| self.realm.error_proto.clone());
10240 let error = self.new_object(Some(proto));
10241 // `name` and `message` are own properties of the instance, which is what
10242 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
10243 // `Error`.
10244 error.define(
10245 "name",
10246 Property::with_attributes(self.string(name), true, false),
10247 );
10248 error.define(
10249 "message",
10250 Property::with_attributes(self.string(message), true, false),
10251 );
10252 // The internal class, which is what tells a printer this is an error rather than a
10253 // plain object with `name` and `message` properties. The constructor path sets it
10254 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
10255 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
10256 // literally `"Error"` in both places — the *name* is read from `name`, which is why
10257 // a `RangeError` still prints as `RangeError`.
10258 self.internal_set(&error, "_class", self.string("Error"));
10259 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
10260 // answered `false` from `Error.isError` while a constructed one answered `true`,
10261 // because only the constructor set the slot. The reference answers `true` for both
10262 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
10263 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
10264 // tests `typeof stack === "string"` to decide on a trailing newline, so every
10265 // engine-thrown error lost its blank line.
10266 self.internal_set(&error, "_error_data", Value::Bool(true));
10267 // The trace is captured where the error is *made*, which is where the reference
10268 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
10269 // way out, so a caught engine error already has its stack even if the handler
10270 // never rethrows it.
10271 self.add_stack(&error);
10272 Value::Object(error)
10273 }
10274
10275 /// Give an error object its `stack` property, from the current frame stack.
10276 ///
10277 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
10278 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
10279 /// `stack` a script set, is not rewritten.
10280 pub fn add_stack(&self, object: &Gc<JsObject>) {
10281 self.add_stack_skipping(object, 0);
10282 }
10283
10284 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
10285 ///
10286 /// An `Error` constructor passes 1: the reference builds those traces with
10287 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
10288 /// constructor itself, while a `RangeError` raised inside `toISOString` does
10289 /// report `at toISOString (native)`.
10290 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
10291 if object.has_own("stack") {
10292 return;
10293 }
10294 // The trace is *captured* here but not installed as a property: `stack` is an
10295 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
10296 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
10297 // is kept in a hidden slot and the getter materialises it on first read.
10298 //
10299 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
10300 // shows it — this is the same discipline `_error_data` and `_class` follow.
10301 let trace = self.stack_trace_skipping(skip);
10302 let text = self.string(trace);
10303 self.internal_set(object, "_stack_trace", text);
10304 }
10305
10306 /// The function object currently being called, if any.
10307 ///
10308 /// A native function is a bare `fn` pointer, so it cannot capture which class
10309 /// it belongs to; it reads that from the callee instead. This is also what a
10310 /// stack trace would use.
10311 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
10312 // A native has no frame of its own — it is recorded in `current_native` — so asking
10313 // `frames` answered with the *bytecode caller's* callee. `Error`'s constructor reads
10314 // the class off this, and every plain call therefore built an `Error`:
10315 // `EvalError(1)` had the name `"Error"` (`try/S12.14_A19_T1`).
10316 //
10317 // Only while the native is the innermost thing running. It stays recorded while the
10318 // native drives *through* user code — `Iterator.prototype.take` calls the `next` a
10319 // script wrote — and answering with it there gave that user code the native's callee:
10320 // `super()` looked up the native's prototype instead of its own constructor's.
10321 // `native_frames` records `frames.len()` from before the native ran, so an equal
10322 // length means nothing has been pushed since.
10323 if let Some(native) = &self.current_native
10324 && self
10325 .native_frames
10326 .last()
10327 .is_some_and(|(_, depth)| *depth == self.frames.len())
10328 {
10329 return Some(native.clone());
10330 }
10331 match &self.frames.last()?.callee {
10332 Value::Object(object) => Some(object.clone()),
10333 _ => None,
10334 }
10335 }
10336
10337 /// The `prototype` property of a constructor, falling back to
10338 /// `Object.prototype` for anything that is not shaped like one.
10339 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
10340 constructor
10341 .own_property("prototype")
10342 .and_then(|property| property.value)
10343 .and_then(|value| value.as_object().cloned())
10344 .unwrap_or_else(|| self.realm.object_proto.clone())
10345 }
10346
10347 /// Throw a `TypeError` carrying `message`.
10348 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
10349 Signal::Throw(self.make_error("TypeError", message.as_ref()))
10350 }
10351
10352 /// Throw a `RangeError` carrying `message`.
10353 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
10354 Signal::Throw(self.make_error("RangeError", message.as_ref()))
10355 }
10356
10357 /// A `ReferenceError`, as the value to throw.
10358 ///
10359 /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10360 /// and its siblings report a `ReferenceError` there, which is what
10361 /// `adopt|defer|move/throws-if-disposed` assert.
10362 pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10363 Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10364 }
10365
10366 /// The `ReferenceError` a read of an uninitialised binding raises.
10367 /// The name of the binding `slot` refers to, for an error message.
10368 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10369 match kind {
10370 VarSlot::Loc => self
10371 .frame()
10372 .code
10373 .code
10374 .vars
10375 .get(slot)
10376 .map(|v| v.name.clone()),
10377 VarSlot::Closure => self
10378 .frame()
10379 .code
10380 .code
10381 .closure_vars
10382 .get(slot)
10383 .map(|c| c.name.clone()),
10384 }
10385 .unwrap_or_default()
10386 }
10387
10388 /// Whether `slot` names a `const` binding, which rejects every store after its
10389 /// initialiser.
10390 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10391 match kind {
10392 VarSlot::Loc => self
10393 .frame()
10394 .code
10395 .code
10396 .vars
10397 .get(slot)
10398 .is_some_and(|v| v.is_const),
10399 VarSlot::Closure => self
10400 .frame()
10401 .code
10402 .code
10403 .closure_vars
10404 .get(slot)
10405 .is_some_and(|c| c.is_const),
10406 }
10407 }
10408
10409 /// The `TypeError` a store to a `const` binding raises.
10410 ///
10411 /// `const` is enforced here rather than at compile time because the binding can be
10412 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10413 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10414 /// both halves of what "checked store" means: the dead zone is over, and the
10415 /// binding is writable.
10416 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10417 let name = self.binding_name(slot, kind);
10418 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10419 }
10420
10421 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10422 let name = match kind {
10423 VarSlot::Loc => self
10424 .frame()
10425 .code
10426 .code
10427 .vars
10428 .get(slot)
10429 .map(|v| v.name.clone()),
10430 VarSlot::Closure => self
10431 .frame()
10432 .code
10433 .code
10434 .closure_vars
10435 .get(slot)
10436 .map(|c| c.name.clone()),
10437 }
10438 .unwrap_or_default();
10439 // The reference has a wording of its own for `this`, because the dead zone it sits
10440 // in is the derived constructor's rather than a `let`'s: `constructor(){ return; }`
10441 // reports `this is not initialized`.
10442 let message = if name == "this" {
10443 "this is not initialized".to_string()
10444 } else {
10445 format!("cannot access '{name}' before initialization")
10446 };
10447 Signal::Throw(self.make_error("ReferenceError", &message))
10448 }
10449
10450 /// The reference a `make_*_ref` opcode builds, from the object it produced.
10451 fn reference_target(&mut self, offset: usize) -> JsResult<RefTarget> {
10452 match self.peek(offset) {
10453 Value::Object(object) => object.reference().ok_or_else(|| {
10454 self.type_error("a reference operation on something that is not a reference")
10455 }),
10456 _ => Err(self.type_error("a reference operation on a non-object")),
10457 }
10458 }
10459
10460 /// `ResolveBinding(name)` for a name the compiler could only resolve statically as "a
10461 /// global".
10462 ///
10463 /// Three answers, in the order §9.1.1.4 asks them:
10464 ///
10465 /// * a local a direct `eval` declared in this frame — the innermost variable
10466 /// environment, so it wins;
10467 /// * an existing global binding or an existing property of the global object;
10468 /// * nothing, which is an **unresolvable** reference (base `undefined`) rather than a
10469 /// failure: reading it throws and a sloppy write creates the global.
10470 fn global_reference(&mut self, name: &crate::value::Wtf8) -> JsResult<RefTarget> {
10471 if let Some((local_vars, phase)) = self.visible_local_vars() {
10472 let key = name.to_string_lossy();
10473 if local_vars.contains(&key)
10474 && let Some(cell) = local_vars.get(&key, phase)
10475 {
10476 return Ok(RefTarget::Cell(cell));
10477 }
10478 }
10479 let key = PropertyKey::String(name.clone());
10480 let global = self.realm.global.clone();
10481 let has = self.has_own_or_inherited(&global, &key)?;
10482 Ok(RefTarget::Property {
10483 base: if has {
10484 Value::Object(global)
10485 } else {
10486 Value::Undefined
10487 },
10488 name: key,
10489 })
10490 }
10491
10492 fn throw_reference(&self, name: &str) -> Signal {
10493 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10494 }
10495
10496 // -- the instruction loop -----------------------------------------------
10497
10498 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10499 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10500 // measured at 16% of a tight arithmetic loop's total time.
10501 #[inline(always)]
10502 fn step(&mut self) -> JsResult<Step> {
10503 // The instruction is already decoded (see [`crate::insn`]), so this is an index
10504 // and a `Copy` read rather than a table lookup plus a width switch. Only the
10505 // borrow lives across the boundary; nothing is cloned.
10506 // **One** borrow of the frame: fetch the record, then advance in the same scope.
10507 // The obvious version borrowed it three times (`last` to read, `last_mut` to
10508 // write, and once more inside the handler), and each is a bounds check plus an
10509 // `Option` unwrap — on the one path every instruction takes.
10510 let Some((insn, next)) = ({
10511 let frame = self
10512 .frames
10513 .last_mut()
10514 .expect("step() is only called with a live frame");
10515 // Past the last instruction is a normal return: the compiler ends a function
10516 // with `return`, and a jump to the end of a block lands here.
10517 let insn = frame.insns().get(frame.pc).copied();
10518 match insn {
10519 None => None,
10520 Some(insn) => {
10521 // A fused record stands for the next few instructions, so the next
10522 // `pc` is its width ahead — the instructions it replaces are never
10523 // dispatched. `at` is the byte offset a stack trace reports; it stays
10524 // an offset because the line table is keyed by bytes.
10525 frame.at = insn.offset as usize;
10526 frame.pc += insn.width();
10527 Some((insn, frame.pc))
10528 }
10529 }
10530 }) else {
10531 return Ok(Step::Return(Value::Undefined));
10532 };
10533 self.check_memory()?;
10534 self.check_interrupt()?;
10535 if insn.fused == crate::insn::Fused::None {
10536 self.execute_instruction(insn.op, insn.a, insn.b, next)
10537 } else {
10538 self.execute_fused(insn)
10539 }
10540 }
10541
10542 /// Run a fused instruction: several bytecode instructions in one dispatch.
10543 ///
10544 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10545 /// it cannot throw and cannot allocate — and anything else falls back to the real
10546 /// instructions, in their real order, so an exception leaves the operand stack
10547 /// exactly as it would have been.
10548 #[inline]
10549 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10550 use crate::insn::Fused;
10551 let slot = insn.a as usize;
10552 match insn.fused {
10553 // `x = k`: `push k; put_loc x`.
10554 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10555 // `x += k`: `get_loc x; push k; add; put_loc x`.
10556 Fused::AddImmLoc => {
10557 let delta = insn.b as i32;
10558 match self.get_loc(slot) {
10559 Value::Int(left) => {
10560 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10561 // that built two `Value`s, called a function, and matched on them
10562 // again to reach this same `checked_add`. It is the innermost
10563 // operation of every accumulator in every program.
10564 let answer = match left.checked_add(delta) {
10565 Some(sum) => Value::Int(sum),
10566 None => Value::Float(left as f64 + delta as f64),
10567 };
10568 self.put_loc(slot, answer);
10569 }
10570 other => {
10571 self.push(other);
10572 self.push(Value::Int(delta));
10573 self.binary_add()?;
10574 let value = self.pop();
10575 self.put_loc(slot, value);
10576 }
10577 }
10578 }
10579 // `x += "literal"` and `x += y`: the two shapes that can append in place.
10580 Fused::AddAtomLoc => {
10581 let text = self.atom_wtf8(insn.b as usize);
10582 let right = self.string_wtf8(text);
10583 self.add_into_loc(slot, right)?;
10584 }
10585 Fused::AddLocLoc => {
10586 let source = (insn.a & 0xFFFF) as usize;
10587 let target = (insn.a >> 16) as usize;
10588 let right = self.get_loc(source);
10589 self.add_into_loc(target, right)?;
10590 }
10591 Fused::AddArgLoc => {
10592 let source = (insn.a & 0xFFFF) as usize;
10593 let target = (insn.a >> 16) as usize;
10594 let right = self.get_arg(source);
10595 self.add_into_loc(target, right)?;
10596 }
10597 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10598 Fused::PostIncLoc => match self.get_loc(slot) {
10599 Value::Int(left) => {
10600 let answer = match left.checked_add(1) {
10601 Some(sum) => Value::Int(sum),
10602 None => Value::Float(left as f64 + 1.0),
10603 };
10604 self.put_loc(slot, answer);
10605 }
10606 other => {
10607 self.push(other);
10608 let raw = self.pop();
10609 let (old, updated) = self.advance_numeric(raw, true)?;
10610 self.push(old);
10611 self.push(updated);
10612 let value = self.pop();
10613 self.put_loc(slot, value);
10614 self.pop();
10615 }
10616 },
10617 // `if (!(x < arg)) goto target`: a loop header.
10618 //
10619 // The comparison is computed rather than replayed on the operand stack. That
10620 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10621 // that throws: the effects happen in the same order, and a handler truncates
10622 // the stack down to its marker, so the intermediate values are unobservable.
10623 Fused::LtLocArgJump => {
10624 let loc = (insn.a >> 16) as usize;
10625 let arg = (insn.a & 0xFFFF) as usize;
10626 let left = self.get_loc(loc);
10627 let right = self.get_arg(arg);
10628 let taken = match (&left, &right) {
10629 (Value::Int(left), Value::Int(right)) => !(left < right),
10630 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10631 };
10632 if taken {
10633 self.frame_mut().pc = insn.b as usize;
10634 }
10635 }
10636 // `i < k` in a loop header, where `k` is an integer literal.
10637 Fused::LtLocImmJump => {
10638 let left = self.get_loc(insn.a as usize);
10639 let right = Value::Int(insn.imm as i32);
10640 let taken = match &left {
10641 Value::Int(left) => !(*left < insn.imm as i32),
10642 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10643 };
10644 if taken {
10645 self.frame_mut().pc = insn.b as usize;
10646 }
10647 }
10648 Fused::None => unreachable!("only called for a fused record"),
10649 }
10650 Ok(Step::Continue)
10651 }
10652
10653 /// Run records that cannot call script, cannot throw and cannot change frames.
10654 ///
10655 /// Returns `Some(value)` when the function ran off the end of its instructions (a
10656 /// normal return), and `None` when it stopped in front of an instruction the slow path
10657 /// has to handle — `pc` is written back either way, so `step` resumes at the right
10658 /// place.
10659 ///
10660 /// **The invariant is the whole point.** Every arm here is restricted to work that
10661 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10662 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10663 /// that the memory limit has to see. An opcode whose operands turn out to need any of
10664 /// that **stops the loop** instead of trying, so the slow path gets the instruction
10665 /// untouched and with its operands still on the stack. That is why the fallback is a
10666 /// `break` and not a duplicated slow arm: a second implementation of the same
10667 /// semantics is how a wrong answer gets in with no test noticing.
10668 ///
10669 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10670 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10671 fn run_fast(&mut self) -> JsResult<Option<Value>> {
10672 use crate::insn::Fused;
10673 // The outer loop exists only so a `Call` can come back through here: once a
10674 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10675 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10676 // frame. Re-entering re-reads both from whichever frame is now on top. Every
10677 // other exit from the inner loop returns, so this costs one loop per call.
10678 'outer: loop {
10679 // One reference-count bump per *slow* instruction (a call, an allocation, a
10680 // property access), never one per instruction — that distinction is worth
10681 // two orders of magnitude and was measured as such.
10682 let (code, mut pc) = {
10683 let frame = self.frame();
10684 (frame.code.clone(), frame.pc)
10685 };
10686 let insns = &code.insns;
10687 loop {
10688 let Some(insn) = insns.get(pc).copied() else {
10689 self.frame_mut().pc = pc;
10690 return Ok(Some(Value::Undefined));
10691 };
10692 match insn.fused {
10693 // `x = k`
10694 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10695 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10696 // object — stops the loop so `binary_add` can decide.
10697 Fused::AddImmLoc => {
10698 let slot = insn.a as usize;
10699 let delta = insn.b as i32;
10700 let Value::Int(left) = self.get_loc(slot) else {
10701 return Ok(self.stop(pc));
10702 };
10703 let sum = match left.checked_add(delta) {
10704 Some(sum) => Value::Int(sum),
10705 None => Value::Float(left as f64 + delta as f64),
10706 };
10707 self.put_loc(slot, sum);
10708 }
10709 // `x += "literal"` / `x += y`: the operand is a string, so the append
10710 // either allocates one or grows one. Both are the slow path's business;
10711 // the fusion's job is only to make the *slot* the sole owner, which is what
10712 // `execute_fused` needs and what `get_loc` alone destroys.
10713 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10714 return Ok(self.stop(pc));
10715 }
10716 // `x++` on an integer, old value dropped.
10717 Fused::PostIncLoc => {
10718 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10719 // value is read in place and overwritten in place, so the reference
10720 // count it held is released by the same assignment that stores the
10721 // new one. `get_loc` plus `put_loc` did two borrows, two table
10722 // lookups and a clone, and this arm is the whole body of a counting
10723 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10724 let slot = insn.a as usize;
10725 let frame = self.frames.last_mut().expect("a frame is live");
10726 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10727 let target = if cell < 0 {
10728 frame.locals.get_mut(slot)
10729 } else {
10730 None
10731 };
10732 let Some(target) = target else {
10733 return Ok(self.stop(pc));
10734 };
10735 let Value::Int(left) = *target else {
10736 return Ok(self.stop(pc));
10737 };
10738 *target = match left.checked_add(1) {
10739 Some(sum) => Value::Int(sum),
10740 None => Value::Float(left as f64 + 1.0),
10741 };
10742 }
10743 // A loop header, `if (!(x < arg)) goto target`, with both sides already
10744 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10745 // bound stayed small integers.
10746 Fused::LtLocArgJump => {
10747 let loc = (insn.a >> 16) as usize;
10748 let arg = (insn.a & 0xFFFF) as usize;
10749 // One borrow for both slots: this arm *is* the whole loop of a
10750 // `for (i = 0; i < n; i++)` with an argument bound, so a second
10751 // `frames.last()` here is paid on every iteration. Measured 7.5% on
10752 // `dispatch:empty-loop`.
10753 let (left, right) = {
10754 let frame = self.frame();
10755 (frame.read_loc(loc), frame.read_arg(arg))
10756 };
10757 // Heavily measured: the bound is very often a `Float` even when the
10758 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10759 // `JSON.parse` or a division is one — so requiring both sides to be
10760 // `Int` sent every iteration of those loops down the slow path. The
10761 // comparison below is the same one `relational` makes for two numbers.
10762 if !is_number(&left) || !is_number(&right) {
10763 return Ok(self.stop(pc));
10764 }
10765 // `if_false` branches on the comparison being false, which is **not**
10766 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10767 // `>=` is also false and would keep it running forever. Clippy wants the
10768 // negation folded; that would be a wrong answer.
10769 let ordered = left.to_number() < right.to_number();
10770 let take_branch = !ordered;
10771 if take_branch {
10772 pc = insn.b as usize;
10773 continue;
10774 }
10775 }
10776 // The same header with a literal bound: `if (!(x < k)) goto target`.
10777 // The bound is an immediate, so only the counter needs a type test.
10778 #[allow(clippy::neg_cmp_op_on_partial_ord)]
10779 Fused::LtLocImmJump => {
10780 let left = self.get_loc(insn.a as usize);
10781 if !is_number(&left) {
10782 return Ok(self.stop(pc));
10783 }
10784 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10785 if take_branch {
10786 pc = insn.b as usize;
10787 continue;
10788 }
10789 }
10790 Fused::None => match insn.op {
10791 // -- branches ---------------------------------------------------
10792 // A jump is an assignment now, because the target is an instruction
10793 // index. No arithmetic, no resolution table.
10794 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10795 let target = insn.a as usize;
10796 // A **back-edge** is a loop, and it is the only place an
10797 // instruction-level checkpoint can stop one: `for(;;){}` compiles
10798 // to a jump to itself and never leaves this loop, so the
10799 // per-instruction checks in `step` never run. That is exactly the
10800 // hole this arm closes — a host's `JS_SetInterruptHandler` did
10801 // nothing to a `for(;;){}` until it did, which is what
10802 // `tests/c/embed.c` is for.
10803 //
10804 // Polling here rather than on every instruction in this loop is
10805 // also the reference's choice (`OP_goto` calls
10806 // `js_poll_interrupts`), and it costs one compare per branch
10807 // instead of one decrement per instruction.
10808 if target <= pc {
10809 self.frame_mut().pc = target;
10810 self.check_memory()?;
10811 self.check_interrupt()?;
10812 }
10813 pc = target;
10814 continue;
10815 }
10816 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10817 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10818 let taken = self.pop().to_boolean();
10819 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10820 if taken == want {
10821 pc = insn.a as usize;
10822 continue;
10823 }
10824 }
10825 // -- slot access -------------------------------------------------
10826 // A load's slot is already an operand (see `insn::implicit_operand`);
10827 // a captured one goes through its cell, which runs no script.
10828 Opcode::GetLoc
10829 | Opcode::GetLoc8
10830 | Opcode::GetLoc0
10831 | Opcode::GetLoc1
10832 | Opcode::GetLoc2
10833 | Opcode::GetLoc3 => {
10834 let value = self.get_loc(insn.a as usize);
10835 self.push(value);
10836 }
10837 Opcode::PutLoc
10838 | Opcode::PutLoc8
10839 | Opcode::PutLoc0
10840 | Opcode::PutLoc1
10841 | Opcode::PutLoc2
10842 | Opcode::PutLoc3 => {
10843 let value = self.pop();
10844 self.put_loc(insn.a as usize, value);
10845 }
10846 Opcode::GetArg
10847 | Opcode::GetArg0
10848 | Opcode::GetArg1
10849 | Opcode::GetArg2
10850 | Opcode::GetArg3 => {
10851 let value = self.get_arg(insn.a as usize);
10852 self.push(value);
10853 }
10854 Opcode::PutArg
10855 | Opcode::PutArg0
10856 | Opcode::PutArg1
10857 | Opcode::PutArg2
10858 | Opcode::PutArg3 => {
10859 let value = self.pop();
10860 self.put_arg(insn.a as usize, value);
10861 }
10862 // `a[i]` with an integer index on a dense array: see `fast_array_get`
10863 // for why a non-hole own element is exactly the slow path's answer.
10864 // The two operands are *peeked*, so a miss leaves the stack as the
10865 // slow path expects to find it.
10866 Opcode::GetArrayEl => {
10867 // One lookup, not two. The guard used `if …is_some()` and the arm
10868 // then called it again to get the value — two `peek`s, two
10869 // `array_get`s and two `Value` clones for one element.
10870 // `fast_array_get` was 13.1% of `array:indexed`, and the same
10871 // double call was the first version of the `get_field` fast path.
10872 let Some(value) = self.fast_array_get() else {
10873 return Ok(self.stop(pc));
10874 };
10875 // `a[i]` consumes both operands and leaves the element in their
10876 // place: one `truncate` and one write, no `pop`/`push` pair.
10877 let frame = self.frame_mut();
10878 frame.stack.truncate(frame.stack.len() - 2);
10879 frame.stack.push(value);
10880 }
10881 // `a[i] = v` on a dense array with an integer index: see
10882 // `fast_array_set` for why the whole store is one step.
10883 Opcode::PutArrayEl if self.fast_array_set() => {}
10884 // `o.x` resolved from the inline cache without leaving the loop.
10885 //
10886 // The cache is keyed by `(receiver identity, atom, site)` and a
10887 // monomorphic read re-validates the same chain every iteration, so
10888 // each one used to cost a `stop(pc)` — a write of `pc` into the
10889 // frame, a return out of this loop, a re-dispatch through `step` and
10890 // a re-entry. `property:monomorphic` spent 18% in
10891 // `read_field_cached` and 21% in `push`, both across that boundary.
10892 //
10893 // The site is `pc + width`, which is exactly the `next` the slow arm
10894 // passes — the two must agree or every fast lookup misses and
10895 // re-records the same entry forever.
10896 //
10897 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10898 // slow arm finds the receiver where it expects it.
10899 // `name` resolved from the global-variable cache inside the loop.
10900 //
10901 // Same shape as `get_field` above and for the same reason: `get_var`
10902 // was not in the fast loop, so reading a global — which `fib` does
10903 // once per recursive call, for its own name — cost a `stop(pc)`, a
10904 // return out of the loop, a `step` re-dispatch and a re-entry, before
10905 // `get_global` even started its `scopes_are_plain` checks.
10906 //
10907 // Everything here is exactly `get_global`'s first branch: not lexical,
10908 // no `eval` scope, cache hit. Anything else leaves the stack untouched
10909 // and lets the slow arm decide.
10910 Opcode::GetVar => {
10911 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10912 return Ok(self.stop(pc));
10913 };
10914 self.push(value);
10915 }
10916 Opcode::GetField | Opcode::GetField2 => {
10917 let Some(value) =
10918 self.fast_field_get(insn.a as usize, pc + insn.width())
10919 else {
10920 return Ok(self.stop(pc));
10921 };
10922 if insn.op == Opcode::GetField2 {
10923 // `get_field2` keeps the receiver for the `call_method` that
10924 // follows.
10925 self.push(value);
10926 } else {
10927 // `get_field` replaces the receiver, so this is one store over
10928 // the top slot rather than a `pop` and a `push`: the length
10929 // never changes, so neither `Vec` arm has a capacity check or a
10930 // drop to run beyond the one the overwrite itself does.
10931 let frame = self.frame_mut();
10932 match frame.stack.last_mut() {
10933 Some(slot) => *slot = value,
10934 None => return Ok(self.stop(pc)),
10935 }
10936 }
10937 }
10938 // -- constants ---------------------------------------------------
10939 Opcode::PushMinus1
10940 | Opcode::Push0
10941 | Opcode::Push1
10942 | Opcode::Push2
10943 | Opcode::Push3
10944 | Opcode::Push4
10945 | Opcode::Push5
10946 | Opcode::Push6
10947 | Opcode::Push7
10948 | Opcode::PushI8
10949 | Opcode::PushI16
10950 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10951 // -- stack shuffling ---------------------------------------------
10952 Opcode::Drop => {
10953 self.pop();
10954 }
10955 // -- arithmetic on two integers ----------------------------------
10956 //
10957 // The operands are *looked at* before they are popped, so a non-integer
10958 // pair leaves the stack exactly as the slow path expects to find it.
10959 Opcode::Add if self.numeric_pair() => {
10960 let right = self.pop();
10961 let left = self.pop();
10962 // Exactly [`add_numbers`], which is what the slow arm reaches.
10963 let answer = match (&left, &right) {
10964 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10965 Some(sum) => Value::Int(sum),
10966 None => Value::Float(*a as f64 + *b as f64),
10967 },
10968 _ => Value::Float(left.to_number() + right.to_number()),
10969 };
10970 self.push(answer);
10971 }
10972 Opcode::Sub
10973 | Opcode::And
10974 | Opcode::Or
10975 | Opcode::Xor
10976 | Opcode::Shl
10977 | Opcode::Sar
10978 | Opcode::Shr
10979 if self.numeric_pair() =>
10980 {
10981 let right = self.pop();
10982 let left = self.pop();
10983 let answer =
10984 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10985 self.push(answer);
10986 }
10987 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10988 if self.numeric_pair() =>
10989 {
10990 let right = self.pop();
10991 let left = self.pop();
10992 let answer = self
10993 .relational(insn.op, left, right)
10994 .expect("numbers cannot throw");
10995 self.push(answer);
10996 }
10997 // -- calls -------------------------------------------------------
10998 //
10999 // A plain call: `callee(arg0, …, argN) -> result`.
11000 //
11001 // This arm exists because of one measurement. `call:recursion` had
11002 // **20.4% of its profile in `execute_instruction`** — the *slow*
11003 // executor — and `fib`'s recursive call is the only thing in that
11004 // function which is not a fast arm. Every call therefore left this
11005 // loop via `stop()`, went through `step()`'s dispatch and
11006 // `execute_instruction`'s match over every opcode, and came back here
11007 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
11008 //
11009 // Two things make it safe to do here rather than only in the slow path:
11010 //
11011 // * the caller's `pc` is stored *before* the call, which is what
11012 // `step` does too — so when the callee returns, the caller resumes
11013 // after the call and not at it;
11014 // * `check_memory` runs, because `step` calls it once per instruction
11015 // and a call allocates a frame, its locals and its cells. Skipping
11016 // the checkpoint here would let a `--memory-limit` script overshoot
11017 // by one call per instruction.
11018 Opcode::Call
11019 | Opcode::Call0
11020 | Opcode::Call1
11021 | Opcode::Call2
11022 | Opcode::Call3 => {
11023 let argc = self.argc_operand(insn.op, insn.a);
11024 let next = pc + insn.width();
11025 {
11026 let frame = self
11027 .frames
11028 .last_mut()
11029 .expect("run_fast() is only called with a live frame");
11030 // `at` is what a stack trace reports for this frame, so a throw
11031 // inside the callee has to see the call site and not whatever
11032 // the last `stop()` left there.
11033 frame.at = insn.offset as usize;
11034 frame.pc = next;
11035 }
11036 self.check_memory()?;
11037 self.check_interrupt()?;
11038 let args = self.pop_n(argc);
11039 let callee = self.pop();
11040 // A plain call has no receiver; the callee decides what to do with
11041 // `undefined` (a sloppy function substitutes the global object).
11042 if let Some(result) =
11043 self.call_or_push(callee, Value::Undefined, args)?
11044 {
11045 // Native, host, generator, async, bound — no frame was pushed,
11046 // so this loop is still describing the right function. `pc`
11047 // is advanced by the loop tail like every other arm; only the
11048 // frame's copy had to be written here, and it already was.
11049 self.push(result);
11050 } else {
11051 // A bytecode callee: its frame is on top now, and `insns` and
11052 // `pc` both belong to the caller. Start over on the new frame.
11053 continue 'outer;
11054 }
11055 }
11056 // -- return ------------------------------------------------------
11057 Opcode::Return => {
11058 let value = self.pop();
11059 self.frame_mut().pc = pc + insn.width();
11060 return Ok(Some(value));
11061 }
11062 Opcode::ReturnUndef => {
11063 self.frame_mut().pc = pc + insn.width();
11064 return Ok(Some(Value::Undefined));
11065 }
11066 // Everything else needs the slow path.
11067 _ => return Ok(self.stop(pc)),
11068 },
11069 }
11070 pc += insn.width();
11071 }
11072 }
11073 }
11074
11075 /// Whether the top two operand-stack values are both numbers.
11076 ///
11077 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
11078 /// cannot run script, so the arm may not throw and may not change frames.
11079 fn numeric_pair(&self) -> bool {
11080 is_number(&self.peek(0)) && is_number(&self.peek(1))
11081 }
11082
11083 /// `a[i]` for a dense array and an integer index, without the string round trip.
11084 ///
11085 /// The slow path answers this by turning `i` into a string (`propkey` →
11086 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
11087 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
11088 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
11089 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
11090 /// without even the cheap `Int` formatting.
11091 ///
11092 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
11093 /// unambiguously the one the slow path would give:
11094 ///
11095 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
11096 /// `2^32-1` is the length, not an index),
11097 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
11098 /// typed array or an ordinary object, all of which have their own rules),
11099 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
11100 /// starts walking the prototype chain, and `a[i]` on a hole must find
11101 /// `Array.prototype[i]` if it exists rather than `undefined`.
11102 ///
11103 /// The last condition is the one that makes this safe rather than merely fast: an own
11104 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
11105 /// `get_var` answered from the global-variable cache, or `None`.
11106 ///
11107 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
11108 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
11109 /// records nothing — the slow arm is about to walk the chain and record it.
11110 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
11111 let frame = self.frame();
11112 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
11113 // "Lexical" is presence in the realm's table, not the closure var's flag: a
11114 // `GlobalRef` forwarded through a nested function has its flags cleared.
11115 if self.realm.globals.contains_key(name) {
11116 return None;
11117 }
11118 if !self.scopes_are_plain() {
11119 return None;
11120 }
11121 let object = &self.realm.global;
11122 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
11123 let cached = self.global_cache[site].as_ref()?;
11124 if !object.upgrades_to(&cached.object) {
11125 return None;
11126 }
11127 object.data_property_at(cached.index, name)
11128 }
11129
11130 /// `o.x` answered entirely from the inline cache, or `None`.
11131 ///
11132 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
11133 /// about to do exactly that and recording it twice would rebuild the chain for every
11134 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
11135 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
11136 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
11137 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
11138 // an object receiver is a reference-count bump that the answer never needs.
11139 let frame = self.frame();
11140 let object = frame.stack.last()?;
11141 let Value::Object(target) = object else {
11142 return None;
11143 };
11144 // A proxy traps the lookup, so no cache entry ever describes it.
11145 if target.proxy_state().is_some() {
11146 return None;
11147 }
11148 let key = frame.code.atom_keys.get(atom)?;
11149 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
11150 if cached.key != *key {
11151 return None;
11152 }
11153 Self::cached_hit(target, cached)
11154 }
11155
11156 fn fast_array_get(&self) -> Option<Value> {
11157 let Value::Int(index) = self.peek(0) else {
11158 return None;
11159 };
11160 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
11161 // set for an `i32`.
11162 if index < 0 {
11163 return None;
11164 }
11165 let Value::Object(object) = self.peek(1) else {
11166 return None;
11167 };
11168 match object.array_get(index as usize) {
11169 Some(value) if !matches!(value, Value::Hole) => Some(value),
11170 _ => None,
11171 }
11172 }
11173
11174 /// `a[i] = v` on a dense array with an integer index, as one store.
11175 ///
11176 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
11177 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
11178 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
11179 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
11180 /// reference at the time it was measured (14.7x).
11181 ///
11182 /// Every condition here is one the slow path would also have to satisfy before
11183 /// storing into the element vector:
11184 ///
11185 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
11186 /// accepts as an index;
11187 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
11188 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
11189 /// one inside a recorded descriptor, reports `false` and the caller stops.
11190 ///
11191 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
11192 /// writes the own element too once `array_set` says it did.
11193 fn fast_array_set(&mut self) -> bool {
11194 // Every test runs *before* anything is popped: a refusal has to leave the stack
11195 // exactly as the slow path expects to find it. Popping first and reporting the
11196 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
11197 // then ran the slow path with nothing to write.
11198 let Value::Int(index) = self.peek(1) else {
11199 return false;
11200 };
11201 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
11202 if index < 0 {
11203 return false;
11204 }
11205 // Only a real array: a typed array's elements live in its buffer, a string-like
11206 // object has no element vector, and `array_set` on either does nothing.
11207 let Value::Object(object) = self.peek(2) else {
11208 return false;
11209 };
11210 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
11211 return false;
11212 }
11213 // A non-extensible array reports `false` here, but the *slow* path has to decide
11214 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
11215 // that with the key and the stack still intact.
11216 if !object.is_extensible() {
11217 return false;
11218 }
11219 // Inside the logical length, so the store cannot change `length`. Combined with
11220 // extensibility above, the only growth left for `array_set` is filling a hole in
11221 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
11222 // shape this fast path exists for. A store past the length would grow the array,
11223 // and whether that is allowed is the slow path's question.
11224 if index as usize >= object.array_length().unwrap_or(0) {
11225 return false;
11226 }
11227 // Only an *own element* can take the inline store. A hole is not an own property,
11228 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
11229 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
11230 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
11231 // the one case this path used to swallow.
11232 //
11233 // The cost is small: `array:indexed` only reads after a 64-element fill, and
11234 // `array:push` appends past the length, which this path already refused.
11235 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
11236 {
11237 return false;
11238 }
11239 // The bound `array_set` refuses past. Checking it here keeps that arm from having
11240 // to report a failure after the operands are gone.
11241 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
11242 return false;
11243 }
11244 let value = self.pop();
11245 self.pop();
11246 self.pop();
11247 object.array_store(self.heap, index as usize, value)
11248 }
11249
11250 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
11251 fn stop(&mut self, pc: usize) -> Option<Value> {
11252 self.frame_mut().pc = pc;
11253 None
11254 }
11255
11256 fn push(&mut self, value: Value) {
11257 self.frame_mut().stack.push(value);
11258 }
11259
11260 fn pop(&mut self) -> Value {
11261 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
11262 }
11263
11264 fn pop_n(&mut self, count: usize) -> Vec<Value> {
11265 let frame = self.frame_mut();
11266 let start = frame.stack.len().saturating_sub(count);
11267 frame.stack.split_off(start)
11268 }
11269
11270 fn peek(&self, back: usize) -> Value {
11271 let frame = self.frame();
11272 frame
11273 .stack
11274 .get(frame.stack.len().wrapping_sub(1 + back))
11275 .cloned()
11276 .unwrap_or(Value::Undefined)
11277 }
11278
11279 #[allow(clippy::too_many_lines)]
11280 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
11281 use Opcode::*;
11282 match op {
11283 // -- constants and stack shuffling -----------------------------
11284 Nop => {}
11285 PushMinus1 => self.push(Value::Int(-1)),
11286 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
11287 let value = match op {
11288 Push0 => 0,
11289 Push1 => 1,
11290 Push2 => 2,
11291 Push3 => 3,
11292 Push4 => 4,
11293 Push5 => 5,
11294 Push6 => 6,
11295 _ => 7,
11296 };
11297 self.push(Value::Int(value));
11298 }
11299 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
11300 PushBigintI32 => {
11301 // The immediate form of a `BigInt` literal; the reference has the same
11302 // split between this and a constant-pool entry.
11303 let value = crate::bigint::BigInt::from_i64(a as i64);
11304 self.push(self.bigint(value));
11305 }
11306 PushTrue => self.push(Value::Bool(true)),
11307 PushFalse => self.push(Value::Bool(false)),
11308 PushEmptyString => self.push(self.string("")),
11309 Undefined => self.push(Value::Undefined),
11310 Null => self.push(Value::Null),
11311 Object => {
11312 let proto = self.realm.object_proto.clone();
11313 self.push(Value::Object(self.new_object(Some(proto))));
11314 }
11315 PushThis => {
11316 let this = self.frame().this.clone();
11317 self.push(this);
11318 }
11319 PushConst | PushConst8 => {
11320 let value = self.constant(a as usize)?;
11321 self.push(value);
11322 }
11323 PushAtomValue => {
11324 let text = self.atom_wtf8(a as usize);
11325 self.push(self.string_wtf8(text));
11326 }
11327 Dup => {
11328 let value = self.peek(0);
11329 self.push(value);
11330 }
11331 Dup2 => {
11332 // `a b -> a b a b`
11333 let b = self.peek(0);
11334 let a = self.peek(1);
11335 self.push(a);
11336 self.push(b);
11337 }
11338 Dup3 => {
11339 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
11340 // prototype and key while reading the current value through them.
11341 let c = self.peek(0);
11342 let b = self.peek(1);
11343 let a = self.peek(2);
11344 self.push(a);
11345 self.push(b);
11346 self.push(c);
11347 }
11348 Swap => {
11349 // `a b -> b a`
11350 let bottom = self.pop();
11351 let top = self.pop();
11352 self.push(bottom);
11353 self.push(top);
11354 }
11355 Perm3 => {
11356 // `a b c -> b a c`, the reference's reordering for a spread method
11357 // call: `obj func array` becomes the `func this array` that `apply`
11358 // takes.
11359 let c = self.pop();
11360 let b = self.pop();
11361 let a = self.pop();
11362 self.push(b);
11363 self.push(a);
11364 self.push(c);
11365 }
11366 Dup1 => {
11367 let value = self.peek(1);
11368 self.push(value);
11369 }
11370 Drop => {
11371 self.pop();
11372 }
11373 Nip => {
11374 // `a b -> b`
11375 let top = self.pop();
11376 self.pop();
11377 self.push(top);
11378 }
11379 Perm4 => {
11380 // `obj prop a b -> a obj prop b`, the reference's reordering for a
11381 // postfix update of a computed element: it puts the *old* value
11382 // underneath the receiver and key so `put_array_el` can consume them
11383 // and leave the old value as the expression's result.
11384 let d = self.pop();
11385 let c = self.pop();
11386 let b = self.pop();
11387 let a = self.pop();
11388 self.push(c);
11389 self.push(a);
11390 self.push(b);
11391 self.push(d);
11392 }
11393 Insert2 => {
11394 // `obj a -> a obj a`
11395 let value = self.pop();
11396 let object = self.pop();
11397 self.push(value.clone());
11398 self.push(object);
11399 self.push(value);
11400 }
11401 Insert3 => {
11402 // `obj prop a -> a obj prop a`
11403 let value = self.pop();
11404 let key = self.pop();
11405 let object = self.pop();
11406 self.push(value.clone());
11407 self.push(object);
11408 self.push(key);
11409 self.push(value);
11410 }
11411 Insert4 => {
11412 // `this obj prop a -> a this obj prop a`
11413 //
11414 // `put_super_value` consumes all four and yields nothing, so the copy
11415 // underneath is what leaves the assignment an expression value.
11416 let value = self.pop();
11417 let key = self.pop();
11418 let object = self.pop();
11419 let receiver = self.pop();
11420 self.push(value.clone());
11421 self.push(receiver);
11422 self.push(object);
11423 self.push(key);
11424 self.push(value);
11425 }
11426 Swap2 => {
11427 // `a b c d -> c d a b`
11428 let d = self.pop();
11429 let c = self.pop();
11430 let b = self.pop();
11431 let a = self.pop();
11432 self.push(c);
11433 self.push(d);
11434 self.push(a);
11435 self.push(b);
11436 }
11437 Rot3l => {
11438 // `x a b -> a b x`
11439 let b = self.pop();
11440 let a = self.pop();
11441 let x = self.pop();
11442 self.push(a);
11443 self.push(b);
11444 self.push(x);
11445 }
11446 Rot3r => {
11447 // `a b c -> c a b`
11448 let c = self.pop();
11449 let b = self.pop();
11450 let a_value = self.pop();
11451 self.push(c);
11452 self.push(a_value);
11453 self.push(b);
11454 }
11455
11456 Rest => {
11457 // `...rest` in a parameter list: the arguments from index `a` on, as a
11458 // real array. It takes nothing off the stack — the arguments are in the
11459 // frame, not on it.
11460 let frame = self.frame();
11461 let from = a as usize;
11462 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11463 let array = self.new_array(collected);
11464 self.push(Value::Object(array));
11465 }
11466
11467 // -- slots ------------------------------------------------------
11468 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11469 let slot = self.slot_operand(op, a);
11470 let value = self.get_loc(slot);
11471 self.push(value);
11472 }
11473 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11474 let slot = self.slot_operand(op, a);
11475 let value = self.pop();
11476 self.put_loc(slot, value);
11477 }
11478 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11479 let slot = self.slot_operand(op, a);
11480 let value = self.pop();
11481 self.put_loc(slot, value.clone());
11482 self.push(value);
11483 }
11484 // The `_check` forms are the temporal dead zone: they throw when the
11485 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11486 // *reads*, so only the two writes may pop — mishandling that quietly
11487 // consumes the value the caller pushed just before.
11488 GetLocCheck => {
11489 let slot = self.slot_operand(op, a);
11490 let value = self.get_loc(slot);
11491 if matches!(value, Value::Uninitialized) {
11492 return Err(self.dead_zone(slot, VarSlot::Loc));
11493 }
11494 self.push(value);
11495 }
11496 PutLocCheck | SetLocCheck => {
11497 let slot = self.slot_operand(op, a);
11498 let value = self.pop();
11499 // The dead zone is a property of the **slot**, not of the value being
11500 // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11501 // initialised yet. Testing the value instead — which is never
11502 // `Uninitialized` in practice — let every such store through, so the check
11503 // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11504 // (`get_loc_check`) were already asking the slot, which is why
11505 // `print(x); let x` threw while `x = 1; let x` did not.
11506 if matches!(self.get_loc(slot), Value::Uninitialized) {
11507 return Err(self.dead_zone(slot, VarSlot::Loc));
11508 }
11509 // The initialiser goes through `put_loc`, not this, so any store that
11510 // reaches here is a later assignment — which a `const` refuses.
11511 if self.is_read_only(slot, VarSlot::Loc) {
11512 return Err(self.read_only(slot, VarSlot::Loc));
11513 }
11514 if op == SetLocCheck {
11515 self.put_loc(slot, value.clone());
11516 self.push(value);
11517 } else {
11518 self.put_loc(slot, value);
11519 }
11520 }
11521 PutLocCheckInit => {
11522 // The one store that *initialises* a lexical slot: `this` in a derived
11523 // constructor, which only exists after `super()` has run. A second
11524 // initialisation is the error the reference reports as
11525 // "'this' can be initialized only once".
11526 let slot = self.slot_operand(op, a);
11527 let value = self.pop();
11528 if !matches!(self.get_loc(slot), Value::Uninitialized) {
11529 return Err(Signal::Throw(self.make_error(
11530 "ReferenceError",
11531 "'this' can be initialized only once",
11532 )));
11533 }
11534 self.put_loc(slot, value);
11535 }
11536 CheckCtor => {
11537 // A class constructor may only run under `new`, which is what makes
11538 // `class A {}; A()` a TypeError.
11539 if matches!(self.frame().new_target, Value::Undefined) {
11540 return Err(Signal::Throw(self.make_error(
11541 "TypeError",
11542 "class constructors must be invoked with 'new'",
11543 )));
11544 }
11545 }
11546 InitCtor => {
11547 // The body a derived class gets when it declares no constructor:
11548 // forward every argument to the parent constructor, keeping `new.target`.
11549 if matches!(self.frame().new_target, Value::Undefined) {
11550 return Err(Signal::Throw(self.make_error(
11551 "TypeError",
11552 "class constructors must be invoked with 'new'",
11553 )));
11554 }
11555 let Some(callee) = self.current_callee() else {
11556 return Err(Signal::Throw(
11557 self.make_error("TypeError", "no constructor to inherit from"),
11558 ));
11559 };
11560 let parent = callee.proto().map_or(Value::Null, Value::Object);
11561 let new_target = self.frame().new_target.clone();
11562 let args = self.frame().passed().to_vec();
11563 let result = self.construct(parent, new_target, args)?;
11564 self.push(result);
11565 }
11566 SetLocUninitialized => {
11567 let slot = self.slot_operand(op, a);
11568 self.put_loc(slot, Value::Uninitialized);
11569 }
11570 CloseLoc => {
11571 // "Close" a binding: give it a *fresh* cell holding the current
11572 // value. Closures created before this point keep the old cell and the
11573 // ones created after see the new one, which is what makes every
11574 // iteration of `for (let i ...)` capture its own `i`, and what freezes
11575 // a block-scoped binding when the block ends.
11576 //
11577 // Clearing the slot instead (which this used to do) broke both: a
11578 // closure over a captured block variable read `undefined`, and a loop
11579 // terminated after one iteration.
11580 let slot = self.slot_operand(op, a);
11581 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11582 if index >= 0 {
11583 let current = self.frame().cells[index as usize].get();
11584 let fresh = self.new_cell(current);
11585 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11586 *cell = fresh;
11587 }
11588 }
11589 }
11590 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11591 let slot = self.slot_operand(op, a);
11592 let value = self.get_arg(slot);
11593 self.push(value);
11594 }
11595 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11596 let slot = self.slot_operand(op, a);
11597 let value = self.pop();
11598 self.put_arg(slot, value);
11599 }
11600 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11601 let slot = self.slot_operand(op, a);
11602 let value = self.pop();
11603 self.put_arg(slot, value.clone());
11604 self.push(value);
11605 }
11606
11607 // -- closure variables ------------------------------------------
11608 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11609 let slot = self.slot_operand(op, a);
11610 // A name a direct `eval` created shadows the binding the compiler chose.
11611 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11612 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11613 // and only a runtime lookup can know that.
11614 if let Some(cell) = self.eval_created_local(slot) {
11615 self.push(cell.get());
11616 return self.step();
11617 }
11618 let value = self.cell_value(slot)?;
11619 self.push(value);
11620 }
11621 GetVarRefCheck => {
11622 let slot = self.slot_operand(op, a);
11623 let value = self.cell_value(slot)?;
11624 if matches!(value, Value::Uninitialized) {
11625 return Err(self.dead_zone(slot, VarSlot::Closure));
11626 }
11627 self.push(value);
11628 }
11629 PutVarRefCheckInit => {
11630 // The captured-form twin of `PutLocCheckInit`. Both exist because `super()`
11631 // may be written inside an arrow, and there `this` is a var-ref rather than
11632 // a local.
11633 let slot = self.slot_operand(op, a);
11634 let value = self.pop();
11635 // The wording differs from the local form because the reference reaches
11636 // this case through `get_var_ref_checkthis`, which reports the dead zone
11637 // rather than the double initialisation.
11638 if !matches!(self.cell_value(slot)?, Value::Uninitialized) {
11639 return Err(Signal::Throw(
11640 self.make_error("ReferenceError", "this is not initialized"),
11641 ));
11642 }
11643 self.set_cell(slot, value)?;
11644 }
11645 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11646 let slot = self.slot_operand(op, a);
11647 let value = self.pop();
11648 if let Some(cell) = self.eval_created_local(slot) {
11649 cell.set(value);
11650 return self.step();
11651 }
11652 // Same two rules as `PutLocCheck`: a checked store to a captured binding
11653 // asks the cell about the dead zone, then refuses a `const` whose
11654 // initialiser has already run.
11655 if op == PutVarRefCheck {
11656 let current = self.cell_value(slot)?;
11657 if matches!(current, Value::Uninitialized) {
11658 return Err(self.dead_zone(slot, VarSlot::Closure));
11659 }
11660 if self.is_read_only(slot, VarSlot::Closure) {
11661 return Err(self.read_only(slot, VarSlot::Closure));
11662 }
11663 }
11664 self.set_cell(slot, value)?;
11665 }
11666 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11667 let slot = self.slot_operand(op, a);
11668 let value = self.pop();
11669 if let Some(cell) = self.eval_created_local(slot) {
11670 cell.set(value.clone());
11671 self.push(value);
11672 return self.step();
11673 }
11674 self.set_cell(slot, value.clone())?;
11675 self.push(value);
11676 }
11677
11678 // -- globals ----------------------------------------------------
11679 GetVar => {
11680 let value = self.get_global(a as usize)?;
11681 self.push(value);
11682 }
11683 GetVarUndef => {
11684 let slot = a as usize;
11685 // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11686 // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11687 // and `GetValue`s it, and only the unresolvable case is forgiven).
11688 //
11689 // The distinction is made by asking whether a binding exists at all: a name
11690 // in the realm's lexical table is declared, so a `ReferenceError` from
11691 // reading it is the dead zone talking. Swallowing every error made
11692 // `eval("typeof x; let x;")` print `"undefined"`.
11693 let declared = self.realm.globals.contains_key(&self.global_name(slot));
11694 let value = if declared {
11695 self.get_global(slot)?
11696 } else {
11697 match self.get_global(slot) {
11698 Ok(value) => value,
11699 Err(Signal::Throw(_)) => Value::Undefined,
11700 Err(other) => return Err(other),
11701 }
11702 };
11703 self.push(value);
11704 }
11705 DeleteVar => {
11706 // `delete name` for a name that is not a declared binding. A lexical
11707 // global lives in the reference table and cannot be deleted; anything
11708 // reachable only as a property of the global object is *implicit* —
11709 // `x = 1` with no declaration — and goes away if it is configurable,
11710 // which is what `delete` on an implicit global answers.
11711 let name = self.atom_text(a as usize);
11712 // A binding a direct `eval` created in the caller's variable environment
11713 // comes first: it is deletable, and removing it is what makes the name
11714 // unbound again.
11715 let local = match self.visible_local_vars() {
11716 Some((local_vars, _)) => local_vars.delete(&name),
11717 None => None,
11718 };
11719 let global = self.realm.global.clone();
11720 let deleted = if let Some(deleted) = local {
11721 deleted
11722 } else if self.realm.globals.contains_key(&name) {
11723 false
11724 } else if global.own_property(&name).is_some() {
11725 self.delete_property(&global, &name)?
11726 } else {
11727 true
11728 };
11729 self.push(Value::Bool(deleted));
11730 }
11731 PutVar => {
11732 let value = self.pop();
11733 self.put_global(a as usize, value)?;
11734 }
11735 PutVarInit => {
11736 let slot = a as usize;
11737 let value = self.pop();
11738 self.init_global(slot, value)?;
11739 }
11740
11741 // -- arithmetic -------------------------------------------------
11742 Add => self.binary_add()?,
11743 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11744 let raw_right = self.pop();
11745 let raw_left = self.pop();
11746 // Two numbers need no `ToPrimitive` at all, which is every `x - y` and
11747 // `flags | mask` in real code.
11748 if is_number(&raw_left) && is_number(&raw_right) {
11749 self.push(arithmetic(op, raw_left, raw_right)?);
11750 } else {
11751 // §13.15.3 steps 1–3: **both** operands are made primitive before the
11752 // disjointness check, left first. Getting the order wrong was observable
11753 // — `ToPrimitive` on the right ran first, so a `valueOf` log read `b,a`
11754 // and a throw from the *left* operand never happened
11755 // (`S11.10.1_A2.3_T1`, `order-of-evaluation`).
11756 //
11757 // Doing the check on the *primitives* rather than on the raw values is
11758 // the second half: `Object(5n) & Object(3n)` has a bigint on neither
11759 // side of the stack yet, so the old check sent it down the `ToNumber`
11760 // path and raised "cannot convert bigint to number"
11761 // (`bigint-non-primitive`).
11762 let left = self.primitive_of(raw_left)?;
11763 let right = self.primitive_of(raw_right)?;
11764 // BigInt arithmetic is a separate path, and not only for the type of
11765 // the result: `ToNumber` of a bigint throws, so mixing the two must be
11766 // an error rather than a silent conversion.
11767 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11768 let value = self.bigint_arithmetic(op, left, right)?;
11769 self.push(value);
11770 } else {
11771 let right = self.numeric(right)?;
11772 let left = self.numeric(left)?;
11773 self.push(arithmetic(op, left, right)?);
11774 }
11775 }
11776 }
11777 Neg => {
11778 let raw = self.pop();
11779 match raw {
11780 // A bigint negates exactly, however wide it is.
11781 Value::BigInt(big) => {
11782 let negated = big.negate();
11783 self.push(self.bigint(negated));
11784 }
11785 other => {
11786 let value = self.numeric_operand(other)?;
11787 if let Value::BigInt(big) = &value {
11788 let negated = big.negate();
11789 self.push(self.bigint(negated));
11790 } else {
11791 self.push(negate(value));
11792 }
11793 }
11794 }
11795 }
11796 Plus => {
11797 let value = self.pop();
11798 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11799 // unary plus is defined to produce a *number*, which a bigint cannot
11800 // become without loss. It used to fall through to `NaN`.
11801 if matches!(value, Value::BigInt(_)) {
11802 return Err(self.type_error("cannot convert bigint to number"));
11803 }
11804 let numeric = self.numeric_of(value)?;
11805 self.push(numeric);
11806 }
11807 Inc => {
11808 let raw = self.pop();
11809 let (_, updated) = self.advance_numeric(raw, true)?;
11810 self.push(updated);
11811 }
11812 Dec => {
11813 let raw = self.pop();
11814 let (_, updated) = self.advance_numeric(raw, false)?;
11815 self.push(updated);
11816 }
11817 PostInc | PostDec => {
11818 // `x -> x x+1`: the *new* value ends up on top, so the store the
11819 // compiler emits right after (`put_var`) writes the incremented
11820 // one, while the old value stays underneath for the expression's
11821 // own result. Getting this backwards makes `i++` a no-op, which
11822 // turns `while (i < 3)` into an infinite loop.
11823 let raw = self.pop();
11824 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11825 self.push(old);
11826 self.push(updated);
11827 }
11828 Not => {
11829 let raw = self.pop();
11830 match raw {
11831 // `~x` on a bigint is `-x - 1`, exact at any width.
11832 Value::BigInt(big) => {
11833 let inverted = big.bitnot();
11834 self.push(self.bigint(inverted));
11835 }
11836 other => {
11837 let value = self.numeric_operand(other)?;
11838 if let Value::BigInt(big) = &value {
11839 let inverted = big.bitnot();
11840 self.push(self.bigint(inverted));
11841 } else {
11842 self.push(Value::Int(!value.to_int32()));
11843 }
11844 }
11845 }
11846 }
11847 Lnot => {
11848 let value = self.pop();
11849 self.push(Value::Bool(!value.to_boolean()));
11850 }
11851
11852 // -- comparison -------------------------------------------------
11853 Lt | Lte | Gt | Gte => {
11854 let right = self.pop();
11855 let left = self.pop();
11856 let answer = self.relational(op, left, right)?;
11857 self.push(answer);
11858 }
11859 Eq | Neq => {
11860 let right = self.pop();
11861 let left = self.pop();
11862 let equal = self.abstract_equals(left, right)?;
11863 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11864 }
11865 StrictEq => {
11866 let right = self.pop();
11867 let left = self.pop();
11868 self.push(Value::Bool(left.strict_equals(&right)));
11869 }
11870 StrictNeq => {
11871 let right = self.pop();
11872 let left = self.pop();
11873 self.push(Value::Bool(!left.strict_equals(&right)));
11874 }
11875 IsUndefined => {
11876 // `=== undefined`, which is what a destructuring default tests. It is
11877 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11878 let value = self.pop();
11879 self.push(Value::Bool(matches!(value, Value::Undefined)));
11880 }
11881 IsUndefinedOrNull => {
11882 let value = self.pop();
11883 self.push(Value::Bool(value.is_nullish()));
11884 }
11885 Typeof => {
11886 let value = self.pop();
11887 self.push(self.string(value.type_of()));
11888 }
11889 ToObject => {
11890 // A destructuring *object* pattern starts here, which is why
11891 // `var {} = null` throws. Only `undefined` and `null` are refused; a
11892 // primitive is boxed.
11893 let value = self.pop();
11894 let object = self.object_from(&value)?;
11895 self.push(Value::Object(object));
11896 }
11897 Instanceof => {
11898 let constructor = self.pop();
11899 let object = self.pop();
11900 // `InstanceofOperator`, not `OrdinaryHasInstance`: the operator consults
11901 // `Symbol.hasInstance` first and throws for a right-hand side that is not an
11902 // object (step 1) or not callable (step 4). Calling `instance_of` directly
11903 // skipped both the protocol and the two `TypeError`s.
11904 let answer = self.instance_of_operator(&object, &constructor)?;
11905 self.push(Value::Bool(answer));
11906 }
11907 In => {
11908 let object = self.pop();
11909 let key = self.pop();
11910 let answer = self.has_property(&key, &object)?;
11911 self.push(Value::Bool(answer));
11912 }
11913 WithHasVar => {
11914 // `obj -> bool`: does this `with` object bind the name?
11915 //
11916 // §9.1.1.2.1 `HasBinding` for an Object Environment Record is **not**
11917 // `HasProperty`: step 2 skips the property entirely when the object's
11918 // `Symbol.unscopables` lists it. So `globalThis[Symbol.unscopables] = {v:
11919 // true}` makes `with (globalThis) { v }` read the *outer* `v`, which is what
11920 // the thirty-odd `unscopables-with` cases assert.
11921 //
11922 // One instruction rather than a hand-expanded sequence of `in`, a
11923 // `Symbol.unscopables` lookup and a second `in`: the same question is asked
11924 // by both the read/write guard and `delete`, and a compiler-side expansion
11925 // would be about ten instructions per name per `with` object.
11926 let object = self.pop();
11927 let name = self.atom_text(a as usize);
11928 let bound = self.with_has_binding(&object, &name)?;
11929 self.push(Value::Bool(bound));
11930 }
11931 WithGetVar => {
11932 // `obj -> value`: the second half of `GetBindingValue`.
11933 let object = self.pop();
11934 let name = self.atom_text(a as usize);
11935 let value = self.with_get_binding(&object, &name)?;
11936 self.push(value);
11937 }
11938 WithPutVar => {
11939 // `obj value ->`: the second half of `SetMutableBinding`. The operand order
11940 // is `put_field`'s (value on top), not the reference's, so that the
11941 // read-modify-write shapes (`perm3`/`insert2`) can be shared with the
11942 // member-expression forms.
11943 let value = self.pop();
11944 let object = self.pop();
11945 let name = self.atom_text(a as usize);
11946 self.with_put_binding(&object, &name, value)?;
11947 }
11948
11949 // -- control flow -----------------------------------------------
11950 Goto | Goto8 | Goto16 => {
11951 self.frame_mut().pc = a as usize;
11952 }
11953 IfTrue | IfTrue8 => {
11954 let value = self.pop();
11955 if value.to_boolean() {
11956 self.frame_mut().pc = a as usize;
11957 }
11958 }
11959 IfFalse | IfFalse8 => {
11960 let value = self.pop();
11961 if !value.to_boolean() {
11962 self.frame_mut().pc = a as usize;
11963 }
11964 }
11965 Catch => {
11966 // Pushes the handler target onto the value stack; `unwind` finds it.
11967 self.push(Value::CatchOffset(a));
11968 }
11969 Gosub => {
11970 self.push(Value::ReturnAddress(next as u32));
11971 self.frame_mut().pc = a as usize;
11972 }
11973 Ret => {
11974 let value = self.pop();
11975 match value {
11976 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11977 _ => {
11978 return Err(Signal::Throw(
11979 self.make_error("InternalError", "invalid return address"),
11980 ));
11981 }
11982 }
11983 }
11984 NipCatch => {
11985 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11986 // including the marker, keeping the top value.
11987 let top = self.pop();
11988 loop {
11989 match self.pop() {
11990 Value::CatchOffset(_) | Value::Undefined => break,
11991 _ => {}
11992 }
11993 if self.frame().stack.is_empty() {
11994 break;
11995 }
11996 }
11997 self.push(top);
11998 }
11999 Throw => {
12000 let value = self.pop();
12001 return Err(Signal::Throw(value));
12002 }
12003 ThrowError => {
12004 let name = self.atom_text(a as usize);
12005 let (class, message) = match b {
12006 0 => ("TypeError", format!("'{name}' is read-only")),
12007 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
12008 2 => ("ReferenceError", format!("'{name}' is not initialized")),
12009 // `delete super.x` is a syntax-level mistake the reference reports
12010 // with this wording, not a property-access failure.
12011 3 => (
12012 "ReferenceError",
12013 "unsupported reference to 'super'".to_string(),
12014 ),
12015 4 => (
12016 "TypeError",
12017 "iterator does not have a throw method".to_string(),
12018 ),
12019 5 => (
12020 "ReferenceError",
12021 "invalid assignment left-hand side".to_string(),
12022 ),
12023 _ => ("TypeError", format!("invalid operation on '{name}'")),
12024 };
12025 return Err(Signal::Throw(self.make_error(class, &message)));
12026 }
12027 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
12028 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
12029 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
12030 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
12031 Await => return Ok(Step::Suspend(SuspendKind::Await)),
12032 ReturnAsync => {
12033 // The reference's `return_async` returns `undefined` and lets the resume
12034 // machinery pick the real value off `sp[-1]`, which is how it tells a
12035 // completion from a suspension. Carrying the value explicitly says the
12036 // same thing without the implicit stack slot.
12037 let value = self.pop();
12038 return Ok(Step::Return(value));
12039 }
12040 Return => {
12041 let value = self.pop();
12042 return Ok(Step::Return(value));
12043 }
12044 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
12045
12046 // -- calls ------------------------------------------------------
12047 Call | Call0 | Call1 | Call2 | Call3 => {
12048 let argc = self.argc_operand(op, a);
12049 let args = self.pop_n(argc);
12050 let callee = self.pop();
12051 // A plain call has no receiver; the callee decides what to do with
12052 // `undefined` (a sloppy function substitutes the global object).
12053 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
12054 self.push(result);
12055 }
12056 }
12057 CallConstructor => {
12058 // `constructor this_obj args… -> object`. The duplicated
12059 // constructor is `new.target`; this milestone does not expose it,
12060 // so the extra copy is simply consumed here.
12061 let argc = a as usize;
12062 let args = self.pop_n(argc);
12063 let new_target = self.pop();
12064 let callee = self.pop();
12065 let result = self.construct(callee, new_target, args)?;
12066 self.push(result);
12067 }
12068 CallMethod => {
12069 let argc = a as usize;
12070 let args = self.pop_n(argc);
12071 let callee = self.pop();
12072 let this = self.pop();
12073 if let Some(result) = self.call_or_push(callee, this, args)? {
12074 self.push(result);
12075 }
12076 }
12077 Apply => {
12078 // `func this array -> result`, the spread-call form: the compiler
12079 // builds one array of arguments, and all that is left here is to
12080 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
12081 let array = self.pop();
12082 let this = self.pop();
12083 let callee = self.pop();
12084 let args = self.array_like_to_args(&array)?;
12085 if a & 1 != 0 {
12086 let result = self.construct(callee, this, args)?;
12087 self.push(result);
12088 } else if let Some(result) = self.call_or_push(callee, this, args)? {
12089 self.push(result);
12090 }
12091 }
12092 TailCall | TailCallMethod => {
12093 // `tail_call` is `call` whose result is returned immediately — the
12094 // reference jumps straight to `done` instead of storing the value and
12095 // running on. The callee still gets its own frame, so deep tail
12096 // recursion hits the stack limit exactly like plain recursion does;
12097 // marking this frame lets the return path unwind without needing
12098 // instructions after the call.
12099 let argc = if op == TailCallMethod {
12100 a as usize
12101 } else {
12102 self.argc_operand(op, a)
12103 };
12104 let args = self.pop_n(argc);
12105 let callee = self.pop();
12106 let this = if op == TailCallMethod {
12107 self.pop()
12108 } else {
12109 Value::Undefined
12110 };
12111 if let Value::Object(function) = &callee
12112 && let Some((code, env)) = bytecode_of(function)
12113 {
12114 // A generator or async body is not run here at all: calling it only
12115 // *creates* the generator/coroutine, so it must not inherit this
12116 // frame. Doing so made `function f(){ return g() }` push `g`'s body
12117 // onto `f`'s frame, and the first `yield`/`await` then reported
12118 // "a generator body ran as an ordinary call".
12119 if code.code.kind.is_generator() || code.code.kind.is_async() {
12120 let value = self.call_value(callee, this, args)?;
12121 return Ok(Step::Return(value));
12122 }
12123 self.frame_mut().tail = true;
12124 self.push_frame(code, env, this, args, callee)?;
12125 return Ok(Step::Continue);
12126 }
12127 // A native callee has no frame to reuse, so its value is simply
12128 // returned.
12129 let value = self.call_value(callee, this, args)?;
12130 return Ok(Step::Return(value));
12131 }
12132
12133 // -- objects ----------------------------------------------------
12134 SpecialObject => {
12135 let value = self.special_object(a)?;
12136 self.push(value);
12137 }
12138 PrivateSymbol => {
12139 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
12140 // symbol each time it is evaluated, which is why the compiler evaluates it
12141 // once (at class definition) and stores it in a class-scope binding.
12142 let name = self.atom_text(a as usize);
12143 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
12144 self.push(Value::Symbol(symbol));
12145 }
12146 GetPrivateField => {
12147 // `obj symbol -> value`. A missing private field is a TypeError, which is what
12148 // makes `#x` inaccessible on any object not built by this class.
12149 let symbol = self.pop();
12150 let object = self.pop();
12151 let value = self.read_private_field(&object, &symbol)?;
12152 self.push(value);
12153 }
12154 PutPrivateField => {
12155 // `obj value symbol ->`, and the store is a plain assignment to a property the
12156 // class already created, so there is no setter to consult.
12157 let symbol = self.pop();
12158 let value = self.pop();
12159 let object = self.pop();
12160 self.write_private_field(&object, &symbol, value)?;
12161 }
12162 DefinePrivateField => {
12163 // `obj symbol value -> obj`: a field initialiser creates the property, and
12164 // redefining one is a TypeError ("already exists").
12165 let value = self.pop();
12166 let symbol = self.pop();
12167 let object = self.pop();
12168 self.define_private_field(&object, &symbol, value)?;
12169 self.push(object);
12170 }
12171 PrivateIn => {
12172 // `obj key -> bool`: `#x in o`. The second operand decides which question is
12173 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
12174 // is a field, so this is an own-property test; a *function* is a method or
12175 // accessor, so this is a brand check.
12176 let key = self.pop();
12177 let object = self.pop();
12178 let Some(target) = object.as_object() else {
12179 return Err(Signal::Throw(
12180 self.make_error("TypeError", "invalid 'in' operand"),
12181 ));
12182 };
12183 let present = match &key {
12184 Value::Object(_) => self.check_brand(target, &key)?,
12185 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
12186 };
12187 self.push(Value::Bool(present));
12188 }
12189 AddBrand => {
12190 // `obj home ->`: create the class brand on `home` if it has none, then give
12191 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
12192 // class definition: only the prototype's copy of the symbol is wanted.
12193 let home = self.pop();
12194 let object = self.pop();
12195 self.add_brand(&object, &home)?;
12196 }
12197 CheckBrand => {
12198 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
12199 // Both stay, because the caller needs them — `nip` halves a read into its
12200 // value and `call_method` uses the pair as receiver and callee.
12201 let function = self.peek(0);
12202 let object = self.peek(1);
12203 let Some(target) = object.as_object() else {
12204 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12205 };
12206 if !self.check_brand(target, &function)? {
12207 return Err(Signal::Throw(
12208 self.make_error("TypeError", "invalid brand on object"),
12209 ));
12210 }
12211 }
12212 GetLength => {
12213 // `get_length` is the `.length` read; an array and a string answer
12214 // from their own length, anything else from the property.
12215 let target = self.pop();
12216 let value = match &target {
12217 Value::Object(object) => match object.array_length() {
12218 Some(length) => crate::object::length_value(length),
12219 None => self.read_field(&target, "length")?,
12220 },
12221 Value::String(text) => Value::Int(text.utf16_len() as i32),
12222 _ => self.read_field(&target, "length")?,
12223 };
12224 self.push(value);
12225 }
12226 GetField | GetField2 => {
12227 let object = self.pop();
12228 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
12229 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
12230 // just below is what lets the borrow outlive the `&mut self` the lookup
12231 // needs — one refcount bump instead of a key clone plus its drop, on the
12232 // hottest property path there is: every `o.x` and every `o.m()` receiver.
12233 let code = self.frame().code.clone();
12234 let key = &code.atom_keys[a as usize];
12235 let value = self.read_field_cached(&object, key, next)?;
12236 if op == GetField2 {
12237 self.push(object);
12238 }
12239 self.push(value);
12240 }
12241 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
12242 let key = self.pop();
12243 let object = self.pop();
12244 // §7.1.1 `GetValue` step 3 orders these two conversions: `ToObject(V.[[Base]])`
12245 // first, then `ToPropertyKey(V.[[ReferencedName]])`. So a nullish base is a
12246 // `TypeError` and the key is **never coerced** — `null[{toString(){throw}}]`
12247 // throws the TypeError, not the key's exception
12248 // (`S11.3.1_A6_T1`). A write has the opposite order, which is why
12249 // `PutArrayEl` deliberately does not do this.
12250 //
12251 // Only nullish is checked here, and the full boxing is still left to
12252 // `read_field_key`: a string base has an index fast path that turning it
12253 // into a `String` object up front would throw away.
12254 if object.is_nullish() {
12255 return Err(Signal::Throw(self.make_error(
12256 "TypeError",
12257 &format!("cannot read property of {}", object.to_js_string()),
12258 )));
12259 }
12260 let key = self.propkey(&key)?;
12261 let value = self.read_field_key(&object, &key)?;
12262 if matches!(op, GetArrayEl2 | GetArrayEl3) {
12263 self.push(object);
12264 }
12265 if op == GetArrayEl3 {
12266 // The key goes back in its *value* form, which the compiler stores
12267 // into the target of a destructuring assignment.
12268 self.push(match &key {
12269 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12270 PropertyKey::String(text) => self.string_wtf8(text.clone()),
12271 });
12272 }
12273 self.push(value);
12274 }
12275 PutField => {
12276 let value = self.pop();
12277 let object = self.pop();
12278 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
12279 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
12280 // only reads. `this.value = …` is the write half of the hottest loop in
12281 // `property:method-call`, and `own_property_key` was 4.8% of the case.
12282 let code = self.frame().code.clone();
12283 let key = &code.atom_keys[a as usize];
12284 self.write_field_key(&object, key, value)?;
12285 }
12286 PutArrayEl => {
12287 let value = self.pop();
12288 let key = self.pop();
12289 let object = self.pop();
12290 let key = self.propkey(&key)?;
12291 self.write_field_key(&object, &key, value)?;
12292 }
12293 DefineField => {
12294 let value = self.pop();
12295 let object = self.pop();
12296 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
12297 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
12298 // three U+FFFD — a property under a different name from the one
12299 // `o["\uD800"]` reads.
12300 let code = self.frame().code.clone();
12301 let key = code.atom_keys[a as usize].clone();
12302 // No naming here. `{m: function(){}}` is named by the *compiler*, which
12303 // emits `set_name` — and only where `NamedEvaluation` applies, so
12304 // `{m: (0, function(){})}` stays anonymous. Naming every function that
12305 // reaches a property definition got that case wrong, and the compiler is
12306 // the only place that can tell the two apart.
12307 self.define_field(&object, &key, value)?;
12308 self.push(object);
12309 }
12310 DefineArrayEl => {
12311 // `obj key value -> obj key`. The *value* form of the key is what goes
12312 // back on the stack — the compiler stores it into the pattern's binding —
12313 // so the symbol is not stringified on the way through.
12314 //
12315 // `define_field` and not `write_field_key`: this is `CreateDataProperty`,
12316 // and only the define algorithm gives `{ ['__proto__']: v }` an ordinary
12317 // own property. Going through `[[Set]]` found `Object.prototype`'s
12318 // `__proto__` accessor on the prototype chain and *changed the prototype*
12319 // instead, and it would have called a user setter from a literal
12320 // (`computed-__proto__`, `__proto__-duplicate-computed`).
12321 let value = self.pop();
12322 let key_value = self.pop();
12323 let object = self.peek(0);
12324 let key = self.propkey(&key_value)?;
12325 self.define_field(&object, &key, value)?;
12326 self.push(key_value);
12327 }
12328 SetHomeObject => {
12329 // `obj func -> obj func`: records the object a method was defined on so
12330 // `super` inside it resolves against that object's prototype.
12331 let function = self.peek(0);
12332 let home = self.peek(1);
12333 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
12334 function.set_home_object(Some(home.clone()));
12335 }
12336 }
12337 Regexp => {
12338 // `pattern flags -> regexp`. A literal compiles here rather than through the
12339 // constructor, which is both what the reference's dedicated opcode is for
12340 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
12341 let flags = self.pop();
12342 let pattern = self.pop();
12343 let pattern = self.checked_to_wtf8(&pattern)?;
12344 let flags = self.to_js_string(&flags)?;
12345 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
12346 self.push(Value::Object(object));
12347 }
12348 UsingDisposeInit => {
12349 // The error state a disposal accumulates into. Uninitialised means "no
12350 // failure yet"; anything else is the exception being propagated.
12351 self.push(Value::Uninitialized);
12352 }
12353 UsingCheck => {
12354 // `value -> value, method`: validate and snapshot the disposer now, so a
12355 // later change to `Symbol.dispose` cannot change what gets called, and so a
12356 // value that is not disposable fails before the body runs.
12357 let value = self.pop();
12358 let method = self.using_method_for(&value, a as u8 == 1)?;
12359 self.push(value);
12360 self.push(method);
12361 }
12362 UsingDispose => {
12363 // `error_state -> error_state'`: dispose the variable at `slot` — its value
12364 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
12365 // the pending error.
12366 let slot = self.slot_operand(op, a);
12367 let error_state = self.pop();
12368 let merged = self.using_dispose_once(slot, error_state)?;
12369 self.push(merged);
12370 }
12371 UsingDisposeMerge => {
12372 let new_error = self.pop();
12373 let error_state = self.pop();
12374 let merged = self.merge_dispose_error(new_error, error_state);
12375 self.push(merged);
12376 }
12377 UsingDisposeEnd => {
12378 // A disposal that failed replaces the block's normal completion, so the
12379 // error state becomes a real throw here rather than at the call site.
12380 let error_state = self.pop();
12381 if !matches!(error_state, Value::Uninitialized) {
12382 return Err(Signal::Throw(error_state));
12383 }
12384 }
12385 // -- references -------------------------------------------------
12386 //
12387 // §6.2.5's Reference, as a value the operand stack can carry. Only emitted
12388 // where a direct `eval` could declare a shadowing `var` between the read and
12389 // the store (§13.15.3 resolves the lvalue once), so nothing hot goes through
12390 // here.
12391 MakeLocRef | MakeArgRef | MakeVarRefRef | MakeVarRef => {
12392 let name = self.atom_wtf8(a as usize);
12393 let target = match op {
12394 // A *global*: the name is looked up afresh, because an `eval` earlier in
12395 // this very function may already have declared it as a local, and
12396 // because an implicit global may not exist at all.
12397 MakeVarRef => self.global_reference(&name)?,
12398 // A slot. `eval_created_local` is the same override an ordinary
12399 // `get_var_ref` makes, so `eval("var x = 9"); x *= (…)` reads the eval's
12400 // `x` while `x *= (eval("var x = 2"), 4)` reads the outer one — the
12401 // difference is only *when* the reference was taken.
12402 // A slot. Three cases, and the first two are easy to confuse:
12403 //
12404 // * a *local* or *argument* — its cell number is in `loc_cell`/`arg_cell`,
12405 // not the slot itself, and `resolve` has already forced it to be
12406 // captured so a cell exists;
12407 // * a *global* reached through the closure table — the cell there is a
12408 // placeholder (`is_global_slot`), so the binding has to be reached by
12409 // name after all;
12410 // * anything else in the closure table — a real cell, but a direct `eval`
12411 // may have shadowed the name with a fresh local, and that shadow is what
12412 // an ordinary read would find.
12413 MakeVarRefRef if self.is_global_slot(b as usize) => {
12414 self.global_reference(&name)?
12415 }
12416 _ => {
12417 let slot = b as usize;
12418 let cell = match op {
12419 MakeLocRef => self
12420 .frame()
12421 .code
12422 .loc_cell
12423 .get(slot)
12424 .copied()
12425 .filter(|cell| *cell >= 0)
12426 .and_then(|cell| self.frame().cells.get(cell as usize).cloned()),
12427 MakeArgRef => self
12428 .frame()
12429 .code
12430 .arg_cell
12431 .get(slot)
12432 .copied()
12433 .filter(|cell| *cell >= 0)
12434 .and_then(|cell| self.frame().cells.get(cell as usize).cloned()),
12435 _ => self.eval_created_local(slot),
12436 };
12437 match cell.or_else(|| self.frame().env.cells.get(slot).cloned()) {
12438 Some(cell) => RefTarget::Cell(cell),
12439 None => {
12440 return Err(Signal::Throw(self.make_error(
12441 "InternalError",
12442 "a reference to a slot with no cell",
12443 )));
12444 }
12445 }
12446 }
12447 };
12448 let object = self.new_object(None);
12449 object.set_reference(target);
12450 self.push(Value::Object(object));
12451 }
12452 GetRefValue => {
12453 // `[ref] -> [ref, value]`: the reference stays, exactly like a `get_field2`,
12454 // so a second half can store through it.
12455 let reference = self.reference_target(0)?;
12456 let value = match reference {
12457 RefTarget::Cell(cell) => cell.get(),
12458 RefTarget::Property { base, name } => {
12459 // An unresolvable reference is a name that is on neither the global
12460 // binding table nor the global object, and reading one is a
12461 // `ReferenceError` in every mode (§6.2.5.5).
12462 if matches!(base, Value::Undefined) {
12463 return Err(self.throw_reference(
12464 &name
12465 .as_wtf8()
12466 .map(|t| t.to_string_lossy().into_owned())
12467 .unwrap_or_default(),
12468 ));
12469 }
12470 self.get_property_key(
12471 base.as_object().ok_or_else(|| {
12472 self.type_error("a reference base must be an object")
12473 })?,
12474 &name,
12475 )?
12476 .unwrap_or(Value::Undefined)
12477 }
12478 };
12479 self.push(value);
12480 }
12481 PutRefValue => {
12482 // `[ref, value] -> []`.
12483 let value = self.pop();
12484 let reference = self.reference_target(0)?;
12485 self.pop();
12486 match reference {
12487 RefTarget::Cell(cell) => cell.set(value),
12488 RefTarget::Property { base, name } => {
12489 if matches!(base, Value::Undefined) {
12490 // Sloppy code creates the global; strict code refuses
12491 // (§9.1.1.4.6 `SetMutableBinding` on an unresolvable name).
12492 if self.current_strict() {
12493 return Err(self.throw_reference(
12494 &name
12495 .as_wtf8()
12496 .map(|t| t.to_string_lossy().into_owned())
12497 .unwrap_or_default(),
12498 ));
12499 }
12500 let global = self.realm.global.clone();
12501 self.set_property_with_key(
12502 &global,
12503 &name,
12504 value,
12505 DeleteFailure::Ignore,
12506 )?;
12507 } else {
12508 let object = base.as_object().ok_or_else(|| {
12509 self.type_error("a reference base must be an object")
12510 })?;
12511 self.set_property_with_key(object, &name, value, DeleteFailure::Throw)?;
12512 }
12513 }
12514 }
12515 }
12516 UsingDisposeAsync => {
12517 // `error_state -> error_state, promise`: the disposer is called here and
12518 // its result wrapped, so the `await` the compiler emits next is what
12519 // actually waits. Calling it and dropping the result lost every failure
12520 // from an `async [Symbol.asyncDispose]` — the rejection had no handler and
12521 // no path back into the error state
12522 // (`throws-error-as-is-if-only-one-error-during-disposal`).
12523 let slot = self.slot_operand(op, a);
12524 let error_state = self.pop();
12525 let value = self.get_loc(slot);
12526 let method = self.get_loc(slot + 1);
12527 let promise = if value.is_nullish()
12528 || matches!(value, Value::Uninitialized)
12529 || matches!(method, Value::Undefined | Value::Uninitialized)
12530 {
12531 // Nothing to dispose: `await undefined` is a no-op, as it is in the
12532 // reference (`sp[0] = JS_UNDEFINED`).
12533 Value::Undefined
12534 } else {
12535 let result = self.call_value(method, value, Vec::new())?;
12536 self.promise_resolve_value(result)?
12537 };
12538 self.push(error_state);
12539 self.push(promise);
12540 }
12541 GetSuper => {
12542 // `obj -> obj's prototype`: the starting point of a `super` lookup.
12543 let object = self.pop();
12544 let proto = match &object {
12545 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
12546 _ => Value::Null,
12547 };
12548 self.push(proto);
12549 }
12550 GetSuperValue => {
12551 // `receiver proto key -> value`, searching from `proto` but reporting to
12552 // `receiver`, which is what `super.g` must do for a getter to see `this`.
12553 //
12554 // Three values in, one out: the receiver is *consumed*, not left under the
12555 // result. Leaving it there was invisible for `super.x` in `return` or
12556 // statement position (the result is what gets popped) and corrupted the
12557 // frame everywhere else — `print(super.x)` left the class where the call
12558 // opcode looks for the receiver and called the class itself.
12559 let key = self.pop();
12560 let proto = self.pop();
12561 let receiver = self.pop();
12562 let value = self.super_read(&receiver, &proto, &key)?;
12563 self.push(value);
12564 }
12565 PutSuperValue => {
12566 // `receiver proto key value ->`: a store that starts at `proto` but
12567 // assigns to `receiver`.
12568 let value = self.pop();
12569 let key = self.pop();
12570 let proto = self.pop();
12571 let receiver = self.pop();
12572 self.super_write(&receiver, &proto, &key, value)?;
12573 }
12574 DefineClass => {
12575 // `parent ctor -> ctor proto`: the constructor becomes the class and a
12576 // fresh prototype object lands on top for the methods to go on.
12577 let name = self.atom_text(a as usize);
12578 let (ctor, proto) = self.define_class(&name, b)?;
12579 self.push(ctor);
12580 self.push(Value::Object(proto));
12581 }
12582 DefineClassComputed => {
12583 // `parent ctor key -> ctor proto key`: the computed name stays put so
12584 // `define_field`-style consumers can still read it.
12585 let key = self.pop();
12586 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12587 let (ctor, proto) = self.define_class(&name, b)?;
12588 self.push(ctor);
12589 self.push(Value::Object(proto));
12590 self.push(key);
12591 }
12592 DefineMethod => {
12593 let function = self.pop();
12594 let object = self.pop();
12595 // The exact key, like `define_field`: a quoted method key may hold an
12596 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
12597 // that `o["\uD800"]` finds.
12598 let code = self.frame().code.clone();
12599 let key = code.atom_keys[a as usize].clone();
12600 // A method's `[[HomeObject]]` is the object it was defined on, which is
12601 // what `super` inside it resolves against.
12602 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12603 function.set_home_object(Some(object.clone()));
12604 }
12605 let name = match key.as_wtf8() {
12606 Some(text) => text.clone(),
12607 // A symbol atom — one of the well-known symbols, which the lexer keeps
12608 // as an atom rather than a runtime value. Its name is the bracketed
12609 // description, like any other symbol key.
12610 None => symbol_key_name(&key),
12611 };
12612 self.set_function_name_wtf8(&function, &accessor_prefixed(&name, b));
12613 if let Some(array) = object.as_object()
12614 && !define_function_property(array, &key, function, b)
12615 {
12616 return Err(self.type_error("property is not configurable"));
12617 }
12618 self.push(object);
12619 }
12620 DefineMethodComputed => {
12621 let function = self.pop();
12622 let key = self.pop();
12623 let object = self.pop();
12624 let key = self.propkey(&key)?;
12625 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
12626 // the name: `super` inside a computed method resolves through it. Without
12627 // this, `class B extends A { [k]() { return super.m() } }` read the
12628 // home object as null and threw.
12629 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12630 function.set_home_object(Some(object.clone()));
12631 }
12632 // A symbol key names the method `[description]`, or `""` without one —
12633 // §7.3.24, the same rule [`Interp::function_name_from_key`] applies to
12634 // `set_name_computed`. Falling back to `to_string` here named every
12635 // `{ [sym](){} }` method `Symbol()` instead.
12636 match &key {
12637 PropertyKey::Symbol(_) => {
12638 // The accessor prefix still applies: `get [Symbol.iterator](){}`
12639 // is named `"get [Symbol.iterator]"`.
12640 let name = accessor_prefixed(&symbol_key_name(&key), a);
12641 self.set_function_name_wtf8(&function, &name);
12642 }
12643 PropertyKey::String(text) => {
12644 let name = accessor_prefixed(text, a);
12645 self.set_function_name_wtf8(&function, &name);
12646 }
12647 }
12648 if let Some(array) = object.as_object()
12649 && !define_function_property(array, &key, function, a)
12650 {
12651 return Err(self.type_error("property is not configurable"));
12652 }
12653 self.push(object);
12654 }
12655 SetProto => {
12656 // `{ __proto__: v }` — §13.2.5.1 step 6: nothing is defined and nothing is
12657 // changed unless `v` is an object or `null`. A primitive was taken as "no
12658 // prototype" instead, so `{ __proto__: undefined }` came out with `null`
12659 // where the answer is an ordinary object
12660 // (`__proto__-value-non-object`).
12661 let proto = self.pop();
12662 let object = self.pop();
12663 if matches!(proto, Value::Null | Value::Object(_))
12664 && let Some(target) = object.as_object()
12665 {
12666 target.set_proto(proto.as_object().cloned());
12667 }
12668 self.push(object);
12669 }
12670 CopyDataProperties => {
12671 let exclusion = self.pop();
12672 let source = self.pop();
12673 let target = self.peek(0);
12674 self.copy_properties(&target, &source, &exclusion)?;
12675 self.push(source);
12676 self.push(exclusion);
12677 }
12678 ToPropkey => {
12679 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12680 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12681 // ordinary `"Symbol(b)"` property.
12682 let value = self.pop();
12683 let key = match self.propkey(&value)? {
12684 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12685 PropertyKey::String(text) => self.string_wtf8(text),
12686 };
12687 self.push(key);
12688 }
12689 SetName => {
12690 let function = self.peek(0);
12691 let name = self.atom_wtf8(a as usize);
12692 self.set_function_name_wtf8(&function, &name);
12693 }
12694 SetNameComputed => {
12695 let key = self.peek(1);
12696 let function = self.peek(0);
12697 let name = self.function_name_from_key(&key)?;
12698 self.set_function_name_wtf8(&function, &name);
12699 }
12700
12701 // -- arrays -----------------------------------------------------
12702 ArrayFrom => {
12703 let count = a as usize;
12704 let elements = self.pop_n(count);
12705 let array = self.new_array(elements);
12706 self.push(Value::Object(array));
12707 }
12708 Append => {
12709 // `array index iterable -> array new_index`
12710 let iterable = self.pop();
12711 self.pop();
12712 let array = self.peek(0);
12713 let added = self.append_enumerate(&array, &iterable)?;
12714 self.push(Value::Int(added));
12715 }
12716
12717 // -- iteration --------------------------------------------------
12718 ForInStart => {
12719 let value = self.pop();
12720 let record = self.for_in_record(&value)?;
12721 self.push(Value::Object(record));
12722 }
12723 ForInNext => {
12724 // `record -> record key done`. The flag is *done*, not "found":
12725 // the compiler tests it with `if_false` to jump back into the body,
12726 // so reporting `true` while keys remain would end the loop at once.
12727 let record = self.peek(0);
12728 match self.for_in_advance(&record)? {
12729 Some(key) => {
12730 let text = self.string(key);
12731 self.push(text);
12732 self.push(Value::Bool(false));
12733 }
12734 None => {
12735 self.push(Value::Undefined);
12736 self.push(Value::Bool(true));
12737 }
12738 }
12739 }
12740 ForOfStart => {
12741 let value = self.pop();
12742 let iterator = self.get_iterator(&value)?;
12743 self.push(iterator.object);
12744 self.push(iterator.next);
12745 self.push(Value::CatchOffset(0));
12746 }
12747 ForOfNext => {
12748 // `iter next catch_offset -> iter next catch_offset value done`.
12749 //
12750 // The operand is how many values sit *above* the iterator triple: a
12751 // destructuring rest element keeps its target array and running index
12752 // there while draining the iterator, so the triple is not at the top.
12753 let extra = a as usize;
12754 let iterator_slot = 2 + extra;
12755 // An exhausted iterator is replaced by `undefined` (see below), so a
12756 // second step must not call `next` again — `Array.from` and a
12757 // destructuring pattern both keep stepping past the end.
12758 let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12759 Ok((Value::Undefined, true))
12760 } else {
12761 let iterator = Iterator {
12762 object: self.peek(iterator_slot),
12763 next: self.peek(1 + extra),
12764 };
12765 self.iterator_step(&iterator)
12766 };
12767 let (value, done) = match stepped {
12768 Ok(stepped) => stepped,
12769 Err(signal) => {
12770 // An exception from `next()` is not an abrupt completion of the
12771 // *body*, so §7.4.6 does not apply and the iterator must not be
12772 // closed: `[ , ] = iterable` with a throwing `next` expects
12773 // `returnCount === 0`. Clearing the slot is how the reference says
12774 // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12775 // returns -1), and it is also what makes the destructor below — the
12776 // exception path's `catch_offset 0` close — a no-op here.
12777 self.clear_iterator_slot(iterator_slot);
12778 return Err(signal);
12779 }
12780 };
12781 if done {
12782 // The result's `value` is meaningless once the iterator is done:
12783 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12784 // rather than binding the generator's return value.
12785 let top = self.frame().stack.len() - 1 - iterator_slot;
12786 self.frame_mut().stack[top] = Value::Undefined;
12787 self.push(Value::Undefined);
12788 self.push(Value::Bool(true));
12789 } else {
12790 self.push(value);
12791 self.push(Value::Bool(false));
12792 }
12793 }
12794 IteratorNext => {
12795 // `iter next catch val -> iter next catch val'`: replace the argument with
12796 // the result of `next(val)`. The triple below stays put, which is why the
12797 // three instructions of the `yield*` loop all address the stack the same way.
12798 let value = self.pop();
12799 let object = self.peek(2);
12800 let next = self.peek(1);
12801 let result = self.call_value(next, object, vec![value])?;
12802 self.push(result);
12803 }
12804 IteratorCall => {
12805 // `iter next catch val -> iter next catch val' flag`.
12806 //
12807 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12808 // The flag is `true` when the method was missing, which is how the
12809 // caller learns that the inner iterator cannot take part in the
12810 // unwinding.
12811 let value = self.pop();
12812 let object = self.peek(2);
12813 let key = if a & 1 != 0 { "throw" } else { "return" };
12814 let method = self.read_field(&object, key)?;
12815 if matches!(method, Value::Undefined | Value::Null) {
12816 self.push(value);
12817 self.push(Value::Bool(true));
12818 } else {
12819 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12820 let result = self.call_value(method, object, argument)?;
12821 self.push(result);
12822 self.push(Value::Bool(false));
12823 }
12824 }
12825 IteratorCheckObject => {
12826 if !matches!(self.peek(0), Value::Object(_)) {
12827 return Err(Signal::Throw(
12828 self.make_error("TypeError", "iterator must return an object"),
12829 ));
12830 }
12831 }
12832 IteratorClose => {
12833 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12834 // calling the iterator's `return` so it can release whatever it holds.
12835 //
12836 // The catch offset goes first, so an exception from `return` is not caught
12837 // by the loop being abandoned. This used to pop the three operands and call
12838 // nothing at all, which made `break` out of a `for of` invisible to an
12839 // iterator with a `return` method.
12840 self.pop();
12841 self.pop();
12842 let iterator = self.pop();
12843 if !matches!(iterator, Value::Undefined) {
12844 let method = self.read_field(&iterator, "return")?;
12845 if !matches!(method, Value::Undefined | Value::Null) {
12846 let result = self.call_value(method, iterator.clone(), Vec::new())?;
12847 // §7.4.6: a `return` that answers a non-object is a TypeError.
12848 if !matches!(result, Value::Object(_)) {
12849 return Err(Signal::Throw(
12850 self.make_error("TypeError", "iterator must return an object"),
12851 ));
12852 }
12853 }
12854 }
12855 }
12856 Import | ImportDefer | ImportSource => {
12857 // `import(specifier, options)`: the options slot is on top. Both are
12858 // `GetValue`-ed by the compiler, which is why this pops values rather than
12859 // references — and why the validation of `options` (§13.3.10.1 step 10)
12860 // happens inside `dynamic_import`, where its failures can be turned into a
12861 // rejection instead of a throw.
12862 //
12863 // The proposal forms have the same stack shape and no options bag: the
12864 // compiler pushes a literal `undefined`, and the phase is the opcode.
12865 let phase = match op {
12866 ImportDefer => js_parse::ast::ImportPhase::Defer,
12867 ImportSource => js_parse::ast::ImportPhase::Source,
12868 _ => js_parse::ast::ImportPhase::Evaluation,
12869 };
12870 let options = self.pop();
12871 let specifier = self.pop();
12872 let promise = self.dynamic_import(specifier, options, phase)?;
12873 self.push(promise);
12874 }
12875 ForAwaitOfStart => {
12876 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12877 // `Symbol.iterator` fallback.
12878 let value = self.pop();
12879 let iterator = self.get_async_iterator(&value)?;
12880 self.push(iterator.object);
12881 self.push(iterator.next);
12882 self.push(Value::CatchOffset(0));
12883 }
12884 ForAwaitOfNext => {
12885 // `for await` steps the iterator and leaves the *result* wrapped in a
12886 // promise, so the `await` the compiler emits right after this can suspend
12887 // on it. Unwrapping happens in `iterator_get_value_done`.
12888 let extra = a as usize;
12889 let iterator_slot = 2 + extra;
12890 // The enumerator marker is **disabled for the step**, and
12891 // `iterator_get_value_done` puts it back once the result has survived the
12892 // awaiting. Both halves are load-bearing for the async case:
12893 //
12894 // * a rejection is not "the body threw", so the loop must not close the
12895 // iterator *again* — the wrapper already did;
12896 // * but until the result arrives the record is live, so a later failure
12897 // still has to close it.
12898 //
12899 // The reference says the same in one line each
12900 // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12901 // offset so that exceptions do not close the iterator */`).
12902 self.clear_iterator_slot(extra);
12903 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12904 Value::Undefined
12905 } else {
12906 let iterator = Iterator {
12907 object: self.peek(iterator_slot),
12908 next: self.peek(1 + extra),
12909 };
12910 let next = iterator.next.clone();
12911 self.call_value(next, iterator.object, Vec::new())?
12912 };
12913 let promise = self.promise_resolve_value(result)?;
12914 self.push(promise);
12915 }
12916 IteratorGetValueDone => {
12917 // `result -> value done`. A missing result object means the iterator was
12918 // already exhausted, which the loop treats as `done`.
12919 let result = self.pop();
12920 // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12921 // from here on the record is closeable again.
12922 {
12923 let depth = self.frame().stack.len();
12924 if depth >= 2 {
12925 self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12926 }
12927 }
12928 let done = match &result {
12929 Value::Object(object) => self
12930 .get_property(object, "done")?
12931 .is_some_and(|value| value.to_boolean()),
12932 _ => true,
12933 };
12934 if done {
12935 // Clear the iterator object so the `iterator_close` the loop emits on
12936 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12937 // on normal completion, and this is where a normal completion is
12938 // recognised — the same trick `for_of_next` uses, which also replaces
12939 // the slot with `undefined`.
12940 //
12941 // The layout is fixed because only `for await` emits this opcode:
12942 // `iter next catch [result]`, so the iterator is three below the top.
12943 let depth = self.frame().stack.len();
12944 if depth >= 3 {
12945 self.frame_mut().stack[depth - 3] = Value::Undefined;
12946 }
12947 self.push(Value::Undefined);
12948 self.push(Value::Bool(true));
12949 } else {
12950 let Value::Object(object) = &result else {
12951 self.push(Value::Undefined);
12952 self.push(Value::Bool(true));
12953 return Ok(Step::Continue);
12954 };
12955 let value = self
12956 .get_property(object, "value")?
12957 .unwrap_or(Value::Undefined);
12958 self.push(value);
12959 self.push(Value::Bool(false));
12960 }
12961 }
12962
12963 Delete => {
12964 // `delete obj[key]`, where the key was just pushed. Deleting an array
12965 // index leaves a *hole* rather than closing the gap, and a
12966 // non-configurable property answers `false` and stays.
12967 let key = self.pop();
12968 let target = self.pop();
12969 let key = self.propkey(&key)?;
12970 let text_label = key.as_str().unwrap_or("").to_string();
12971 let deleted = match &target {
12972 Value::Object(object) => {
12973 let object = object.clone();
12974 self.delete_property_key(&object, &key)?
12975 }
12976 // A string's `length` and its index properties are
12977 // non-configurable, so deleting one answers `false`.
12978 Value::String(text) => {
12979 !(text_label == "length"
12980 || array_index(&text_label)
12981 .is_some_and(|index| (index as usize) < text.utf16_len()))
12982 }
12983 // "delete null.a" is a TypeError, not a no-op: the operator needs an
12984 // object to delete from, and only a *boxable* primitive has one.
12985 Value::Undefined | Value::Null => {
12986 return Err(Signal::Throw(
12987 self.make_error("TypeError", "cannot convert to object"),
12988 ));
12989 }
12990 // Any other primitive has no own properties; deleting nothing
12991 // succeeds.
12992 _ => true,
12993 };
12994 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12995 // `TypeError` rather than a `false` result. Sloppy mode silently reports
12996 // the refusal, which is why the same statement throws here but not there.
12997 if !deleted && self.current_strict() {
12998 return Err(Signal::Throw(
12999 self.make_error("TypeError", "cannot delete property"),
13000 ));
13001 }
13002 self.push(Value::Bool(deleted));
13003 }
13004
13005 // -- exceptions and bookkeeping ---------------------------------
13006 Fclosure | Fclosure8 => {
13007 let value = self.closure(a as usize)?;
13008 self.push(value);
13009 }
13010
13011 other => {
13012 let name = other.info().name;
13013 return Err(Signal::Throw(self.make_error(
13014 "InternalError",
13015 &format!("{name} is not implemented yet"),
13016 )));
13017 }
13018 }
13019 Ok(Step::Continue)
13020 }
13021
13022 // -- operand helpers ----------------------------------------------------
13023
13024 /// The slot index an operand names, taking short forms into account.
13025 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
13026 use Opcode::*;
13027 match op {
13028 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
13029 | SetVarRef0 => 0,
13030 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
13031 | SetVarRef1 => 1,
13032 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
13033 | SetVarRef2 => 2,
13034 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
13035 | SetVarRef3 => 3,
13036 _ => a as usize,
13037 }
13038 }
13039
13040 /// The argument count of a call, taking `call0`…`call3` into account.
13041 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
13042 use Opcode::*;
13043 match op {
13044 Call0 => 0,
13045 Call1 => 1,
13046 Call2 => 2,
13047 Call3 => 3,
13048 _ => a as usize,
13049 }
13050 }
13051
13052 /// The atom's name as a property key.
13053 ///
13054 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
13055 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
13056 /// `String::clone` was a heap allocation and a copy — per property access.
13057 /// The atom at `index`, as a property key.
13058 ///
13059 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
13060 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
13061 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
13062 /// 5.3% of `property:monomorphic`.
13063 /// The atom's text, exactly — including an unpaired surrogate.
13064 ///
13065 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
13066 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
13067 /// `atom_text` below is for the other kind of use, where the atom is a key in the
13068 /// engine's own tables.
13069 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
13070 self.frame()
13071 .code
13072 .code
13073 .atoms
13074 .get(index)
13075 .map(|atom| match atom {
13076 Atom::Str(text) => text.clone(),
13077 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
13078 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
13079 Atom::Null => crate::value::Wtf8::new(String::new()),
13080 })
13081 .unwrap_or_default()
13082 }
13083
13084 fn atom_text(&self, index: usize) -> String {
13085 self.frame()
13086 .code
13087 .code
13088 .atoms
13089 .get(index)
13090 .map(|atom| match atom {
13091 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
13092 // compare it to an identifier, and a surrogate-bearing name is reachable
13093 // through `atom_wtf8` where it matters.
13094 Atom::Str(text) => text.to_string_lossy().into_owned(),
13095 Atom::Index(value) => value.to_string(),
13096 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
13097 // `throw_error`, `delete super.x`) never read it.
13098 Atom::Null => String::new(),
13099 })
13100 .unwrap_or_default()
13101 }
13102
13103 fn constant(&mut self, index: usize) -> JsResult<Value> {
13104 let constant = self.frame().code.code.cpool.get(index).cloned();
13105 Ok(match &constant {
13106 Some(Constant::Number(number)) => Value::Float(*number),
13107 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
13108 Some(Constant::BigInt { digits, radix }) => {
13109 match crate::bigint::BigInt::from_radix(digits, *radix) {
13110 Some(big) => self.bigint(big),
13111 // A literal the parser accepted is always parseable; a failure here
13112 // would be a compiler bug, so it reads as an `InternalError`.
13113 None => {
13114 return Err(Signal::Throw(
13115 self.make_error("InternalError", "unparseable bigint literal"),
13116 ));
13117 }
13118 }
13119 }
13120 Some(Constant::Function(_)) => {
13121 return Err(Signal::Throw(
13122 self.make_error("InternalError", "a bare function constant"),
13123 ));
13124 }
13125 // A tagged template's call site: a frozen array of the cooked chunks with a
13126 // frozen `raw` array beside it, which is what `String.raw` reads back.
13127 //
13128 // §13.2.8.1 caches it on the realm: `runTemplate()` called twice must hand the
13129 // tag the *same* object, and only a registry gives that. The site is
13130 // (code object, constant index) — see [`Realm::template_map`].
13131 Some(Constant::Template { site, cooked, raw }) => {
13132 // Weakly held, and reaped when the map gets crowded: a program that calls
13133 // `eval` with a tagged template in a loop compiles a fresh site each time,
13134 // and keeping a strong handle would grow this map without bound. Losing an
13135 // expired entry costs nothing — nothing is using the object it named.
13136 if let Some(cached) = self
13137 .realm
13138 .template_map
13139 .get(site)
13140 .and_then(|weak| weak.upgrade())
13141 {
13142 return Ok(Value::Object(cached));
13143 }
13144 let cooked_values: Vec<Value> = cooked
13145 .iter()
13146 .map(|chunk| match chunk {
13147 Some(text) => self.string_wtf8(text.clone()),
13148 None => Value::Undefined,
13149 })
13150 .collect();
13151 let raw_values: Vec<Value> =
13152 raw.iter().map(|text| self.string(text.clone())).collect();
13153 let raw_array = self.new_array(raw_values);
13154 let template = self.new_array(cooked_values);
13155 template.define(
13156 "raw",
13157 Property::with_attributes(Value::Object(raw_array.clone()), false, false),
13158 );
13159 // `SetIntegrityLevel(…, frozen)`, not just a refusal of new properties: the
13160 // template object's indices have to be non-writable and non-configurable, and
13161 // so does `length`. `set_extensible(false)` alone left every index writable,
13162 // which is what `template-object` checks with `verifyProperty`.
13163 // An array of template strings cannot be a proxy, so neither call can be
13164 // refused — `freeze_object` is `?` rather than best-effort on purpose.
13165 crate::builtins::object::freeze_object(self, &raw_array)?;
13166 crate::builtins::object::freeze_object(self, &template)?;
13167 if self.realm.template_map.len() > 256 {
13168 self.realm
13169 .template_map
13170 .retain(|_, weak| weak.upgrade().is_some());
13171 }
13172 self.realm.template_map.insert(*site, template.downgrade());
13173 Value::Object(template)
13174 }
13175 _ => Value::Undefined,
13176 })
13177 }
13178
13179 /// The reference cell a closure-variable slot names.
13180 ///
13181 /// Two kinds of binding share this addressing: a genuine closure variable
13182 /// (captured from an enclosing function) lives in this frame's environment,
13183 /// while a *declared global* lives in the realm so that a script, a function
13184 /// declaration and their uses all see one binding. A plain `Global` — an
13185 /// undeclared name that may be satisfied by the global object — has no cell at
13186 /// all, which is how `typeof x` still works for a name that does not exist.
13187 /// The reference cell a closure-variable slot names.
13188 ///
13189 /// The environment is resolved once, when the closure is built, and this is
13190 /// just the lookup afterwards. A *declared global* is in there too, pointing at
13191 /// the realm's cell, so a script, a hoisted function declaration and their uses
13192 /// all share one binding. A plain `Global` — a name the script never declared —
13193 /// is read and written through `get_var`/`put_var` by name instead, which is
13194 /// what lets the global object satisfy it.
13195 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
13196 self.frame().env.cells.get(slot).cloned()
13197 }
13198
13199 /// Whether `slot` refers to a global binding through the reference table.
13200 ///
13201 /// A global's cell in the closure environment only exists so the slot has
13202 /// something to point at; the binding itself lives on the global object (a `var`)
13203 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
13204 /// be routed, not performed on the placeholder.
13205 fn is_global_slot(&self, slot: usize) -> bool {
13206 self.frame()
13207 .code
13208 .code
13209 .closure_vars
13210 .get(slot)
13211 .is_some_and(|c| {
13212 // A module's declarations and imports are *not* globals: their cells are
13213 // the module environment's, filled by the host, so the placeholder routing
13214 // must not apply to them.
13215 matches!(
13216 c.closure_type,
13217 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
13218 )
13219 })
13220 }
13221
13222 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
13223 if self.is_global_slot(slot) {
13224 return self.get_global(slot);
13225 }
13226 Ok(self
13227 .var_ref_cell(slot)
13228 .map(|cell| cell.get())
13229 .unwrap_or(Value::Undefined))
13230 }
13231
13232 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
13233 // A function declaration is hoisted by storing into a global reference before
13234 // the body runs, so this path is also what puts it on the global object.
13235 if self.is_global_slot(slot) {
13236 return self.put_global(slot, value);
13237 }
13238 if let Some(cell) = self.var_ref_cell(slot) {
13239 cell.set(value);
13240 }
13241 Ok(())
13242 }
13243
13244 // -- closures -----------------------------------------------------------
13245
13246 /// Build the closure for the function constant `index`.
13247 ///
13248 /// Every entry in the child's closure table names where its binding lives in
13249 /// *this* frame: a local or argument slot that was marked captured, or a cell
13250 /// this frame is itself holding. That is how a variable three functions deep
13251 /// stays one binding.
13252 fn closure(&mut self, index: usize) -> JsResult<Value> {
13253 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
13254 else {
13255 return Err(Signal::Throw(
13256 self.make_error("InternalError", "fclosure of a non-function"),
13257 ));
13258 };
13259 let mut cells = Vec::with_capacity(function.closure_vars.len());
13260 for closure_var in &function.closure_vars {
13261 let cell = match closure_var.closure_type {
13262 ClosureType::Arg => {
13263 let slot = closure_var.var_idx as usize;
13264 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
13265 }
13266 ClosureType::Local => {
13267 let slot = closure_var.var_idx as usize;
13268 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
13269 }
13270 ClosureType::Ref | ClosureType::GlobalRef => {
13271 // A `Ref` names a cell in this frame's own closure table; a
13272 // `GlobalRef` also starts there, then resolves by name below.
13273 let slot = closure_var.var_idx as usize;
13274 if let Some(cell) = self.frame().env.cells.get(slot) {
13275 cells.push(cell.clone());
13276 continue;
13277 }
13278 -1
13279 }
13280 _ => -1,
13281 };
13282 if cell >= 0 {
13283 let cell = self.frame().cells[cell as usize].clone();
13284 cells.push(cell);
13285 continue;
13286 }
13287 // A global: the cell is created on demand and shared through the realm,
13288 // so every function sees one binding.
13289 let name = closure_var.name.clone();
13290 let cell = match self.realm.globals.get(&name) {
13291 Some(cell) => cell.clone(),
13292 None => {
13293 let cell = self.new_cell(Value::Undefined);
13294 self.realm.globals.insert(name.clone(), cell.clone());
13295 cell
13296 }
13297 };
13298 cells.push(cell);
13299 }
13300 let name = function.name.clone();
13301 // `.length` is the arity before any default or rest parameter, not the number
13302 // of slots a pattern parameter needs.
13303 let length = function.defined_args;
13304 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
13305 // function and an arrow function do not. A *method* also does not, but that is not
13306 // known here — the method is marked when the `[[HomeObject]]` is attached (see
13307 // `set_home_object`), which is the moment it becomes a method.
13308 let function_kind = function.kind;
13309 let constructible =
13310 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
13311 let code = Gc::new(self.heap, CompiledCode::new(*function));
13312 // A closure built inside an `eval` inherits the eval's view of the enclosing
13313 // bindings, so it can still read them once the eval has returned.
13314 let eval_scope = self
13315 .active_eval_scope
13316 .clone()
13317 .or_else(|| self.frame().env.eval_scope.clone());
13318 // A closure sees the variables a direct `eval` declared in the frame it was
13319 // created in — the ones declared before *and after* it, so the same object is
13320 // shared; only the phase bounds which of them are visible.
13321 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
13322 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
13323 let env = Gc::new(
13324 self.heap,
13325 ClosureEnv {
13326 cells,
13327 eval_scope,
13328 local_vars,
13329 local_phase,
13330 },
13331 );
13332 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
13333 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
13334 // the only thing that carries `Symbol.toStringTag`, so without it
13335 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
13336 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
13337 let proto = match function_kind {
13338 js_compile::bytecode::FunctionKind::AsyncGenerator => self
13339 .realm
13340 .async_generator_function_proto
13341 .clone()
13342 .or_else(|| self.realm.function_proto.clone().into()),
13343 js_compile::bytecode::FunctionKind::Generator => self
13344 .realm
13345 .generator_function_proto
13346 .clone()
13347 .or_else(|| self.realm.function_proto.clone().into()),
13348 js_compile::bytecode::FunctionKind::Async => self
13349 .realm
13350 .async_function_proto
13351 .clone()
13352 .or_else(|| self.realm.function_proto.clone().into()),
13353 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
13354 };
13355 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
13356 object.set_constructible(constructible);
13357 object.define(
13358 "length",
13359 Property::name_or_length(Value::Int(length as i32)),
13360 );
13361 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
13362 // that checks the own-property descriptor fails if the property is missing.
13363 object.define("name", Property::name_or_length(self.string(name)));
13364 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
13365 // when `[[Construct]]` is created, so an async function and an arrow function have
13366 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
13367 // function) an own `prototype` property, which `builtin.js` checks for absence.
13368 //
13369 // A **generator** function is the exception that is not constructible: it still
13370 // gets a `prototype` field, because that object is what a generator *instance*
13371 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
13372 // made `function* g(){}; g.prototype` `undefined` and every generator share
13373 // `%GeneratorPrototype%` as its direct prototype.
13374 if constructible {
13375 self.install_function_prototype(&object);
13376 } else if matches!(
13377 function_kind,
13378 js_compile::bytecode::FunctionKind::Generator
13379 | js_compile::bytecode::FunctionKind::AsyncGenerator
13380 ) {
13381 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
13382 self.realm.generator_proto.clone()
13383 } else {
13384 self.realm
13385 .async_generator_proto
13386 .clone()
13387 .unwrap_or_else(|| self.realm.generator_proto.clone())
13388 };
13389 self.install_generator_prototype(&object, parent);
13390 }
13391 Ok(Value::Object(object))
13392 }
13393
13394 // -- conversions used by the operators ----------------------------------
13395
13396 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
13397 // `+x` is `ToNumber`, which for a string parses it and for an object runs
13398 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
13399 // string, which then behaves differently in every later comparison.
13400 match value {
13401 Value::Int(_) | Value::Float(_) => Ok(value),
13402 other => Ok(Value::Float(self.to_js_number(&other)?)),
13403 }
13404 }
13405
13406 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
13407 ///
13408 /// Returns the *converted* old value and the new one, because the two callers need
13409 /// different halves: `++x` yields the new value, while `x++` yields the old one and
13410 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
13411 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
13412 /// boolean.
13413 ///
13414 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
13415 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
13416 /// a bigint algorithm then ran exactly once.
13417 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
13418 if let Value::BigInt(big) = &value {
13419 let one = crate::bigint::BigInt::from_i64(1);
13420 let next = if up { big.add(&one) } else { big.sub(&one) };
13421 return Ok((value, self.bigint(next)));
13422 }
13423 let old = self.numeric_operand(value)?;
13424 if let Value::BigInt(big) = &old {
13425 let one = crate::bigint::BigInt::from_i64(1);
13426 let next = if up { big.add(&one) } else { big.sub(&one) };
13427 return Ok((old, self.bigint(next)));
13428 }
13429 let new = if up {
13430 increment(old.clone())
13431 } else {
13432 decrement(old.clone())
13433 };
13434 Ok((old, new))
13435 }
13436
13437 /// `ToNumeric` for a unary or update operand: `ToPrimitive(number)`, then either branch.
13438 ///
13439 /// The unary operators are defined on `Numeric`, not on `Number`: `-x` and `~x` are
13440 /// `Numeric::unaryMinus`/`bitwiseNOT`, which a bigint answers exactly. [`Interp::numeric`]
13441 /// is `ToNumber` and collapses a bigint to a float, so an operand that is a *wrapper
13442 /// object* — `-Object(5n)` — lost its bigint-ness before the operator ever saw it and
13443 /// raised "cannot convert bigint to number". A primitive bigint never took that path
13444 /// (`Neg`/`Not` matched `Value::BigInt` first), which is why only the boxed form broke.
13445 fn numeric_operand(&mut self, value: Value) -> JsResult<Value> {
13446 let primitive = match value {
13447 Value::Int(_) | Value::Float(_) | Value::BigInt(_) => value,
13448 other => self.to_primitive(other, Hint::Number)?,
13449 };
13450 match primitive {
13451 Value::BigInt(_) => Ok(primitive),
13452 other => self.numeric(other),
13453 }
13454 }
13455
13456 fn numeric(&mut self, value: Value) -> JsResult<Value> {
13457 // `ToNumber` on an object runs `ToPrimitive` first, which is how
13458 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
13459 // heard at all. Reading the object's own tag instead (`other.to_number()`)
13460 // turned the whole operand into `NaN` and swallowed the exception.
13461 match value {
13462 Value::Int(_) | Value::Float(_) => Ok(value),
13463 other => Ok(Value::Float(self.to_js_number(&other)?)),
13464 }
13465 }
13466
13467 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
13468 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
13469 match value {
13470 Value::BigInt(big) => Ok((**big).clone()),
13471 // The reference words this the same way for every operator, so a failing
13472 // script reads identically; the operator itself adds nothing a caller can use.
13473 _ => Err(Signal::Throw(
13474 self.make_error("TypeError", "cannot convert bigint to number"),
13475 )),
13476 }
13477 }
13478
13479 /// Arithmetic where at least one operand is a `BigInt`.
13480 ///
13481 /// The two numeric types never mix, so a bigint paired with anything else is an error
13482 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
13483 /// that the relational operators handle it separately.
13484 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13485 use Opcode::*;
13486 let a = self.bigint_operand(&left)?;
13487 let b = self.bigint_operand(&right)?;
13488 let result = match op {
13489 Add => a.add(&b),
13490 Sub => a.sub(&b),
13491 Mul => a.mul(&b),
13492 Div | Mod => {
13493 let Some((quotient, remainder)) = a.div_rem(&b) else {
13494 return Err(Signal::Throw(
13495 self.make_error("RangeError", "division by zero"),
13496 ));
13497 };
13498 if op == Div { quotient } else { remainder }
13499 }
13500 Pow => {
13501 let Some(value) = a.pow(&b) else {
13502 return Err(Signal::Throw(self.make_error(
13503 "RangeError",
13504 "BigInt exponent must be non-negative and not absurdly large",
13505 )));
13506 };
13507 value
13508 }
13509 And => a.bitand(&b),
13510 Or => a.bitor(&b),
13511 Xor => a.bitxor(&b),
13512 Shl | Sar => {
13513 // A shift count is a `BigInt` here, and both directions are exact; a
13514 // negative count would be the other direction, which the spec forbids.
13515 let Some(count) = b.to_i64() else {
13516 return Err(Signal::Throw(
13517 self.make_error("RangeError", "BigInt shift count is too large"),
13518 ));
13519 };
13520 if count < 0 {
13521 return Err(Signal::Throw(self.make_error(
13522 "RangeError",
13523 "BigInt shift count must be non-negative",
13524 )));
13525 }
13526 if op == Shl {
13527 a.shl(count as u64)
13528 } else {
13529 a.shr(count as u64)
13530 }
13531 }
13532 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
13533 _ => {
13534 return Err(Signal::Throw(self.make_error(
13535 "TypeError",
13536 "BigInts have no unsigned right shift, use >> instead",
13537 )));
13538 }
13539 };
13540 Ok(self.bigint(result))
13541 }
13542
13543 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
13544 ///
13545 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
13546 /// is on the mathematical values, and nothing is rounded first.
13547 /// `<`, `<=`, `>`, `>=`.
13548 ///
13549 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
13550 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
13551 /// It is a `?`-returning function for exactly that reason: an object operand can run
13552 /// script, and script can throw. The old version compared `to_number` of the raw
13553 /// values, which answered `false` for every object instead of calling `valueOf` —
13554 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
13555 /// never ran.
13556 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13557 // The hot arm first: `i < n` with both sides already integers. No conversion, no
13558 // call, nothing that can throw.
13559 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13560 let ordering = Some(left.cmp(right));
13561 return Ok(ordering_answer(op, ordering));
13562 }
13563 // Anything that can run script has to be converted first, in this order.
13564 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
13565 {
13566 (
13567 self.to_primitive(left, Hint::Number)?,
13568 self.to_primitive(right, Hint::Number)?,
13569 )
13570 } else {
13571 (left, right)
13572 };
13573 let ordering = match (&left, &right) {
13574 // The loop condition `i < n` is integer against integer, and it runs once
13575 // per iteration of every loop in every program. Without this arm it took the
13576 // `to_number` path twice, which is a `match` plus a conversion each.
13577 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
13578 // **Code unit** order, not code point order. They differ exactly where a
13579 // surrogate pair meets a BMP character above U+E000: `"\uDC00" > "\uD800"` is
13580 // true because 0xDC00 > 0xD800, while comparing code points would have turned
13581 // both lone surrogates into U+FFFD and called them equal
13582 // (`greater-than/S11.8.2_A4.12_T1`).
13583 (Value::String(a), Value::String(b)) => Some(compare_code_units(a, b)),
13584 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
13585 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
13586 // is true even though `2.5` has no bigint form.
13587 // §7.2.13 step 3.d-3.e: a bigint against a string goes through
13588 // `StringToBigInt`, **not** `ToNumber` — `"9007199254740993" > 9007199254740992n`
13589 // is true because both sides stay exact integers, which converting the string to
13590 // a double would destroy. A string that is not an integer literal makes the
13591 // whole comparison `undefined`, i.e. `false` for every relational operator.
13592 (Value::BigInt(a), Value::String(text)) => {
13593 string_to_bigint(&text.to_string_lossy()).map(|b| a.cmp(&b))
13594 }
13595 (Value::String(text), Value::BigInt(b)) => {
13596 string_to_bigint(&text.to_string_lossy()).map(|a| b.cmp(&a).reverse())
13597 }
13598 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
13599 let b = self.number_operand(other)?;
13600 if b.is_nan() {
13601 None
13602 } else {
13603 compare_bigint_and_f64(a, b)
13604 }
13605 }
13606 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
13607 let a = self.number_operand(other)?;
13608 if a.is_nan() {
13609 None
13610 } else {
13611 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
13612 }
13613 }
13614 // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
13615 // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
13616 // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
13617 _ => self
13618 .to_js_number(&left)?
13619 .partial_cmp(&self.to_js_number(&right)?),
13620 };
13621 Ok(ordering_answer(op, ordering))
13622 }
13623
13624 /// `ToNumber(V)`, refusing a Symbol instead of answering `NaN`.
13625 ///
13626 /// §7.1.4 throws for a Symbol, and the relational operators inherit that: `3n < Symbol()`
13627 /// is a `TypeError`, not `false`. `Value::to_number` is a total function — it has to be,
13628 /// because it is also what `Number(x)` uses — so the check lives here.
13629 fn number_operand(&self, value: &Value) -> JsResult<f64> {
13630 if matches!(value, Value::Symbol(_)) {
13631 return Err(self.type_error("cannot convert symbol to number"));
13632 }
13633 Ok(value.to_number())
13634 }
13635
13636 fn binary_add(&mut self) -> JsResult<()> {
13637 let right = self.pop();
13638 let left = self.pop();
13639 // Two integers add without any of the machinery below: no `ToPrimitive` (an
13640 // `Int` is already primitive), no string check, no bigint check, no allocation.
13641 // `x += 1` in a loop is the single most common instruction sequence in real
13642 // script, and it used to walk every one of those checks before reaching the
13643 // same `checked_add`.
13644 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13645 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
13646 return Ok(());
13647 }
13648 let left = self.primitive_of(left)?;
13649 let right = self.primitive_of(right)?;
13650 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
13651 // that check comes before the bigint one: `"" + 1n` is a string, not a
13652 // mixed-type error.
13653 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
13654 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
13655 // `TypeError`, the one place a symbol and a string do not mix.
13656 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
13657 // between a copy and a rope from their lengths, and a rope is what turns
13658 // `text += "abc"` in a loop from quadratic into linear.
13659 if let (Value::String(left), Value::String(right)) = (&left, &right) {
13660 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
13661 // reports as `InternalError: string too long`.
13662 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
13663 return Err(Signal::Throw(
13664 self.make_error("InternalError", "string too long"),
13665 ));
13666 };
13667 self.push(Value::String(Gc::new(self.heap, joined)));
13668 return Ok(());
13669 }
13670 // At least one operand was not a string, so `ToString` it. This rejects a
13671 // symbol, which is the one place a symbol and a string do not mix.
13672 let left = self.checked_to_wtf8(&left)?;
13673 let right = self.checked_to_wtf8(&right)?;
13674 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
13675 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
13676 let text = left.concat(&right);
13677 self.push(self.string_wtf8(text));
13678 return Ok(());
13679 }
13680 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
13681 // not a conversion.
13682 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
13683 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
13684 self.push(value);
13685 return Ok(());
13686 }
13687 let left = self.numeric(left)?;
13688 let right = self.numeric(right)?;
13689 self.push(add_numbers(left, right));
13690 Ok(())
13691 }
13692
13693 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
13694 self.to_primitive(value, Hint::Default)
13695 }
13696
13697 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
13698 ///
13699 /// The order depends on the hint: the "number" order tries `valueOf` first and
13700 /// `toString` second, the "string" order the other way round, and the default
13701 /// hint uses the number order. A result that is still an object is a `TypeError`,
13702 /// because no built-in `valueOf`/`toString` returns one.
13703 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
13704 let Value::Object(object) = &value else {
13705 return Ok(value);
13706 };
13707 // A Date overrides the default hint to mean "string", which is what
13708 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
13709 // this, `"" + new Date()` would print the milliseconds, not the date.
13710 let hint = if hint == Hint::Default && is_date_object(self, object) {
13711 Hint::String
13712 } else {
13713 hint
13714 };
13715 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
13716 // handed the hint as a string. This is the hook a Date uses for its default hint
13717 // and a script uses to take over conversion entirely.
13718 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
13719 // `GetMethod`, not "is it a callable object": the property has to be read and then
13720 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
13721 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
13722 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
13723 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
13724 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
13725 // callable.
13726 match self.get_property_key(object, &key)? {
13727 None | Some(Value::Undefined) | Some(Value::Null) => {}
13728 Some(Value::Object(function)) if function.is_callable() => {
13729 let hint = match hint {
13730 Hint::String => "string",
13731 Hint::Number => "number",
13732 Hint::Default => "default",
13733 };
13734 let hint = self.string(hint);
13735 let result = self.call_value(
13736 Value::Object(function),
13737 Value::Object(object.clone()),
13738 vec![hint],
13739 )?;
13740 if !matches!(result, Value::Object(_)) {
13741 return Ok(result);
13742 }
13743 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
13744 }
13745 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
13746 }
13747 let order: [&str; 2] = match hint {
13748 Hint::String => ["toString", "valueOf"],
13749 Hint::Number | Hint::Default => ["valueOf", "toString"],
13750 };
13751 let receiver = object.clone();
13752 for method in order {
13753 if let Some(function) = self.get_property(&receiver, method)?
13754 && matches!(&function, Value::Object(object) if object.is_callable())
13755 {
13756 let result =
13757 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13758 if !matches!(result, Value::Object(_)) {
13759 return Ok(result);
13760 }
13761 }
13762 }
13763 Err(self.type_error("cannot convert object to primitive value"))
13764 }
13765
13766 /// `ToString` with the object case going through `ToPrimitive`.
13767 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13768 if matches!(value, Value::Object(_)) {
13769 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13770 return Ok(primitive.to_js_string());
13771 }
13772 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13773 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13774 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13775 // check here broke `String(Symbol())` and 45 cases that print a symbol.
13776 Ok(value.to_js_string())
13777 }
13778
13779 /// `ToString(value)`, with §7.1.19's symbol refusal.
13780 ///
13781 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13782 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13783 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13784 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13785 if matches!(value, Value::Symbol(_)) {
13786 return Err(self.type_error("cannot convert a Symbol to a string"));
13787 }
13788 if matches!(value, Value::Object(_)) {
13789 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13790 if matches!(primitive, Value::Symbol(_)) {
13791 return Err(self.type_error("cannot convert a Symbol to a string"));
13792 }
13793 return Ok(primitive.to_js_string());
13794 }
13795 Ok(value.to_js_string())
13796 }
13797
13798 /// `ToString` that keeps the string's code units instead of flattening them.
13799 ///
13800 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13801 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13802 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13803 if matches!(value, Value::Symbol(_)) {
13804 return Err(Signal::Throw(
13805 self.make_error("TypeError", "cannot convert symbol to string"),
13806 ));
13807 }
13808 // An object runs `ToPrimitive` first, which may itself produce a symbol.
13809 let value = self.to_primitive(value.clone(), Hint::String)?;
13810 match value {
13811 Value::Symbol(_) => Err(Signal::Throw(
13812 self.make_error("TypeError", "cannot convert symbol to string"),
13813 )),
13814 Value::String(text) => Ok(text.wtf8().clone()),
13815 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13816 }
13817 }
13818
13819 /// `ToNumber` with the object case going through `ToPrimitive`.
13820 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13821 let value = if matches!(value, Value::Object(_)) {
13822 self.to_primitive(value.clone(), Hint::Number)?
13823 } else {
13824 value.clone()
13825 };
13826 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13827 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13828 // `NaN` to stay total, and the operators check for the bigint themselves — but
13829 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13830 // refuse, and answering `NaN` made them silently wrong instead.
13831 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13832 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13833 match value {
13834 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13835 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13836 other => Ok(other.to_number()),
13837 }
13838 }
13839
13840 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13841 /// [`ElementType::write`].
13842 ///
13843 /// This is separated from the write because both conversions are observable script —
13844 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13845 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13846 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13847 /// setters, and a plain `a[i] = v`.
13848 pub(crate) fn element_value(
13849 &mut self,
13850 element: crate::builtins::typedarray::ElementType,
13851 value: Value,
13852 ) -> JsResult<Value> {
13853 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13854 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13855 let primitive = match &value {
13856 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13857 _ => value,
13858 };
13859 if element.is_bigint() {
13860 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13861 Ok(Value::BigInt(Gc::new(self.heap, big)))
13862 } else {
13863 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13864 Ok(Value::Float(self.to_js_number(&primitive)?))
13865 }
13866 }
13867
13868 /// `ToPropertyKey`: what a computed member access uses as its key.
13869 ///
13870 /// A symbol is returned as itself, never stringified — that is what keeps
13871 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13872 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13873 match value {
13874 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13875 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13876 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13877 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13878 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13879 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13880 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13881 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13882 other.to_js_string(),
13883 ))),
13884 },
13885 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13886 }
13887 }
13888
13889 /// `ToPropertyKey` for the callers that can only use a string key.
13890 ///
13891 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13892 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13893 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13894 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13895 /// program continues with a value nobody asked for.
13896 /// `SetFunctionName`'s name for a computed key, which is not `ToPropertyKey`.
13897 ///
13898 /// §7.3.24 step 1: when the key is a **Symbol**, the name is `"[" + description + "]"`
13899 /// — or the empty string when the symbol has no description. Going through
13900 /// `ToPropertyKey` instead gave `Symbol(test262)` and `Symbol()`, so every
13901 /// `{ [sym](){} }` method had the wrong `name` (`fn-name-fn` and its generated
13902 /// relatives, in both `expressions/object` and `statements/class`).
13903 ///
13904 /// Everything else is an ordinary `ToPropertyKey` — a string key keeps its code units,
13905 /// which is what makes `{ "\uD800": function () {} }.name` the lone surrogate.
13906 fn function_name_from_key(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13907 if let Value::Symbol(symbol) = value {
13908 return Ok(match symbol.description() {
13909 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
13910 None => crate::value::Wtf8::default(),
13911 });
13912 }
13913 self.propkey_of(value)
13914 }
13915
13916 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13917 use crate::value::Wtf8;
13918 Ok(match value {
13919 // A string key keeps its code units. Going through a lossy `String` would make
13920 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13921 Value::String(text) => text.wtf8().clone(),
13922 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13923 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13924 // falling back to its `ToString` would print `[object Object]`.
13925 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13926 Value::String(text) => text.wtf8().clone(),
13927 other => Wtf8::new(other.to_js_string()),
13928 },
13929 other => Wtf8::new(other.to_js_string()),
13930 })
13931 }
13932
13933 // -- object operations used by instructions -----------------------------
13934
13935 /// Read `object[key]`, returning `undefined` when the property is missing.
13936 ///
13937 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13938 /// primitive (looking through its prototype) as well as an object — which is what
13939 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13940 /// argument needs too.
13941 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13942 self.read_field_key(object, &PropertyKey::from(key))
13943 }
13944
13945 /// [`Interp::read_field`] with a key that may be a symbol.
13946 ///
13947 /// A symbol key never reaches the string shortcuts: a string's `length` and its
13948 /// indices are string properties, and a symbol named `length` is a different
13949 /// property that a string primitive cannot have.
13950 /// [`Interp::read_field_key`], with an inline cache in front of it.
13951 ///
13952 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13953 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13954 /// without this the engine walked the chain and compared ~40 property names on each
13955 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13956 ///
13957 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13958 /// missing property. Those answers depend on running code or on state the guard below
13959 /// does not cover, and a wrong answer here is far more expensive than a lookup.
13960 ///
13961 /// A hit is re-validated against the *whole* walked chain, not just the level that
13962 /// answered: the receiver and every prototype down to that level must still be the same
13963 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13964 /// property-table *lengths* — which is what catches a property appearing on an
13965 /// intermediate prototype and shadowing the cached one.
13966 pub fn read_field_cached(
13967 &mut self,
13968 object: &Value,
13969 key: &PropertyKey,
13970 slot: usize,
13971 ) -> JsResult<Value> {
13972 let index = Self::field_cache_slot(object, key, slot);
13973 let Value::Object(target) = object else {
13974 return self.read_field_key(object, key);
13975 };
13976 if target.proxy_state().is_some() {
13977 return self.read_field_key(object, key);
13978 }
13979 if let Some(cached) = &self.field_cache[index]
13980 && cached.key == *key
13981 && let Some(value) = Self::cached_hit(target, cached)
13982 {
13983 return Ok(value);
13984 }
13985 let value = self.read_field_key(object, key)?;
13986 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13987 Ok(value)
13988 }
13989
13990 /// Whether a cache entry still describes this lookup, and if so the value.
13991 ///
13992 /// The guard is the whole point of the entry: identity plus property-table length for
13993 /// every level walked. Re-checked per level rather than once at the receiving end,
13994 /// because a shadowing property can appear anywhere along the chain.
13995 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13996 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13997 // starts with: a clone is a reference-count bump and a drop, and for
13998 // `property:monomorphic` every single hit takes only this arm.
13999 let (weak, len) = cached.chain[0].as_ref()?;
14000 if !target.upgrades_to(weak) {
14001 return None;
14002 }
14003 if cached.level == 0 {
14004 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
14005 return target.cached_property_at(cached.index, &cached.key, *len);
14006 }
14007 if target.props_len() != *len {
14008 return None;
14009 }
14010 let mut level = 1;
14011 let mut current = target.proto()?;
14012 loop {
14013 let (weak, len) = cached.chain[level].as_ref()?;
14014 if !current.upgrades_to(weak) || current.props_len() != *len {
14015 return None;
14016 }
14017 if level == cached.level as usize {
14018 // The level that answered: the value is only reusable while the key is
14019 // still there and still a plain data property.
14020 return current.cached_data_property(cached.index, &cached.key);
14021 }
14022 current = current.proto()?;
14023 level += 1;
14024 }
14025 }
14026
14027 /// Build a cache entry for a lookup that just went through the slow path.
14028 ///
14029 /// Records the chain only when the answer came from a plain data property at a level
14030 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
14031 /// costs the next lookup the walk it would have cost anyway.
14032 fn record_field_lookup(
14033 target: &Gc<JsObject>,
14034 key: &PropertyKey,
14035 _value: Value,
14036 ) -> Option<FieldCache> {
14037 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
14038 [None, None, None];
14039 let mut current = target.clone();
14040 for level in 0..MAX_CACHED_CHAIN {
14041 chain[level] = Some((current.downgrade(), current.props_len()));
14042 if let Some((found, _)) = current.own_property_index(key) {
14043 // `own_property_index` declines an accessor and a hole, which is exactly
14044 // the set that must not be cached.
14045 return Some(FieldCache {
14046 key: key.clone(),
14047 index: found,
14048 level: level as u8,
14049 chain,
14050 });
14051 }
14052 current = current.proto()?;
14053 }
14054 None
14055 }
14056
14057 /// Which cache slot a lookup uses.
14058 ///
14059 /// Mixes the object's address, the name and the site, so that two properties of one
14060 /// object, and one property of two objects, land in different slots — which is what lets
14061 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
14062 /// other iteration.
14063 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
14064 let mut hash = match object {
14065 Value::Object(object) => object.address(),
14066 _ => 0,
14067 };
14068 hash = hash
14069 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
14070 .rotate_left(17)
14071 .wrapping_add(key.hash_code());
14072 hash = hash.wrapping_add(site.wrapping_mul(31));
14073 // The table is a power of two, so the low bits are the slot.
14074 hash & (FIELD_CACHE_SLOTS - 1)
14075 }
14076
14077 /// Read `key` from `object`, without the inline cache.
14078 ///
14079 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
14080 /// prototype chain, while the cached form answers an own data property from memory.
14081 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
14082 let text = key.as_str().unwrap_or("");
14083 let Value::Object(object) = object else {
14084 // Reading a property of `undefined`/`null` is the classic TypeError.
14085 if object.is_nullish() {
14086 return Err(Signal::Throw(self.make_error(
14087 "TypeError",
14088 &format!("cannot read property '{key}' of {}", object.to_js_string()),
14089 )));
14090 }
14091 // A string has `length` and index access without being boxed.
14092 if let Value::String(value) = object {
14093 if text == "length" {
14094 return Ok(Value::Int(value.utf16_len() as i32));
14095 }
14096 if let Some(index) = array_index(text) {
14097 return Ok(match value.wtf8().unit_at(index as usize) {
14098 Some(unit) => self.string_wtf8(unit),
14099 None => Value::Undefined,
14100 });
14101 }
14102 }
14103 // A property of a primitive is looked up on its prototype: this is what
14104 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
14105 let prototype = match object {
14106 Value::String(_) => self.realm.string_proto.clone(),
14107 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14108 Value::Bool(_) => self.realm.boolean_proto.clone(),
14109 // A symbol's methods live on `Symbol.prototype`, reached the same way —
14110 // `sym.description` reads through the prototype, not off the symbol.
14111 Value::Symbol(_) => self.realm.symbol_proto.clone(),
14112 // …and a bigint's on `BigInt.prototype`, which is how
14113 // `(255n).toString(16)` reaches its method.
14114 Value::BigInt(_) => self.realm.bigint_proto.clone(),
14115 _ => None,
14116 };
14117 if let Some(prototype) = prototype
14118 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
14119 {
14120 return Ok(value);
14121 }
14122 return Ok(Value::Undefined);
14123 };
14124 Ok(self
14125 .get_property_key(object, key)?
14126 .unwrap_or(Value::Undefined))
14127 }
14128
14129 /// The `#name` a private symbol stands for, for error messages.
14130 ///
14131 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
14132 /// was made from.
14133 fn private_name(symbol: &Value) -> Option<String> {
14134 match symbol {
14135 Value::Symbol(symbol) if symbol.is_private() => Some(
14136 symbol
14137 .description()
14138 .map(|text| text.to_string())
14139 .unwrap_or_default(),
14140 ),
14141 _ => None,
14142 }
14143 }
14144
14145 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
14146 ///
14147 /// Every private-field opcode takes the symbol the class stored in its own scope; a
14148 /// non-symbol here would be a compiler bug, and the reference guards it with
14149 /// `JS_ThrowTypeErrorNotASymbol`.
14150 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
14151 match symbol {
14152 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
14153 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
14154 }
14155 }
14156
14157 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
14158 ///
14159 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
14160 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
14161 /// would hit if the parser did not reject it first.
14162 fn define_private_field(
14163 &mut self,
14164 object: &Value,
14165 symbol: &Value,
14166 value: Value,
14167 ) -> JsResult<()> {
14168 let key = self.private_key(symbol)?;
14169 let Some(target) = object.as_object() else {
14170 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14171 };
14172 if !target.is_extensible() {
14173 return Err(Signal::Throw(
14174 self.make_error("TypeError", "object is not extensible"),
14175 ));
14176 }
14177 if target.own_property_key(&key).is_some() {
14178 let name = Self::private_name(symbol).unwrap_or_default();
14179 return Err(Signal::Throw(self.make_error(
14180 "TypeError",
14181 &format!("private class field '{name}' already exists"),
14182 )));
14183 }
14184 target.define_data_key(&key, value);
14185 Ok(())
14186 }
14187
14188 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
14189 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
14190 let key = self.private_key(symbol)?;
14191 let Some(target) = object.as_object() else {
14192 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14193 };
14194 match target.own_property_key(&key) {
14195 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
14196 None => {
14197 let name = Self::private_name(symbol).unwrap_or_default();
14198 Err(Signal::Throw(self.make_error(
14199 "TypeError",
14200 &format!("private class field '{name}' does not exist"),
14201 )))
14202 }
14203 }
14204 }
14205
14206 /// `JS_SetPrivateField`: the store half of the same rule.
14207 fn write_private_field(
14208 &mut self,
14209 object: &Value,
14210 symbol: &Value,
14211 value: Value,
14212 ) -> JsResult<()> {
14213 let key = self.private_key(symbol)?;
14214 let Some(target) = object.as_object() else {
14215 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14216 };
14217 if target.write_value_key(&key, value) {
14218 return Ok(());
14219 }
14220 let name = Self::private_name(symbol).unwrap_or_default();
14221 Err(Signal::Throw(self.make_error(
14222 "TypeError",
14223 &format!("private class field '{name}' does not exist"),
14224 )))
14225 }
14226
14227 /// The `in` half: does `object` have this private field?
14228 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
14229 ///
14230 /// The symbol is created once per class — the first `add_brand` on a given home object
14231 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
14232 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
14233 /// emit for the *instance* brand passes null because all it wants is the symbol.
14234 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
14235 let Some(home_object) = home.as_object() else {
14236 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14237 };
14238 let symbol = match home_object.private_brand() {
14239 Some(symbol) => symbol,
14240 None => {
14241 let symbol = Gc::new(
14242 self.heap,
14243 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
14244 );
14245 home_object.set_private_brand(symbol.clone());
14246 symbol
14247 }
14248 };
14249 let Some(target) = object.as_object() else {
14250 // Not an object: nothing to brand. The reference does the same, and `undefined`
14251 // here would otherwise turn a field initialiser into a TypeError.
14252 return Ok(());
14253 };
14254 if !target.is_extensible() {
14255 return Err(Signal::Throw(
14256 self.make_error("TypeError", "object is not extensible"),
14257 ));
14258 }
14259 if target.carries_brand(&symbol) {
14260 return Err(Signal::Throw(
14261 self.make_error("TypeError", "private method is already present"),
14262 ));
14263 }
14264 target.add_brand(symbol);
14265 Ok(())
14266 }
14267
14268 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
14269 ///
14270 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
14271 /// decides whether to throw.
14272 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
14273 let Some(function) = function.as_object() else {
14274 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14275 };
14276 let Some(home) = function.home_object() else {
14277 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14278 };
14279 let Some(brand) = home.private_brand() else {
14280 return Err(Signal::Throw(
14281 self.make_error("TypeError", "expecting <brand> private field"),
14282 ));
14283 };
14284 Ok(object.carries_brand(&brand))
14285 }
14286
14287 /// `CreateDataPropertyOrThrow(object, key, value)` — §7.3.3.
14288 ///
14289 /// What a property definition does: `[[DefineOwnProperty]]` with all three attributes
14290 /// true. Not `[[Set]]`, which walks the prototype chain and may run a setter there.
14291 fn define_field(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
14292 if let Some(target) = object.as_object() {
14293 // `CreateDataProperty` cannot reshape a non-configurable own property: its
14294 // descriptor asks for `writable` and `configurable`, and a non-configurable
14295 // property may become neither (`class C { static ['prototype'] = 1 }` is a
14296 // `TypeError`, since the constructor's `prototype` is both). The general define
14297 // path only validates *partial* descriptors — see the note there — so this has
14298 // to be said here.
14299 if self
14300 .object_get_own_property(target, key)?
14301 .is_some_and(|existing| {
14302 !existing.configurable && (existing.is_accessor() || !existing.writable)
14303 })
14304 {
14305 return Err(Signal::Throw(self.make_error(
14306 "TypeError",
14307 &format!(
14308 "cannot define property '{key}' of {}",
14309 Value::Object(target.clone()).to_js_string()
14310 ),
14311 )));
14312 }
14313 // Only an *array* stores into the element vector. A numeric key
14314 // on an ordinary object is an ordinary property, which is what
14315 // makes `{1: 'a'}` iterate as a key rather than disappear.
14316 let stored = target.is_array()
14317 && key.as_str().and_then(array_index).is_some_and(|index| {
14318 target.array_set(self.heap, index as usize, value.clone())
14319 });
14320 if !stored {
14321 // `CreateDataPropertyOrThrow`, not a raw table insert: a class
14322 // field is defined with `[[DefineOwnProperty]]`, so a frozen
14323 // receiver throws (`class Test { f = Object.freeze(this); g = 1 }`
14324 // must fail on `g`) and a **proxy** receiver runs its
14325 // `defineProperty` trap (`class-field-is-observable-by-proxy`
14326 // counts the trap's calls). `define_data_key` writes straight into
14327 // the table, which did neither.
14328 // `?` and not `unwrap_or(false)`: a proxy's `defineProperty` trap
14329 // may *throw*, and that exception is the answer
14330 // (`public-class-field-initialization-is-visible-to-proxy` throws
14331 // a `Test262Error` from the trap and expects it, not a `TypeError`).
14332 let defined =
14333 self.object_define_own_property(target, key, Property::data(value))?;
14334 if !defined {
14335 let target = Value::Object(target.clone());
14336 return Err(Signal::Throw(self.make_error(
14337 "TypeError",
14338 &format!(
14339 "cannot define property '{key}' of {}",
14340 target.to_js_string()
14341 ),
14342 )));
14343 }
14344 }
14345 }
14346 Ok(())
14347 }
14348
14349 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
14350 let Value::Object(object) = object else {
14351 // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
14352 // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
14353 // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
14354 // `undefined` still throw, with their own message.
14355 if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
14356 return Ok(());
14357 }
14358 return Err(Signal::Throw(self.make_error(
14359 "TypeError",
14360 &format!("cannot set property '{key}' of {}", object.to_js_string()),
14361 )));
14362 };
14363 // The write half of the property inline cache, in effect: an own, writable,
14364 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
14365 // decide — no prototype walk (an own property shadows the chain before a setter
14366 // there could matter), no extensibility check (the object already has the key),
14367 // and no `[[DefineOwnProperty]]`.
14368 //
14369 // `this.value = …` inside a method is the whole write side of
14370 // `property:method-call`, and it was reaching `set_property_with_key` with its
14371 // proxy test, its typed-array test, its array-index test and finally a linear
14372 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
14373 //
14374 // Every disqualifier is checked here: a proxy traps the set, an array index and
14375 // `length` live outside the property table, and a typed array's element is stored
14376 // through its view's element type.
14377 if object.proxy_state().is_none()
14378 && !object.is_array()
14379 && object.typed_array_element_type().is_none()
14380 && object.write_value_key(key, value.clone())
14381 {
14382 return Ok(());
14383 }
14384 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
14385 let on_failure = if self.frame().code.code.strict {
14386 DeleteFailure::Throw
14387 } else {
14388 DeleteFailure::Ignore
14389 };
14390 self.set_property_with_key(object, key, value, on_failure)
14391 }
14392
14393 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
14394 ///
14395 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
14396 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
14397 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
14398 /// `Number.parseInt(sym)` — so those callers use this instead.
14399 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
14400 if matches!(value, Value::Symbol(_)) {
14401 return Err(Signal::Throw(
14402 self.make_error("TypeError", "cannot convert symbol to string"),
14403 ));
14404 }
14405 // An object runs `ToPrimitive` first, which may itself produce a symbol —
14406 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
14407 let value = self.to_primitive(value.clone(), Hint::String)?;
14408 if matches!(value, Value::Symbol(_)) {
14409 return Err(Signal::Throw(
14410 self.make_error("TypeError", "cannot convert symbol to string"),
14411 ));
14412 }
14413 Ok(value.to_js_string())
14414 }
14415
14416 /// `ToPropertyKey` for a builtin that takes a key argument.
14417 ///
14418 /// Fallible: a key whose `toString` throws has to propagate that error, both for
14419 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
14420 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
14421 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
14422 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
14423 self.propkey(value)
14424 }
14425
14426 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
14427 ///
14428 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
14429 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
14430 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
14431 /// `RangeError` — and why this cannot be a plain `ToNumber`.
14432 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
14433 ///
14434 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
14435 /// then a `RangeError` when they disagree. Two conversions rather than one is
14436 /// observable: a `valueOf` that runs the first time can make `length` non-writable
14437 /// before the second, which turns the store into a refused write
14438 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
14439 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
14440 let first = self.array_length_of(value)?;
14441 let second = self.array_length_of(value)?;
14442 debug_assert_eq!(first, second);
14443 Ok(first)
14444 }
14445
14446 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
14447 ///
14448 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
14449 /// conversion can say so; a caller that needs the spec's two uses that instead.
14450 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
14451 let number = match value {
14452 Value::Int(number) => *number as f64,
14453 Value::Float(number) => *number,
14454 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
14455 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
14456 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
14457 // reference answers 0.
14458 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
14459 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
14460 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
14461 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
14462 _ => {
14463 // The primitive comes back through this same conversion, so a wrapper of a
14464 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
14465 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
14466 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
14467 return self.array_length_of(&primitive);
14468 }
14469 };
14470 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
14471 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
14472 // is a `RangeError`, not `0`.
14473 if !number.is_finite()
14474 || number.fract() != 0.0
14475 || !(0.0..=u32::MAX as f64).contains(&number)
14476 {
14477 return Err(self.range_error("invalid array length"));
14478 }
14479 Ok(number as u32)
14480 }
14481
14482 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
14483 /// `Object.getOwnPropertySymbols` put in their result array.
14484 pub fn key_value(&self, key: &PropertyKey) -> Value {
14485 match key {
14486 PropertyKey::String(text) => self.string_wtf8(text.clone()),
14487 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
14488 }
14489 }
14490
14491 /// Fill in a String exotic object: `_value`, `length` and the index properties.
14492 ///
14493 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
14494 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
14495 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
14496 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
14497 /// the two paths had drifted; this is the one both now use.
14498 ///
14499 /// The indices are *code units*, so an astral character occupies two of them — the
14500 /// same rule `s.length` and `s[i]` follow.
14501 /// Give an already-created object the internal slot that makes it a wrapper of
14502 /// `value`, so the primitive's prototype methods work on it.
14503 ///
14504 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
14505 /// which are wrappers of their own type holding the empty value.
14506 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
14507 self.internal_set(object, "_value", value);
14508 }
14509
14510 pub(crate) fn init_string_wrapper(
14511 &mut self,
14512 object: &Gc<JsObject>,
14513 text: &Gc<crate::value::JsString>,
14514 ) {
14515 object.define(
14516 "length",
14517 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
14518 );
14519 for index in 0..text.utf16_len() {
14520 if let Some(unit) = text.wtf8().unit_at(index) {
14521 object.define(
14522 &index.to_string(),
14523 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
14524 Property::with_attributes(self.string_wtf8(unit), false, true),
14525 );
14526 }
14527 }
14528 object.define_key(
14529 &self.internal_slot("_value"),
14530 Property::with_attributes(Value::String(text.clone()), false, false),
14531 );
14532 }
14533
14534 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
14535 ///
14536 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
14537 /// throws. The wrapper carries its primitive in `_value` — the same slot
14538 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
14539 /// on a boxed value no constructor ever built.
14540 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14541 let (prototype, primitive) = match value {
14542 Value::Object(object) => return Ok(object.clone()),
14543 Value::String(text) => {
14544 let object = self.new_object(self.realm.string_proto.clone());
14545 self.init_string_wrapper(&object, text);
14546 return Ok(object);
14547 }
14548 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
14549 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
14550 // A symbol and a bigint box into wrappers whose methods live on
14551 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
14552 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
14553 // branch below instead produced an object with *no* prototype, so those
14554 // methods were unreachable on a box.
14555 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
14556 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
14557 Value::Undefined | Value::Null => {
14558 return Err(Signal::Throw(self.make_error(
14559 "TypeError",
14560 &format!("cannot convert {} to object", value.to_js_string()),
14561 )));
14562 }
14563 _ => (None, value.clone()),
14564 };
14565 let object = self.new_object(prototype);
14566 self.internal_set(&object, "_value", primitive);
14567 Ok(object)
14568 }
14569
14570 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
14571 ///
14572 /// Split out for a reader that has to create the object *before* it knows what it wraps:
14573 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
14574 /// written before its primitive, so the placeholder has to exist first and be filled in
14575 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
14576 /// than a second in the deserialiser.
14577 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
14578 let prototype = match value {
14579 Value::String(_) => self.realm.string_proto.clone(),
14580 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14581 Value::Bool(_) => self.realm.boolean_proto.clone(),
14582 Value::Symbol(_) => self.realm.symbol_proto.clone(),
14583 Value::BigInt(_) => self.realm.bigint_proto.clone(),
14584 _ => {
14585 return Err(Signal::Throw(self.make_error(
14586 "TypeError",
14587 &format!("cannot box {}", value.to_js_string()),
14588 )));
14589 }
14590 };
14591 object.set_proto(prototype);
14592 if let Value::String(text) = value {
14593 self.init_string_wrapper(object, text);
14594 return Ok(());
14595 }
14596 self.internal_set(object, "_value", value.clone());
14597 Ok(())
14598 }
14599
14600 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
14601 ///
14602 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
14603 /// through the `Symbol` function object, so the registry is reachable as a method rather
14604 /// than only from `builtins::symbol`.
14605 pub fn symbol_for(&mut self, key: &str) -> Value {
14606 if let Some(existing) = self.realm.symbol_registry.get(key) {
14607 return existing.clone();
14608 }
14609 let symbol = crate::builtins::symbol::symbol_value(
14610 self,
14611 crate::value::JsSymbol::registered(key.to_string()),
14612 );
14613 self.realm
14614 .symbol_registry
14615 .insert(key.to_string(), symbol.clone());
14616 symbol
14617 }
14618
14619 /// `a == b`, the coercing comparison.
14620 ///
14621 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
14622 /// which is what makes `[] == ""` true: `[]` becomes `""` via
14623 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
14624 /// because the conversion is allowed to call script code, so the two primitive
14625 /// operands are handed back to it.
14626 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
14627 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
14628 return Ok(left.loose_equals(&right));
14629 }
14630 // `null == undefined` holds even though neither is an object.
14631 if matches!(left, Value::Undefined | Value::Null)
14632 && matches!(right, Value::Undefined | Value::Null)
14633 {
14634 return Ok(true);
14635 }
14636 if matches!(left, Value::Undefined | Value::Null)
14637 || matches!(right, Value::Undefined | Value::Null)
14638 {
14639 return Ok(false);
14640 }
14641 // Two objects compare by identity. Only an object *against a primitive* is
14642 // converted, which is why `{} == {}` is false while `[] == ""` is true.
14643 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
14644 return Ok(a.ptr_eq(b));
14645 }
14646 let left = self.to_primitive(left, Hint::Default)?;
14647 let right = self.to_primitive(right, Hint::Default)?;
14648 Ok(left.loose_equals(&right))
14649 }
14650
14651 /// `HasBinding(N)` for an Object Environment Record whose binding object is `object`.
14652 ///
14653 /// §9.1.1.2.1: `HasProperty` **and then** not listed in the object's
14654 /// `Symbol.unscopables`. The `unscopables` object is read with a plain `Get`, so a
14655 /// getter on it runs exactly once per lookup — `with/with-get-unscopables-once` counts
14656 /// the calls.
14657 fn with_has_binding(&mut self, object: &Value, name: &str) -> JsResult<bool> {
14658 let key = PropertyKey::from(name);
14659 if !self.has_property_value(object, &key)? {
14660 return Ok(false);
14661 }
14662 let unscopables_key = self.realm.well_known_key(WellKnown::Unscopables);
14663 let unscopables = self.read_field_key(object, &unscopables_key)?;
14664 let Value::Object(_) = unscopables else {
14665 // `undefined` (the usual case) or a primitive: nothing is excluded.
14666 return Ok(true);
14667 };
14668 let excluded = self.read_field_key(&unscopables, &key)?;
14669 Ok(!excluded.to_boolean())
14670 }
14671
14672 /// `GetBindingValue(N, S)` for an Object Environment Record: §9.1.1.2.4.
14673 ///
14674 /// `HasProperty` is asked a **second** time — the guard already asked it — because the
14675 /// object may have changed in between: `GetBindingValue` step 2 is a fresh lookup, and
14676 /// a proxy sees two `has` traps plus the `get`. The `unscopables` step is *not*
14677 /// repeated: that belongs to `HasBinding`, not to `GetBindingValue`.
14678 ///
14679 /// When the property has gone, strict code throws and sloppy code reads `undefined`
14680 /// from the environment (step 2's `S` is the strictness of the *running* code, not of
14681 /// the declaration).
14682 fn with_get_binding(&mut self, object: &Value, name: &str) -> JsResult<Value> {
14683 let key = PropertyKey::from(name);
14684 if !self.has_property_value(object, &key)? {
14685 if self.frame().code.code.strict {
14686 return Err(self.throw_reference(name));
14687 }
14688 return Ok(Value::Undefined);
14689 }
14690 self.read_field_key(object, &key)
14691 }
14692
14693 /// `SetMutableBinding(N, V, S)` for an Object Environment Record: §9.1.1.2.5.
14694 ///
14695 /// Same second `HasProperty`, and the same strict-mode `ReferenceError` when the
14696 /// property is gone — before the store, which is what makes
14697 /// `set-mutable-binding-binding-deleted-with-typed-array-in-proto-chain-strict-mode`
14698 /// a `ReferenceError` rather than whatever the failed store would have thrown.
14699 fn with_put_binding(&mut self, object: &Value, name: &str, value: Value) -> JsResult<()> {
14700 let key = PropertyKey::from(name);
14701 if !self.has_property_value(object, &key)? && self.frame().code.code.strict {
14702 return Err(self.throw_reference(name));
14703 }
14704 self.write_field_key(object, &key, value)
14705 }
14706
14707 /// `HasProperty(O, P)` on a `Value`, without the `in`-operator error for a primitive.
14708 fn has_property_value(&mut self, object: &Value, key: &PropertyKey) -> JsResult<bool> {
14709 match object {
14710 Value::Object(target) => self.has_property_key(target, key),
14711 // `with` boxes its object when the statement is entered (`to_object`), so a
14712 // primitive cannot arrive here; `false` is the honest answer rather than a
14713 // panic if it ever does.
14714 _ => Ok(false),
14715 }
14716 }
14717
14718 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
14719 let Value::Object(object) = object else {
14720 return Err(Signal::Throw(
14721 self.make_error("TypeError", "cannot use 'in' on a non-object"),
14722 ));
14723 };
14724 let key = self.propkey(key)?;
14725 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
14726 // trap. One implementation, so an array's derived `length` and its inherited holes
14727 // cannot be right in one caller and wrong in another.
14728 self.has_own_or_inherited(object, &key)
14729 }
14730
14731 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
14732 ///
14733 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
14734 /// whole reason the operator is a hook rather than a prototype walk.
14735 ///
14736 /// §13.10.2 `InstanceofOperator(O, C)`, which is stricter than
14737 /// [`Interp::ordinary_instance_of`]: step 1 throws when `C` is not an object at all
14738 /// (`true instanceof true`) and step 4 throws when it is an object but not callable
14739 /// (`1 instanceof Math`). Both used to answer `false`, which is `OrdinaryHasInstance`'s
14740 /// rule (its step 2) and not this operator's — so nine `expressions/instanceof` cases
14741 /// expected a `TypeError` and got a value.
14742 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14743 // Step 1, before any method lookup.
14744 if constructor.as_object().is_none() {
14745 return Err(Signal::Throw(self.make_error(
14746 "TypeError",
14747 "right-hand side of 'instanceof' is not an object",
14748 )));
14749 }
14750 let Value::Object(function) = constructor else {
14751 unreachable!("just checked");
14752 };
14753 // Step 2. A primitive `C` cannot reach here, so `get_property_key` on the object is
14754 // the whole of it.
14755 let key = self.realm.well_known_key(WellKnown::HasInstance);
14756 let method = self.get_property_key(function, &key)?;
14757 if let Some(method) = method
14758 && !matches!(method, Value::Undefined)
14759 {
14760 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
14761 return Ok(answer.to_boolean());
14762 }
14763 // Step 4.
14764 if !function.is_callable() {
14765 return Err(Signal::Throw(self.make_error(
14766 "TypeError",
14767 "right-hand side of 'instanceof' is not callable",
14768 )));
14769 }
14770 // Step 5.
14771 self.instance_of(object, constructor)
14772 }
14773
14774 /// `OrdinaryHasInstance`: the prototype walk on its own.
14775 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14776 self.instance_of(object, constructor)
14777 }
14778
14779 /// `IsArray`: an array, or a proxy whose target is one.
14780 ///
14781 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
14782 /// makes `Array.isArray(new Proxy([], {}))` true.
14783 pub fn is_array_value(&self, value: &Value) -> bool {
14784 match value {
14785 Value::Object(object) => {
14786 if let Some(state) = object.proxy_state() {
14787 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
14788 }
14789 object.is_array()
14790 }
14791 _ => false,
14792 }
14793 }
14794
14795 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
14796 ///
14797 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
14798 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
14799 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
14800 /// see [`Interp::enqueue_job_function`].
14801 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
14802 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
14803 // the handler is reported rather than lost — the same reason a `then` reaction needs a
14804 // promise to settle.
14805 let promise = self.new_promise();
14806 self.fulfill_promise(&promise, Value::Undefined);
14807 self.jobs.push_back(Job::Reaction {
14808 handler: Some(function),
14809 argument: Value::Undefined,
14810 rejected: false,
14811 promise,
14812 });
14813 Ok(())
14814 }
14815
14816 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
14817 ///
14818 /// Four of its steps were missing or wrong, and each one is a test262 case in
14819 /// `Function/prototype/Symbol.hasInstance/`:
14820 ///
14821 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
14822 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
14823 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
14824 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
14825 /// `prototype` of its own, so without this step the walk below gives `false`;
14826 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
14827 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
14828 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14829 let Value::Object(function) = constructor else {
14830 return Ok(false);
14831 };
14832 if !function.is_callable() {
14833 return Ok(false);
14834 }
14835 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
14836 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
14837 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
14838 if let Some((target, this)) = function.bound_target_and_this() {
14839 let object = if this.as_object().is_some() {
14840 this
14841 } else {
14842 object.clone()
14843 };
14844 return self.instance_of(&object, &target);
14845 }
14846 let Value::Object(target) = object else {
14847 return Ok(false);
14848 };
14849 let prototype = self.get_property(function, "prototype")?;
14850 let Some(Value::Object(prototype)) = prototype else {
14851 return Err(Signal::Throw(self.make_error(
14852 "TypeError",
14853 "function has non-object prototype in instanceof check",
14854 )));
14855 };
14856 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
14857 // which is also what makes `proxyOfInstance instanceof C` work.
14858 let mut current = Some(target.clone());
14859 while let Some(object) = current {
14860 if object.ptr_eq(&prototype) {
14861 return Ok(true);
14862 }
14863 current = self.object_prototype_of(&object)?;
14864 }
14865 Ok(false)
14866 }
14867
14868 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
14869 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
14870 if let Some(proto) = self.proxy_get_prototype_of(object)? {
14871 return Ok(proto);
14872 }
14873 if let Some(exotic) = object.exotic()
14874 && let Some(proto) = exotic.get_prototype(self, object)?
14875 {
14876 return Ok(proto);
14877 }
14878 Ok(object.proto())
14879 }
14880
14881 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
14882 pub fn object_set_prototype_of(
14883 &mut self,
14884 object: &Gc<JsObject>,
14885 proto: Option<Gc<JsObject>>,
14886 ) -> JsResult<bool> {
14887 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
14888 return Ok(answer);
14889 }
14890 if let Some(exotic) = object.exotic()
14891 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
14892 {
14893 return Ok(answer);
14894 }
14895 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
14896 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
14897 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
14898 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
14899 if self
14900 .internal_get(object, "_immutable_proto")
14901 .is_some_and(|flag| flag.to_boolean())
14902 && !same_proto(object.proto().as_ref(), proto.as_ref())
14903 {
14904 return Ok(false);
14905 }
14906 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
14907 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
14908 // inheriting from itself, which every later prototype walk then had to defend
14909 // against — and `Reflect.setPrototypeOf` reported success for an operation the
14910 // language says is impossible.
14911 if let Some(proto) = &proto {
14912 let mut current = Some(proto.clone());
14913 let mut guard = 0;
14914 while let Some(node) = current {
14915 if node.ptr_eq(object) {
14916 // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
14917 // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
14918 // while `Reflect.setPrototypeOf` reports it
14919 // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
14920 return Ok(false);
14921 }
14922 guard += 1;
14923 if guard > 1000 {
14924 break;
14925 }
14926 current = node.proto();
14927 }
14928 }
14929 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14930 // re-setting it to the *same* one is a no-op `true`. Missing this made
14931 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14932 // actually reparent the object — and it is what
14933 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14934 // forwarding path has nothing else left to refuse it.
14935 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14936 return Ok(false);
14937 }
14938 object.set_proto(proto);
14939 Ok(true)
14940 }
14941
14942 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14943 ///
14944 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14945 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14946 /// already one.
14947 /// `HasProperty(O, P)`.
14948 ///
14949 /// One implementation, shared with the `in` operator. It used to be a second copy that
14950 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14951 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14952 /// proxy ran the wrong hook and could even disagree with `in`. The
14953 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14954 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14955 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14956 self.has_own_or_inherited(object, key)
14957 }
14958
14959 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14960 ///
14961 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14962 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14963 /// boolean as well, and it needs the receiver to be the one the caller named.
14964 pub fn set_property_with_key_receiver(
14965 &mut self,
14966 object: &Gc<JsObject>,
14967 key: &PropertyKey,
14968 value: Value,
14969 receiver: Option<&Value>,
14970 on_failure: DeleteFailure,
14971 ) -> JsResult<bool> {
14972 let receiver = receiver
14973 .cloned()
14974 .unwrap_or_else(|| Value::Object(object.clone()));
14975 if object.proxy_state().is_some() {
14976 return match self.proxy_set(object, key, value, &receiver)? {
14977 Some(accepted) => Ok(accepted),
14978 None => Ok(true),
14979 };
14980 }
14981 // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14982 // receiver. This has to be answered here as well as in the storing path below,
14983 // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14984 if object.module_namespace_marker() {
14985 return Ok(false);
14986 }
14987 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14988 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14989 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14990 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14991 //
14992 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14993 //
14994 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14995 // * an *invalid* index with a different receiver answers `true` and does nothing,
14996 // not even converting `V` (`valueOfCalls` stays 0);
14997 // * a valid index with a different receiver falls through to
14998 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14999 // value lands on the **receiver**, unconverted, and can be refused by a
15000 // non-extensible receiver, an accessor, or a read-only index there.
15001 //
15002 // The last one used to write into the view itself, which left `target[0]` changed
15003 // and `receiver[0]` untouched — backwards.
15004 if object.typed_array_element_type().is_some()
15005 && let Some(numeric) = canonical_numeric_index(key)
15006 {
15007 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
15008 if same {
15009 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
15010 return Ok(true);
15011 }
15012 if !typed_array_index_is_valid(object, numeric) {
15013 return Ok(true);
15014 }
15015 let Some(receiver) = receiver.as_object().cloned() else {
15016 return Ok(false);
15017 };
15018 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
15019 if existing.is_accessor() || !existing.writable {
15020 return Ok(false);
15021 }
15022 let property = Property {
15023 value: Some(value),
15024 ..existing
15025 };
15026 return self.object_define_own_property(&receiver, key, property);
15027 }
15028 return self.object_define_own_property(&receiver, key, Property::data(value));
15029 }
15030 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
15031 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
15032 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
15033 // `Reflect.set` to *report* the refusal instead of raising.
15034 //
15035 // A receiver that is not the object turns the whole operation into
15036 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
15037 // `[[Set]]` rather than a lookup — that is what makes
15038 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
15039 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
15040 // writes to `object`, so it cannot express that and is only used when the two are
15041 // the same.
15042 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
15043 if !same {
15044 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
15045 }
15046 // Same receiver: the plain path below writes into `object`, which is right, but it
15047 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
15048 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
15049 if let Some(existing) = self.object_get_own_property(object, key)? {
15050 if existing.is_accessor() {
15051 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
15052 Some(setter) => {
15053 self.call_value(setter, receiver, vec![value])?;
15054 Ok(true)
15055 }
15056 None => Ok(false),
15057 };
15058 }
15059 if !existing.writable {
15060 return Ok(false);
15061 }
15062 }
15063 // Otherwise it is an ordinary create-or-write into `object` itself.
15064 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
15065 Ok(true)
15066 }
15067
15068 /// `[[IsExtensible]]`, with the proxy trap when there is one.
15069 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
15070 if let Some(answer) = self.proxy_is_extensible(object)? {
15071 return Ok(answer);
15072 }
15073 if let Some(exotic) = object.exotic()
15074 && let Some(answer) = exotic.is_extensible(self, object)?
15075 {
15076 return Ok(answer);
15077 }
15078 Ok(object.is_extensible())
15079 }
15080
15081 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
15082 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
15083 if let Some(answer) = self.proxy_prevent_extensions(object)? {
15084 return Ok(answer);
15085 }
15086 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
15087 //
15088 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
15089 //
15090 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
15091 // created with an explicit length, because the buffer can still move it. That is
15092 // what makes `Object.freeze` refuse every such view, including a zero-length one
15093 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
15094 // plain buffer is allowed.
15095 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
15096 && buffer
15097 .array_buffer_storage()
15098 .is_some_and(|storage| storage.borrow().is_resizable())
15099 {
15100 return Err(
15101 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
15102 );
15103 }
15104 if let Some(exotic) = object.exotic()
15105 && let Some(answer) = exotic.prevent_extensions(self, object)?
15106 {
15107 return Ok(answer);
15108 }
15109 object.set_extensible(false);
15110 Ok(true)
15111 }
15112
15113 fn copy_properties(
15114 &mut self,
15115 target: &Value,
15116 source: &Value,
15117 exclusion: &Value,
15118 ) -> JsResult<()> {
15119 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
15120 // does contribute: its index properties are own, enumerable and writable, which
15121 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
15122 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
15123 // is a no-op.
15124 let Some(target) = target.as_object() else {
15125 return Ok(());
15126 };
15127 let source_object = match source {
15128 Value::Object(object) => object.clone(),
15129 Value::String(text) => {
15130 // Untaken keys are the string's indices, which are code units.
15131 for index in 0..text.utf16_len() {
15132 if let Some(unit) = text.wtf8().unit_at(index) {
15133 target.define_data(&index.to_string(), self.string_wtf8(unit));
15134 }
15135 }
15136 return Ok(());
15137 }
15138 _ => return Ok(()),
15139 };
15140 // An object *rest* element passes the keys already taken by the literal part as
15141 // an array of **key values**; a spread passes `null`, which excludes nothing. The
15142 // array is read by its elements rather than by its own property names, and the
15143 // values stay `PropertyKey`s: a computed key can be a symbol, and
15144 // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
15145 // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
15146 // strings made a symbol exclusion a no-op.
15147 let mut excluded: Vec<PropertyKey> = Vec::new();
15148 if let Value::Object(list) = exclusion
15149 && let Some(length) = list.array_length()
15150 {
15151 for index in 0..length {
15152 if let Some(value) = list.array_get(index) {
15153 excluded.push(self.propkey(&value)?);
15154 }
15155 }
15156 }
15157 let source = &source_object;
15158 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
15159 // Reading the property table directly made every spread of a proxy empty.
15160 let keys = self.object_own_property_keys(source)?;
15161 for as_key in keys {
15162 // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
15163 // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
15164 // Skipping them silently lost every symbol on every spread and every object
15165 // rest element (`obj-rest-order`).
15166 //
15167 if excluded.contains(&as_key) {
15168 continue;
15169 }
15170 let enumerable = self
15171 .object_get_own_property(source, &as_key)?
15172 .is_some_and(|property| property.enumerable);
15173 if !enumerable {
15174 continue;
15175 }
15176 let value = self
15177 .get_property_key(source, &as_key)?
15178 .unwrap_or(Value::Undefined);
15179 target.define_data_key(&as_key, value);
15180 }
15181 Ok(())
15182 }
15183
15184 // -- iteration ---------------------------------------------------------
15185
15186 /// One object's own keys in enumeration order: array indices ascending, then the
15187 /// rest in insertion order.
15188 ///
15189 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
15190 /// whether the key is enumerable, which the caller resolves per key because an
15191 /// array's elements are not in the same store as its named properties.
15192 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
15193 // An index can arrive twice, once from the array's element store and once from
15194 // its property map, so the numeric keys go through a map that keeps the
15195 // enumerable answer if either source gave one.
15196 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
15197 for (key, enumerable) in &own {
15198 if let Some(index) = key.as_str().and_then(array_index) {
15199 let entry = numeric.entry(index).or_insert(false);
15200 *entry = *entry || *enumerable;
15201 }
15202 }
15203 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
15204 .into_iter()
15205 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
15206 .collect();
15207 ordered.extend(
15208 own.into_iter()
15209 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
15210 );
15211 ordered
15212 }
15213
15214 /// Build the key list a `for-in` loop walks.
15215 ///
15216 /// The order is the specification's: own properties before inherited ones, and
15217 /// within one object the integer-like keys in ascending numeric order ahead of the
15218 /// string keys in insertion order. A shadowed key only appears once, and a key that
15219 /// is a non-enumerable own property anywhere nearer is skipped entirely.
15220 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
15221 let record = self.new_object(None);
15222 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
15223 // A proxy supplies its own key list, and — the reason this is not just another
15224 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
15225 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
15226 // descriptor there.
15227 if let Value::Object(object) = value
15228 && object.proxy_state().is_some()
15229 {
15230 let own = self
15231 .proxy_own_keys(object)?
15232 .unwrap_or_else(|| object.own_property_keys());
15233 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
15234 let mut numeric: Vec<u32> = Vec::new();
15235 let mut rest: Vec<PropertyKey> = Vec::new();
15236 for key in own {
15237 match key.as_str().and_then(array_index) {
15238 Some(index) => numeric.push(index),
15239 None => rest.push(key),
15240 }
15241 }
15242 numeric.sort_unstable();
15243 ordered.extend(
15244 numeric
15245 .into_iter()
15246 .map(|index| PropertyKey::from(index.to_string())),
15247 );
15248 ordered.extend(rest);
15249 for (index, key) in ordered.into_iter().enumerate() {
15250 record.define_data(&index.to_string(), self.key_value(&key));
15251 }
15252 record.define_data("__index", Value::Int(0));
15253 // The mark that makes `for_in_advance` re-ask the proxy per key.
15254 record.define_data("__proxy", Value::Object(object.clone()));
15255 return Ok(record);
15256 }
15257 if let Value::Object(object) = value {
15258 let mut chain = vec![object.clone()];
15259 chain.extend(object.chain());
15260 // Every own string key the walk has seen, enumerable or not. A
15261 // non-enumerable own property still hides a same-named enumerable one
15262 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
15263 // keeps `x` out of the loop even when the prototype has one.
15264 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
15265 for object in chain {
15266 // A namespace's bindings are materialised by `[[GetOwnProperty]]`, and a
15267 // binding still in its dead zone throws there (§10.4.6.8). Enumerating
15268 // through the raw table skipped that, so `for (var k in ns)` on a namespace
15269 // whose module was still evaluating saw the keys and read `undefined`
15270 // (`namespace/internals/enumerate-binding-uninit`).
15271 if object.module_namespace_marker() {
15272 for key in object.own_property_keys() {
15273 self.object_get_own_property(&object, &key)?;
15274 }
15275 }
15276 let mut own: Vec<(crate::value::Wtf8, bool)> = object
15277 .own_property_keys()
15278 .iter()
15279 .filter_map(|key| key.as_wtf8().cloned())
15280 .map(|key| {
15281 let enumerable = object
15282 .own_property(&key.to_string_lossy())
15283 .map(|property| property.enumerable)
15284 .unwrap_or(false);
15285 (key, enumerable)
15286 })
15287 .collect();
15288 if let Some(length) = object.array_length() {
15289 own.retain(|(key, _)| key.as_str() != Some("length"));
15290 for index in 0..length {
15291 // A dense element is enumerable; a **hole** is not there at all —
15292 // and a hole is also what an index with a recorded descriptor
15293 // leaves behind, in which case the table entry above already
15294 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
15295 // defines index 0 non-enumerable and `for…in` must skip it).
15296 if let Some(value) = object.array_get(index)
15297 && !matches!(value, Value::Hole)
15298 {
15299 own.push((crate::value::Wtf8::new(index.to_string()), true));
15300 }
15301 }
15302 }
15303 // Integer-like keys come first in ascending order, then the rest in
15304 // insertion order — and the ordering is *per object*, not for the chain
15305 // as a whole: one pass over every collected key lifted a prototype's
15306 // `"4"` above the target's own `x`/`y`, which is not the order
15307 // `for…in` reports.
15308 for (key, enumerable) in Self::order_own_keys(own) {
15309 if visited.contains(&key) {
15310 continue;
15311 }
15312 visited.push(key.clone());
15313 if enumerable {
15314 keys.push(key);
15315 }
15316 }
15317 }
15318 }
15319 for (index, key) in keys.into_iter().enumerate() {
15320 record.define_data(&index.to_string(), self.string_wtf8(key));
15321 }
15322 record.define_data("__index", Value::Int(0));
15323 Ok(record)
15324 }
15325
15326 /// The next key of a `for…in` record, `None` when the loop is done.
15327 ///
15328 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
15329 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
15330 /// the loop reaches it, so a handler that stops reporting a key partway through drops
15331 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
15332 /// key the handler had already withdrawn.
15333 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
15334 let Value::Object(record) = record else {
15335 return Ok(None);
15336 };
15337 let proxy = record
15338 .own_property("__proxy")
15339 .and_then(|property| property.value);
15340 loop {
15341 let index = record
15342 .own_property("__index")
15343 .and_then(|property| property.value)
15344 .map(|value| value.to_int32())
15345 .unwrap_or(0);
15346 let Some(candidate) = record
15347 .own_property(&index.to_string())
15348 .and_then(|property| property.value)
15349 else {
15350 return Ok(None);
15351 };
15352 record.define_data("__index", Value::Int(index + 1));
15353 let text = candidate.to_js_string();
15354 let Some(Value::Object(proxy)) = &proxy else {
15355 return Ok(Some(text));
15356 };
15357 // The candidate is already a key string here, so the lookup does not need a
15358 // second `ToPropertyKey` conversion.
15359 let key = PropertyKey::from(text.as_str());
15360 let live = match self.proxy_get_own_property(proxy, &key)? {
15361 Some(descriptor) => descriptor,
15362 // Not a proxy after all, or it lost its state: fall back to the target.
15363 None => proxy.own_property_key(&key),
15364 };
15365 if live.is_some_and(|property| property.enumerable) {
15366 return Ok(Some(text));
15367 }
15368 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
15369 // next one.
15370 }
15371 }
15372
15373 /// The iterator for `for-of`: the object and its `next` method.
15374 ///
15375 /// An object that already carries a `next` method is used as it is — that is what
15376 /// `arr.values()` returns — and only arrays and strings get the built-in
15377 /// sequence iterator.
15378 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
15379 ///
15380 /// Callers that must choose between the iterable and the array-like protocol — the
15381 /// typed-array constructor is the main one — need to ask *before* committing to one.
15382 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
15383 let key = self.realm.well_known_key(WellKnown::Iterator);
15384 let method = self.read_field_key(value, &key)?;
15385 if matches!(method, Value::Undefined | Value::Null) {
15386 return Ok(false);
15387 }
15388 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15389 return Err(Signal::Throw(
15390 self.make_error("TypeError", "Symbol.iterator is not callable"),
15391 ));
15392 }
15393 Ok(true)
15394 }
15395
15396 /// Collect everything an iterable yields.
15397 ///
15398 /// The cap is a guard against a generator that never ends: an unbounded collect would
15399 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
15400 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
15401 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
15402 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
15403 const MAX_ITEMS: usize = 1 << 24;
15404 let iterator = self.get_iterator(value)?;
15405 let mut out = Vec::new();
15406 loop {
15407 let (element, done) = self.iterator_step(&iterator)?;
15408 if done {
15409 return Ok(out);
15410 }
15411 out.push(element);
15412 if out.len() > MAX_ITEMS {
15413 // Close before refusing: the walk is being abandoned, so the iterator's
15414 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
15415 // unrun and a locked resource unreleased.
15416 self.close_iterator_after_throw(&iterator)?;
15417 return Err(self.range_error("iterable is too long to collect"));
15418 }
15419 }
15420 }
15421
15422 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
15423 ///
15424 /// A native constructor calls this once it has validated its arguments, which is the
15425 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
15426 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
15427 /// never reached. The prototype comes from `new.target` when it is an object, and from
15428 /// `default_proto` otherwise.
15429 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
15430 let proto = self.ctor_prototype(default_proto)?;
15431 Ok(self.new_object(Some(proto)))
15432 }
15433
15434 /// An **array** whose prototype comes from `new.target`.
15435 ///
15436 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
15437 /// instance from `new.target.prototype`, and building a plain array instead made every
15438 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
15439 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
15440 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
15441 Ok(JsObject::array(self.heap, Some(proto), 0))
15442 }
15443
15444 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
15445 ///
15446 /// The `Option` form is for the constructors that build their instance in a helper which
15447 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
15448 /// from `await`'s internal promise, and only the first has a `new.target`.
15449 fn ctor_prototype_opt(
15450 &mut self,
15451 default_proto: Option<Gc<JsObject>>,
15452 ) -> JsResult<Option<Gc<JsObject>>> {
15453 // `active_new_target`: by the time a native constructor runs, `call_value` has
15454 // already consumed the parked value.
15455 let Some(target) = self
15456 .active_new_target
15457 .as_object()
15458 .cloned()
15459 .map(Value::Object)
15460 else {
15461 return Ok(default_proto);
15462 };
15463 let Some(target) = target.as_object().cloned() else {
15464 return Ok(default_proto);
15465 };
15466 match self.get_property(&target, "prototype")? {
15467 Some(Value::Object(proto)) => Ok(Some(proto)),
15468 _ => Ok(default_proto),
15469 }
15470 }
15471
15472 /// `new.target.prototype`, or `default_proto` when this is a plain call.
15473 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
15474 let Some(target) = self.active_new_target.as_object().cloned() else {
15475 return Ok(default_proto);
15476 };
15477 match self.get_property(&target, "prototype")? {
15478 Some(Value::Object(proto)) => Ok(proto),
15479 _ => Ok(default_proto),
15480 }
15481 }
15482
15483 /// `CreateDataPropertyOrThrow(O, key, value)`.
15484 ///
15485 /// A *definition*, not an assignment. The difference is visible the moment the target
15486 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
15487 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
15488 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
15489 /// refused (`configurable: false`).
15490 ///
15491 /// The fast path exists because this is called once per element by `map`, `filter`,
15492 /// `slice` and friends: a plain array with no custom element descriptors and a writable
15493 /// `length` can store straight into its element vector.
15494 pub fn create_data_property_or_throw(
15495 &mut self,
15496 object: &Gc<JsObject>,
15497 index: usize,
15498 value: Value,
15499 ) -> JsResult<()> {
15500 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
15501 // an array (that is what `Array.isArray` must say), so the element fast path would
15502 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
15503 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
15504 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
15505 // records the exact trap sequence.
15506 if object.proxy_state().is_none()
15507 && object.is_array()
15508 && object.elements_writable()
15509 && !object.has_element_descriptors()
15510 && object.is_extensible()
15511 && object.array_set(self.heap, index, value.clone())
15512 {
15513 return Ok(());
15514 }
15515 let key = PropertyKey::from(index.to_string());
15516 let property = Property {
15517 value: Some(value),
15518 writable: true,
15519 enumerable: true,
15520 configurable: true,
15521 ..Property::default()
15522 };
15523 // `CreateDataProperty` always asks for the default attributes, so it can only ever
15524 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
15525 // the rest. Checking here rather than inside `object_define_own_property` is
15526 // deliberate: that function receives a fully-populated `Property` and cannot tell
15527 // an omitted attribute from an explicit `false`, so the generic check it would need
15528 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
15529 // writable property (that cost eight `Object/defineProperty` tests).
15530 if object.proxy_state().is_none()
15531 && let Some(existing) = self.object_get_own_property(object, &key)?
15532 && !existing.configurable
15533 {
15534 return Err(self.type_error("cannot create the property"));
15535 }
15536 if self.object_define_own_property(object, &key, property)? {
15537 return Ok(());
15538 }
15539 Err(self.type_error("cannot create the property"))
15540 }
15541
15542 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
15543 ///
15544 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
15545 /// its callers have; this is the same operation for the named properties a built-in
15546 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
15547 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
15548 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
15549 pub fn create_named_data_property_or_throw(
15550 &mut self,
15551 object: &Gc<JsObject>,
15552 key: &str,
15553 value: Value,
15554 ) -> JsResult<()> {
15555 let key = PropertyKey::from(key);
15556 let property = Property {
15557 value: Some(value),
15558 writable: true,
15559 enumerable: true,
15560 configurable: true,
15561 ..Property::default()
15562 };
15563 if object.proxy_state().is_none()
15564 && let Some(existing) = self.object_get_own_property(object, &key)?
15565 && !existing.configurable
15566 {
15567 return Err(self.type_error("cannot create the property"));
15568 }
15569 if self.object_define_own_property(object, &key, property)? {
15570 return Ok(());
15571 }
15572 Err(self.type_error("cannot create the property"))
15573 }
15574
15575 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
15576 ///
15577 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
15578 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
15579 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
15580 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
15581 /// run user code and both can throw.
15582 pub fn species_constructor(
15583 &mut self,
15584 object: &Gc<JsObject>,
15585 default: Value,
15586 ) -> JsResult<Value> {
15587 let Some(constructor) = self.get_property(object, "constructor")? else {
15588 return Ok(default);
15589 };
15590 let constructor = match constructor {
15591 Value::Undefined => return Ok(default),
15592 Value::Object(constructor) => constructor,
15593 _ => return Err(self.type_error("constructor is not an object")),
15594 };
15595 let key = self.realm.well_known_key(WellKnown::Species);
15596 let species = self.get_property_key(&constructor, &key)?;
15597 match species {
15598 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
15599 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
15600 Some(_) => Err(self.type_error("species is not a constructor")),
15601 }
15602 }
15603
15604 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
15605 ///
15606 /// The result is an array of `length` holes whose prototype comes from
15607 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
15608 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
15609 /// is why the `IsArray` check is the first step and not an optimisation.
15610 pub fn array_species_create(
15611 &mut self,
15612 original: &Value,
15613 length: usize,
15614 ) -> JsResult<Gc<JsObject>> {
15615 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
15616 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
15617 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
15618 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
15619 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
15620 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
15621 // realm** — the species may be a user function that ignores the length entirely, and
15622 // then `2**53 - 1` is not its problem
15623 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
15624 // a short proxy and expects the copy loop to run).
15625 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
15626 if length > ARRAY_CREATE_LIMIT {
15627 return Err(interp.range_error("invalid array length"));
15628 }
15629 Ok(interp.new_array_of_length(length))
15630 };
15631 let Some(object) = original.as_object().cloned() else {
15632 return default(self);
15633 };
15634 if !object.is_array() {
15635 return default(self);
15636 }
15637 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
15638 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
15639 let Some(constructor) = self.get_property(&object, "constructor")? else {
15640 return default(self);
15641 };
15642 let species = match constructor {
15643 Value::Undefined => return Ok(self.new_array_of_length(length)),
15644 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
15645 return default(self);
15646 }
15647 Value::Object(constructor) => {
15648 let key = self.realm.well_known_key(WellKnown::Species);
15649 match self.get_property_key(&constructor, &key)? {
15650 None | Some(Value::Undefined) | Some(Value::Null) => {
15651 return default(self);
15652 }
15653 Some(species) => species,
15654 }
15655 }
15656 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
15657 // is a `TypeError`, not "the default". Treating it as the default made
15658 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
15659 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
15660 // `concat/create-ctor-non-object` are the same rule three times.
15661 _ => return Err(self.type_error("constructor is not an object")),
15662 };
15663 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
15664 // that is merely callable is the `create-species-non-ctor` case.
15665 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
15666 return Err(self.type_error("species is not a constructor"));
15667 }
15668 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
15669 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
15670 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
15671 let created = self.construct(
15672 species.clone(),
15673 species,
15674 vec![crate::object::length_value(length)],
15675 )?;
15676 let Some(created) = created.as_object().cloned() else {
15677 return Err(self.type_error("species constructor did not answer an object"));
15678 };
15679 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
15680 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
15681 // object, and `create-species-with-non-writable-property` asserts exactly that.
15682 // The length is set for the array case; the generic case is the caller's
15683 // `Set(A, "length", …)`.
15684 if created.is_array() {
15685 created.array_set_length(self.heap, length);
15686 }
15687 Ok(created)
15688 }
15689
15690 /// Whether `object` is this realm's `%Array%`.
15691 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
15692 self.realm
15693 .array_constructor
15694 .as_ref()
15695 .is_some_and(|array| array.ptr_eq(object))
15696 }
15697
15698 /// A fresh `length`-hole array with the intrinsic prototype.
15699 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
15700 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
15701 array.array_set_length(self.heap, length);
15702 array
15703 }
15704
15705 /// Whether this call is a construction, i.e. `new.target` is defined.
15706 ///
15707 /// A native constructor receives `this = undefined` (it builds its own instance), so it
15708 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
15709 /// The native function currently executing, if any.
15710 pub fn current_native(&self) -> Option<Gc<JsObject>> {
15711 self.current_native.clone()
15712 }
15713
15714 /// Whether this call is a construction, i.e. `new.target` is defined.
15715 pub fn is_constructing(&self) -> bool {
15716 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
15717 // `call_value` before a native runs, so by the time a constructor body asks, the
15718 // answer is only in the active slot.
15719 matches!(self.active_new_target, Value::Object(_))
15720 }
15721
15722 /// The `TypeError` a constructor too primitive to have a wrapper raises.
15723 ///
15724 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
15725 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
15726 /// happens inside the native function, which is why the trace carries an
15727 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
15728 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
15729 /// constructor`, and an unnamed one reports the leading space of `" is not a
15730 /// constructor"` because the reference formats the empty name as it is.
15731 ///
15732 /// It is also the answer for a `new.target` that cannot be named at all — not a
15733 /// function, or a throwing `name` getter — where the reference falls back to the bare
15734 /// `not a constructor`.
15735 pub fn not_a_constructor_error(&mut self) -> Signal {
15736 let target = self.active_new_target.clone();
15737 self.not_a_constructor_error_for(target)
15738 }
15739
15740 /// The same `TypeError` for an explicit target, for the callers that check
15741 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
15742 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
15743 let target = match target {
15744 Value::Object(target) if target.is_callable() => target,
15745 _ => return self.type_error("not a constructor"),
15746 };
15747 let name = match self.get_property(&target, "name") {
15748 Ok(Some(value)) => value.to_js_string(),
15749 _ => return self.type_error("not a constructor"),
15750 };
15751 self.type_error(format!("{name} is not a constructor"))
15752 }
15753
15754 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
15755 ///
15756 /// True whenever `new.target` is not the callee itself, or when it has no usable
15757 /// `prototype` — the cases where reading the property is observable at all.
15758 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
15759 match &self.active_new_target {
15760 Value::Object(target) => !target.ptr_eq(callee),
15761 Value::Undefined => false,
15762 _ => true,
15763 }
15764 }
15765
15766 /// The symbol key for one of the engine's own hidden slots.
15767 ///
15768 /// Cached on the realm, so every object of a kind shares one key and a slot can be
15769 /// read back by name.
15770 /// Whether any object on `object`'s **prototype chain** owns an array index.
15771 ///
15772 /// The one question the array methods' dense fast paths have to ask before touching the
15773 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
15774 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
15775 /// vector an unreliable answer. Walking the chain once per call is cheap because a
15776 /// prototype almost never holds an index.
15777 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
15778 let mut current = object.proto();
15779 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
15780 for _ in 0..10_000 {
15781 let Some(proto) = current else {
15782 return false;
15783 };
15784 if proto.has_indexed_own_property() {
15785 return true;
15786 }
15787 current = proto.proto();
15788 }
15789 false
15790 }
15791
15792 /// The hidden symbol a named internal slot is keyed by, created on first use.
15793 ///
15794 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
15795 /// either keeping a table of its own.
15796 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
15797 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
15798 return PropertyKey::Symbol(symbol.clone());
15799 }
15800 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
15801 self.realm
15802 .internal_slots
15803 .borrow_mut()
15804 .insert(name, Value::Symbol(symbol.clone()));
15805 PropertyKey::Symbol(symbol)
15806 }
15807
15808 /// Read a hidden slot, or `None` when the object has none of that name.
15809 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
15810 let slots = self.realm.internal_slots.borrow();
15811 let Value::Symbol(symbol) = slots.get(name)? else {
15812 return None;
15813 };
15814 object
15815 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
15816 .and_then(|property| property.value)
15817 }
15818
15819 /// Define a hidden slot.
15820 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
15821 let key = self.internal_slot(name);
15822 object.define_key(&key, Property::with_attributes(value, false, false));
15823 }
15824
15825 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
15826 ///
15827 /// The method is looked up on the value (through its prototype), called with no
15828 /// arguments, and its result becomes the iterator. A generator gets here through
15829 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
15830 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
15831 ///
15832 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
15833 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
15834 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
15835 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
15836 /// does, and a user-defined iterable works without a special case.
15837 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
15838 /// `Symbol.iterator`.
15839 ///
15840 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
15841 /// iterable is legal there, and each value it produces is simply already settled by
15842 /// the time the `await` around it runs.
15843 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15844 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
15845 let method = self.read_field_key(value, &async_key)?;
15846 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
15847 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
15848 // is *present but not callable* is a TypeError — it does not mean "try the other
15849 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
15850 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
15851 // guard is there to catch.
15852 let absent = matches!(method, Value::Undefined | Value::Null);
15853 if !absent {
15854 let Value::Object(object) = &method else {
15855 return Err(Signal::Throw(
15856 self.make_error("TypeError", "value is not iterable"),
15857 ));
15858 };
15859 if !object.is_callable() {
15860 return Err(Signal::Throw(
15861 self.make_error("TypeError", "value is not iterable"),
15862 ));
15863 }
15864 }
15865 if absent {
15866 // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
15867 // generator's `yield*` both reach here, and the wrapper is what puts
15868 // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
15869 // caller — a poisoned `constructor` on that value rejects instead of being
15870 // yielded, and a rejection closes the synchronous iterator first.
15871 let sync = self.get_iterator(value)?;
15872 return self.async_from_sync_iterator(sync);
15873 }
15874 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15875 if !matches!(iterator, Value::Object(_)) {
15876 return Err(Signal::Throw(
15877 self.make_error("TypeError", "iterator is not an object"),
15878 ));
15879 }
15880 let next = self.read_field(&iterator, "next")?;
15881 Ok(Iterator {
15882 object: iterator,
15883 next,
15884 })
15885 }
15886
15887 /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
15888 ///
15889 /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
15890 /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
15891 /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
15892 fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
15893 let Some(factory) = self.realm.async_from_sync.clone() else {
15894 // No wrapper installed (a realm whose heap refused to hold it): fall back to the
15895 // raw synchronous iterator rather than refusing to iterate at all.
15896 return Ok(sync);
15897 };
15898 let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
15899 let next = self.read_field(&wrapper, "next")?;
15900 Ok(Iterator {
15901 object: wrapper,
15902 next,
15903 })
15904 }
15905
15906 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
15907 /// read — `@@iterator` is **not** consulted.
15908 ///
15909 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
15910 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
15911 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
15912 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
15913 /// refused it with "[object Object] is not iterable".
15914 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
15915 if !matches!(value, Value::Object(_)) {
15916 return Err(self.type_error("iterator is not an object"));
15917 }
15918 let next = self.read_field(&value, "next")?;
15919 Ok(Iterator {
15920 object: value,
15921 next,
15922 })
15923 }
15924
15925 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15926 let key = self.realm.well_known_key(WellKnown::Iterator);
15927 let method = self.read_field_key(value, &key)?;
15928 let Value::Object(function) = &method else {
15929 return Err(Signal::Throw(self.make_error(
15930 "TypeError",
15931 &format!("{} is not iterable", value.to_js_string()),
15932 )));
15933 };
15934 if !function.is_callable() {
15935 return Err(Signal::Throw(self.make_error(
15936 "TypeError",
15937 &format!("{} is not iterable", value.to_js_string()),
15938 )));
15939 }
15940 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15941 // The spec requires an object here; a primitive iterator has no `next` to call
15942 // and would fail one step later with a confusing message.
15943 if !matches!(iterator, Value::Object(_)) {
15944 return Err(Signal::Throw(
15945 self.make_error("TypeError", "iterator is not an object"),
15946 ));
15947 }
15948 let next = self.read_field(&iterator, "next")?;
15949 Ok(Iterator {
15950 object: iterator,
15951 next,
15952 })
15953 }
15954
15955 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15956 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15957 /// exception from `return` propagates normally instead of being swallowed. That is the
15958 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15959 /// because confusing them is exactly the bug both exist to avoid.
15960 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15961 let method = self.read_field(&iterator.object, "return")?;
15962 if matches!(method, Value::Undefined | Value::Null) {
15963 return Ok(());
15964 }
15965 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15966 return Err(self.type_error("iterator return is not a function"));
15967 }
15968 self.call_value(method, iterator.object.clone(), Vec::new())?;
15969 Ok(())
15970 }
15971
15972 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15973 /// cannot replace it.
15974 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15975 let method = self.read_field(&iterator.object, "return")?;
15976 if matches!(method, Value::Undefined | Value::Null) {
15977 return Ok(());
15978 }
15979 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15980 return Err(self.type_error("iterator return is not a function"));
15981 }
15982 self.call_value(method, iterator.object.clone(), Vec::new())?;
15983 Ok(())
15984 }
15985
15986 /// One step of an internal iterator: the value and whether it is exhausted.
15987 /// Replace the iterator slot of an iteration record with `undefined`.
15988 ///
15989 /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15990 /// `undefined` record is what every close path already treats as "nothing to close", so
15991 /// one store both records "this iterator must not be closed" and keeps
15992 /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15993 fn clear_iterator_slot(&mut self, slot: usize) {
15994 let frame = self.frame_mut();
15995 let depth = frame.stack.len();
15996 if depth > slot {
15997 frame.stack[depth - 1 - slot] = Value::Undefined;
15998 }
15999 }
16000
16001 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
16002 // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
16003 // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
16004 // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
16005 // before the first step, so an iterator with no `next` still gets its `return`
16006 // called by `it.return()` instead of failing up front
16007 // (`array-rest-iter-rtrn-close-err`).
16008 if let Value::Object(object) = &iterator.next
16009 && object.is_callable()
16010 {
16011 let result =
16012 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
16013 let Some(result) = result.as_object().cloned() else {
16014 return Err(self.type_error("iterator result is not an object"));
16015 };
16016 let done = self
16017 .get_property(&result, "done")?
16018 .is_some_and(|value| value.to_boolean());
16019 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
16020 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
16021 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
16022 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
16023 // made an unrelated `value` getter observable after the loop was over.
16024 if done {
16025 return Ok((Value::Undefined, true));
16026 }
16027 let value = self
16028 .get_property(&result, "value")?
16029 .unwrap_or(Value::Undefined);
16030 return Ok((value, false));
16031 }
16032 // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
16033 // tested at the call. Treating a non-callable `next` as "exhausted" instead made
16034 // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
16035 // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
16036 Err(Signal::Throw(self.make_error(
16037 "TypeError",
16038 "iterator's next method is not callable",
16039 )))
16040 }
16041
16042 /// `[...iterable]`: append everything the iterator yields, and answer the next
16043 /// index.
16044 ///
16045 /// This goes through the same iterator machinery `for-of` uses rather than copying
16046 /// an array's elements, because a spread source is any iterable: a string spreads
16047 /// into its characters and an array iterator spreads into its results. Handling
16048 /// only arrays made `[..."ab"]` come out empty with no error at all.
16049 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
16050 let Some(target) = array.as_object().cloned() else {
16051 return Ok(0);
16052 };
16053 let start = target.array_length().unwrap_or(0);
16054 let mut added = 0;
16055 let iterator = self.get_iterator(iterable)?;
16056 loop {
16057 let (value, done) = self.iterator_step(&iterator)?;
16058 if done {
16059 break;
16060 }
16061 target.array_set(self.heap, start + added, value);
16062 added += 1;
16063 }
16064 Ok((start + added) as i32)
16065 }
16066
16067 /// How an uncaught exception is reported.
16068 ///
16069 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
16070 /// with `ToString` — `js_std_dump_error` is three lines that end in
16071 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
16072 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
16073 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
16074 ///
16075 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
16076 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
16077 /// `toString`"; it does call it, but only for objects of a class it does not know how
16078 /// to walk, and never for errors, arrays or plain objects.
16079 ///
16080 /// A printer that fails must not take the reporter down with it, so that case falls
16081 /// back to the `ToString` rendering.
16082 pub fn describe_exception(&mut self, value: &Value) -> String {
16083 match crate::print::sprint(self, value) {
16084 Ok(text) => text,
16085 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
16086 }
16087 }
16088
16089 /// The file name of whatever is running, innermost frame first.
16090 ///
16091 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
16092 /// innermost frame's file name, without distinguishing a module body from a plain
16093 /// script. `import()` uses it as the base for a relative specifier, which is why
16094 /// `import('./x.js')` inside a script resolves next to the script and not next to the
16095 /// process's working directory.
16096 pub fn script_or_module_name(&self) -> Option<String> {
16097 self.script_or_module_name_at(0)
16098 }
16099
16100 /// [`Interp::script_or_module_name`] `level` frames further out.
16101 ///
16102 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
16103 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
16104 /// frame without a file name is skipped rather than counted, because a native call
16105 /// pushes no frame of its own and so cannot be a level.
16106 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
16107 self.frames
16108 .iter()
16109 .rev()
16110 .filter_map(|frame| frame.code.code.filename.clone())
16111 .nth(level)
16112 }
16113
16114 /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
16115 ///
16116 /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
16117 /// because that is what a stack trace should print, but §19.2.1.1's
16118 /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
16119 /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
16120 /// produced the bare specifier `x.js`, which the loader then looked for in the working
16121 /// directory instead of beside the file that called `eval`.
16122 pub fn script_or_module_file_name(&self) -> Option<String> {
16123 self.frames.iter().rev().find_map(|frame| {
16124 let name = frame.code.code.filename.as_deref()?;
16125 (!name.starts_with('<')).then(|| name.to_string())
16126 })
16127 }
16128
16129 /// The current call stack, formatted the way `qjs` prints `error.stack`.
16130 ///
16131 /// One ` at name (file:line:col)` line per active frame, innermost first. The
16132 /// position is the one recorded for the instruction each frame is stopped on, which
16133 /// is why the compiler builds a pc-to-position table per function: without it a
16134 /// trace could only name the function, not the line inside it.
16135 ///
16136 /// A frame whose code has no positions prints just `(file)`, matching the
16137 /// reference's output for stripped bytecode.
16138 pub fn stack_trace(&self) -> String {
16139 self.stack_trace_skipping(0)
16140 }
16141
16142 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
16143 fn stack_trace_skipping(&self, skip: usize) -> String {
16144 // One ordered list, innermost first, so `skip` counts the same thing whether the
16145 // frames it leaves out are native or bytecode. Indices rather than references: a
16146 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
16147 let depth = self.frames.len();
16148 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
16149 // A native entered while `at` bytecode frames were live was called *from* the
16150 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
16151 // entered at the current depth are therefore innermost of all.
16152 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
16153 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
16154 if *at == wanted {
16155 order.push((true, index));
16156 }
16157 }
16158 };
16159 push_natives(&mut order, depth);
16160 for index in (0..depth).rev() {
16161 order.push((false, index));
16162 push_natives(&mut order, index);
16163 }
16164 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
16165 // barrier. Natives entered at exactly the barrier depth are the eval entry point
16166 // itself (`evalScript (native)`), and the reference leaves those out too.
16167 if let Some(barrier) = self.trace_barriers.last().copied() {
16168 order.retain(|(is_native, index)| match is_native {
16169 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
16170 false => *index >= barrier,
16171 });
16172 }
16173
16174 let mut out = String::new();
16175 for (is_native, index) in order.into_iter().skip(skip) {
16176 match is_native {
16177 true => {
16178 out.push_str(" at ");
16179 let (native, _) = &self.native_frames[index];
16180 let name = native
16181 .own_property("name")
16182 .and_then(|property| property.value)
16183 .map(|value| value.to_js_string())
16184 .unwrap_or_default();
16185 out.push_str(&name);
16186 out.push_str(" (native)\n");
16187 }
16188 false => {
16189 let frame = &self.frames[index];
16190 let code = &frame.code.code;
16191 let file = code.filename.as_deref().unwrap_or("<input>");
16192 // The name comes from the function *object*, not from the compiled code:
16193 // an anonymous function expression is named by the property it is stored
16194 // in (`{valueOf: function(){}}`), which only the object knows.
16195 let bound_name = match &frame.callee {
16196 Value::Object(object) => {
16197 object
16198 .own_property("name")
16199 .and_then(|property| match property.value {
16200 Some(Value::String(text)) if !text.wtf8().is_empty() => {
16201 Some(text.to_string_lossy().into_owned())
16202 }
16203 _ => None,
16204 })
16205 }
16206 _ => None,
16207 };
16208 // No callee object means the body was entered by the host, so the
16209 // name has to come from the compiled code. Two cases differ:
16210 //
16211 // * an *unnamed* function of any kind — the reference reads the
16212 // `name` property, finds it empty, and prints `<anonymous>`;
16213 // * a *module* body, which has no `name` property at all: the
16214 // reference builds that function object with `js_closure2` and
16215 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
16216 // so a trace reaching it also prints `<anonymous>` — while a
16217 // *script* body prints `<eval>`, its `name`.
16218 let unnamed = code.name.is_empty() || code.module.is_some();
16219 out.push_str(" at ");
16220 match bound_name.as_deref() {
16221 Some(name) => out.push_str(name),
16222 None if unnamed => out.push_str("<anonymous>"),
16223 None => out.push_str(&code.name),
16224 }
16225 match code.position_at(frame.at as u32) {
16226 Some((line, column)) => {
16227 out.push_str(&format!(" ({file}:{line}:{column})\n"));
16228 }
16229 None => out.push_str(&format!(" ({file})\n")),
16230 }
16231 }
16232 }
16233 }
16234 out
16235 }
16236
16237 /// Give an anonymous function the name of the property it is stored in.
16238 ///
16239 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
16240 /// enumerable and not configurable, and a function that already has a real name
16241 /// keeps it.
16242 ///
16243 /// "Already named" means a *non-empty* name: every function object is created with
16244 /// a `name` of `""` so the property exists on all of them, and treating that empty
16245 /// string as a name left every anonymous function nameless — which is how a stack
16246 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
16247 /// `SetFunctionName`, for a name that came from source text.
16248 fn set_function_name(&mut self, function: &Value, name: &str) {
16249 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
16250 }
16251
16252 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
16253 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
16254 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
16255 let Value::Object(object) = function else {
16256 return;
16257 };
16258 // `SetFunctionName` applies to *functions* and classes only, and only when they are
16259 // anonymous. Without the callability guard, `{value: someObject}` renamed
16260 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
16261 // on the right-hand side of a property. That is how a `zipKeyed` result object
16262 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
16263 // has no `NamedEvaluation` at all.
16264 if !object.is_callable() {
16265 return;
16266 }
16267 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
16268 && !existing.wtf8().is_empty()
16269 {
16270 return;
16271 }
16272 let text = self.string_wtf8(name.clone());
16273 object.define("name", Property::name_or_length(text));
16274 }
16275
16276 // -- global declarations -----------------------------------------------
16277
16278 /// Declare a global binding, creating its reference cell.
16279 /// Declare a `var` or function global, whose home is the global object.
16280 ///
16281 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
16282 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
16283 /// such as `print`, or a redeclaration — is left alone.
16284 pub fn declare_var_global(&mut self, name: &str) {
16285 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
16286 // global object is exactly the leak `typeof my_var === "undefined"` after
16287 // `eval("var my_var=2")` rules out.
16288 if let Some(scope) = self.eval_scope.last_mut() {
16289 scope.entry(name.to_string()).or_insert(Value::Undefined);
16290 return;
16291 }
16292 // A sloppy direct eval declares into its *caller's* variable environment. Doing
16293 // this on the global object instead made `eval("var c = 1")` inside a parameter
16294 // list overwrite a global `c`, and made two calls to the same function share one
16295 // binding.
16296 if let Some(cell) = self.declare_eval_local(name) {
16297 cell.set(Value::Undefined);
16298 return;
16299 }
16300 // The caller's frame already binds the name, so the declaration is satisfied by
16301 // that binding and there is nothing new to create. Without this the fall-through
16302 // below declared a *global* as well, so `var q; eval("var q = 5")` left a
16303 // `globalThis.q` behind (`eval-code/direct/var-env-var-init-local-exstng`).
16304 if self.eval_caller.flatten().is_some_and(|caller| {
16305 self.eval_bindings
16306 .iter()
16307 .any(|binding| binding.name == name && binding.frame == caller)
16308 }) {
16309 return;
16310 }
16311 let global = self.realm.global.clone();
16312 if global.own_property(name).is_some() {
16313 return;
16314 }
16315 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
16316 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
16317 // whole point of that trick and what lets `Object.defineProperty` reshape it
16318 // afterwards. `eval_scope` is `Some` while an eval is running.
16319 let from_eval = self.eval_depth > 0 || !self.eval_scope.is_empty();
16320 global.define(
16321 name,
16322 Property {
16323 value: Some(Value::Undefined),
16324 writable: true,
16325 enumerable: true,
16326 configurable: from_eval,
16327 ..Property::default()
16328 },
16329 );
16330 }
16331
16332 /// Declare a *lexical* global binding, which starts in its dead zone.
16333 ///
16334 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
16335 /// global object and is created when its initialiser runs.
16336 pub fn declare_global(&mut self, name: &str, is_const: bool) {
16337 if is_const {
16338 self.realm.lexical_consts.insert(name.to_string());
16339 }
16340 if !self.realm.globals.contains_key(name) {
16341 // `Uninitialized` rather than `Undefined`: the binding exists but is not
16342 // readable until its initialiser runs, and that is what `let x` before
16343 // `x = 1` has to observe.
16344 let cell = self.new_cell(Value::Uninitialized);
16345 self.realm.globals.insert(name.to_string(), cell);
16346 self.realm.declared.push(name.to_string());
16347 }
16348 }
16349}
16350
16351/// The bytecode and environment of a function object, if it is a bytecode function.
16352///
16353/// Extracted before a call so no borrow of the object is held across it.
16354fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
16355 function.with(|data| match &data.kind {
16356 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
16357 _ => None,
16358 })
16359}
16360
16361/// A native call target, extracted before the call so no borrow is held.
16362enum NativeCall {
16363 Native(NativeFn),
16364 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
16365 /// not hold that object's `RefCell` borrow.
16366 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
16367 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
16368 Bound {
16369 target: Value,
16370 this: Value,
16371 leading: Vec<Value>,
16372 },
16373 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
16374 Revoker(crate::object::ProxyRef),
16375 /// A promise's `resolve`.
16376 PromiseResolve(Gc<JsObject>),
16377 /// A promise's `reject`.
16378 PromiseReject(Gc<JsObject>),
16379 /// The executor `NewPromiseCapability(C)` hands a user constructor.
16380 CapabilityExecutor {
16381 state: Gc<JsObject>,
16382 },
16383 /// One leg of a `then` that settles through a user capability.
16384 ThenShim {
16385 handler: Option<Value>,
16386 resolve: Value,
16387 reject: Value,
16388 fulfilled: bool,
16389 },
16390 /// One continuation of an `await`.
16391 AwaitResume {
16392 coroutine: Gc<JsObject>,
16393 promise: Gc<JsObject>,
16394 kind: ResumeKind,
16395 },
16396 /// One element of a `Promise` combinator settling.
16397 CombinatorSettle {
16398 state: Gc<JsObject>,
16399 index: usize,
16400 fulfilled: bool,
16401 },
16402 /// One of `Promise.prototype.finally`'s two shims.
16403 FinallyShim {
16404 callback: Option<Value>,
16405 fulfilled: bool,
16406 constructor: Value,
16407 },
16408 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
16409 ReturnValue(Value),
16410 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
16411 ThrowValue(Value),
16412 /// Settle a promise with a fixed outcome.
16413 SettlePromise {
16414 promise: Gc<JsObject>,
16415 value: Value,
16416 rejected: bool,
16417 },
16418 /// §16.2.1.5.3.1 `AsyncModuleExecutionFulfilled(module)`.
16419 ModuleEvaluationFulfilled {
16420 module: Gc<crate::module::ModuleRecord>,
16421 },
16422 /// §16.2.1.5.3.1 `AsyncModuleExecutionRejected(module, error)`.
16423 ModuleEvaluationRejected {
16424 module: Gc<crate::module::ModuleRecord>,
16425 },
16426 /// §16.2.1.5.4: resolve a pending `import()` with the module's namespace.
16427 ModuleNamespaceForImport {
16428 module: Gc<crate::module::ModuleRecord>,
16429 promise: Gc<JsObject>,
16430 },
16431 /// Continue an async generator after its `await` settled.
16432 GeneratorResume {
16433 generator: Gc<JsObject>,
16434 promise: Gc<JsObject>,
16435 kind: ResumeKind,
16436 },
16437 /// Read a module namespace's binding out of its cell.
16438 ModuleBinding(Gc<Cell>),
16439 /// Finish a completed async generator's `return(v)` once `v` has settled.
16440 CompletedReturn {
16441 generator: Gc<JsObject>,
16442 promise: Gc<JsObject>,
16443 rejected: bool,
16444 },
16445 /// Answer a pending async-generator method with `{value, done}`.
16446 YieldResult {
16447 generator: Gc<JsObject>,
16448 promise: Gc<JsObject>,
16449 done: bool,
16450 },
16451 /// One step of `AsyncDisposableStack.disposeAsync`.
16452 DisposeStep {
16453 remaining: Gc<JsObject>,
16454 promise: Gc<JsObject>,
16455 error: Value,
16456 rejected: bool,
16457 awaited: bool,
16458 needs_await: bool,
16459 },
16460}
16461
16462/// What a store does when the object refuses the write.
16463#[derive(Clone, Copy, PartialEq, Eq)]
16464pub enum DeleteFailure {
16465 /// Raise a `TypeError`, which is what strict mode and every built-in does.
16466 Throw,
16467 /// Ignore the write, which is what a sloppy-mode assignment does.
16468 Ignore,
16469}
16470
16471/// Whether `object` is a `Date` instance, by the class tag it carries.
16472///
16473/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
16474/// builtins module depending on the interpreter's conversion order.
16475fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
16476 interp
16477 .internal_get(object, "_class")
16478 .is_some_and(|value| value.to_js_string() == "Date")
16479}
16480
16481/// Which type `ToPrimitive` prefers when it converts an object.
16482#[derive(Clone, Copy, PartialEq, Eq)]
16483pub enum Hint {
16484 /// The default hint, which behaves like [`Hint::Number`].
16485 Default,
16486 /// `Number(obj)` and the arithmetic operators.
16487 Number,
16488 /// `String(obj)` and `ToPropertyKey`.
16489 String,
16490}
16491
16492/// Which table a binding slot indexes, for the messages that name it.
16493#[derive(Clone, Copy)]
16494enum VarSlot {
16495 Loc,
16496 Closure,
16497}
16498
16499/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
16500fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
16501 Ok(this)
16502}
16503
16504/// An internal iterator: the sequence plus a cursor.
16505pub(crate) struct Iterator {
16506 pub(crate) object: Value,
16507 pub(crate) next: Value,
16508}
16509
16510/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
16511/// and plain `a` for a method.
16512///
16513/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
16514/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
16515/// reads `at get a (file:1:2)`.
16516/// The same prefixing, for a name that may hold an unpaired surrogate.
16517fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
16518 let prefix = match flags & 3 {
16519 1 => "get ",
16520 2 => "set ",
16521 _ => return key.clone(),
16522 };
16523 let mut units: Vec<u16> = prefix.encode_utf16().collect();
16524 units.extend_from_slice(&key.to_units());
16525 crate::value::Wtf8::from_units(&units)
16526}
16527
16528/// `SetFunctionName`'s name for a symbol property key: `[description]`, or `""`.
16529///
16530/// §7.3.24 step 1. A symbol without a description names the function the empty string, not
16531/// `Symbol()` — the two are different and test262 checks both.
16532fn symbol_key_name(key: &PropertyKey) -> crate::value::Wtf8 {
16533 let PropertyKey::Symbol(symbol) = key else {
16534 return crate::value::Wtf8::default();
16535 };
16536 match symbol.description() {
16537 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
16538 None => crate::value::Wtf8::default(),
16539 }
16540}
16541
16542/// Define a method or accessor property, per the `define_method` flag byte.
16543///
16544/// The low two bits pick value/getter/setter and bit 2 marks the property
16545/// enumerable.
16546///
16547/// A getter and a setter arrive as two separate `define_method` instructions, and the
16548/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
16549/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
16550/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
16551/// `JS_DefineProperty`, which leaves the other half alone.
16552fn define_function_property(
16553 object: &Gc<JsObject>,
16554 key: &PropertyKey,
16555 function: Value,
16556 flags: u32,
16557) -> bool {
16558 let enumerable = flags & 4 != 0;
16559 let kind = flags & 3;
16560 let existing = object.own_property_key(key);
16561 let property = match kind {
16562 1 => Property {
16563 getter: Some(function),
16564 // The setter half, if this literal already defined one.
16565 setter: existing
16566 .filter(Property::is_accessor)
16567 .and_then(|p| p.setter),
16568 enumerable,
16569 configurable: true,
16570 ..Property::default()
16571 },
16572 2 => Property {
16573 getter: existing
16574 .filter(Property::is_accessor)
16575 .and_then(|p| p.getter),
16576 setter: Some(function),
16577 enumerable,
16578 configurable: true,
16579 ..Property::default()
16580 },
16581 _ => Property {
16582 value: Some(function),
16583 writable: true,
16584 enumerable,
16585 configurable: true,
16586 ..Property::default()
16587 },
16588 };
16589 object.create_data_property_key(key, property)
16590}
16591
16592// ---------------------------------------------------------------------------
16593// Operand decoding
16594// ---------------------------------------------------------------------------
16595
16596/// How `print` renders a value: the reference's `JS_PrintValue`.
16597///
16598/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
16599/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
16600/// The format is reproduced closely because the test suite compares output text:
16601///
16602/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
16603/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
16604/// * a cycle prints `[circular N]` with `N` the stack index of the object;
16605/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
16606/// end print as `<N empty item(s)>`;
16607/// * a string is quoted inside a container but raw at the top level, which is why
16608/// `print("x")` and `print(["x"])` differ.
16609pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
16610 // A string argument is printed raw: `js_print` converts it with `ToString`
16611 // instead of dumping it, and the quoting only appears inside a container.
16612 if let Value::String(text) = value {
16613 return text.to_string_lossy().into_owned();
16614 }
16615 let mut printer = Printer {
16616 interp,
16617 out: String::new(),
16618 stack: Vec::new(),
16619 };
16620 printer.value(value, 0);
16621 printer.out
16622}
16623
16624/// The internal class name an object carries, when it has one.
16625fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
16626 interp
16627 .internal_get(object, "_class")
16628 .map(|value| value.to_js_string())
16629}
16630
16631/// A string property, looked up the way `GetProperty` does: own first, then the
16632/// prototype chain. Needed because the print formatter holds the interpreter
16633/// immutably and so cannot run getters.
16634fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
16635 let mut current = Some(object.clone());
16636 // Bounded, because a prototype cycle would otherwise loop forever.
16637 for _ in 0..100 {
16638 let node = current?;
16639 if let Some(property) = node.own_property(name)
16640 && let Some(value) = property.value
16641 {
16642 return Some(value.to_js_string());
16643 }
16644 current = node.with(|data| data.proto.clone());
16645 }
16646 None
16647}
16648
16649/// The `JS_PrintValue` state: output, and the objects currently being printed.
16650struct Printer<'a, 'rt> {
16651 /// Kept for the class-name lookups that typed arrays and `Date` will need.
16652 #[allow(dead_code)]
16653 interp: &'a Interp<'rt>,
16654 out: String,
16655 stack: Vec<Gc<JsObject>>,
16656}
16657
16658impl Printer<'_, '_> {
16659 /// Depth past which a container is summarised by its class name.
16660 const MAX_DEPTH: usize = 2;
16661
16662 fn value(&mut self, value: &Value, level: usize) {
16663 match value {
16664 Value::Undefined
16665 | Value::Uninitialized
16666 | Value::Hole
16667 | Value::CatchOffset(_)
16668 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
16669 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
16670 // The printer writes a bigint the way the language spells one, so a dump is
16671 // unambiguous about which kind of number it is showing.
16672 Value::BigInt(big) => {
16673 self.out.push_str(&big.to_decimal_string());
16674 self.out.push('n');
16675 }
16676 Value::Null => self.out.push_str("null"),
16677 Value::Bool(true) => self.out.push_str("true"),
16678 Value::Bool(false) => self.out.push_str("false"),
16679 Value::Int(number) => self.out.push_str(&number.to_string()),
16680 Value::Float(number) => {
16681 self.out
16682 .push_str(&crate::value::number_to_string_for_print(*number));
16683 }
16684 Value::String(text) => self.print_string(&text.to_string_lossy()),
16685 Value::Object(object) => self.object(object, level),
16686 }
16687 }
16688
16689 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
16690 // A cycle is reported rather than followed; the index is where the object
16691 // already sits in the print stack, which is what the reference shows.
16692 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
16693 self.out.push_str(&format!("[circular {index}]"));
16694 return;
16695 }
16696 if object.is_callable() {
16697 let name = object
16698 .own_property("name")
16699 .and_then(|property| property.value)
16700 .map(|value| value.to_js_string())
16701 .unwrap_or_default();
16702 if name.is_empty() {
16703 self.out.push_str("[Function (anonymous)]");
16704 } else {
16705 self.out.push_str(&format!("[Function {name}]"));
16706 }
16707 return;
16708 }
16709 if level >= Self::MAX_DEPTH {
16710 let class = if object.is_array() { "Array" } else { "Object" };
16711 self.out.push_str(&format!("[{class}]"));
16712 return;
16713 }
16714 // A `RegExp` prints as its own literal, `js_print_regexp`'s `/%s/%s`. Without this
16715 // it fell through to the plain-object form and `print(/x/)` answered `{ }` — no
16716 // properties, so nothing to show, and the value's identity lost.
16717 if let Some(data) = object.regexp() {
16718 let source = crate::builtins::regexp::escaped_source(&data.source);
16719 self.out.push('/');
16720 self.out.push_str(&source.to_string_lossy());
16721 self.out.push('/');
16722 self.out.push_str(&data.flags);
16723 return;
16724 }
16725 // `Date` and `Error` print as themselves rather than as bags of properties:
16726 // the ISO string, and `Name: message` followed by the trace.
16727 if let Some(class) = class_of(self.interp, object) {
16728 if class == "Date" {
16729 self.date(object);
16730 return;
16731 }
16732 if class == "Error" {
16733 self.error(object);
16734 return;
16735 }
16736 }
16737 self.stack.push(object.clone());
16738 if object.is_array() {
16739 self.array(object, level);
16740 } else {
16741 self.plain_object(object, level);
16742 }
16743 self.stack.pop();
16744 }
16745
16746 /// A Date prints as its ISO string; an invalid one falls through to the plain
16747 /// object form, the way the reference falls back when `toISOString` throws.
16748 fn date(&mut self, object: &Gc<JsObject>) {
16749 let value = self
16750 .interp
16751 .internal_get(object, "_date_value")
16752 .map(|value| value.to_number());
16753 match value.and_then(crate::builtins::date::iso_string) {
16754 Some(text) => self.out.push_str(&text),
16755 None => self.plain_object(object, 0),
16756 }
16757 }
16758
16759 /// `Name: message`, then the trace with its trailing newline removed.
16760 fn error(&mut self, object: &Gc<JsObject>) {
16761 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
16762 self.out.push_str(&name);
16763 if let Some(message) = inherited(object, "message")
16764 && !message.is_empty()
16765 {
16766 self.out.push_str(": ");
16767 self.out.push_str(&message);
16768 }
16769 if let Some(stack) = inherited(object, "stack") {
16770 self.out.push('\n');
16771 self.out.push_str(stack.trim_end_matches('\n'));
16772 }
16773 }
16774
16775 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
16776 let elements = object.array_elements().unwrap_or_default();
16777 self.out.push_str("[ ");
16778 // An interior hole means the array is "sparse": the reference prints those
16779 // as `index: value` pairs and says nothing about the holes themselves, while
16780 // a hole run at the end becomes a single `<N empty items>` note.
16781 let last_present = elements
16782 .iter()
16783 .rposition(|value| !matches!(value, Value::Hole));
16784 let has_interior_hole = match last_present {
16785 Some(last) => elements[..last]
16786 .iter()
16787 .any(|value| matches!(value, Value::Hole)),
16788 None => false,
16789 };
16790 let mut first = true;
16791 if has_interior_hole {
16792 let mut index = 0;
16793 while index < elements.len() {
16794 let value = &elements[index];
16795 if matches!(value, Value::Hole) {
16796 index += 1;
16797 continue;
16798 }
16799 if !first {
16800 self.out.push_str(", ");
16801 }
16802 first = false;
16803 self.out.push_str(&format!("{index}: "));
16804 self.value(value, level + 1);
16805 index += 1;
16806 }
16807 } else {
16808 for (index, value) in elements.iter().enumerate() {
16809 if matches!(value, Value::Hole) {
16810 continue;
16811 }
16812 if !first {
16813 self.out.push_str(", ");
16814 }
16815 first = false;
16816 let _ = index;
16817 self.value(value, level + 1);
16818 }
16819 if let Some(last) = last_present {
16820 let trailing = elements.len() - last - 1;
16821 if trailing > 0 {
16822 if !first {
16823 self.out.push_str(", ");
16824 }
16825 self.out.push_str(&format!(
16826 "<{trailing} empty item{}>",
16827 if trailing > 1 { "s" } else { "" }
16828 ));
16829 }
16830 } else if !elements.is_empty() {
16831 let count = elements.len();
16832 self.out.push_str(&format!(
16833 "<{count} empty item{}>",
16834 if count > 1 { "s" } else { "" }
16835 ));
16836 }
16837 }
16838 self.out.push_str(" ]");
16839 }
16840
16841 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
16842 self.out.push_str("{ ");
16843 let mut first = true;
16844 for key in object.own_keys() {
16845 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
16846 continue;
16847 };
16848 if !property.enumerable {
16849 continue;
16850 }
16851 if !first {
16852 self.out.push_str(", ");
16853 }
16854 first = false;
16855 self.out
16856 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
16857 &key.to_string_lossy(),
16858 )));
16859 self.out.push_str(": ");
16860 // An accessor has no value to dump; the reference names the half that
16861 // exists instead of calling it.
16862 if property.is_accessor() {
16863 let text = match (property.getter.is_some(), property.setter.is_some()) {
16864 (true, true) => "[Getter/Setter]",
16865 (false, true) => "[Setter]",
16866 _ => "[Getter]",
16867 };
16868 self.out.push_str(text);
16869 } else {
16870 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
16871 }
16872 }
16873 self.out.push_str(" }");
16874 }
16875
16876 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
16877 fn print_string(&mut self, text: &str) {
16878 self.out.push('"');
16879 for character in text.chars() {
16880 match character {
16881 '"' => self.out.push_str("\\\""),
16882 '\\' => self.out.push_str("\\\\"),
16883 '\n' => self.out.push_str("\\n"),
16884 '\r' => self.out.push_str("\\r"),
16885 '\t' => self.out.push_str("\\t"),
16886 c if (c as u32) < 0x20 => {
16887 self.out.push_str(&format!("\\u{:04x}", c as u32));
16888 }
16889 c => self.out.push(c),
16890 }
16891 }
16892 self.out.push('"');
16893 }
16894}
16895
16896/// How `print` renders a value.
16897///
16898/// `ToString`, except that negative zero keeps its sign — the reference's host
16899/// printer does that while `String(-0)` is `"0"`.
16900pub fn display(value: &Value) -> String {
16901 match value {
16902 Value::Float(number) => crate::value::number_to_string_for_print(*number),
16903 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
16904 "undefined".to_string()
16905 }
16906 other => other.to_js_string(),
16907 }
16908}
16909
16910// ---------------------------------------------------------------------------
16911// Numeric operators
16912// ---------------------------------------------------------------------------
16913
16914/// `a + b` keeping the `Int` representation when it fits.
16915fn add_numbers(left: Value, right: Value) -> Value {
16916 match (&left, &right) {
16917 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
16918 Some(sum) => Value::Int(sum),
16919 None => Value::Float(*a as f64 + *b as f64),
16920 },
16921 _ => Value::Float(left.to_number() + right.to_number()),
16922 }
16923}
16924
16925/// The arithmetic operators other than `+`, which needs string concatenation.
16926fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16927 use Opcode::*;
16928 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
16929 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
16930 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
16931 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
16932 return Ok(match op {
16933 And => Value::Int(x & y),
16934 Or => Value::Int(x | y),
16935 Xor => Value::Int(x ^ y),
16936 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
16937 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
16938 Shr => match (*x as u32) >> ((*y as u32) & 31) {
16939 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
16940 shifted => Value::Float(shifted as f64),
16941 },
16942 Sub => match x.checked_sub(*y) {
16943 Some(value) => Value::Int(value),
16944 None => Value::Float(*x as f64 - *y as f64),
16945 },
16946 _ => return arithmetic_slow(op, left, right),
16947 });
16948 }
16949 arithmetic_slow(op, left, right)
16950}
16951
16952/// [`arithmetic`] for everything the integer fast path above does not take.
16953fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16954 use Opcode::*;
16955 let (a, b) = (left.to_number(), right.to_number());
16956 Ok(match op {
16957 Sub => match (&left, &right) {
16958 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
16959 Some(value) => Value::Int(value),
16960 None => Value::Float(a - b),
16961 },
16962 _ => Value::Float(a - b),
16963 },
16964 Mul => Value::Float(a * b),
16965 Div => Value::Float(a / b),
16966 Mod => Value::Float(js_mod(a, b)),
16967 Pow => Value::Float(a.powf(b)),
16968 And => Value::Int(left.to_int32() & right.to_int32()),
16969 Or => Value::Int(left.to_int32() | right.to_int32()),
16970 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
16971 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
16972 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
16973 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
16974 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
16975 // fits the small-integer representation stays an `Int`; the rest become a
16976 // float, which is how the reference keeps `n >>> 0` non-negative.
16977 Shr => {
16978 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
16979 match i32::try_from(shifted) {
16980 Ok(value) => Value::Int(value),
16981 Err(_) => Value::Float(shifted as f64),
16982 }
16983 }
16984 _ => Value::Float(a),
16985 })
16986}
16987
16988/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16989///
16990/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16991/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16992/// slow path where the rules live.
16993fn is_number(value: &Value) -> bool {
16994 matches!(value, Value::Int(_) | Value::Float(_))
16995}
16996
16997/// The `Value::Bool` a comparison operator answers for `ordering`.
16998///
16999/// `None` is the unordered case — a `NaN` on either side — and every operator answers
17000/// false for it, including `<=` and `>=`.
17001fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
17002 use Opcode::*;
17003 let answer = match (op, ordering) {
17004 (_, None) => false,
17005 (Lt, Some(ordering)) => ordering.is_lt(),
17006 (Lte, Some(ordering)) => ordering.is_le(),
17007 (Gt, Some(ordering)) => ordering.is_gt(),
17008 (Gte, Some(ordering)) => ordering.is_ge(),
17009 _ => false,
17010 };
17011 Value::Bool(answer)
17012}
17013
17014/// `%`, which follows the sign of the dividend rather than Rust's.
17015fn js_mod(left: f64, right: f64) -> f64 {
17016 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
17017 return f64::NAN;
17018 }
17019 if right.is_infinite() {
17020 return left;
17021 }
17022 let remainder = left % right;
17023 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
17024 // the spec makes the sign match the dividend.
17025 if remainder == 0.0 {
17026 0.0f64.copysign(left)
17027 } else {
17028 remainder
17029 }
17030}
17031
17032fn negate(value: Value) -> Value {
17033 match value {
17034 Value::Int(0) => Value::Float(-0.0),
17035 Value::Int(i) => Value::Int(-i),
17036 other => Value::Float(-other.to_number()),
17037 }
17038}
17039
17040fn increment(value: Value) -> Value {
17041 match value {
17042 Value::Int(i) => match i.checked_add(1) {
17043 Some(next) => Value::Int(next),
17044 None => Value::Float(i as f64 + 1.0),
17045 },
17046 other => Value::Float(other.to_number() + 1.0),
17047 }
17048}
17049
17050fn decrement(value: Value) -> Value {
17051 match value {
17052 Value::Int(i) => match i.checked_sub(1) {
17053 Some(next) => Value::Int(next),
17054 None => Value::Float(i as f64 - 1.0),
17055 },
17056 other => Value::Float(other.to_number() - 1.0),
17057 }
17058}
17059
17060/// Compare a `BigInt` with an `f64` on their mathematical values.
17061///
17062/// Neither side is rounded to the other's precision: the number is split into its integer
17063/// part (compared as an exact bigint) and its fraction, which is what decides the answer
17064/// when the integer parts are equal. An infinite value is larger than every bigint.
17065fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
17066 use std::cmp::Ordering;
17067 if number.is_nan() {
17068 return None;
17069 }
17070 if number.is_infinite() {
17071 return Some(if number > 0.0 {
17072 Ordering::Less
17073 } else {
17074 Ordering::Greater
17075 });
17076 }
17077 // The comparison is **exact**, because rounding it is observable: an f64 is
17078 // `m * 2^e` with `m` a 53-bit integer, so scaling the bigint by the same power of two
17079 // turns this into an integer comparison at any width. Converting the *bigint* to f64
17080 // instead — which is what this used to do once the number was wider than `i128` —
17081 // rounds it to the nearest double, and `0xfffffffffffff7ff…n < Number.MAX_VALUE` is
17082 // decided by a difference of one bit at 2^971, which rounding erases
17083 // (`less-than/bigint-and-number-extremes`).
17084 // Both branches answer `big.cmp(number)`; which side gets scaled depends on the sign of
17085 // the exponent, because scaling the smaller one keeps the shift bounded by the f64's own
17086 // range (at most 1074 bits) instead of by the bigint's width.
17087 let (mantissa, exponent) = decompose_f64(number);
17088 let product = crate::bigint::BigInt::from_i64(mantissa);
17089 Some(if exponent >= 0 {
17090 // `number = mantissa * 2^exponent`, and that product is the exact f64 value.
17091 big.cmp(&product.shl(exponent as u64))
17092 } else {
17093 // `number = mantissa / 2^-exponent`; scale the *bigint* up instead so both sides stay
17094 // integers.
17095 big.shl((-exponent) as u64).cmp(&product)
17096 })
17097}
17098
17099/// `value` as `(mantissa, exponent)` with `value == mantissa * 2^exponent` exactly.
17100///
17101/// `mantissa` carries the sign and is the f64's significand with its implicit bit made
17102/// explicit, so `|mantissa| <= 2^53` and the `i64` conversion is exact. `value` must be
17103/// finite.
17104fn decompose_f64(value: f64) -> (i64, i32) {
17105 let bits = value.abs().to_bits();
17106 let raw_exponent = ((bits >> 52) & 0x7ff) as i32;
17107 let fraction = bits & ((1u64 << 52) - 1);
17108 // A subnormal has no implicit bit and an exponent of `1 - 1023`; a normal one carries a
17109 // leading 1 at bit 52, and the `-1075` folds in the bias and the 52 fraction bits.
17110 let (significand, exponent) = if raw_exponent == 0 {
17111 (fraction, -1074)
17112 } else {
17113 (fraction | (1u64 << 52), raw_exponent - 1075)
17114 };
17115 let significand = significand as i64;
17116 let mantissa = if value < 0.0 {
17117 -significand
17118 } else {
17119 significand
17120 };
17121 (mantissa, exponent)
17122}
17123
17124/// The UTF-16 code unit ordering of two strings, which is what `<` compares.
17125///
17126/// `JsString` caches its code units on first access, so the first `code_unit_at` builds the
17127/// cache and the rest are O(1) — no allocation here, and no decoding in the loop.
17128fn compare_code_units(
17129 a: &crate::value::JsString,
17130 b: &crate::value::JsString,
17131) -> std::cmp::Ordering {
17132 let (left, right) = (a.utf16_len(), b.utf16_len());
17133 for index in 0..left.min(right) {
17134 let (x, y) = (
17135 a.code_unit_at(index).unwrap_or(0),
17136 b.code_unit_at(index).unwrap_or(0),
17137 );
17138 if x != y {
17139 return x.cmp(&y);
17140 }
17141 }
17142 // A proper prefix sorts first, which is what the length comparison gives.
17143 left.cmp(&right)
17144}
17145
17146/// `StringToBigInt(argument)` (§7.1.14): the string read as an **integer** literal.
17147///
17148/// `undefined` — `None` here — for anything that is only a *number* literal: `"0."`,
17149/// `".0"`, `"0e0"` and `"Infinity"` all fail, which is why `1n > "0."` is `false` rather
17150/// than `true` (`greater-than/bigint-and-incomparable-string`). Leading zeros are outside
17151/// the grammar too (`"007"`), and so is whitespace between the sign and the digits.
17152///
17153/// The empty string *is* `0n`: §7.1.14 turns a whitespace-only literal into `0`.
17154fn string_to_bigint(text: &str) -> Option<crate::bigint::BigInt> {
17155 let trimmed = text.trim();
17156 let body = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
17157 let signed = body.len() != trimmed.len();
17158 // A radix prefix admits no sign, and the digits must follow immediately.
17159 let (radix, digits) = if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
17160 (16, rest)
17161 } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
17162 (8, rest)
17163 } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
17164 (2, rest)
17165 } else {
17166 (10, body)
17167 };
17168 if signed && radix != 10 && signed {
17169 // `StrNonDecimalIntegerLiteral` has no sign.
17170 return None;
17171 }
17172 if radix == 10 && digits.len() > 1 && digits.starts_with('0') {
17173 // `StrUnsignedDecimalLiteral : 0 | NonZeroDigit DecimalDigits?`.
17174 return None;
17175 }
17176 crate::bigint::BigInt::from_string(trimmed)
17177}
17178
17179/// `CanonicalNumericIndexString(argument)` (§7.1.21).
17180///
17181/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
17182/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
17183/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
17184/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
17185/// rather than treating it as `0`.
17186fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
17187 let PropertyKey::String(text) = key else {
17188 // A symbol is never an index.
17189 return None;
17190 };
17191 let text = text.to_string_lossy();
17192 if text == "-0" {
17193 return Some(-0.0);
17194 }
17195 let number: f64 = text.parse().ok()?;
17196 // The round-trip test *is* the definition: only the canonical spelling qualifies.
17197 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
17198 // `"0.10"` does not.
17199 let rendered = Value::Float(number).to_js_string();
17200 (rendered == text).then_some(number)
17201}
17202
17203/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
17204///
17205/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
17206/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
17207/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
17208/// numeric and invalid, which is why they stop the prototype chain instead of falling
17209/// through it.
17210///
17211/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
17212/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
17213/// `in`, `delete` and `defineProperty` separately to make sure it does not.
17214fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
17215 numeric.is_finite()
17216 && numeric.fract() == 0.0
17217 && !(numeric == 0.0 && numeric.is_sign_negative())
17218 && numeric >= 0.0
17219 && object
17220 .typed_array_length()
17221 .is_some_and(|length| (numeric as usize) < length)
17222}
17223
17224/// `ArrayCreate`'s length bound, `2**32 - 1`.
17225///
17226/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
17227/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
17228/// through — can enforce it without depending on a builtin module.
17229const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;