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 },
598 /// An async generator resuming after the value it awaited settled.
599 GeneratorResume {
600 /// The async generator to continue.
601 generator: Gc<JsObject>,
602 /// The promise the pending method returned.
603 promise: Gc<JsObject>,
604 /// Whether this delivers the value or raises the reason.
605 kind: ResumeKind,
606 /// The settled value, or the rejection reason.
607 value: Value,
608 },
609 /// An async function resuming after the value it awaited settled.
610 Resume {
611 /// The body, parked in a coroutine.
612 coroutine: Gc<JsObject>,
613 /// The promise the async function handed its caller.
614 promise: Gc<JsObject>,
615 /// Whether this resumption delivers a value or raises one.
616 kind: ResumeKind,
617 /// The settled value, or the rejection reason.
618 value: Value,
619 },
620}
621
622/// One macro-task: work the event loop owes the script but has not run yet.
623///
624/// The microtask queue ([`Job`]) is different: those run before the host regains control.
625/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
626/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
627/// logic: the engine decides *what* is due, the host decides *how to wait*.
628///
629/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
630/// reference counting even though nothing else references it — the same rule the `HostFn`
631/// documentation states from the other side (a host closure must not hold a `Gc`, so the
632/// `Gc` lives here instead).
633pub enum Task {
634 /// A `setTimeout` that is due at `due_at`.
635 ///
636 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
637 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
638 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
639 /// would give this engine a timer the reference cannot produce, with nothing to
640 /// compare it against.
641 Timer {
642 /// The id `setTimeout` returned, for `clearTimeout`.
643 id: i32,
644 /// What to call when it fires.
645 callback: Value,
646 /// When it becomes runnable, as a monotonic instant.
647 due_at: std::time::Instant,
648 },
649}
650
651/// A descriptor the host has to poll, and which directions have a handler.
652///
653/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
654/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
655/// blocks on it, and the host reports back through [`Interp::fire_fd`].
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
657pub struct FdInterest {
658 /// The descriptor to watch.
659 pub fd: i32,
660 /// Whether `os.setReadHandler` registered a callback.
661 pub read: bool,
662 /// Whether `os.setWriteHandler` registered a callback.
663 pub write: bool,
664}
665
666/// The callbacks registered for one descriptor, per direction.
667#[derive(Default)]
668pub(crate) struct FdHandlers {
669 /// `os.setReadHandler`'s callback.
670 pub read: Option<Value>,
671 /// `os.setWriteHandler`'s callback.
672 pub write: Option<Value>,
673}
674
675/// The file name `eval` reports, which the reference does not inherit from the caller.
676///
677/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
678/// reference and the names show up in stack traces.
679/// The description of the private symbol a class brand is made from.
680///
681/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
682/// place no script can reach, since no expression can name a private symbol.
683const BRAND_DESCRIPTION: &str = "brand";
684
685/// One validated property lookup.
686///
687/// Covers both own-property hits and prototype hits. The second kind was deliberately left
688/// uncached at first ("a prototype hit depends on more than the object and the name"), and
689/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
690/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
691/// names on every iteration (measured: 100 ns per call over an empty loop).
692pub struct FieldCache {
693 /// The name, so two different properties of one object do not collide.
694 key: PropertyKey,
695 /// Where the value was found, relative to the chain below.
696 index: usize,
697 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
698 level: u8,
699 /// The receiver and every prototype down to (and including) the level that answered,
700 /// each with the length of its property table at the time.
701 ///
702 /// That length is the whole guard, and it is sufficient for the ways the answer can
703 /// change without a lookup: adding or deleting any property moves it, and a
704 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
705 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
706 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
707 /// the one that was cached.
708 ///
709 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
710 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
711 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
712}
713
714/// How many links of a prototype chain a [`FieldCache`] remembers.
715///
716/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
717/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
718/// at three.
719const MAX_CACHED_CHAIN: usize = 3;
720
721/// A remembered global-variable lookup.
722///
723/// A `var` global is an ordinary property of the global object, so reading one walks the
724/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
725/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
726/// fixed by the bytecode, and the slot in the object's table only changes if the global
727/// object is mutated, which the index-and-name check below catches.
728pub struct GlobalCache {
729 /// The global object the lookup was resolved on, weakly.
730 object: js_gc::WeakGc<JsObject>,
731 /// Index of the data property in the global object's table.
732 index: usize,
733}
734
735/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
736const GLOBAL_CACHE_SLOTS: usize = 1024;
737
738/// How many property lookups are remembered.
739///
740/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
741/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
742/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
743/// lookup itself. Making it bigger stops helping: the working set of a real program's
744/// property sites is bounded by its code size.
745const FIELD_CACHE_SLOTS: usize = 4096;
746
747/// How much the heap may grow past the last `out of memory` before saying it again.
748///
749/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
750/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
751/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
752/// because it looks like it works. The reference gets this for free: it fails inside
753/// `js_malloc`, and its printing path happens not to allocate.
754///
755/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
756/// allocating is stopped within a rounding error of the limit) and far above what a
757/// handler needs.
758const OOM_HYSTERESIS: usize = 64 * 1024;
759
760/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
761pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
762
763/// How many instructions run between polls of [`Interp::interrupt`].
764///
765/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
766/// order of magnitude on both implementations — which is what lets a C driver compare its
767/// output byte for byte (see `scripts/m15-capi.sh --embed`).
768pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
769
770/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
771///
772/// Chosen so that the byte budget is what actually decides for every ordinary
773/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
774/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
775/// millions of frames.
776pub const MAX_FRAMES: usize = 200_000;
777
778const EVAL_FILE: &str = "<input>";
779
780/// The file name `std.evalScript` reports.
781const EVAL_SCRIPT_FILE: &str = "<evalScript>";
782
783/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
784///
785/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
786/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
787fn clamp_delay(delay_ms: f64) -> std::time::Duration {
788 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
789 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
790 // non-positive delay mean "due now".
791 if delay_ms.is_nan() || delay_ms <= 0.0 {
792 return std::time::Duration::ZERO;
793 }
794 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
795}
796
797impl js_gc::Trace for Task {
798 fn trace(&self, tracer: &mut js_gc::Tracer) {
799 let Task::Timer { callback, .. } = self;
800 callback.trace(tracer);
801 }
802}
803
804/// What one turn of the event loop did, so the caller cannot spin by accident.
805///
806/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
807/// core until the timer is due. Naming the three cases makes the wait explicit.
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809pub enum Turn {
810 /// Something ran. Call again immediately — there may be more ready work.
811 Ran,
812 /// Nothing is runnable, but descriptors are registered: the host must poll
813 /// [`Interp::pending_fds`] for at most this long, then report readiness with
814 /// [`Interp::fire_fd`].
815 ///
816 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
817 /// the failure this project treats as worst — a handler that silently never fires —
818 /// so the two cannot be confused by accident.
819 Poll(std::time::Duration),
820 /// Nothing is runnable yet, but something is pending. Block at most this long, then
821 /// call again.
822 Wait(std::time::Duration),
823 /// Nothing is pending at all: the loop is done.
824 Done,
825}
826
827impl js_gc::Trace for Job {
828 fn trace(&self, tracer: &mut js_gc::Tracer) {
829 match self {
830 Job::Reaction {
831 handler,
832 argument,
833 promise,
834 ..
835 } => {
836 if let Some(handler) = handler {
837 handler.trace(tracer);
838 }
839 argument.trace(tracer);
840 tracer.visit(promise);
841 }
842 Job::Thenable {
843 then,
844 value,
845 promise,
846 } => {
847 then.trace(tracer);
848 value.trace(tracer);
849 tracer.visit(promise);
850 }
851 Job::Resume {
852 coroutine,
853 promise,
854 value,
855 ..
856 } => {
857 tracer.visit(coroutine);
858 tracer.visit(promise);
859 value.trace(tracer);
860 }
861 Job::Import { promise, .. } => tracer.visit(promise),
862 Job::GeneratorResume {
863 generator,
864 promise,
865 value,
866 ..
867 } => {
868 tracer.visit(generator);
869 tracer.visit(promise);
870 value.trace(tracer);
871 }
872 }
873 }
874}
875
876/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
877#[derive(Debug, Clone, Copy, PartialEq, Eq)]
878pub enum ResumeKind {
879 /// The generator was just created and is being run to its first suspension.
880 Start,
881 /// `next(v)`.
882 Next,
883 /// `return(v)`.
884 Return,
885 /// `throw(e)`.
886 Throw,
887}
888
889/// A generator object's saved execution.
890///
891/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
892/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
893/// separately allocated buffers.
894pub struct GeneratorState {
895 /// The detached frame, or `None` once the generator has finished or while it runs.
896 frame: Option<Frame>,
897 /// How far it got.
898 phase: GeneratorPhase,
899 /// Whether the last suspension was an `await` rather than a `yield`.
900 ///
901 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
902 /// value and a magic number, because the emitted code branches on which method
903 /// resumed it, while an `await` simply continues with its value. Getting this wrong
904 /// leaves an extra value on the operand stack that the next instruction then
905 /// consumes — a wrong answer rather than a crash.
906 parked_on_await: bool,
907 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
908 ///
909 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
910 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
911 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
912 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
913 /// delegating. Tracking it as part of the phase, the way the reference splits
914 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
915 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
916 /// exception and never reached `xs.throw`.
917 parked_on_yield_star: bool,
918 /// Pending `next`/`return`/`throw` calls, oldest first.
919 ///
920 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
921 /// called back to back must answer in that order, with the second call's value
922 /// arriving at the *second* `yield`. Running each call straight into the body — which
923 /// is what this engine did before — delivered the last queued value to whichever
924 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
925 /// `a === b ===` the final argument.
926 ///
927 /// The front entry is the one being served; it stays there (with `async_busy` set)
928 /// until its promise settles, because an `await` inside the body is a suspension of
929 /// the *driver*, not the end of the request.
930 requests: std::collections::VecDeque<AsyncRequest>,
931 /// Whether the front request is in flight.
932 async_busy: bool,
933 /// Whether this came from an `async function*`.
934 ///
935 /// A sync generator and an async one share `ObjectKind::Generator`, so without this
936 /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
937 /// `AsyncGeneratorValidate` has to tell them apart
938 /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
939 pub is_async: bool,
940}
941
942/// How one async-generator request ended.
943enum AsyncOutcome {
944 /// The method answered this `{value, done}`.
945 Value(Value),
946 /// The body threw.
947 Error(Value),
948}
949
950/// One queued `next`/`return`/`throw` on an async generator: the reference's
951/// `JSAsyncGeneratorRequest`.
952pub struct AsyncRequest {
953 /// Which method was called.
954 kind: ResumeKind,
955 /// Its argument.
956 value: Value,
957 /// The promise the method answered.
958 promise: Gc<JsObject>,
959}
960
961/// Which of §27.5.3.3's states a generator is in.
962#[derive(Debug, Clone, Copy, PartialEq, Eq)]
963enum GeneratorPhase {
964 /// Created, `initial_yield` reached, body not entered.
965 SuspendedStart,
966 /// Parked at a `yield`.
967 SuspendedYield,
968 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
969 Executing,
970 /// Finished; the frame is gone.
971 Completed,
972}
973
974impl js_gc::Trace for GeneratorState {
975 fn trace(&self, tracer: &mut js_gc::Tracer) {
976 if let Some(frame) = &self.frame {
977 frame.trace(tracer);
978 }
979 for request in &self.requests {
980 request.value.trace(tracer);
981 tracer.visit(&request.promise);
982 }
983 }
984}
985
986/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
987/// them in.
988///
989/// Each is a field rather than a map entry because the runtime reads them on hot paths
990/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
991/// failure — reaching a default here means the builtin did not install, and every
992/// accessor panics rather than silently answering `undefined`.
993///
994/// [`builtins::symbol`]: crate::builtins::symbol
995#[derive(Default)]
996pub struct WellKnownSymbols {
997 /// The symbol values, positionally. Empty until `Symbol` installs.
998 symbols: Vec<Value>,
999}
1000
1001/// Which well-known symbol a caller wants.
1002///
1003/// A typed accessor beats passing a name around: a typo is a compile error rather than
1004/// an `undefined` key that quietly matches nothing.
1005#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1006pub enum WellKnown {
1007 /// `Symbol.toPrimitive`.
1008 ToPrimitive,
1009 /// `Symbol.iterator`.
1010 Iterator,
1011 /// `Symbol.match`.
1012 Match,
1013 /// `Symbol.matchAll`.
1014 MatchAll,
1015 /// `Symbol.replace`.
1016 Replace,
1017 /// `Symbol.search`.
1018 Search,
1019 /// `Symbol.split`.
1020 Split,
1021 /// `Symbol.toStringTag`.
1022 ToStringTag,
1023 /// `Symbol.isConcatSpreadable`.
1024 IsConcatSpreadable,
1025 /// `Symbol.hasInstance`.
1026 HasInstance,
1027 /// `Symbol.species`.
1028 Species,
1029 /// `Symbol.unscopables`.
1030 Unscopables,
1031 /// `Symbol.asyncIterator`.
1032 AsyncIterator,
1033 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1034 Disposable,
1035 /// `Symbol.asyncDispose` — the awaited form.
1036 AsyncDisposable,
1037}
1038
1039impl WellKnown {
1040 /// The index `Symbol`'s installer creates this symbol at.
1041 fn index(self) -> usize {
1042 match self {
1043 WellKnown::ToPrimitive => 0,
1044 WellKnown::Iterator => 1,
1045 WellKnown::Match => 2,
1046 WellKnown::MatchAll => 3,
1047 WellKnown::Replace => 4,
1048 WellKnown::Search => 5,
1049 WellKnown::Split => 6,
1050 WellKnown::ToStringTag => 7,
1051 WellKnown::IsConcatSpreadable => 8,
1052 WellKnown::HasInstance => 9,
1053 WellKnown::Species => 10,
1054 WellKnown::Unscopables => 11,
1055 WellKnown::AsyncIterator => 12,
1056 WellKnown::Disposable => 13,
1057 WellKnown::AsyncDisposable => 14,
1058 }
1059 }
1060}
1061
1062impl Realm {
1063 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1064 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1065 self.well_known_symbols.symbols = symbols;
1066 }
1067
1068 /// A well-known symbol.
1069 pub fn well_known(&self, which: WellKnown) -> Value {
1070 self.well_known_symbols
1071 .symbols
1072 .get(which.index())
1073 .cloned()
1074 .unwrap_or(Value::Undefined)
1075 }
1076
1077 /// The well-known symbol as a property key.
1078 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1079 match self.well_known(which) {
1080 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1081 // Unreachable once `Symbol` has installed; an empty string key matches
1082 // nothing, which degrades to "the object has no such method".
1083 _ => PropertyKey::from(String::new()),
1084 }
1085 }
1086}
1087
1088/// The interpreter: a realm plus a frame stack.
1089pub struct Interp<'a> {
1090 /// The heap everything is allocated on.
1091 pub heap: &'a Heap,
1092 /// The realm.
1093 pub realm: Realm,
1094 /// Active frames, outermost first.
1095 frames: Vec<Frame>,
1096 /// Value buffers from frames that have finished, reused by the next call.
1097 ///
1098 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1099 /// the locals and the operand stack — and free all four on return. `call:recursion`
1100 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1101 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1102 ///
1103 /// Bounded in both directions: a few buffers per kind, and none larger than
1104 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1105 /// and keeping its buffer would pin that memory for the rest of the run.
1106 free_values: Vec<Vec<Value>>,
1107 /// A strict-mode `eval`'s own variable scope, while its script runs.
1108 ///
1109 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1110 /// become a global. Name lookups still fall through to the realm, which is why
1111 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1112 /// A **stack**, innermost last, because evals nest: the inner eval of
1113 /// `eval("var a; eval('a')")` must still see the outer one's `a`, and each strict eval
1114 /// gets a fresh environment of its own layered over the previous.
1115 eval_scope: Vec<BTreeMap<String, Value>>,
1116 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1117 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1118 eval_depth: usize,
1119 /// Whether the program currently being compiled is an `eval` body rather than a
1120 /// global script. See [`Compiler::eval_body`].
1121 compiling_eval_body: bool,
1122 /// The calling frame's own bindings, which the running `eval` can read and write.
1123 ///
1124 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1125 /// come from the frame, and a write is applied back to the frame (or to the cell
1126 /// the frame captured) when the eval finishes. That is what makes
1127 /// `f("a = 3")` visible to the caller as `a === 3`.
1128 eval_bindings: Vec<EvalBinding>,
1129 /// The calling frame's `arguments`, while an `eval` runs.
1130 ///
1131 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1132 /// own yet still has to see the caller's `arguments`.
1133 eval_arguments: Option<Value>,
1134 /// The `with` objects live at the moment the running `eval` started, innermost first.
1135 ///
1136 /// `None` outside an eval, which is what keeps a finished block's object from
1137 /// shadowing ordinary bytecode reads.
1138 eval_with: Option<Vec<Gc<JsObject>>>,
1139 /// The bindings the running direct `eval` makes visible, as name → cell.
1140 ///
1141 /// Set for the duration of an eval and then restored, but every closure created
1142 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1143 /// `eval("f = () => i")` work after the eval has returned.
1144 active_eval_scope: Option<Gc<EvalScope>>,
1145 /// The frame that called the direct `eval` currently running, if any.
1146 ///
1147 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1148 /// on the global object, which is what keeps
1149 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1150 /// gives each call its own `x`.
1151 eval_caller: Option<Option<usize>>,
1152 /// The caller's `new.target`, while an `eval` runs.
1153 ///
1154 /// The eval'd code is a script with no constructor of its own, so it inherits the
1155 /// one the enclosing function was called with.
1156 eval_new_target: Option<Value>,
1157 /// `new.target` for the frame about to be pushed.
1158 ///
1159 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1160 /// value reaches the frame without threading a parameter through every call site.
1161 ///
1162 /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1163 /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1164 /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1165 /// value was parked for the outer call and never consumed.
1166 pending_new_target: Option<Value>,
1167 /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1168 ///
1169 /// `undefined` outside a `new` call.
1170 active_new_target: Value,
1171 /// Names of the native functions currently executing, outermost first.
1172 ///
1173 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1174 /// trace still names it with `(native)` instead of a position, so the names are
1175 /// tracked separately and stitched into [`Interp::stack_trace`].
1176 ///
1177 /// The third field is how many bytecode frames were live when the native was entered,
1178 /// which is what places it *among* them rather than before all of them. Native
1179 /// functions used to be emitted up front on the grounds that they never re-enter
1180 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1181 /// The natives currently running, innermost last: the function object and the
1182 /// depth it was entered at.
1183 ///
1184 /// The *name* is deliberately not stored. It used to be, read with
1185 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1186 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1187 /// benchmark. A stack trace is built rarely; it can read the name then.
1188 native_frames: Vec<(Gc<JsObject>, usize)>,
1189 /// The native function currently executing, for the ones that have to know *which*
1190 /// function they are — a typed-array constructor reads its element type off itself.
1191 ///
1192 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1193 /// reports whatever the enclosing bytecode frame was called with.
1194 current_native: Option<Gc<JsObject>>,
1195 /// Text written by `print` and friends, in order.
1196 ///
1197 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1198 /// once at the end, which is also when upstream's line buffering becomes
1199 /// visible for the cases compared here.
1200 pub output: String,
1201 /// Where `print` also writes, as it goes. `output` keeps the full log for
1202 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1203 ///
1204 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1205 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1206 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1207 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1208 /// would show a script's output all at once when it finished.
1209 pub output_sink: Option<Box<dyn std::io::Write>>,
1210 /// Where recent property reads found their value.
1211 ///
1212 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1213 /// table remembering *which object* and *which entry of its property table* answered a
1214 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1215 /// can move; the property can become an accessor), which is what makes a stale entry a
1216 /// miss rather than a wrong answer.
1217 ///
1218 /// The object is held weakly: a cache that held it strongly would keep up to
1219 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1220 /// program cannot see and cannot work around.
1221 pub field_cache: Vec<Option<FieldCache>>,
1222 /// Global lookups, by binding slot. See [`GlobalCache`].
1223 global_cache: Vec<Option<GlobalCache>>,
1224 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1225 /// under its limit. See [`Interp::check_memory`].
1226 pub oom_reported_at: usize,
1227 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1228 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1229 ///
1230 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1231 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1232 /// host that wants to stop a runaway script must not have to wait for it to return.
1233 ///
1234 /// Two things this cannot do, both of them differences a host can observe:
1235 ///
1236 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1237 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1238 /// needs a signal that the `catch` machinery does not see, which is a change to
1239 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1240 /// a host that stops the script itself.
1241 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1242 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1243 /// both, so the difference is when the counter hits zero, not whether it will.
1244 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1245 /// Instructions until the next [`Interp::interrupt`] poll.
1246 pub interrupt_counter: u32,
1247 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1248 ///
1249 /// A separate field from [`Interp::uncatchable`] because the two live for different
1250 /// spans. This one is the host's standing request; it survives the start of an
1251 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1252 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1253 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1254 /// cleared it before the script it was set for had a chance to throw.
1255 pub uncatchable_next: bool,
1256 /// Whether the exception now unwinding may be caught by a `catch`.
1257 ///
1258 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1259 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1260 /// a host stopping a runaway loop is not fought by the loop.
1261 ///
1262 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1263 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1264 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1265 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1266 pub uncatchable: bool,
1267 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1268 ///
1269 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1270 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1271 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1272 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1273 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1274 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1275 ///
1276 /// The numbers come out close for the same reason a C frame and a heap frame of this
1277 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1278 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1279 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1280 /// `crates/quickjs-cli/tests/limits.rs`.
1281 pub stack_limit: usize,
1282 /// The most frames that may be live at once, whatever the byte budget says.
1283 ///
1284 /// A second bound for a reason the reference does not have: our frames cost less than
1285 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1286 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1287 /// `--stack-size 1G` from being a memory bomb.
1288 pub max_frames: usize,
1289 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1290 ///
1291 /// Script execution does not return until this has drained, which is what makes
1292 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1293 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1294 /// not a `for`.
1295 pub(crate) jobs: std::collections::VecDeque<Job>,
1296 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1297 ///
1298 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1299 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1300 pub(crate) tasks: Vec<Task>,
1301 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1302 /// barrier'd evaluation started.
1303 ///
1304 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1305 /// lets a REPL report an error from the line it just evaluated without also reporting
1306 /// its own readline loop.
1307 trace_barriers: Vec<usize>,
1308 /// `os.signal` handlers, keyed by signal number.
1309 ///
1310 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1311 /// a handler cannot be freed while it is still registered.
1312 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1313 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1314 ///
1315 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1316 /// that is only reachable from a host closure could be freed while still registered.
1317 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1318 /// The next timer id.
1319 ///
1320 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1321 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1322 next_timer_id: i32,
1323 /// Errors thrown by timer callbacks, already rendered.
1324 ///
1325 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1326 /// that throws has no promise behind it. Both are reported by the host at the end of
1327 /// the loop, but only one is fixed up by a later `.catch`.
1328 timer_errors: Vec<String>,
1329 /// The module registry, keyed by canonical name.
1330 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1331 /// How the host turns a specifier into bytes.
1332 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1333 /// The module the host was asked to run, for `import.meta.main`.
1334 pub main_module_name: Option<String>,
1335 /// The name to register the *entry* module under, when the host supplies one.
1336 ///
1337 /// The entry's bytes come from a path on disk; this is the name the module graph should
1338 /// know it by. They differ for a host that evaluates a file it did not write — a test
1339 /// runner that prepends a harness, a bundler, a REPL — and getting it wrong is visible:
1340 /// a module importing *itself* resolves the specifier against the real path, finds no
1341 /// record under that name, and loads a second copy with its own bindings.
1342 pub entry_module_name: Option<String>,
1343 /// Module bodies currently running, innermost last.
1344 ///
1345 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1346 /// this is the only place that knows which module that is.
1347 pub module_stack: Vec<String>,
1348 /// Rejections that no handler has claimed, with the promise they belong to.
1349 ///
1350 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1351 /// reason alone cannot say whether somebody eventually listened.
1352 unhandled: Vec<(Gc<JsObject>, Value)>,
1353}
1354
1355impl<'a> Interp<'a> {
1356 /// Build an interpreter over `heap`, with a fresh realm.
1357 pub fn new(heap: &'a Heap) -> Interp<'a> {
1358 let object_proto = JsObject::ordinary(heap, None);
1359 let function_proto = JsObject::function(
1360 heap,
1361 Some(object_proto.clone()),
1362 Callable::Native {
1363 func: |_, _, _| Ok(Value::Undefined),
1364 own_instance: false,
1365 },
1366 );
1367 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1368 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1369 let mut interp = Interp {
1370 heap,
1371 realm: Realm {
1372 global,
1373 object_proto,
1374 function_proto,
1375 array_proto,
1376 array_constructor: None,
1377 promise_constructor: None,
1378 object_proto_to_string: None,
1379 globals: BTreeMap::new(),
1380 declared: Vec::new(),
1381 lexical_consts: BTreeSet::new(),
1382 errors: BTreeMap::new(),
1383 string_proto: None,
1384 number_proto: None,
1385 boolean_proto: None,
1386 bigint_proto: None,
1387 error_proto: JsObject::ordinary(heap, None),
1388 date_proto: JsObject::ordinary(heap, None),
1389 throw_type_error: None,
1390 generator_proto: JsObject::ordinary(heap, None),
1391 promise_proto: None,
1392 async_generator_proto: None,
1393 async_iterator_proto: None,
1394 symbol_proto: None,
1395 symbol_registry: BTreeMap::new(),
1396 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1397 regexp_proto: None,
1398 regexp_ctor: None,
1399 suppressed_error_proto: None,
1400 disposable_stack_proto: None,
1401 map_proto: None,
1402 set_proto: None,
1403 finalization_registries: Vec::new(),
1404 array_buffer_proto: None,
1405 typed_array_proto: None,
1406 typed_array_protos: Vec::new(),
1407 data_view_proto: None,
1408 async_disposable_stack_proto: None,
1409 async_from_sync: None,
1410 iterator_proto: None,
1411 iterator_ctor: None,
1412 iterator_helper_proto: None,
1413 iterator_wrap_proto: None,
1414 generator_function_proto: None,
1415 async_function_proto: None,
1416 async_generator_function_proto: None,
1417 iterator_protos: std::collections::BTreeMap::new(),
1418 well_known_symbols: WellKnownSymbols::default(),
1419 host_classes: HostClasses::new(),
1420 template_map: std::collections::HashMap::new(),
1421 },
1422 frames: Vec::new(),
1423 free_values: Vec::new(),
1424 global_cache: {
1425 let mut cache = Vec::new();
1426 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1427 cache
1428 },
1429 eval_scope: Vec::new(),
1430 eval_depth: 0,
1431 compiling_eval_body: false,
1432 eval_bindings: Vec::new(),
1433 eval_arguments: None,
1434 eval_with: None,
1435 active_eval_scope: None,
1436 eval_caller: None,
1437 pending_new_target: None,
1438 active_new_target: Value::Undefined,
1439 eval_new_target: None,
1440 native_frames: Vec::new(),
1441 current_native: None,
1442 output: String::new(),
1443 output_sink: None,
1444 field_cache: {
1445 let mut cache = Vec::new();
1446 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1447 cache
1448 },
1449 oom_reported_at: 0,
1450 interrupt: None,
1451 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1452 uncatchable_next: false,
1453 uncatchable: false,
1454 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1455 // absent.
1456 stack_limit: DEFAULT_STACK_SIZE,
1457 max_frames: MAX_FRAMES,
1458 jobs: std::collections::VecDeque::new(),
1459 tasks: Vec::new(),
1460 trace_barriers: Vec::new(),
1461 signal_handlers: std::collections::BTreeMap::new(),
1462 fd_handlers: std::collections::BTreeMap::new(),
1463 next_timer_id: 1,
1464 timer_errors: Vec::new(),
1465 modules: std::collections::BTreeMap::new(),
1466 module_loader: None,
1467 main_module_name: None,
1468 entry_module_name: None,
1469 module_stack: Vec::new(),
1470 unhandled: Vec::new(),
1471 };
1472 crate::builtins::install(&mut interp);
1473 interp
1474 }
1475
1476 // -- allocation helpers -------------------------------------------------
1477
1478 /// A new string value.
1479 /// A `BigInt` value from a computed big integer.
1480 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1481 Value::BigInt(Gc::new(self.heap, value))
1482 }
1483
1484 /// A string value from bytes that are already WTF-8, which is how a string with an
1485 /// unpaired surrogate reaches a `Value`.
1486 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1487 Value::string_wtf8(self.heap, text)
1488 }
1489
1490 /// A new string value, from text that is valid UTF-8.
1491 pub fn string(&self, text: impl Into<String>) -> Value {
1492 Value::string(self.heap, text)
1493 }
1494
1495 /// A new ordinary object with the given prototype.
1496 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1497 JsObject::ordinary(self.heap, proto)
1498 }
1499
1500 // -- host classes -------------------------------------------------------
1501
1502 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1503 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1504 self.realm.host_classes.register(def)
1505 }
1506
1507 /// Register `def` under an id the host already holds (`JS_NewClass`).
1508 ///
1509 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1510 /// `JS_NewClass`.
1511 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1512 self.realm.host_classes.define(id, def)
1513 }
1514
1515 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1516 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1517 self.realm.host_classes.set_proto(id, proto);
1518 }
1519
1520 /// The prototype installed for `id`, if any.
1521 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1522 self.realm.host_classes.proto(id)
1523 }
1524
1525 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1526 ///
1527 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1528 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1529 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1530 /// host installed none.
1531 ///
1532 /// Answers `None` for an id that was never registered: the C API would return an
1533 /// exception, and silently making an ordinary object instead would move the failure to
1534 /// the first `JS_GetOpaque` that no longer matches.
1535 pub fn new_host_object(
1536 &mut self,
1537 proto: Option<Gc<JsObject>>,
1538 class_id: ClassId,
1539 ) -> Option<Gc<JsObject>> {
1540 let class = self.realm.host_classes.def(class_id)?;
1541 let proto = proto
1542 .or_else(|| self.realm.host_classes.proto(class_id))
1543 .or_else(|| Some(self.realm.object_proto.clone()));
1544 Some(JsObject::host_object(self.heap, proto, class_id, class))
1545 }
1546
1547 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1548 ///
1549 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1550 /// object, it is an object of another class, or the class never got a payload. A host
1551 /// that has to tell them apart uses [`JsObject::host_class_id`].
1552 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1553 let object = value.as_object()?;
1554 if object.host_class_id()? != class_id {
1555 return None;
1556 }
1557 object.host_opaque()
1558 }
1559
1560 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1561 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1562 match value.as_object() {
1563 Some(object) => object.set_host_opaque(opaque),
1564 None => false,
1565 }
1566 }
1567
1568 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1569 ///
1570 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1571 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1572 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1573 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1574 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1575 /// said `[object Object]` instead of `[object Array Iterator]`.
1576 ///
1577 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1578 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1579 /// its own.
1580 pub fn new_iterator_prototype(
1581 &mut self,
1582 tag: &str,
1583 next: crate::object::NativeFn,
1584 ) -> Gc<JsObject> {
1585 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1586 return existing.clone();
1587 }
1588 let parent = self.realm.iterator_proto.clone();
1589 let proto = self.new_object(parent);
1590 let next = self.new_native("next", 0, next);
1591 proto.define(
1592 "next",
1593 Property::with_attributes(Value::Object(next), true, false),
1594 );
1595 let key = self.realm.well_known_key(WellKnown::Iterator);
1596 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1597 proto.define_key(
1598 &key,
1599 Property::with_attributes(Value::Object(identity), true, false),
1600 );
1601 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1602 let tag_value = self.string(tag);
1603 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1604 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1605 // checks it.
1606 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1607 self.realm
1608 .iterator_protos
1609 .insert(tag.to_string(), proto.clone());
1610 proto
1611 }
1612
1613 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1614 ///
1615 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1616 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1617 /// produced. That is why the two branches are not merged.
1618 pub fn object_own_property_keys(
1619 &mut self,
1620 object: &Gc<JsObject>,
1621 ) -> JsResult<Vec<PropertyKey>> {
1622 if let Some(keys) = self.proxy_own_keys(object)? {
1623 return Ok(keys);
1624 }
1625 // Integer-like keys ascending, then the string keys in insertion order, then the
1626 // symbols — the order every schema that walks an object expects.
1627 let entries = object.property_entries();
1628 let mut numeric: Vec<u32> = Vec::new();
1629 // An integer-indexed exotic object reports its indices as own keys even though they
1630 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1631 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1632 // order). The length is asked per call, so a resizable buffer's view reports the
1633 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1634 if object.typed_array_parts().is_some() {
1635 for index in 0..object.typed_array_length().unwrap_or(0) {
1636 // `u32::try_from` cannot fail for a real length, but the length is a
1637 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1638 // as an array index and one element beyond is not.
1639 match u32::try_from(index) {
1640 Ok(index) => numeric.push(index),
1641 Err(_) => break,
1642 }
1643 }
1644 }
1645 let mut strings: Vec<PropertyKey> = Vec::new();
1646 let mut symbols: Vec<PropertyKey> = Vec::new();
1647 for (key, _) in entries {
1648 match &key {
1649 // A class-private name is never reported by any enumeration: that is the
1650 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1651 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1652 // symbol skip, `Object.assign`) therefore cannot see it.
1653 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1654 PropertyKey::Symbol(_) => symbols.push(key),
1655 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1656 Some(index) => {
1657 if !numeric.contains(&index) {
1658 numeric.push(index);
1659 }
1660 }
1661 None => strings.push(key),
1662 },
1663 }
1664 }
1665 // An array's `length` is an own property from the moment the array exists, so it
1666 // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1667 // as `["length", "a"]`, not `["a", "length"]`
1668 // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1669 // than stored in the property table, which is why it has to be placed here.
1670 if object.is_array() && object.proxy_state().is_none() {
1671 // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1672 // the property table, at whatever position the *define* happened, but the key
1673 // lists it as the array's oldest string property because that is what it is.
1674 if let Some(position) = strings
1675 .iter()
1676 .position(|key| key.as_str() == Some("length"))
1677 {
1678 strings.remove(position);
1679 }
1680 strings.insert(0, PropertyKey::from("length"));
1681 }
1682 numeric.sort_unstable();
1683 let mut keys: Vec<PropertyKey> = numeric
1684 .into_iter()
1685 .map(|index| PropertyKey::from(index.to_string()))
1686 .collect();
1687 keys.extend(strings);
1688 keys.extend(symbols);
1689 Ok(keys)
1690 }
1691
1692 /// The state behind a promise object, or `None` when `object` is not one.
1693 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1694 object.with(|data| match &data.kind {
1695 ObjectKind::Promise(state) => Some(state.clone()),
1696 _ => None,
1697 })
1698 }
1699
1700 /// A new pending promise.
1701 pub fn new_promise(&mut self) -> Gc<JsObject> {
1702 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1703 // the one place every promise is built, and a subclass that builds its instances
1704 // somewhere else would be invisible to `instanceof`.
1705 let default = self.realm.promise_proto.clone();
1706 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1707 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1708 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1709 // `prototype` getter therefore still gets a working promise; the alternative is a
1710 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1711 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1712 Self::make_promise_object(self.heap, proto)
1713 }
1714
1715 /// A promise object with an explicit prototype, and nothing else.
1716 ///
1717 /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1718 /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1719 /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1720 /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1721 pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1722 let promise = JsObject::ordinary(heap, proto);
1723 promise.with_mut(|data| {
1724 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1725 crate::object::PromiseState::default(),
1726 )));
1727 });
1728 promise
1729 }
1730
1731 /// Fulfil `promise`, unless it has already settled.
1732 ///
1733 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1734 /// after `reject`, changes nothing.
1735 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1736 let Some(state) = self.promise_state(promise) else {
1737 return;
1738 };
1739 let reactions = {
1740 let mut state = state.borrow_mut();
1741 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1742 return;
1743 }
1744 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1745 std::mem::take(&mut state.reactions)
1746 };
1747 self.queue_reactions(reactions, value, false);
1748 }
1749
1750 /// Reject `promise`, unless it has already settled.
1751 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1752 let Some(state) = self.promise_state(promise) else {
1753 return;
1754 };
1755 let reactions = {
1756 let mut state = state.borrow_mut();
1757 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1758 return;
1759 }
1760 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1761 std::mem::take(&mut state.reactions)
1762 };
1763 // Remember it only when nothing is listening *now*; a `then` registered later
1764 // prunes the entry in `perform_then`.
1765 if reactions.is_empty() {
1766 self.unhandled.push((promise.clone(), reason.clone()));
1767 }
1768 self.queue_reactions(reactions, reason, true);
1769 }
1770
1771 /// Queue one job per reaction.
1772 ///
1773 /// This is what makes `then` asynchronous even on an already-settled promise:
1774 /// `p.then(f); g()` calls `g` first.
1775 fn queue_reactions(
1776 &mut self,
1777 reactions: Vec<crate::object::PromiseReaction>,
1778 argument: Value,
1779 rejected: bool,
1780 ) {
1781 for reaction in reactions {
1782 let handler = if rejected {
1783 reaction.on_rejected.clone()
1784 } else {
1785 reaction.on_fulfilled.clone()
1786 };
1787 self.jobs.push_back(Job::Reaction {
1788 handler,
1789 argument: argument.clone(),
1790 rejected,
1791 promise: reaction.promise,
1792 });
1793 }
1794 }
1795
1796 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1797 /// resolve/reject pair.
1798 ///
1799 /// The pair are callable objects rather than Rust closures, because the script gets
1800 /// them and may stash them for later.
1801 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1802 let promise = self.new_promise();
1803 // Both handlers are built-ins with an empty name and length 1, in
1804 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1805 // off `Object.getOwnPropertyNames`.
1806 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1807 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1808 (promise, Value::Object(resolve), Value::Object(reject))
1809 }
1810
1811 /// §27.2.1.5 `NewPromiseCapability(C)`.
1812 ///
1813 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1814 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1815 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1816 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1817 /// silently ignored argument.
1818 ///
1819 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1820 /// the engine's own executor is exactly what `new_promise_capability` builds.
1821 pub fn new_promise_capability_for(
1822 &mut self,
1823 constructor: &Value,
1824 ) -> JsResult<(Value, Value, Value)> {
1825 let Some(object) = constructor.as_object().cloned() else {
1826 return Err(self.type_error("promise constructor is not a constructor"));
1827 };
1828 if !object.is_constructor() {
1829 return Err(self.type_error("promise constructor is not a constructor"));
1830 }
1831 if self
1832 .realm
1833 .promise_constructor
1834 .as_ref()
1835 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1836 {
1837 let (promise, resolve, reject) = self.new_promise_capability();
1838 return Ok((Value::Object(promise), resolve, reject));
1839 }
1840 let state = self.new_object(Some(self.realm.object_proto.clone()));
1841 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1842 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1843 // which only a *custom* constructor can observe, and none of the combinator tests
1844 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1845 let executor = self.builtin_function(
1846 "",
1847 2,
1848 Callable::CapabilityExecutor {
1849 state: state.clone(),
1850 },
1851 );
1852 let promise = self.construct(
1853 Value::Object(object.clone()),
1854 Value::Object(object),
1855 vec![Value::Object(executor)],
1856 )?;
1857 // The pair is read *after* the constructor returns, so a constructor that never
1858 // called its executor, or called it with non-callables, is the spec's step 11
1859 // `TypeError` — not something the engine can paper over.
1860 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1861 return Err(self.type_error("promise executor never ran"));
1862 };
1863 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1864 return Err(self.type_error("promise executor never ran"));
1865 };
1866 for handler in [&resolve, &reject] {
1867 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1868 return Err(self.type_error("promise capability handler is not callable"));
1869 }
1870 }
1871 Ok((promise, resolve, reject))
1872 }
1873
1874 /// §27.2.3.1 `PromiseResolve(C, x)`.
1875 ///
1876 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1877 /// an `x` that is already a promise of exactly this constructor is handed back
1878 /// unchanged, and anything else gets a fresh capability from `C`.
1879 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1880 if let Value::Object(object) = &value
1881 && self.promise_state(object).is_some()
1882 {
1883 // `x.constructor === C` means "already the right kind", so no capability is
1884 // built — which is observable through a `resolve` that counts its calls.
1885 let x_constructor = self.get_property(object, "constructor")?;
1886 let same = match (
1887 x_constructor.as_ref().and_then(Value::as_object),
1888 constructor.as_object(),
1889 ) {
1890 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1891 _ => false,
1892 };
1893 if same {
1894 return Ok(value);
1895 }
1896 }
1897 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1898 // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1899 // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1900 // the intrinsic one swallows its own self-resolution error.
1901 self.call_value(resolve, Value::Undefined, vec![value])?;
1902 Ok(promise)
1903 }
1904
1905 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1906 /// promise, as `{ value: completion }`.
1907 ///
1908 /// The three cases are the reference's, and they differ on purpose:
1909 ///
1910 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1911 /// exception before any promise exists;
1912 /// * a **runtime** error rejects the returned promise;
1913 /// * success resolves it with `{ value }`, where the value is the script's completion
1914 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1915 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1916 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1917 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1918 ///
1919 /// # What this does not do
1920 ///
1921 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1922 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1923 /// the parser and the suspension machinery to accept a suspended top-level script, and
1924 /// is not implemented — such source is a syntax error here. Everything else about the
1925 /// flag is reproduced.
1926 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1927 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1928 // too, and the reference truncates that one at the same place as a runtime failure.
1929 if barrier {
1930 let depth = self.frames.len();
1931 self.trace_barriers.push(depth);
1932 }
1933 // Compiled before the promise exists, so a parse failure propagates as a throw
1934 // instead of being folded into a rejection.
1935 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1936 Ok(compiled) => compiled,
1937 Err(error) => {
1938 if barrier {
1939 self.trace_barriers.pop();
1940 }
1941 return Err(error);
1942 }
1943 };
1944 // An async body answers its own promise, and that promise is what the reference
1945 // hands back — the same object, not a wrapper around it. Its resolution value is
1946 // the `{value}` object the compiled epilogue built.
1947 if compiled.kind.is_async() {
1948 let strict = compiled.strict;
1949 let promise = self.run_eval_script(compiled, strict)?;
1950 if barrier {
1951 self.trace_barriers.pop();
1952 }
1953 return Ok(promise);
1954 }
1955 let (promise, resolve, reject) = self.new_promise_capability();
1956 let strict = compiled.strict;
1957 match self.run_eval_script(compiled, strict) {
1958 Ok(value) => {
1959 // `{ value }` is a plain object, so resolving with it adopts nothing even
1960 // when the completion value is itself a promise.
1961 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1962 self.set_property(&wrapped, "value", value)?;
1963 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1964 }
1965 Err(Signal::Throw(error)) => {
1966 self.call_value(reject, Value::Undefined, vec![error])?;
1967 }
1968 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1969 }
1970 if barrier {
1971 self.trace_barriers.pop();
1972 }
1973 Ok(Value::Object(promise))
1974 }
1975
1976 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1977 ///
1978 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1979 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1980 /// timer table, where the collector already scans it.
1981 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1982 let (promise, resolve, _reject) = self.new_promise_capability();
1983 let resolve = self.new_host_function(
1984 "resolve",
1985 1,
1986 Box::new(
1987 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1988 let value = args.first().cloned().unwrap_or(Value::Undefined);
1989 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1990 },
1991 ),
1992 );
1993 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1994 // timer table is part of what the collector walks.
1995 self.schedule_timer(Value::Object(resolve), delay_ms);
1996 Ok(Value::Object(promise))
1997 }
1998
1999 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
2000 /// new promise resolved with it.
2001 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
2002 if let Value::Object(object) = &value
2003 && self.promise_state(object).is_some()
2004 {
2005 return Ok(value);
2006 }
2007 let promise = self.new_promise();
2008 self.resolve_promise_with(&promise, value)?;
2009 Ok(Value::Object(promise))
2010 }
2011
2012 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
2013 ///
2014 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
2015 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
2016 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
2017 /// therefore observable — which is exactly what
2018 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
2019 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
2020 /// shortcut.
2021 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
2022 if let Value::Object(object) = &value
2023 && self.promise_state(object).is_some()
2024 {
2025 let constructor = self.get_property(object, "constructor")?;
2026 let same = match (&constructor, &self.realm.promise_constructor) {
2027 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2028 _ => false,
2029 };
2030 if same {
2031 return Ok(value);
2032 }
2033 }
2034 let promise = self.new_promise();
2035 self.resolve_promise_with(&promise, value)?;
2036 Ok(Value::Object(promise))
2037 }
2038
2039 /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2040 ///
2041 /// The pair of resolving functions a promise hands to its executor shares this record, so
2042 /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2043 /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2044 pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2045 let Some(state) = self.promise_state(promise) else {
2046 return true;
2047 };
2048 let mut state = state.borrow_mut();
2049 if state.resolved {
2050 return false;
2051 }
2052 state.resolved = true;
2053 true
2054 }
2055
2056 /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2057 fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2058 let Some(state) = self.promise_state(promise) else {
2059 return;
2060 };
2061 state.borrow_mut().resolved = false;
2062 }
2063
2064 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2065 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2066 // Resolving a promise with itself is a `TypeError`. The check exists because the
2067 // alternative is a chain of self-reactions that never settles.
2068 if let Value::Object(object) = &value
2069 && object.ptr_eq(promise)
2070 {
2071 // The spec rejects *and* throws, so both the promise and the caller see it.
2072 let thrown = self.type_error("cannot resolve a promise with itself");
2073 let Signal::Throw(error) = thrown.clone() else {
2074 unreachable!("type_error always throws")
2075 };
2076 self.reject_promise(promise, error);
2077 return Err(thrown);
2078 }
2079 // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2080 // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2081 // whoever resolved it — a poisoned `then` getter is the case every
2082 // `*-poisoned-then` test is written against.
2083 let then = match &value {
2084 Value::Object(object) => match self.get_property(object, "then") {
2085 Ok(then) => then,
2086 Err(signal) => {
2087 if let Signal::Throw(reason) = signal {
2088 self.reject_promise(promise, reason);
2089 return Ok(());
2090 }
2091 return Err(signal);
2092 }
2093 },
2094 _ => None,
2095 };
2096 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2097 if !callable_then {
2098 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2099 self.fulfill_promise(promise, value);
2100 return Ok(());
2101 }
2102 // Adopting a thenable is asynchronous — `then` is called from a job, never from
2103 // inside `resolve`, so a script cannot make a promise settle synchronously.
2104 self.jobs.push_back(Job::Thenable {
2105 then: then.expect("checked callable"),
2106 value,
2107 promise: promise.clone(),
2108 });
2109 Ok(())
2110 }
2111
2112 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2113 ///
2114 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2115 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2116 ///
2117 /// The property read is **not** short-circuitable even for a real promise: the spec says
2118 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2119 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2120 /// the combinator's loop infinite — the test's iterator never sets `done`.
2121 pub fn invoke_then(
2122 &mut self,
2123 thenable: Value,
2124 on_fulfilled: Value,
2125 on_rejected: Value,
2126 ) -> JsResult<()> {
2127 let then = match &thenable {
2128 Value::Object(object) => self.get_property(object, "then")?,
2129 primitive => {
2130 let boxed = self.object_from(primitive)?;
2131 self.get_property(&boxed, "then")?
2132 }
2133 };
2134 let Some(then) = then else {
2135 return Err(self.type_error("thenable has no then method"));
2136 };
2137 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2138 return Err(self.type_error("then is not a function"));
2139 }
2140 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2141 Ok(())
2142 }
2143
2144 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2145 ///
2146 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2147 /// promise.
2148 pub fn perform_then(
2149 &mut self,
2150 promise: &Gc<JsObject>,
2151 on_fulfilled: Option<Value>,
2152 on_rejected: Option<Value>,
2153 ) -> JsResult<Value> {
2154 let Some(state) = self.promise_state(promise) else {
2155 return Err(self.type_error("not a promise"));
2156 };
2157 // Whether a rejection handler is being attached decides whether a recorded
2158 // rejection stops being unhandled, so it is read before the values are moved.
2159 let has_rejection_handler = on_rejected.is_some();
2160 let derived = self.new_promise();
2161 let reaction = crate::object::PromiseReaction {
2162 on_fulfilled,
2163 on_rejected,
2164 promise: derived.clone(),
2165 };
2166 let settled = {
2167 let mut state = state.borrow_mut();
2168 // A rejection somebody reacts to is no longer unhandled.
2169 state.handled = true;
2170 match &state.status {
2171 crate::object::PromiseStatus::Pending => {
2172 state.reactions.push(reaction.clone());
2173 None
2174 }
2175 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2176 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2177 }
2178 };
2179 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2180 // later, means somebody is listening after all.
2181 if has_rejection_handler {
2182 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2183 }
2184 if let Some((argument, rejected)) = settled {
2185 let handler = if rejected {
2186 reaction.on_rejected
2187 } else {
2188 reaction.on_fulfilled
2189 };
2190 self.jobs.push_back(Job::Reaction {
2191 handler,
2192 argument,
2193 rejected,
2194 promise: reaction.promise,
2195 });
2196 }
2197 Ok(Value::Object(derived))
2198 }
2199
2200 /// The rejections nobody listened to, formatted the way the reference reports them.
2201 ///
2202 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2203 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2204 /// unhandled at the point the queue drains, because a `then` may still be attached
2205 /// before the host acts on it.
2206 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2207 let entries = std::mem::take(&mut self.unhandled);
2208 // Somebody may have attached a handler after the rejection was recorded, so the
2209 // promise is the authority rather than the list.
2210 let still_unhandled: Vec<Value> = entries
2211 .into_iter()
2212 .filter_map(|(promise, reason)| {
2213 let handled = self
2214 .promise_state(&promise)
2215 .map(|state| state.borrow().handled)
2216 .unwrap_or(true);
2217 (!handled).then_some(reason)
2218 })
2219 .collect();
2220 still_unhandled
2221 .into_iter()
2222 .map(|reason| {
2223 let text = self.describe_exception(&reason);
2224 let stack = match &reason {
2225 Value::Object(object) => self
2226 .get_property(object, "stack")
2227 .ok()
2228 .flatten()
2229 .map(|value| value.to_js_string())
2230 // `stack` carries a trailing newline of its own, which would leave
2231 // a blank line between two reported rejections.
2232 .map(|text| text.trim_end().to_string())
2233 .unwrap_or_default(),
2234 _ => String::new(),
2235 };
2236 if stack.is_empty() {
2237 format!("Possibly unhandled promise rejection: {text}")
2238 } else {
2239 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2240 }
2241 })
2242 .collect()
2243 }
2244
2245 /// Run the microtask queue to exhaustion.
2246 ///
2247 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2248 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2249 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2250 ///
2251 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2252 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2253 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2254 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2255 crate::builtins::json::parse_text(self, text, true)
2256 }
2257
2258 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2259 ///
2260 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2261 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2262 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2263 ///
2264 /// The callback is called with **no arguments**. The reference stores only the function
2265 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2266 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2267 /// extra arguments arrive as `undefined`.
2268 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2269 let id = self.next_timer_id;
2270 // Wrap rather than grow: the id reaches the script as an `Int32`.
2271 self.next_timer_id = if self.next_timer_id == i32::MAX {
2272 1
2273 } else {
2274 self.next_timer_id + 1
2275 };
2276 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2277 self.tasks.push(Task::Timer {
2278 id,
2279 callback,
2280 due_at,
2281 });
2282 id
2283 }
2284
2285 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2286 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2287 pub fn cancel_timer(&mut self, id: i32) -> bool {
2288 let before = self.tasks.len();
2289 self.tasks.retain(|task| match task {
2290 Task::Timer { id: task_id, .. } => *task_id != id,
2291 });
2292 self.tasks.len() != before
2293 }
2294
2295 /// How long until the earliest pending timer, or `None` when none is pending.
2296 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2297 let now = std::time::Instant::now();
2298 self.tasks
2299 .iter()
2300 .map(|task| match task {
2301 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2302 })
2303 .min()
2304 }
2305
2306 /// Run one turn of the event loop.
2307 ///
2308 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2309 /// run at most one due timer, then drain again. The blocking belongs to the caller
2310 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2311 /// is how it asks.
2312 ///
2313 /// One timer per turn rather than all of them: a timer callback may schedule another
2314 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2315 /// starve the microtask queue.
2316 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2317 self.drain_jobs()?;
2318 let now = std::time::Instant::now();
2319 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2320 // followed by `setTimeout(g, 1)` must run `g` first.
2321 let due = self
2322 .tasks
2323 .iter()
2324 .enumerate()
2325 .filter(|(_, task)| match task {
2326 Task::Timer { due_at, .. } => *due_at <= now,
2327 })
2328 .min_by_key(|(_, task)| match task {
2329 Task::Timer { due_at, .. } => *due_at,
2330 })
2331 .map(|(index, _)| index);
2332 let Some(index) = due else {
2333 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2334 // descriptor is registered but no timer is closer, so a script that never
2335 // touches the descriptor still gets control back. Without a cap a handler on a
2336 // descriptor that is never ready would block for as long as the host allows.
2337 let timeout = self
2338 .next_timeout()
2339 .unwrap_or(std::time::Duration::from_secs(10))
2340 .min(std::time::Duration::from_secs(10));
2341 if !self.fd_handlers.is_empty() {
2342 // Blocking on a timer while descriptors are registered would starve them,
2343 // and blocking on the descriptors while a timer is due would delay it; the
2344 // host polls with the earlier of the two deadlines, which this timeout is.
2345 return Ok(Turn::Poll(timeout));
2346 }
2347 return Ok(match self.next_timeout() {
2348 Some(wait) => Turn::Wait(wait),
2349 None => Turn::Done,
2350 });
2351 };
2352 let Task::Timer { callback, .. } = self.tasks.remove(index);
2353 let this = Value::Undefined;
2354 // A throwing timer callback must not stop the loop: the reference reports it and
2355 // keeps going, because the alternative is that one bad timer silently stops every
2356 // later one.
2357 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2358 match self.call_value(callback, this, Vec::new()) {
2359 Ok(_) => {}
2360 Err(Signal::Throw(value)) => {
2361 let text = self.describe_exception(&value);
2362 self.timer_errors.push(text);
2363 }
2364 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2365 }
2366 self.drain_jobs()?;
2367 Ok(Turn::Ran)
2368 }
2369
2370 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2371 ///
2372 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2373 /// left is removed — the reference does the same, so a script can rely on
2374 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2375 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2376 let entry = self.fd_handlers.entry(fd).or_default();
2377 if readable {
2378 entry.read = callback;
2379 } else {
2380 entry.write = callback;
2381 }
2382 if entry.read.is_none() && entry.write.is_none() {
2383 self.fd_handlers.remove(&fd);
2384 }
2385 }
2386
2387 /// Register or clear an `os.signal` handler.
2388 ///
2389 /// `None` removes it; the host separately restores the default disposition or sets
2390 /// ignore, because which of those happened is the script's choice (`null` versus
2391 /// `undefined`) and not something this table can express.
2392 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2393 match handler {
2394 Some(handler) => {
2395 self.signal_handlers.insert(signal, handler);
2396 }
2397 None => {
2398 self.signal_handlers.remove(&signal);
2399 }
2400 }
2401 }
2402
2403 /// Run the handler for `signal`, reporting whether one ran.
2404 ///
2405 /// A throwing handler is reported and the loop continues, like a timer's.
2406 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2407 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2408 return Ok(false);
2409 };
2410 match self.call_value(handler, Value::Undefined, Vec::new()) {
2411 Ok(_) => {}
2412 Err(Signal::Throw(value)) => {
2413 let text = self.describe_exception(&value);
2414 self.timer_errors.push(text);
2415 }
2416 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2417 }
2418 self.drain_jobs()?;
2419 Ok(true)
2420 }
2421
2422 /// The descriptors the host has to poll, and in which direction.
2423 ///
2424 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2425 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2426 /// `os_poll` asks for.
2427 pub fn pending_fds(&self) -> Vec<FdInterest> {
2428 self.fd_handlers
2429 .iter()
2430 .map(|(fd, entry)| FdInterest {
2431 fd: *fd,
2432 read: entry.read.is_some(),
2433 write: entry.write.is_some(),
2434 })
2435 .collect()
2436 }
2437
2438 /// Call the handler registered for `fd`, reporting whether one ran.
2439 ///
2440 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2441 /// poll iteration and then restarts the loop, because the handler may have changed the
2442 /// registration list underneath it; doing the same here keeps a handler that
2443 /// unregisters itself from being called with stale state.
2444 ///
2445 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2446 /// every later one, exactly as with timers.
2447 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2448 let Some(entry) = self.fd_handlers.get(&fd) else {
2449 return Ok(false);
2450 };
2451 let callback = if readable {
2452 entry.read.clone()
2453 } else if writable {
2454 entry.write.clone()
2455 } else {
2456 None
2457 };
2458 let Some(callback) = callback else {
2459 return Ok(false);
2460 };
2461 self.drain_jobs()?;
2462 match self.call_value(callback, Value::Undefined, Vec::new()) {
2463 Ok(_) => {}
2464 Err(Signal::Throw(value)) => {
2465 let text = self.describe_exception(&value);
2466 self.timer_errors.push(text);
2467 }
2468 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2469 }
2470 self.drain_jobs()?;
2471 Ok(true)
2472 }
2473
2474 /// Take the errors timer callbacks threw, leaving the list empty.
2475 pub fn take_timer_errors(&mut self) -> Vec<String> {
2476 std::mem::take(&mut self.timer_errors)
2477 }
2478
2479 /// Whether anything is still pending: a microtask or a timer.
2480 pub fn has_pending_work(&self) -> bool {
2481 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2482 }
2483
2484 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2485 pub fn has_pending_timers_or_jobs(&self) -> bool {
2486 !self.jobs.is_empty() || !self.tasks.is_empty()
2487 }
2488
2489 /// Run every queued microtask, including ones queued while draining.
2490 pub fn drain_jobs(&mut self) -> JsResult<()> {
2491 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2492 // would spin forever, so the drain is bounded the way the call stack is.
2493 let mut budget = 1_000_000usize;
2494 while let Some(job) = self.jobs.pop_front() {
2495 if budget == 0 {
2496 return Err(Signal::Throw(
2497 self.make_error("InternalError", "promise job queue did not drain"),
2498 ));
2499 }
2500 budget -= 1;
2501 self.run_job(job)?;
2502 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2503 // engine may run script that the script itself did not ask for. Doing it here
2504 // rather than from a drop hook is what keeps the callback out of arbitrary
2505 // engine bookkeeping — see `builtins::weak`'s header.
2506 crate::builtins::weak::drain_finalizers(self)?;
2507 }
2508 // A script that queued no jobs may still have dropped targets, so the checkpoint
2509 // runs once more after the queue empties.
2510 crate::builtins::weak::drain_finalizers(self)?;
2511 Ok(())
2512 }
2513
2514 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2515 ///
2516 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2517 /// `None` and is swept out here. This is also where the realm learns that a registry
2518 /// died, which is why it is a mutation rather than a read.
2519 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2520 let handles = std::mem::take(&mut self.realm.finalization_registries);
2521 let mut live = Vec::with_capacity(handles.len());
2522 for handle in handles {
2523 let Some(object) = handle.upgrade() else {
2524 continue;
2525 };
2526 let Some(state) = object.finalization_state() else {
2527 continue;
2528 };
2529 live.push((object.clone(), *state));
2530 self.realm.finalization_registries.push(object.downgrade());
2531 }
2532 live
2533 }
2534
2535 /// Run one microtask.
2536 fn run_job(&mut self, job: Job) -> JsResult<()> {
2537 match job {
2538 Job::Reaction {
2539 handler: None,
2540 argument,
2541 rejected,
2542 promise,
2543 } => {
2544 // No handler: the settlement passes straight through to the derived
2545 // promise, which is why `p.catch(f)` ignores fulfilments.
2546 if rejected {
2547 self.reject_promise(&promise, argument);
2548 } else {
2549 self.fulfill_promise(&promise, argument);
2550 }
2551 Ok(())
2552 }
2553 Job::Reaction {
2554 handler: Some(handler),
2555 argument,
2556 promise,
2557 ..
2558 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2559 Ok(answer) => {
2560 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2561 self.reject_promise(&promise, error);
2562 }
2563 Ok(())
2564 }
2565 Err(Signal::Throw(reason)) => {
2566 self.reject_promise(&promise, reason);
2567 Ok(())
2568 }
2569 Err(other) => Err(other),
2570 },
2571 Job::Thenable {
2572 then,
2573 value,
2574 promise,
2575 } => {
2576 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2577 // the value it produces settles `promise`.
2578 // The thenable's `then` gets this promise's own pair, so whatever it
2579 // produces settles `promise`.
2580 // `length: 1`, `name: ""` — a resolve/reject function is a
2581 // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2582 // with `JsObject::function` left `length` at 0, which a test reads straight
2583 // off the function (`finally/resolved-observable-then-calls-argument`
2584 // requires `resolve.length === 1` for the pair handed to a thenable).
2585 let resolve =
2586 self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2587 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2588 // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2589 // so the one-shot record starts over. Without the reset the pair above was
2590 // already spent by the `resolve` that queued this job, and a thenable that
2591 // calls `reject` left the promise pending forever
2592 // (`Promise/all/reject-immed`).
2593 self.forget_resolution(&promise);
2594 let reject = Value::Object(reject);
2595 match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2596 Ok(_) => Ok(()),
2597 // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2598 // reject function, whose one-shot record makes this a no-op once `then`
2599 // has already resolved the promise
2600 // (`exception-after-resolve-in-thenable-job`).
2601 Err(Signal::Throw(reason)) => {
2602 self.call_value(reject, Value::Undefined, vec![reason])?;
2603 Ok(())
2604 }
2605 Err(other) => Err(other),
2606 }
2607 }
2608 Job::Resume {
2609 coroutine,
2610 promise,
2611 kind,
2612 value,
2613 } => self.drive_async(&coroutine, &promise, kind, value),
2614 Job::GeneratorResume {
2615 generator,
2616 promise,
2617 kind,
2618 value,
2619 } => self.step_async_generator(&generator, &promise, kind, value),
2620 Job::Import {
2621 specifier,
2622 referrer,
2623 promise,
2624 } => {
2625 self.run_dynamic_import(&specifier, &referrer, &promise);
2626 Ok(())
2627 }
2628 }
2629 }
2630
2631 /// One element of a `Promise` combinator settled.
2632 ///
2633 /// The shared state object holds the result array, the number still outstanding, and
2634 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2635 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2636 /// to settle, only whatever `Sub` said a capability is.
2637 ///
2638 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2639 /// and `any` must ignore every later settlement, and `all` must not report a second
2640 /// rejection after the first.
2641 fn settle_combinator(
2642 &mut self,
2643 state: &Gc<JsObject>,
2644 index: usize,
2645 fulfilled: bool,
2646 value: Value,
2647 ) -> JsResult<()> {
2648 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2649 // Each element settles at most once: a thenable may call `onFulfilled` twice
2650 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2651 // call a no-op. Without it the second call decremented `remaining` again and settled
2652 // `all` with a short values array (`call-resolve-element-items`).
2653 let done = field("done");
2654 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2655 let settled = field("settled").is_some_and(|value| value.to_boolean());
2656 if settled {
2657 return Ok(());
2658 }
2659 if let Some(Value::Object(done)) = &done {
2660 if done
2661 .array_get(index)
2662 .is_some_and(|value| value.to_boolean())
2663 {
2664 return Ok(());
2665 }
2666 done.array_set(self.heap, index, Value::Bool(true));
2667 }
2668 let resolve = field("resolve");
2669 let reject = field("reject");
2670 let keys = field("keys");
2671 let results = field("results").and_then(|value| value.as_object().cloned());
2672 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2673 // promise: the handler is a plain function the constructor chose.
2674 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2675 if let Some(handler) = handler {
2676 interp.call_value(handler, Value::Undefined, vec![value])?;
2677 }
2678 Ok(())
2679 };
2680 match kind {
2681 // `race`: the first settlement wins and stops the rest.
2682 3 => {
2683 state.define_data("settled", Value::Bool(true));
2684 let handler = if fulfilled { resolve } else { reject };
2685 settle_with(self, handler, value)?;
2686 return Ok(());
2687 }
2688 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2689 // the first rejection wins outright.
2690 0 | 4 if !fulfilled => {
2691 state.define_data("settled", Value::Bool(true));
2692 settle_with(self, reject, value)?;
2693 return Ok(());
2694 }
2695 // `any`: the first fulfilment wins.
2696 2 if fulfilled => {
2697 state.define_data("settled", Value::Bool(true));
2698 settle_with(self, resolve, value)?;
2699 return Ok(());
2700 }
2701 _ => {}
2702 }
2703 let Some(results) = &results else {
2704 return Ok(());
2705 };
2706 match kind {
2707 4 => {
2708 results.array_set(self.heap, index, value);
2709 }
2710 0 => {
2711 results.array_set(self.heap, index, value);
2712 }
2713 // `allSettled` (and its keyed twin) never rejects; each slot records what
2714 // happened.
2715 1 | 5 => {
2716 let record = self.new_object(Some(self.realm.object_proto.clone()));
2717 if fulfilled {
2718 record.define_data("status", self.string("fulfilled"));
2719 record.define_data("value", value);
2720 } else {
2721 record.define_data("status", self.string("rejected"));
2722 record.define_data("reason", value);
2723 }
2724 results.array_set(self.heap, index, Value::Object(record));
2725 }
2726 // `any`: a rejection is parked in the errors array and the sweep continues.
2727 2 => {
2728 results.array_set(self.heap, index, value);
2729 }
2730 _ => {}
2731 }
2732 let remaining = field("remaining")
2733 .map(|value| value.to_int32())
2734 .unwrap_or(0);
2735 let left = remaining - 1;
2736 state.define_data("remaining", Value::Int(left));
2737 if left != 0 {
2738 return Ok(());
2739 }
2740 state.define_data("settled", Value::Bool(true));
2741 match kind {
2742 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2743 // The keyed result: an ordinary object with a **null** prototype, holding the
2744 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2745 4 | 5 => {
2746 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2747 settle_with(self, resolve, keyed)?;
2748 }
2749 2 => {
2750 // The rejection is an `AggregateError` whose `errors` is the results array
2751 // itself — the slots are the reasons, in input order.
2752 let errors = results.array_elements().unwrap_or_default();
2753 let error = self.aggregate_error(errors, "all promises were rejected");
2754 settle_with(self, reject, error)?;
2755 }
2756 _ => {}
2757 }
2758 Ok(())
2759 }
2760
2761 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2762 ///
2763 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2764 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2765 /// prototype is load-bearing in both directions: a key called `toString` must not
2766 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2767 /// (`resolves-empty-object.js`).
2768 pub(crate) fn keyed_result_object(
2769 &mut self,
2770 keys: Option<&Value>,
2771 values: &Gc<JsObject>,
2772 ) -> JsResult<Value> {
2773 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2774 return Ok(Value::Object(self.new_object(None)));
2775 };
2776 let result = self.new_object(None);
2777 let count = values.array_length().unwrap_or(0);
2778 for index in 0..count {
2779 let Some(key) = keys.array_get(index) else {
2780 continue;
2781 };
2782 let Some(value) = values.array_get(index) else {
2783 continue;
2784 };
2785 let property = Property::with_attributes(value, true, true);
2786 match &key {
2787 Value::Symbol(symbol) => {
2788 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2789 }
2790 other => {
2791 let text = self.to_js_string(other)?;
2792 result.define_key(&PropertyKey::from(text.as_str()), property);
2793 }
2794 }
2795 }
2796 Ok(Value::Object(result))
2797 }
2798
2799 /// Build an async function's result: a promise whose body runs as a coroutine.
2800 pub fn new_async_function(
2801 &mut self,
2802 function: Value,
2803 this: Value,
2804 args: Vec<Value>,
2805 ) -> JsResult<Value> {
2806 let promise = self.new_promise();
2807 let coroutine = self.new_coroutine(function, this, args)?;
2808 if let Err(Signal::Throw(reason)) =
2809 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2810 {
2811 self.reject_promise(&promise, reason);
2812 }
2813 Ok(Value::Object(promise))
2814 }
2815
2816 /// The coroutine an async body runs in.
2817 ///
2818 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2819 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2820 /// than growing a second state machine. The difference is only in the ending — a
2821 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2822 /// Run `code` as an async function body, answering the promise it settles.
2823 ///
2824 /// Used for a module with top-level `await`: its body is an async function whose
2825 /// caller is the host, so there is no function object to pass through
2826 /// [`Interp::new_async_function`].
2827 pub fn run_async_body(
2828 &mut self,
2829 code: Gc<CompiledCode>,
2830 env: Gc<ClosureEnv>,
2831 this: Value,
2832 ) -> JsResult<Value> {
2833 let promise = self.new_promise();
2834 let coroutine = self.new_coroutine_from(code, env, this, Vec::new(), Value::Undefined)?;
2835 if let Err(Signal::Throw(reason)) =
2836 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2837 {
2838 self.reject_promise(&promise, reason);
2839 }
2840 Ok(Value::Object(promise))
2841 }
2842
2843 fn new_coroutine(
2844 &mut self,
2845 function: Value,
2846 this: Value,
2847 args: Vec<Value>,
2848 ) -> JsResult<Gc<JsObject>> {
2849 let Some(object) = function.as_object().cloned() else {
2850 return Err(self.type_error("not a function"));
2851 };
2852 let Some((code, env)) = bytecode_of(&object) else {
2853 return Err(self.type_error("not a function"));
2854 };
2855 self.new_coroutine_from(code, env, this, args, function)
2856 }
2857
2858 /// Build a coroutine over an already-resolved body.
2859 ///
2860 /// `callee` is the function object the body belongs to, or `undefined` when there is
2861 /// none — a module with top-level `await`. It has to be handed over rather than
2862 /// defaulted: the frame's callee is what `special_object 2` answers, and an async
2863 /// function's body uses that to initialise its own-name binding. Passing `undefined`
2864 /// made `var f = async function Binding(){ return typeof Binding }` answer
2865 /// `"undefined"`, so a named async function expression could not see its own name and
2866 /// `Binding = 1` inside it silently succeeded (`named-reassign-fn-name-in-body`).
2867 fn new_coroutine_from(
2868 &mut self,
2869 code: Gc<CompiledCode>,
2870 env: Gc<ClosureEnv>,
2871 this: Value,
2872 args: Vec<Value>,
2873 callee: Value,
2874 ) -> JsResult<Gc<JsObject>> {
2875 self.push_frame(code, env, this, args, callee)?;
2876 let frame = self.frames.pop().expect("push_frame just pushed it");
2877 let state = GeneratorState {
2878 frame: Some(frame),
2879 phase: GeneratorPhase::SuspendedStart,
2880 parked_on_await: false,
2881 parked_on_yield_star: false,
2882 requests: std::collections::VecDeque::new(),
2883 async_busy: false,
2884 // An `async function` body is driven by `drive_async`, never by the generator
2885 // protocol, and the object is not reachable from script.
2886 is_async: false,
2887 };
2888 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2889 coroutine.with_mut(|data| {
2890 data.kind = ObjectKind::Generator(Box::new(state));
2891 });
2892 Ok(coroutine)
2893 }
2894
2895 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2896 /// `await` and `value` is what it awaited.
2897 fn resume_coroutine(
2898 &mut self,
2899 coroutine: &Gc<JsObject>,
2900 kind: ResumeKind,
2901 value: Value,
2902 ) -> JsResult<(Value, bool)> {
2903 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2904 ObjectKind::Generator(state) => {
2905 let is_async = state.is_async;
2906 Some(std::mem::replace(
2907 state.as_mut(),
2908 GeneratorState {
2909 frame: None,
2910 phase: GeneratorPhase::Executing,
2911 parked_on_await: false,
2912 parked_on_yield_star: false,
2913 requests: std::collections::VecDeque::new(),
2914 async_busy: false,
2915 is_async,
2916 },
2917 ))
2918 }
2919 _ => None,
2920 }) else {
2921 return Err(self.type_error("not a coroutine"));
2922 };
2923 let result = self.step_generator(&mut state, kind, value);
2924 coroutine.with_mut(|data| {
2925 data.kind = ObjectKind::Generator(Box::new(state));
2926 });
2927 let (value, done, _ready, _reason) = result?;
2928 Ok((value, done))
2929 }
2930
2931 /// Advance an async body and settle its promise with the outcome.
2932 fn drive_async(
2933 &mut self,
2934 coroutine: &Gc<JsObject>,
2935 promise: &Gc<JsObject>,
2936 kind: ResumeKind,
2937 value: Value,
2938 ) -> JsResult<()> {
2939 match self.resume_coroutine(coroutine, kind, value) {
2940 Ok((value, true)) => {
2941 // `Ok` with `done` means the body finished *normally*, even when it was
2942 // resumed by a `throw` — `try { await p } catch {}` completes by
2943 // returning. Only the `Err` arm below is a rejection.
2944 //
2945 // Resolving rather than fulfilling matters: `return promise` in an async
2946 // body adopts the inner promise, so `async function f(){ return
2947 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2948 // promise.
2949 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2950 self.reject_promise(promise, reason);
2951 }
2952 Ok(())
2953 }
2954 Ok((value, false)) => {
2955 // Parked on `await`: follow what it awaited and resume with the outcome.
2956 let awaited = match self.promise_resolve_value(value) {
2957 Ok(awaited) => awaited,
2958 Err(Signal::Throw(error)) => {
2959 self.reject_promise(promise, error);
2960 return Ok(());
2961 }
2962 Err(other) => return Err(other),
2963 };
2964 self.hook_await(awaited, coroutine, promise)
2965 }
2966 Err(Signal::Throw(reason)) => {
2967 self.reject_promise(promise, reason);
2968 Ok(())
2969 }
2970 Err(other) => Err(other),
2971 }
2972 }
2973
2974 /// Arrange for `coroutine` to resume when `awaited` settles.
2975 fn hook_await(
2976 &mut self,
2977 awaited: Value,
2978 coroutine: &Gc<JsObject>,
2979 promise: &Gc<JsObject>,
2980 ) -> JsResult<()> {
2981 let resumed = JsObject::function(
2982 self.heap,
2983 Some(self.realm.function_proto.clone()),
2984 Callable::AwaitResume {
2985 coroutine: coroutine.clone(),
2986 promise: promise.clone(),
2987 kind: ResumeKind::Next,
2988 },
2989 );
2990 let raised = JsObject::function(
2991 self.heap,
2992 Some(self.realm.function_proto.clone()),
2993 Callable::AwaitResume {
2994 coroutine: coroutine.clone(),
2995 promise: promise.clone(),
2996 kind: ResumeKind::Throw,
2997 },
2998 );
2999 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
3000 // guarantees one; the fallback keeps a mis-shaped value from panicking.
3001 let Value::Object(awaited) = &awaited else {
3002 self.jobs.push_back(Job::Resume {
3003 coroutine: coroutine.clone(),
3004 promise: promise.clone(),
3005 kind: ResumeKind::Next,
3006 value: awaited,
3007 });
3008 return Ok(());
3009 };
3010 self.perform_then(
3011 awaited,
3012 Some(Value::Object(resumed)),
3013 Some(Value::Object(raised)),
3014 )?;
3015 Ok(())
3016 }
3017
3018 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
3019 /// things an engine keeps outside it — array elements and an array's `length`.
3020 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3021 if let Some(property) = object.own_property_key(key) {
3022 return Some(property);
3023 }
3024 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3025 // be synthesized too — and every one of them is a plain writable, enumerable,
3026 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3027 // `undefined` before this, which made `key-is-numericindex` fail on its own
3028 // side effect check.
3029 //
3030 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3031 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3032 // likewise not elements however numeric they look.
3033 if object.typed_array_element_type().is_some()
3034 && let Some(numeric) = canonical_numeric_index(key)
3035 && numeric.is_finite()
3036 && numeric.fract() == 0.0
3037 && !(numeric == 0.0 && numeric.is_sign_negative())
3038 && numeric >= 0.0
3039 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3040 {
3041 let value = object.typed_array_element(numeric as usize)?;
3042 return Some(Property::data(value));
3043 }
3044 // An array's elements live in their own vector rather than the property table, so
3045 // a descriptor for one has to be synthesized — with the attributes an element has.
3046 if let Some(index) = key.as_str().and_then(array_index)
3047 && let Some(value) = object.array_get(index as usize)
3048 && !matches!(value, Value::Hole)
3049 {
3050 return Some(Property::data(value));
3051 }
3052 // `length` is an own property of an array that is not in its property table
3053 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3054 // and non-enumerable.
3055 if key.as_str() == Some("length")
3056 && let Some(length) = object.array_length()
3057 {
3058 return Some(Property {
3059 value: Some(crate::object::length_value(length)),
3060 writable: object.length_writable(),
3061 enumerable: false,
3062 configurable: false,
3063 getter: None,
3064 setter: None,
3065 descriptor_fields: None,
3066 });
3067 }
3068 None
3069 }
3070
3071 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3072 pub fn object_get_own_property(
3073 &mut self,
3074 object: &Gc<JsObject>,
3075 key: &PropertyKey,
3076 ) -> JsResult<Option<Property>> {
3077 if let Some(answer) = self.proxy_get_own_property(object, key)? {
3078 return Ok(answer);
3079 }
3080 if let Some(exotic) = object.exotic()
3081 && let Some(answer) = exotic.get_own_property(self, object, key)?
3082 {
3083 return Ok(answer);
3084 }
3085 // A module namespace's bindings are accessors internally and data properties to
3086 // script; see `namespace_own_property`.
3087 if object.module_namespace_marker() {
3088 return self.namespace_own_property(object, key);
3089 }
3090 // A mapped `arguments` index is a data property as far as script can see: the
3091 // accessor pair that aliases the parameter is plumbing, and exposing it would
3092 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3093 // report a `get` where the spec has a `[[Value]]`.
3094 if let Some(index) = key.as_str().and_then(crate::object::array_index)
3095 && let Some(cell) = object.mapped_argument_cell(index as usize)
3096 {
3097 // Non-configurable is *not* the default: an ordinary mapped index is
3098 // configurable, and only becomes non-configurable once something
3099 // redefines it. Preserve whatever the property table currently says.
3100 // The attributes come from whatever the property table holds, because they
3101 // can be changed independently of the mapping; only the *value* and the
3102 // data-property *kind* are the accessor's secret.
3103 let flags = Self::ordinary_own_property(object, key);
3104 if let Some(existing) = &flags
3105 && !existing.is_accessor()
3106 {
3107 // Already demapped: the table entry is the answer, not the cell.
3108 return Ok(flags);
3109 }
3110 return Ok(Some(Property {
3111 value: Some(cell.get()),
3112 writable: true,
3113 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3114 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3115 ..Property::default()
3116 }));
3117 }
3118 Ok(Self::ordinary_own_property(object, key))
3119 }
3120
3121 /// Whether `object` is a module namespace exotic object (§10.4.6).
3122 ///
3123 /// Recognised by shape rather than by a flag: a namespace is the only object whose
3124 /// properties are all accessors over a `ModuleBinding` cell. That is the same
3125 /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3126 /// distinction in one place instead of adding a boolean every constructor has to
3127 /// remember to set.
3128 pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3129 object.module_namespace_marker()
3130 }
3131
3132 /// `[[GetOwnProperty]]` for a module namespace exotic object.
3133 ///
3134 /// The bindings are stored as getters — that is the only way a live binding can be read
3135 /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3136 /// descriptor:
3137 ///
3138 /// ```text
3139 /// { [[Value]]: current value, [[Writable]]: true,
3140 /// [[Enumerable]]: true, [[Configurable]]: false }
3141 /// ```
3142 ///
3143 /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3144 /// `undefined`. Reporting the accessor instead — which is what the property table holds
3145 /// — made every one of test262's namespace descriptor assertions fail, in both the
3146 /// `await-ns-*` and `promise-then-ns-*` families.
3147 ///
3148 /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3149 /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3150 /// property`); the ordinary descriptor machinery derives that from these attributes.
3151 pub fn namespace_own_property(
3152 &mut self,
3153 object: &Gc<JsObject>,
3154 key: &PropertyKey,
3155 ) -> JsResult<Option<Property>> {
3156 let Some(stored) = Self::ordinary_own_property(object, key) else {
3157 return Ok(None);
3158 };
3159 let Some(Property {
3160 getter: Some(getter),
3161 ..
3162 }) = Some(&stored)
3163 else {
3164 return Ok(Some(stored));
3165 };
3166 // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3167 // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3168 // rather than stored.
3169 let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3170 Ok(Some(Property {
3171 value: Some(value),
3172 writable: true,
3173 enumerable: true,
3174 configurable: false,
3175 ..Property::default()
3176 }))
3177 }
3178
3179 /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3180 ///
3181 /// Modelled as "does this descriptor describe the property that is already there?",
3182 /// because a namespace property's attributes are fixed and its value cannot be changed
3183 /// through the namespace. The three ways to succeed:
3184 ///
3185 /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3186 /// * one whose `[[Value]]` is `SameValue` the current binding value;
3187 /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3188 /// configurable: false}`.
3189 ///
3190 /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3191 /// false), so it goes through the same check against its stored value — which is what
3192 /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3193 /// answer `true` while `{value: "Other"}` answers `false`.
3194 fn namespace_define_own_property(
3195 &mut self,
3196 object: &Gc<JsObject>,
3197 key: &PropertyKey,
3198 property: &Property,
3199 ) -> JsResult<bool> {
3200 let Some(current) = self.namespace_own_property(object, key)? else {
3201 // A name the namespace does not export cannot be added to it.
3202 return Ok(false);
3203 };
3204 if let Some(value) = &property.value {
3205 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3206 if !self.same_value(value, current_value)? {
3207 return Ok(false);
3208 }
3209 }
3210 Ok(true)
3211 }
3212
3213 /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3214 ///
3215 /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3216 /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3217 /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3218 /// descriptor with no fields at all therefore succeeds, which is what
3219 /// `Reflect.defineProperty(ns, k, {})` checks.
3220 ///
3221 /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3222 /// stored property, and a namespace stores its bindings as accessors, so every
3223 /// definition looked like "accessor → data kind changed" or carried `writable: false`
3224 /// from the accessor's own entry. Presence is only available here, before the merge.
3225 pub fn namespace_define_from_descriptor(
3226 &mut self,
3227 object: &Gc<JsObject>,
3228 key: &PropertyKey,
3229 descriptor: &Gc<JsObject>,
3230 ) -> JsResult<bool> {
3231 let Some(current) = self.namespace_own_property(object, key)? else {
3232 return Ok(false);
3233 };
3234 // An accessor descriptor can never describe a namespace binding.
3235 if self.get_property(descriptor, "get")?.is_some()
3236 || self.get_property(descriptor, "set")?.is_some()
3237 {
3238 return Ok(false);
3239 }
3240 if let Some(value) = self.get_property(descriptor, "value")? {
3241 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3242 if !self.same_value(&value, current_value)? {
3243 return Ok(false);
3244 }
3245 }
3246 // The three attribute fields, when named, must restate what the property already
3247 // has. Not a fixed shape: an exported binding reports
3248 // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3249 // is a real own data property with `{false, false, false}`, and both are namespace
3250 // properties. Comparing against `current` is what makes one rule cover both.
3251 for (name, have) in [
3252 ("writable", current.writable),
3253 ("enumerable", current.enumerable),
3254 ("configurable", current.configurable),
3255 ] {
3256 if let Some(named) = self.get_property(descriptor, name)?
3257 && named.to_boolean() != have
3258 {
3259 return Ok(false);
3260 }
3261 }
3262 Ok(true)
3263 }
3264
3265 /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3266 /// compare a requested value against a live binding.
3267 pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3268 Ok(a.same_value(b))
3269 }
3270
3271 ///
3272 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3273 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3274 /// abstract operation here rather than a private helper in `error.rs`.
3275 ///
3276 /// The name is the whole point: the setter must behave as if the prototype were not
3277 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3278 /// the accessor for every error object in the realm. Everything below follows from that:
3279 ///
3280 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3281 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3282 /// accessor's own home an error rather than a self-shadow.
3283 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3284 /// either has a string or has made a mistake.
3285 /// 4. An existing *own* property decides the path — an own setter is called, an own
3286 /// non-writable data property is a `TypeError` — and only a missing own property
3287 /// falls through to defining one.
3288 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3289 /// traps and a non-extensible receiver is a `TypeError`.
3290 ///
3291 /// The installed shape is writable + configurable, not enumerable.
3292 pub fn setter_that_ignores_prototype_properties(
3293 &mut self,
3294 this_value: Value,
3295 home: &Gc<JsObject>,
3296 property_key: &str,
3297 args: &[Value],
3298 ) -> JsResult<Value> {
3299 self.setter_that_ignores_prototype_properties_key(
3300 this_value,
3301 home,
3302 &PropertyKey::from(property_key),
3303 args,
3304 )
3305 }
3306
3307 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3308 ///
3309 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3310 pub fn setter_that_ignores_prototype_properties_key(
3311 &mut self,
3312 this_value: Value,
3313 home: &Gc<JsObject>,
3314 key: &PropertyKey,
3315 args: &[Value],
3316 ) -> JsResult<Value> {
3317 let Some(receiver) = this_value.as_object().cloned() else {
3318 return Err(self.type_error("setter called on a non-object"));
3319 };
3320 if Gc::ptr_eq(&receiver, home) {
3321 return Err(self.type_error("cannot assign to the accessor's own home object"));
3322 }
3323 // No type check here: §7.3.40 takes an arbitrary `v`, and
3324 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3325 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3326 // before calling this.
3327 let value = args.first().cloned().unwrap_or(Value::Undefined);
3328 // Step 4: an own property on the receiver changes what happens, and there are three
3329 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3330 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3331 // `Set` with `throw = true`, and a test exists for each.
3332 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3333 if existing.is_accessor() && existing.setter.is_none() {
3334 // A getter-only own accessor cannot be written through.
3335 return Err(self.type_error("no setter for the own property"));
3336 }
3337 // Everything else — an own data property, or an own accessor *with* a setter —
3338 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3339 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3340 // an own user setter receives the value (`setter-own-accessor`), because
3341 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3342 // setter directly is the difference between one code path and two that can
3343 // disagree.
3344 self.set_property_with_key(
3345 &receiver,
3346 key,
3347 value.clone(),
3348 crate::interp::DeleteFailure::Throw,
3349 )?;
3350 return Ok(Value::Undefined);
3351 }
3352 let property = Property {
3353 value: Some(value.clone()),
3354 writable: true,
3355 // Enumerable, despite the accessor it shadows not being. The reference installs
3356 // it that way and six cases check it (`setter-creates-own-property` and friends).
3357 enumerable: true,
3358 configurable: true,
3359 ..Property::default()
3360 };
3361 if !self.object_define_own_property(&receiver, key, property)? {
3362 return Err(self.type_error("the receiver refused the definition"));
3363 }
3364 Ok(Value::Undefined)
3365 }
3366
3367 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3368 ///
3369 /// The indices of a typed array are not properties at all — they are bytes in the
3370 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3371 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3372 /// enumerable and configurable, so a definition can only ever change the *value*, and
3373 /// every other descriptor is refused rather than applied.
3374 ///
3375 /// The order of the checks is the spec's, and two of them are load-bearing:
3376 ///
3377 /// * the index is validated **before** the value is converted, because the conversion
3378 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3379 /// detaches from a `valueOf` and still expects `true` with no store, which only
3380 /// happens when the index was valid on the way in;
3381 /// * the store is attempted even when the index has gone out of bounds by the time the
3382 /// conversion finishes, because the store is a silent no-op rather than a failure —
3383 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3384 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3385 ///
3386 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3387 /// the existing element, which is harmless here: every valid index is already
3388 /// writable, enumerable and configurable, so a `false` in the merged property can only
3389 /// have come from the descriptor having named `false`.
3390 fn integer_indexed_define_own_property(
3391 &mut self,
3392 object: &Gc<JsObject>,
3393 numeric: f64,
3394 property: &Property,
3395 ) -> JsResult<bool> {
3396 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3397 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3398 if !typed_array_index_is_valid(object, numeric) {
3399 return Ok(false);
3400 }
3401 // Step 6: the indices are data properties, so an accessor descriptor is refused
3402 // rather than converted. `Object.defineProperty` turns the `false` into a
3403 // `TypeError`; `Reflect.defineProperty` reports it.
3404 if property.is_accessor() {
3405 return Ok(false);
3406 }
3407 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3408 // definition that asks for anything else cannot be honoured.
3409 if !property.writable || !property.enumerable || !property.configurable {
3410 return Ok(false);
3411 }
3412 // Step 10: only a descriptor that names a value stores anything.
3413 let Some(value) = property.value.clone() else {
3414 return Ok(true);
3415 };
3416 let Some(element) = object.typed_array_element_type() else {
3417 return Ok(false);
3418 };
3419 let stored = self.element_value(element, value)?;
3420 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3421 return Err(self.type_error(reason));
3422 }
3423 Ok(true)
3424 }
3425
3426 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3427 pub fn object_define_own_property(
3428 &mut self,
3429 object: &Gc<JsObject>,
3430 key: &PropertyKey,
3431 property: Property,
3432 ) -> JsResult<bool> {
3433 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3434 return Ok(accepted);
3435 }
3436 // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3437 //
3438 // The only definitions that can succeed are ones describing the property the
3439 // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3440 // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3441 // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3442 // `writable: false`, `configurable: true`, or any name the namespace does not
3443 // export is `false`.
3444 //
3445 // The ordinary path gets the no-change case right by accident — it compares against
3446 // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3447 // is an accessor internally while the definition script writes is a data descriptor.
3448 // Answering here is what makes that attribute-only definition a no-op rather than a
3449 // refusal (`namespace/await-ns-define-own-property`).
3450 if object.module_namespace_marker() {
3451 return self.namespace_define_own_property(object, key, &property);
3452 }
3453 // A proxy always answers above — with `Some` from its trap, or with `None` when
3454 // the trap is absent, and then the definition belongs to the **target**
3455 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3456 // when there is no trap). Falling through to the ordinary path here defined the
3457 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3458 // property the target never saw.
3459 if object.proxy_state().is_some() {
3460 let Some((target, _handler)) = self.proxy_parts(object)? else {
3461 return Err(self.type_error("cannot use a proxy that has been revoked"));
3462 };
3463 return self.object_define_own_property(&target, key, property);
3464 }
3465 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3466 // they accept exactly one descriptor shape. This has to happen before the
3467 // ordinary path, which would happily store a data property next to the buffer —
3468 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3469 // and `TypedArray/prototype/set` are about this section.
3470 if object.typed_array_element_type().is_some()
3471 && let Some(index) = canonical_numeric_index(key)
3472 {
3473 return self.integer_indexed_define_own_property(object, index, &property);
3474 }
3475 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3476 // non-extensible object. The check lives here rather than in the callers because
3477 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3478 // `Array.prototype.filter` uses to store its result, and a species object made
3479 // non-extensible by its own constructor must make that a `TypeError`
3480 // (`target-array-non-extensible`).
3481 // Note the `is_none()`: an already-present property may still be **redefined** on a
3482 // non-extensible object, and only *adding* one is refused (as Distinct from
3483 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3484 // properties — testing extensibility before looking for the property made every
3485 // `Object.freeze` of an ordinary object refuse its own second step).
3486 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3487 return Ok(false);
3488 }
3489 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3490 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3491 // an omitted field is left alone). Merging here rather than at each call site is
3492 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3493 // the value and `enumerable` in place.
3494 //
3495 // The merge is a no-op when the property is absent: there is nothing to keep.
3496 let was_partial = property.descriptor_fields.is_some();
3497 let property = match property.descriptor_fields {
3498 None => property,
3499 Some(fields) => {
3500 let base = self.object_get_own_property(object, key)?;
3501 let mut merged = base.clone().unwrap_or_default();
3502 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3503 // descriptor names, and switching kind discards the other half —
3504 // `{set: f}` on a data property is an accessor with no getter, not a data
3505 // property whose `get` happens to be absent.
3506 let wants_accessor = fields.get || fields.set;
3507 let wants_data = fields.value || fields.writable;
3508 if wants_accessor {
3509 merged.value = None;
3510 merged.writable = false;
3511 merged.getter = property.getter.clone();
3512 merged.setter = property.setter.clone();
3513 } else if wants_data {
3514 merged.getter = None;
3515 merged.setter = None;
3516 if fields.value {
3517 merged.value = property.value.clone();
3518 }
3519 if fields.writable {
3520 merged.writable = property.writable;
3521 }
3522 }
3523 if fields.enumerable {
3524 merged.enumerable = property.enumerable;
3525 }
3526 if fields.configurable {
3527 merged.configurable = property.configurable;
3528 }
3529 merged.descriptor_fields = None;
3530 merged
3531 }
3532 };
3533 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3534 // descriptor. `define_property_on` runs the same check before it calls here, so an
3535 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3536 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3537 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3538 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3539 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3540 // own define would have refused.
3541 //
3542 // Only partial descriptors are validated here. A whole `Property` passed by an
3543 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3544 // what the descriptor "named", and those callers rely on the write landing.
3545 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3546 // Every branch below is gated on `!existing.configurable`: a *configurable*
3547 // property may be reshaped however the descriptor likes, which is why an
3548 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3549 // must succeed. Testing only `writable` refused that and broke
3550 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3551 let same_kind = existing.is_accessor() == property.is_accessor();
3552 if !same_kind {
3553 // Step 4: a non-configurable property may not change kind.
3554 if !existing.configurable {
3555 return Ok(false);
3556 }
3557 } else if existing.is_accessor() {
3558 // Step 6: an accessor's halves are its value.
3559 if !existing.configurable
3560 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3561 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3562 {
3563 return Ok(false);
3564 }
3565 } else if !existing.configurable && !existing.writable {
3566 // Step 7: a non-configurable *and* non-writable data property's value is
3567 // fixed, and it may not become writable again.
3568 if property.writable {
3569 return Ok(false);
3570 }
3571 let current = existing.value.clone().unwrap_or(Value::Undefined);
3572 let requested = property.value.clone().unwrap_or(Value::Undefined);
3573 if !current.same_value(&requested) {
3574 return Ok(false);
3575 }
3576 }
3577 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3578 // is frozen with it.
3579 if !existing.configurable
3580 && (property.configurable || property.enumerable != existing.enumerable)
3581 {
3582 return Ok(false);
3583 }
3584 }
3585 // A host class that intercepts definitions owns the attributes of the properties it
3586 // defines: `_class`-style storage on the native side is the usual reason.
3587 if let Some(exotic) = object.exotic()
3588 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3589 {
3590 return Ok(accepted);
3591 }
3592 // An array index is stored in the element vector, which can hold a plain value and
3593 // nothing else. An accessor — or a data property with non-default attributes —
3594 // therefore has to live in the property table, and the element slot is blanked so
3595 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3596 // {get})` stored the accessor where no read ever looked, and the array kept
3597 // answering its old value.
3598 // An array's `length` is not stored in the property table, so defining it has to
3599 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3600 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3601 // {value: 1})` reported success and changed nothing.
3602 if key.as_str() == Some("length") && object.is_array() {
3603 // `{writable: false}` on `length` does not change the length, but it does make
3604 // it read-only — after which neither a later `{writable: true}` nor a store
3605 // past the end may succeed.
3606 if property.value.is_none() {
3607 if !object.length_writable() && property.writable {
3608 return Ok(false);
3609 }
3610 object.set_length_writable(property.writable);
3611 return Ok(true);
3612 }
3613 if !object.length_writable() {
3614 return Ok(false);
3615 }
3616 }
3617 if key.as_str() == Some("length")
3618 && object.is_array()
3619 && let Some(value) = property.value.clone()
3620 {
3621 let requested = value.to_number();
3622 let valid = requested.is_finite()
3623 && requested >= 0.0
3624 && requested.fract() == 0.0
3625 && requested <= u32::MAX as f64;
3626 if !valid {
3627 return Err(self.range_error("invalid array length"));
3628 }
3629 // Truncating deletes the elements above the new length, and a non-configurable
3630 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3631 // makes `a.length = 2` fail rather than quietly drop it.
3632 let current = object.array_length().unwrap_or(0);
3633 let requested = requested as usize;
3634 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3635 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3636 // `[[Writable]]: false` when the descriptor asked for it — the length is
3637 // left at its old value but locked. Returning `false` alone left it
3638 // writable, which `verifyProperty` catches
3639 // (`defineProperties/15.2.3.7-6-a-164`).
3640 if property
3641 .descriptor_fields
3642 .is_some_and(|fields| fields.writable)
3643 && !property.writable
3644 && object.length_writable()
3645 {
3646 object.set_length_writable(false);
3647 }
3648 return Ok(false);
3649 }
3650 object.array_set_length(self.heap, requested);
3651 return Ok(true);
3652 }
3653 let plain = property.writable
3654 && property.enumerable
3655 && property.configurable
3656 && !property.is_accessor();
3657 if let Some(index) = key.as_str().and_then(array_index)
3658 && object.is_array()
3659 {
3660 // Growing the array needs a writable `length`: after
3661 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3662 // be added.
3663 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3664 return Ok(false);
3665 }
3666 if plain && property.value.is_some() {
3667 // An ordinary element: the vector is where a read looks first, so it has
3668 // to be the vector that changes — unless the index is too far out to be
3669 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3670 // one property, because past its own limit it stores the index as an
3671 // ordinary key. Falling through to `define_key` below is the same choice,
3672 // and the alternative was worse: the store used to be *dropped* and the
3673 // length left at 0, which is a silent wrong answer.
3674 let value = property.value.clone().unwrap_or(Value::Undefined);
3675 object.delete_key(key);
3676 if object.array_set(self.heap, index as usize, value) {
3677 return Ok(true);
3678 }
3679 // Past the dense limit the element lives in the table like any property.
3680 object.note_element_descriptor();
3681 object.define_key(key, property);
3682 // A sparse store past the dense limit still extends `length`, which is what
3683 // `a[a.length] = v` relies on — but only extends: shortening would delete
3684 // the sparse properties above the index, including this one.
3685 if index as usize + 1 > object.array_length().unwrap_or(0) {
3686 object.array_set_length(self.heap, index as usize + 1);
3687 }
3688 return Ok(true);
3689 }
3690 // A non-plain element — an accessor, or an attribute that is not the default —
3691 // lives in the table while the slot becomes a hole. Recording it keeps every
3692 // later `a[i] = v` off the dense path, where the write would have shadowed the
3693 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3694 // replace the accessor with a plain data property.
3695 object.note_element_descriptor();
3696 object.define_key(key, property);
3697 // The slot stays, so `length` does not shrink; a hole is not an element, so
3698 // the table entry is now what a read finds.
3699 object.array_set(self.heap, index as usize, Value::Hole);
3700 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3701 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3702 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3703 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3704 if index as usize + 1 > object.array_length().unwrap_or(0) {
3705 object.array_set_length(self.heap, index as usize + 1);
3706 }
3707 return Ok(true);
3708 }
3709 object.define_key(key, property);
3710 Ok(true)
3711 }
3712
3713 /// Build a proxy object over `target`, with its traps read from `handler`.
3714 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3715 JsObject::proxy(self.heap, target, handler)
3716 }
3717
3718 /// The `revoke` function for a proxy's slots.
3719 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3720 let revoke = JsObject::function(
3721 self.heap,
3722 Some(self.realm.function_proto.clone()),
3723 Callable::Revoker(slots),
3724 );
3725 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3726 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3727 // inherited from `Function.prototype` reads the same but fails the three cases that
3728 // check the own-property list (`revocation-function-{length,name,property-order}`).
3729 revoke.define("length", Property::name_or_length(Value::Int(0)));
3730 revoke.define("name", Property::name_or_length(self.string("")));
3731 revoke
3732 }
3733
3734 /// A new array.
3735 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3736 let array = JsObject::array(
3737 self.heap,
3738 Some(self.realm.array_proto.clone()),
3739 elements.len(),
3740 );
3741 for (index, element) in elements.into_iter().enumerate() {
3742 array.array_set(self.heap, index, element);
3743 }
3744 array
3745 }
3746
3747 /// A new native function object.
3748 ///
3749 /// The observable `name` and `length` are installed as properties here, which is
3750 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3751 /// so `f.name = "x"` behaves like the writable property it is.
3752 /// A native constructor that builds its own instance after validating its arguments.
3753 ///
3754 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3755 /// check runs before `new.target.prototype` is read.
3756 pub fn new_native_ctor(
3757 &self,
3758 name: impl Into<String>,
3759 length: u32,
3760 func: NativeFn,
3761 ) -> Gc<JsObject> {
3762 let function = JsObject::function(
3763 self.heap,
3764 Some(self.realm.function_proto.clone()),
3765 Callable::Native {
3766 func,
3767 own_instance: true,
3768 },
3769 );
3770 function.set_constructible(true);
3771 function.define(
3772 "length",
3773 Property::name_or_length(Value::Int(length as i32)),
3774 );
3775 function.define("name", Property::name_or_length(self.string(name)));
3776 function
3777 }
3778
3779 /// A native constructor that lets `new` build the instance first.
3780 ///
3781 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3782 /// validation that must precede reading `new.target.prototype`, so the object can be
3783 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3784 /// which makes a *method* and therefore not a constructor at all.
3785 pub fn new_native_constructor(
3786 &self,
3787 name: impl Into<String>,
3788 length: u32,
3789 func: NativeFn,
3790 ) -> Gc<JsObject> {
3791 let function = self.new_native(name, length, func);
3792 function.set_constructible(true);
3793 function
3794 }
3795
3796 /// A new host function object: a native closure that carries its own state.
3797 ///
3798 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3799 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3800 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3801 /// this safe: the closure must not capture a `Gc`.
3802 pub fn new_host_function(
3803 &self,
3804 name: impl Into<String>,
3805 length: u32,
3806 func: crate::object::HostFn,
3807 ) -> Gc<JsObject> {
3808 self.new_host_inner(name.into(), length, func, false)
3809 }
3810
3811 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3812 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3813 pub fn new_host_ctor(
3814 &self,
3815 name: impl Into<String>,
3816 length: u32,
3817 func: crate::object::HostFn,
3818 ) -> Gc<JsObject> {
3819 let function = self.new_host_inner(name.into(), length, func, true);
3820 function.set_constructible(true);
3821 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3822 // installs its own methods on it, so it starts as a plain object.
3823 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3824 function.define(
3825 "prototype",
3826 Property {
3827 value: Some(Value::Object(proto)),
3828 writable: true,
3829 enumerable: false,
3830 configurable: false,
3831 ..Property::default()
3832 },
3833 );
3834 function
3835 }
3836
3837 fn new_host_inner(
3838 &self,
3839 name: String,
3840 length: u32,
3841 func: crate::object::HostFn,
3842 own_instance: bool,
3843 ) -> Gc<JsObject> {
3844 let function = JsObject::function(
3845 self.heap,
3846 Some(self.realm.function_proto.clone()),
3847 Callable::Host {
3848 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3849 own_instance,
3850 },
3851 );
3852 function.define(
3853 "length",
3854 Property::name_or_length(Value::Int(length as i32)),
3855 );
3856 function.define("name", Property::name_or_length(self.string(name)));
3857 function
3858 }
3859
3860 /// A callable object with the `length`/`name` a built-in function has, in that order.
3861 ///
3862 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3863 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3864 /// [`JsObject::function`] defines neither, which is why every capability helper built
3865 /// with it reported no own `length` and no own `name` at all.
3866 ///
3867 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3868 /// configurable.
3869 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3870 let function =
3871 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3872 function.define(
3873 "length",
3874 Property::name_or_length(Value::Int(length as i32)),
3875 );
3876 function.define("name", Property::name_or_length(self.string(name)));
3877 function
3878 }
3879
3880 /// A new native function object.
3881 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3882 let function = JsObject::function(
3883 self.heap,
3884 Some(self.realm.function_proto.clone()),
3885 Callable::Native {
3886 func,
3887 own_instance: false,
3888 },
3889 );
3890 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3891 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3892 // `length,name` and this listed `name,length`. A bytecode function already gets it
3893 // the right way round; only native ones were built backwards.
3894 function.define(
3895 "length",
3896 Property::name_or_length(Value::Int(length as i32)),
3897 );
3898 function.define("name", Property::name_or_length(self.string(name)));
3899 function
3900 }
3901
3902 /// A new bound function.
3903 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3904 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3905 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3906 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3907 let constructible = target
3908 .as_object()
3909 .is_some_and(|target| target.is_constructor());
3910 let bound = JsObject::function(
3911 self.heap,
3912 Some(self.realm.function_proto.clone()),
3913 Callable::Bound { target, this, args },
3914 );
3915 bound.set_constructible(constructible);
3916 bound
3917 }
3918
3919 /// A new reference cell.
3920 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3921 Gc::new(self.heap, Cell::new(value))
3922 }
3923
3924 // -- running ------------------------------------------------------------
3925
3926 /// Evaluate `code` as a script body and return its completion value.
3927 /// Compile and run `source` for the engine's own use, returning its completion value.
3928 ///
3929 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3930 /// needs to be a real async function, and the engine already runs those as coroutines,
3931 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3932 ///
3933 /// Differences from [`Self::eval_in_global`], both deliberate:
3934 ///
3935 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3936 /// being built, and the source is an IIFE that only constructs a closure, so there
3937 /// is nothing to drain — and draining here would run script-queued jobs in the
3938 /// middle of `install`.
3939 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3940 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3941 /// and it should not look like the user wrote something wrong.
3942 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3943 let program = match js_parse::parse_script(source) {
3944 Ok(program) => program,
3945 Err(error) => {
3946 let message = format!("builtin source does not parse: {error}");
3947 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3948 }
3949 };
3950 let mut code = match js_compile::compile_script_with_source(&program, source) {
3951 Ok(code) => code,
3952 Err(error) => {
3953 let message = format!("builtin source does not compile: {}", error.message);
3954 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3955 }
3956 };
3957 // The frame has to name something, and `<builtin>` is what a stack trace through
3958 // this code should say.
3959 code.set_filename("<builtin>");
3960 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3961 let closure_vars = compiled.code.closure_vars.clone();
3962 let env = self.global_env(&closure_vars);
3963 let this = Value::Object(self.realm.global.clone());
3964 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3965 }
3966
3967 /// Run an already-parsed script and drain the microtasks it queued.
3968 ///
3969 /// The drain is what lets an `async` function's body advance past its first `await`
3970 /// before the host sees the result: nothing else pumps the job queue.
3971 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3972 let this = Value::Object(self.realm.global.clone());
3973 self.run_script_with_this(code, this)
3974 }
3975
3976 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3977 ///
3978 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3979 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3980 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3981 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3982 /// state the next script evaluation tripped over.
3983 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3984 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3985 let closure_vars = compiled.code.closure_vars.clone();
3986 let env = self.global_env(&closure_vars);
3987 let callee = Value::Undefined;
3988 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3989 // The script is done, so the microtasks it queued run before the host sees the
3990 // result. Without this an `async` function's body would never advance past its
3991 // first `await`, because nothing else drains the queue.
3992 self.drain_jobs()?;
3993 Ok(result)
3994 }
3995
3996 /// Compile and run `source` in global scope, returning its completion value.
3997 ///
3998 /// This is what `eval` and `new Function` use. Running it as a script means it
3999 /// sees the global object and nothing else, which is right for `eval("1+1")` and
4000 /// for a `Function` body; a *direct* eval that reads a local variable would need
4001 /// the compiler to hand its variable environment over, which is not implemented.
4002 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
4003 self.eval_in_global_named(source, EVAL_FILE, false, true)
4004 }
4005
4006 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
4007 ///
4008 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
4009 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
4010 /// through the code, so they cannot share one constant.
4011 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
4012 // *Not* an eval body: `evalScript` evaluates a global script, so its top-level
4013 // `let`/`const`/`class` are global lexical bindings that outlive the call — which
4014 // is exactly what `global-code/script-decl-lex*` assert.
4015 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier, false)
4016 }
4017
4018 /// Evaluate `source` as a global script, reported under `file`.
4019 ///
4020 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
4021 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
4022 /// from inside a C callback, where the interpreter is the running one rather than a
4023 /// context's own.
4024 pub fn eval_in_global_named(
4025 &mut self,
4026 source: &str,
4027 file: &str,
4028 barrier: bool,
4029 is_eval: bool,
4030 ) -> JsResult<Value> {
4031 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4032 // eval-created global binding — configurable, unlike a script's own `var`.
4033 self.eval_depth += 1;
4034 if barrier {
4035 let depth = self.frames.len();
4036 self.trace_barriers.push(depth);
4037 }
4038 let result = self.eval_in_global_inner(source, file, is_eval);
4039 if barrier {
4040 self.trace_barriers.pop();
4041 }
4042 self.eval_depth -= 1;
4043 result
4044 }
4045
4046 fn eval_in_global_inner(&mut self, source: &str, file: &str, is_eval: bool) -> JsResult<Value> {
4047 self.compiling_eval_body = is_eval;
4048 let compiled = self.compile_global_script(source, file, false);
4049 self.compiling_eval_body = false;
4050 let compiled = compiled?;
4051 let strict = compiled.strict;
4052 self.run_eval_script(compiled, strict)
4053 }
4054
4055 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4056 ///
4057 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4058 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4059 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4060 /// direct eval's is.
4061 pub fn eval_script_with_this(
4062 &mut self,
4063 source: &str,
4064 file: &str,
4065 this: Value,
4066 ) -> JsResult<Value> {
4067 let program = match js_parse::parse_script(source) {
4068 Ok(program) => program,
4069 Err(error) => {
4070 return Err(Signal::Throw(self.syntax_error_at(
4071 file,
4072 error.span.start.line,
4073 error.span.start.column,
4074 &error.message,
4075 )));
4076 }
4077 };
4078 let mut compiled = match js_compile::compile_script(&program) {
4079 Ok(compiled) => compiled,
4080 Err(error) => {
4081 return Err(Signal::Throw(self.syntax_error_at(
4082 file,
4083 error.span.start.line,
4084 error.span.start.column,
4085 &error.message,
4086 )));
4087 }
4088 };
4089 compiled.set_filename(file);
4090 self.run_script_with_this(compiled, this)
4091 }
4092
4093 /// Parse and compile `source` as a global script, without running it.
4094 ///
4095 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4096 /// before a promise exists to reject — while still evaluating in the same eval context
4097 /// (direct-eval strictness, `new.target`, `super`).
4098 fn compile_global_script(
4099 &mut self,
4100 source: &str,
4101 file: &str,
4102 async_body: bool,
4103 ) -> JsResult<CompiledFunction> {
4104 // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4105 // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4106 // context at all. The site is what tells the two apart — an indirect call leaves no
4107 // site behind, since only a bare `eval(...)` is recorded.
4108 let site = self.eval_site_at_cursor();
4109 // Strictness follows the same rule, and it is *not* a detail: §19.2.1.1 step 4
4110 // makes the eval code strict when the caller is strict **and the call is direct**.
4111 // So `var s = eval; s("var eval;")` called from strict code is sloppy — legal —
4112 // while `eval("var eval;")` there is a `SyntaxError`
4113 // (`statements/variable/12.2.1-*-s`). Inheriting unconditionally rejected the
4114 // indirect form. A `"use strict"` prologue in the source still works either way:
4115 // the parser reads the directive itself, which is how a script becomes strict.
4116 let strict = site.is_some() && self.current_strict();
4117 // `eval` runs in the caller's function context, so `new.target` is legal here
4118 // even though the source is a bare script — and so is `super.x` when the caller
4119 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4120 // caller's, which is what `special_object 4` already does.
4121 let private = site
4122 .map(|site| site.private_names.clone())
4123 .unwrap_or_default();
4124 let context = js_parse::EvalContext {
4125 in_method: site.is_some() && self.enclosing_home_object().is_some(),
4126 // `super()` belongs to a derived constructor, and an eval'd body is not a
4127 // constructor at all: the caller frame's `this` is already built.
4128 in_derived_constructor: false,
4129 // Private names are lexically scoped, so a direct `eval` inside a class body
4130 // can see them; see `Interp::eval_private_names`.
4131 private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4132 arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4133 // §19.2.1.1 asks the *caller's* function for `new.target`, and a script or
4134 // module body is not one: at the top level `eval('new.target')` is a
4135 // `SyntaxError`, not `undefined` (`eval-code/direct/new.target`).
4136 // The *nearest non-arrow* frame, because an arrow has no `new.target` of its
4137 // own and `() => eval("new.target")` at the top level is still a
4138 // `SyntaxError` (`new.target-arrow`).
4139 new_target_allowed: site.is_some()
4140 && !self
4141 .frames
4142 .iter()
4143 .rposition(|frame| !frame.code.code.is_arrow)
4144 .map(|index| self.frames[index].code.code.is_script_body)
4145 .unwrap_or(true),
4146 };
4147 // A *global* eval is not a function body: `new.target` and `super` are out of
4148 // reach there. Its `{async: true}` form differs in the other direction — the body
4149 // may `await` — so the two flags are independent and the reference sets both from
4150 // the eval type rather than from the caller.
4151 let parsed = if async_body {
4152 js_parse::parse_suspensible_global_eval(source, strict)
4153 } else {
4154 js_parse::parse_eval_script_in(source, strict, context)
4155 };
4156 let program = match parsed {
4157 Ok(program) => program,
4158 Err(error) => {
4159 // The message is bare: the position lives in `fileName`,
4160 // `lineNumber`, `columnNumber` and the stack frame above, which is where
4161 // the reference puts it. An `invalid source: L:C: ` prefix made
4162 // `e.message` differ from the reference while the stack already agreed.
4163 return Err(Signal::Throw(self.syntax_error_at(
4164 file,
4165 error.span.start.line,
4166 error.span.start.column,
4167 &error.message,
4168 )));
4169 }
4170 };
4171 let is_eval_body = self.compiling_eval_body;
4172 let mut compiled = match if async_body {
4173 js_compile::compile_eval_with_private(&program, &private, true, is_eval_body)
4174 } else {
4175 js_compile::compile_eval_with_private(&program, &private, false, is_eval_body)
4176 } {
4177 Ok(compiled) => compiled,
4178 // A construct the compiler does not handle yet is reported the same way a
4179 // parse error is: it happens before anything runs, so the trace is the
4180 // position in the source followed by the caller.
4181 Err(error) => {
4182 return Err(Signal::Throw(self.syntax_error_at(
4183 file,
4184 error.span.start.line,
4185 error.span.start.column,
4186 &error.message,
4187 )));
4188 }
4189 };
4190 compiled.set_filename(file);
4191 Ok(compiled)
4192 }
4193
4194 /// The private names the code at the current position can see, innermost first.
4195 ///
4196 /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4197 /// direct `eval` runs inside its caller's scope, so
4198 /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4199 /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4200 /// here rather than being derivable from the eval'd source.
4201 ///
4202 /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4203 /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4204 /// [`Interp::run_eval_script`] uses for "direct".
4205 fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4206 let frame = self.frames.last()?;
4207 let (line, column) = frame
4208 .code
4209 .code
4210 .position_at(frame.at as u32)
4211 .unwrap_or_default();
4212 // The nearest site at or before the current position: the recorded position of the
4213 // `call` instruction is the callee's, which sits a few columns inside the call
4214 // expression the compiler recorded, so an exact match would never be found.
4215 frame
4216 .code
4217 .code
4218 .eval_sites
4219 .iter()
4220 .filter(|site| (site.line, site.column) <= (line, column))
4221 .max_by_key(|site| (site.line, site.column))
4222 }
4223
4224 /// Run an `eval`'d script in the caller's scope.
4225 ///
4226 /// Three things have to come from the calling frame, because the eval'd code is a
4227 /// script and would otherwise see only the global object:
4228 ///
4229 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4230 /// * `arguments`, exposed as a binding of the eval's own scope, so
4231 /// `f("arguments.length", 1)` sees the caller's arguments;
4232 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4233 /// `eval("var v = 1")` into the global object.
4234 ///
4235 /// Locals of the calling function are *not* reachable: that needs the compiler to
4236 /// hand its variable environment over, which this milestone does not do.
4237 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4238 // `this` and `arguments` come from the innermost frame only — those are not
4239 // lexical — while the name bindings come from the whole chain of frames, part
4240 // of it being ordinary scope resolution.
4241 // An arrow has no `this` of its own, so an `eval` inside one inherits the
4242 // enclosing function's receiver — the lexical `this` the arrow was compiled to
4243 // read from its closure.
4244 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4245 // variable environment is the innermost frame of all: an arrow's own body is where
4246 // `var`s declared by an `eval` inside it belong.
4247 let caller_index = self
4248 .frames
4249 .iter()
4250 .rposition(|frame| !frame.code.code.is_arrow)
4251 .or_else(|| self.frames.len().checked_sub(1));
4252 let env_index = self.frames.len().checked_sub(1);
4253 let caller = caller_index.and_then(|index| self.frames.get(index));
4254 let (this, passed) = match caller {
4255 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4256 // No frame at all: the eval is running at the top level, so there is
4257 // nothing to inherit and the global receiver is right.
4258 None => (Value::Object(self.realm.global.clone()), Vec::new()),
4259 };
4260 // Innermost frame first, so the first binding found for a name is the one that
4261 // shadows the rest. A script frame (`<eval>`) contributes nothing.
4262 let mut bindings: Vec<EvalBinding> = Vec::new();
4263 // The calling function's own bindings, resolved by the compiler at the call
4264 // site. That table is the only reliable answer when a name is declared twice in
4265 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4266 // body means, and guessing by declaration order picks the wrong one as soon as
4267 // two loops in a row use the same name.
4268 // Only a *direct* eval sees the caller's scope. The compiler records a site for
4269 // every direct call — a bare `eval(...)` callee — so finding one at the current
4270 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4271 // callee to a value first and leave no site behind.
4272 let mut direct = false;
4273 let mut resolved_here = false;
4274 if let Some(frame) = self.frames.last() {
4275 let (line, column) = frame
4276 .code
4277 .code
4278 .position_at(frame.at as u32)
4279 .unwrap_or_default();
4280 // The nearest site at or before the current position, not an exact match:
4281 // the recorded position of the `call` instruction is the callee's, which
4282 // sits a few columns inside the call expression the compiler recorded. A
4283 // site is unique per call, so "the closest one behind us" identifies it.
4284 if let Some(site) = frame
4285 .code
4286 .code
4287 .eval_sites
4288 .iter()
4289 .filter(|site| (site.line, site.column) <= (line, column))
4290 .max_by_key(|site| (site.line, site.column))
4291 {
4292 direct = true;
4293 resolved_here = true;
4294 for binding in &site.bindings {
4295 // An enclosing function's frame sits `owner` levels below the one
4296 // running the call.
4297 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4298 else {
4299 continue;
4300 };
4301 bindings.push(EvalBinding {
4302 name: binding.name.clone(),
4303 frame,
4304 slot: if binding.is_arg {
4305 EvalSlot::Arg
4306 } else {
4307 EvalSlot::Local
4308 },
4309 index: binding.index as usize,
4310 });
4311 }
4312 }
4313 }
4314 for frame_index in (0..self.frames.len()).rev() {
4315 // Skip the innermost frame's flat scan when the compiler already answered
4316 // for it; an enclosing frame still needs one, because the eval resolves
4317 // those names dynamically.
4318 if resolved_here && frame_index == self.frames.len() - 1 {
4319 continue;
4320 }
4321 let frame = &self.frames[frame_index];
4322 for (index, arg) in frame.code.code.args.iter().enumerate() {
4323 bindings.push(EvalBinding {
4324 name: arg.name.clone(),
4325 frame: frame_index,
4326 slot: EvalSlot::Arg,
4327 index,
4328 });
4329 }
4330 for (index, local) in frame.code.code.vars.iter().enumerate() {
4331 bindings.push(EvalBinding {
4332 name: local.name.clone(),
4333 frame: frame_index,
4334 slot: EvalSlot::Local,
4335 index,
4336 });
4337 }
4338 }
4339 let mut seen = BTreeSet::new();
4340 bindings.retain(|binding| seen.insert(binding.name.clone()));
4341
4342 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4343 // elements is all the spec's ordinary uses need.
4344 //
4345 // Known divergence: this is bound for a *global* eval too, where there is no
4346 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4347 // needs "does the calling frame have an `arguments` of its own", which is not
4348 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4349 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4350 // the call-site detection does not answer it. Modelled as a binding in the caller's
4351 // variable environment, this would fall out; that is a larger change than the one
4352 // this comment is attached to.
4353 let arguments = Value::Object(self.new_array(passed));
4354
4355 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4356 // declares its `var`s in the caller's — which for a top-level eval is the global
4357 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4358 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4359 // vanish into a scope nobody reads back from.
4360 if code_strict {
4361 self.eval_scope.push(BTreeMap::new());
4362 }
4363 // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4364 // in global scope, where `arguments` means whatever the global object says — which
4365 // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4366 // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4367 // answer the array instead.
4368 let previous_arguments = if direct {
4369 self.eval_arguments.replace(arguments)
4370 } else {
4371 None
4372 };
4373 let previous_with = self.eval_with.replace(self.with_objects());
4374 let inherited_new_target = self
4375 .frames
4376 .iter()
4377 .rev()
4378 .find(|frame| !frame.code.code.is_arrow)
4379 .map(|frame| frame.new_target.clone());
4380 let previous_new_target = self
4381 .eval_new_target
4382 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4383 let eval_cells = self.eval_cells_for(&bindings);
4384 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4385 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4386 // `declare_eval_local` needs to know which frame that is.
4387 // An indirect eval gets the global environment, so nothing of the caller's is
4388 // recorded as the place its `var`s belong.
4389 let previous_caller = self
4390 .eval_caller
4391 .replace(if direct { env_index } else { None });
4392 // The cell-based view of the same bindings, which is what a closure created
4393 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4394 // whose compiler did not put a binding in a cell simply does not appear here —
4395 // reads and writes still work through `eval_bindings`, they just cannot outlive
4396 // the eval.
4397 let previous_eval_scope = self
4398 .active_eval_scope
4399 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4400 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4401 let closure_vars = compiled.code.closure_vars.clone();
4402 // Declaration instantiation is where this belongs: the check needs the caller frame
4403 // (recorded just above) and the eval's own var names, and it raises before any of
4404 // the eval's code runs.
4405 self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4406 let env = self.global_env(&closure_vars);
4407 let callee = Value::Undefined;
4408 // An async body does not run here: it becomes a coroutine and answers a promise,
4409 // which is what makes `await` legal in it. `this` still has to be the caller's
4410 // (for a global eval, the global object), because `this` is not part of `await`.
4411 let result = if compiled.code.kind.is_async() {
4412 self.run_async_body(compiled, env, this)
4413 } else {
4414 self.execute(compiled, env, this, Vec::new(), callee)
4415 };
4416 if code_strict {
4417 self.eval_scope.pop();
4418 }
4419 self.eval_arguments = previous_arguments;
4420 self.eval_with = previous_with;
4421 self.eval_new_target = previous_new_target;
4422 self.eval_bindings = previous_bindings;
4423 self.eval_caller = previous_caller;
4424 self.active_eval_scope = previous_eval_scope;
4425 result
4426 }
4427
4428 /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4429 /// rather than bindings.
4430 ///
4431 /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4432 /// declaration that cannot exist:
4433 ///
4434 /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4435 /// parameter expressions a separate parameter environment, and `arguments` is bound
4436 /// implicitly there, so a `var` of that name collides. An arrow that binds no
4437 /// `arguments` of its own has nothing to collide with and is allowed — see the table in
4438 /// [`Interp::check_eval_var_named_arguments`].
4439 /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4440 /// false; the operation is a `TypeError`, and `eval("var x")` with
4441 /// `Object.preventExtensions(this)` must raise rather than quietly do nothing
4442 /// (`non-definable-global-var` and its four siblings).
4443 fn check_eval_var_named_arguments(
4444 &self,
4445 closure_vars: &[js_compile::bytecode::ClosureVar],
4446 strict: bool,
4447 ) -> JsResult<()> {
4448 if strict {
4449 // A strict eval declares nothing outside itself, so none of the checks below
4450 // apply — they are all about the environment the declarations land in.
4451 return Ok(());
4452 }
4453 // §19.2.1.3 step 5.a: a `var` name that the *caller's* lexical environment already
4454 // binds is a `SyntaxError`, because the declaration would have to go into a
4455 // variable environment that sits inside that binding. `{ let x; eval("var x") }`
4456 // and a top-level `let x; eval("var x")` are both refused
4457 // (`var-env-lower-lex-non-strict`, `var-env-global-lex-non-strict`).
4458 //
4459 // The realm's `let`/`const`/`class` table is the global case; a caller frame's
4460 // lexical local is the nested one. `EvalSlot::Local` covers both, so the check has
4461 // to ask each binding whether it is lexical — which the *compiled code* knows.
4462 // A **declaration**, not a mention: the closure table carries an entry for every
4463 // global name the body touches, and only `GlobalDecl` means the eval itself would
4464 // create the binding. Without this, `for (let a …) eval("() => a")` looked like an
4465 // eval declaring `a` and was refused.
4466 let var_names = closure_vars.iter().filter(|var| {
4467 !var.is_lexical
4468 // `arguments` is not a lexical declaration wherever it appears: the
4469 // implicit one is var-like, and a *parameter* named `arguments` is handled
4470 // by the parameter-scope rule further down. Treating it as lexical made
4471 // every `eval("var arguments")` inside a nested arrow a `SyntaxError`.
4472 && var.name != "*default*"
4473 && var.name != "arguments"
4474 && matches!(
4475 var.closure_type,
4476 js_compile::bytecode::ClosureType::GlobalDecl
4477 )
4478 });
4479 for var in var_names {
4480 if self.realm.globals.contains_key(&var.name) {
4481 return Err(Signal::Throw(self.make_error(
4482 "SyntaxError",
4483 &format!(
4484 "eval declares '{}', which an enclosing lexical binding also names",
4485 var.name
4486 ),
4487 )));
4488 }
4489 // Only a *direct* eval has a caller environment to collide with. An indirect
4490 // one declares into the global environment, whose `thisLex` is already
4491 // `varEnv`, so the walk in §19.2.1.3 step 5.d has nothing to traverse —
4492 // `{ let x; (0, eval)("var x") }` is legal
4493 // (`eval-code/indirect/var-env-lower-lex-non-strict`).
4494 let lexical = self.eval_caller.flatten().is_some()
4495 && self.eval_bindings.iter().any(|binding| {
4496 binding.name == var.name
4497 && matches!(binding.slot, EvalSlot::Local)
4498 && self
4499 .frames
4500 .get(binding.frame)
4501 .and_then(|frame| frame.code.code.vars.get(binding.index))
4502 .is_some_and(|local| local.is_lexical)
4503 });
4504 if lexical {
4505 return Err(Signal::Throw(self.make_error(
4506 "SyntaxError",
4507 &format!(
4508 "eval declares '{}', which an enclosing lexical binding also names",
4509 var.name
4510 ),
4511 )));
4512 }
4513 }
4514 // A `var` this eval would declare on the global object, where there is no room for it.
4515 //
4516 // Two different rules, and the difference is the whole reason `ClosureVar` carries
4517 // `is_function_decl`:
4518 //
4519 // * `CanDeclareGlobalVar` — `var` — only asks that the global object be extensible
4520 // when the property does not exist at all, so `eval("var NaN")` is fine.
4521 // * `CanDeclareGlobalFunction` also refuses an existing property that is
4522 // non-configurable unless it is a writable, enumerable data property, so
4523 // `eval("function NaN(){}")` is a `TypeError`
4524 // (`non-definable-global-function`).
4525 let global = &self.realm.global;
4526 for var in closure_vars {
4527 if var.is_lexical || var.name == "*default*" {
4528 continue;
4529 }
4530 if !matches!(
4531 var.closure_type,
4532 js_compile::bytecode::ClosureType::GlobalDecl
4533 ) {
4534 continue;
4535 }
4536 match global.own_property(&var.name) {
4537 None => {
4538 if !global.is_extensible() {
4539 return Err(Signal::Throw(self.make_error(
4540 "TypeError",
4541 "cannot declare a global in a non-extensible global object",
4542 )));
4543 }
4544 }
4545 Some(existing) => {
4546 if var.is_function_decl
4547 && !existing.configurable
4548 && !(!existing.is_accessor() && existing.writable && existing.enumerable)
4549 {
4550 return Err(Signal::Throw(self.make_error(
4551 "TypeError",
4552 &format!("cannot declare global function '{}'", var.name),
4553 )));
4554 }
4555 }
4556 }
4557 }
4558 // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4559 // global environment, where `var arguments` is an ordinary global.
4560 let Some(caller) = self.eval_caller.flatten() else {
4561 return Ok(());
4562 };
4563 // §19.2.1.1 step 8: in a sloppy eval, a `var` name that the *running lexical
4564 // environment* already binds is a `SyntaxError`. While a default expression is being
4565 // evaluated that environment is the **parameter** scope, so
4566 // `function(a = eval("var a = 42")){}` throws rather than writing to the parameter —
4567 // the eval would otherwise declare into an environment that is about to be copied
4568 // into the body. A *different* name is fine, and so is the same name in a function
4569 // with a simple parameter list, where there is no separate parameter environment and
4570 // the `var` belongs to the function's own.
4571 //
4572 // The names come from `args`, which is exactly the plain-identifier parameters. A
4573 // pattern parameter's bindings are also in that scope but are not recoverable from
4574 // the bytecode, so `function([a] = eval("var a")){}` is still accepted; that gap is
4575 // narrower than the one this closes and needs the parameter scope published in the
4576 // compiled function to fix.
4577 if self.in_parameter_list_at(caller) {
4578 let parameter_names: Vec<String> = self
4579 .frames
4580 .get(caller)
4581 .map(|frame| {
4582 frame
4583 .code
4584 .code
4585 .args
4586 .iter()
4587 .map(|arg| arg.name.clone())
4588 .collect()
4589 })
4590 .unwrap_or_default();
4591 let collides = closure_vars.iter().any(|var| {
4592 !var.is_lexical && var.name != "*default*" && parameter_names.contains(&var.name)
4593 });
4594 if collides {
4595 return Err(Signal::Throw(self.make_error(
4596 "SyntaxError",
4597 "eval declares a var that the parameter scope already binds",
4598 )));
4599 }
4600 }
4601 if !closure_vars
4602 .iter()
4603 .any(|var| var.name == "arguments" && !var.is_lexical)
4604 {
4605 return Ok(());
4606 }
4607 // The body of a function is a different environment from its parameter list, and only
4608 // the parameter list is separate from `arguments`.
4609 if !self.in_parameter_list_at(caller) {
4610 return Ok(());
4611 }
4612 let caller_is_arrow = self
4613 .frames
4614 .get(caller)
4615 .is_some_and(|frame| frame.code.code.is_arrow);
4616 // A *parameter* named `arguments`, not merely a binding of that name: a body
4617 // `let arguments` is in the body's environment, which is the one that is separate and
4618 // therefore cannot collide. The slot tells them apart — an argument lives in
4619 // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4620 let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4621 binding.frame == caller
4622 && binding.name == "arguments"
4623 && matches!(binding.slot, EvalSlot::Arg)
4624 });
4625 if caller_is_arrow && !parameter_scope_binds_arguments {
4626 return Ok(());
4627 }
4628 Err(Signal::Throw(self.make_error(
4629 "SyntaxError",
4630 "eval declares 'arguments' in a function's parameter scope",
4631 )))
4632 }
4633
4634 /// The cell-backed subset of `bindings`, in the same priority order.
4635 ///
4636 /// Both lookup routes have to agree — the eval's own reads go through
4637 /// [`Interp::eval_binding_value`] and the closures it builds go through
4638 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4639 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4640 /// is not in a cell simply does not appear: reads and writes still work, they just
4641 /// cannot be handed to a closure that outlives the eval.
4642 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4643 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4644 for binding in bindings {
4645 let Some(frame) = self.frames.get(binding.frame) else {
4646 continue;
4647 };
4648 let cell = match binding.slot {
4649 EvalSlot::Arg => frame
4650 .code
4651 .arg_cell
4652 .get(binding.index)
4653 .copied()
4654 .unwrap_or(-1),
4655 EvalSlot::Local => frame
4656 .code
4657 .loc_cell
4658 .get(binding.index)
4659 .copied()
4660 .unwrap_or(-1),
4661 };
4662 if cell < 0 {
4663 continue;
4664 }
4665 if let Some(cell) = frame.cells.get(cell as usize) {
4666 names.push((binding.name.clone(), cell.clone()));
4667 }
4668 }
4669 names
4670 }
4671
4672 /// A `SyntaxError` that reports where in the source it happened.
4673 ///
4674 /// Compile-time failures never run, so they have no frame of their own; the
4675 /// reference still puts the position first in the trace, with no function name and
4676 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4677 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4678 /// reference borrows), which is how a script reads the position without parsing
4679 /// the trace.
4680 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4681 ///
4682 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4683 /// `columnNumber`, which is how the reference prints one. A positionless error
4684 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4685 /// the reference raises it from `js_resolve_module`, where there is no position.
4686 pub(crate) fn syntax_error_plain(
4687 &mut self,
4688 error: &js_parse::SyntaxError,
4689 file: &str,
4690 ) -> Value {
4691 if error.positionless {
4692 return self.make_error("SyntaxError", &error.message);
4693 }
4694 self.syntax_error_at(
4695 file,
4696 error.span.start.line,
4697 error.span.start.column,
4698 &error.message,
4699 )
4700 }
4701
4702 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4703 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4704 let value = self.make_error("SyntaxError", message);
4705 if let Value::Object(object) = &value {
4706 let text = self.string(blamed);
4707 // `stack` is an own data property, and the reference keeps it
4708 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4709 object.define("stack", Property::with_attributes(text, true, false));
4710 let name = self.string(file);
4711 object.define("fileName", Property::with_attributes(name, true, true));
4712 object.define(
4713 "lineNumber",
4714 Property::with_attributes(Value::Int(line as i32), true, true),
4715 );
4716 object.define(
4717 "columnNumber",
4718 Property::with_attributes(Value::Int(column as i32), true, true),
4719 );
4720 }
4721 value
4722 }
4723
4724 /// Run a compiled script whose completion value is a function, returning it.
4725 ///
4726 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4727 /// get the closure out, which keeps the constant-pool plumbing in one place.
4728 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4729 self.run_script(code)
4730 }
4731
4732 /// The environment of a script or of any function compiled at global scope:
4733 /// every entry is a global binding, so each one resolves to the realm's cell.
4734 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4735 let mut cells = Vec::with_capacity(closure_vars.len());
4736 for closure_var in closure_vars {
4737 let cell = match closure_var.closure_type {
4738 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4739 if closure_var.is_lexical =>
4740 {
4741 // A lexical declaration: the cell is created here holding the
4742 // dead-zone marker, which is what makes the binding exist and
4743 // unreadable before its initialiser runs.
4744 self.declare_global(&closure_var.name, closure_var.is_const);
4745 self.realm.globals[&closure_var.name].clone()
4746 }
4747 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4748 // A `var` or function declaration becomes a property of the global
4749 // object, and it exists from here on — which is why
4750 // `print(v); var v = 1` prints `undefined` instead of raising.
4751 // Declaring it at instantiation time (rather than at the
4752 // initialiser) is also what makes it non-configurable: the store
4753 // then lands on an existing property instead of creating one.
4754 self.declare_var_global(&closure_var.name);
4755 // The cell is a placeholder that nothing indexes; it cannot be
4756 // omitted because the slot has to hold something.
4757 self.new_cell(Value::Undefined)
4758 }
4759 _ => {
4760 // An undeclared global is read by name; the cell is a
4761 // placeholder that nothing indexes.
4762 self.new_cell(Value::Undefined)
4763 }
4764 };
4765 cells.push(cell);
4766 }
4767 Gc::new(
4768 self.heap,
4769 ClosureEnv {
4770 cells,
4771 eval_scope: None,
4772 local_vars: None,
4773 local_phase: 1,
4774 },
4775 )
4776 }
4777
4778 /// Push a frame and run until it returns.
4779 pub(crate) fn execute(
4780 &mut self,
4781 code: Gc<CompiledCode>,
4782 env: Gc<ClosureEnv>,
4783 this: Value,
4784 args: Vec<Value>,
4785 callee: Value,
4786 ) -> JsResult<Value> {
4787 let depth = self.frames.len();
4788 if depth == 0 {
4789 // A throw that reached the host ends the *active* mode: the next one is catchable
4790 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4791 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4792 // for the throw that evaluation will raise.
4793 self.uncatchable = false;
4794 }
4795 self.push_frame(code, env, this, args, callee)?;
4796 loop {
4797 // The fast loop first: it runs whole runs of records with `pc` in a register.
4798 //
4799 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4800 // reads it again — a store, a load and two bounds checks that a loop body does
4801 // not need, because nothing outside the loop can run in between. This is the
4802 // classic split: advance a register, and only spill it when leaving.
4803 //
4804 // `Some(value)` means the function ended by running off the end of its
4805 // instruction array, which is a normal return.
4806 let step = match self.run_fast() {
4807 Ok(Some(value)) => Ok(Step::Return(value)),
4808 Ok(None) => self.step(),
4809 Err(signal) => Err(signal),
4810 };
4811 match step {
4812 Ok(Step::Continue) => {}
4813 Ok(Step::Return(value)) => {
4814 self.pop_frame();
4815 // A frame that ended in a `tail_call` hands its value straight to
4816 // its caller: nothing after the call can run, so every frame above
4817 // the callee unwinds with the same value. See [`Frame::tail`] —
4818 // the reference does not reuse frames either, so recursion depth
4819 // and the stack-overflow limit behave the same way.
4820 while self.frames.len() > depth && self.frame().tail {
4821 self.pop_frame();
4822 }
4823 if self.frames.len() == depth {
4824 return Ok(value);
4825 }
4826 // The caller resumes with the value on its stack.
4827 self.frames
4828 .last_mut()
4829 .expect("a caller is live")
4830 .stack
4831 .push(value);
4832 }
4833 Err(Signal::Throw(value)) => {
4834 // The host's standing request becomes the active mode for this unwind,
4835 // and is consumed here so it does not leak into the next throw.
4836 if self.uncatchable_next {
4837 self.uncatchable_next = false;
4838 self.uncatchable = true;
4839 }
4840 // An uncatchable throw walks past every `catch` on the way out. The
4841 // frames are still popped, because the values they hold have to be
4842 // dropped — only the search for a handler is skipped.
4843 if self.uncatchable {
4844 while self.frames.len() > depth {
4845 self.frames.pop();
4846 }
4847 return Err(Signal::Throw(value));
4848 }
4849 // A handler lives on the stack of the frame that is throwing —
4850 // `catch` pushed it there — so this frame gets the first chance
4851 // to catch before it is popped.
4852 let mut value = value;
4853 loop {
4854 if self.frames.len() <= depth {
4855 return Err(Signal::Throw(value));
4856 }
4857 if self.catch_here(&mut value).is_some() {
4858 break;
4859 }
4860 self.frames.pop();
4861 }
4862 }
4863 // A `yield` in a frame that `execute` is running directly means a
4864 // generator body was entered as an ordinary call, which only happens if
4865 // the generator check in `call_or_push` was bypassed.
4866 Ok(Step::Suspend(_)) => {
4867 return Err(Signal::Throw(self.make_error(
4868 "InternalError",
4869 "a generator body ran as an ordinary call",
4870 )));
4871 }
4872 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4873 }
4874 }
4875 }
4876
4877 /// Install a handler for `value` if this frame has one, resuming at it.
4878 ///
4879 /// The scan is the reference's: walk the frame's stack downwards looking for the
4880 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4881 /// enumerator marker rather than a handler — `for of` keeps one under its record so
4882 /// that `break` and `return` can find the iterator — and an exception reaching one
4883 /// **closes that iterator** before the unwinding continues.
4884 ///
4885 /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4886 /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4887 /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4888 /// close the iterator while the reference to store into is being worked out.
4889 ///
4890 /// `value` is `&mut` because closing the iterator may replace it: see
4891 /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4892 fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4893 loop {
4894 // Popped one at a time so no frame borrow is held across the close below.
4895 let top = self.frames.last_mut()?.stack.pop()?;
4896 let Value::CatchOffset(offset) = top else {
4897 continue;
4898 };
4899 if offset != 0 {
4900 let frame = self.frames.last_mut().expect("the frame was just read");
4901 frame.stack.push(value.clone());
4902 frame.pc = offset as usize;
4903 return Some(());
4904 }
4905 // The record's `iter` and `next` sit directly below the marker.
4906 let close = {
4907 let frame = self.frames.last_mut().expect("the frame was just read");
4908 let next = frame.stack.pop();
4909 let iterator = frame.stack.pop();
4910 match (iterator, next) {
4911 (Some(iterator), Some(_next)) => Some(iterator),
4912 // A malformed record cannot be closed, but unwinding still has to go
4913 // on: this is not a handler, so there is nothing to resume at.
4914 _ => None,
4915 }
4916 };
4917 if let Some(iterator) = close {
4918 self.close_iterator_on_throw(iterator);
4919 }
4920 }
4921 }
4922
4923 /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4924 ///
4925 /// Two things differ from the ordinary close, both from the spec's step ordering:
4926 ///
4927 /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4928 /// return ? completion`) comes before step 5, so an exception raised by `return()`
4929 /// itself — or by reading it — is discarded;
4930 /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4931 ///
4932 /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4933 /// it saves the pending exception, clears the slot, and re-throws the saved one from
4934 /// `done:` no matter what happened in between.
4935 fn close_iterator_on_throw(&mut self, iterator: Value) {
4936 if matches!(iterator, Value::Undefined) {
4937 return;
4938 }
4939 let Ok(method) = self.read_field(&iterator, "return") else {
4940 return;
4941 };
4942 if matches!(method, Value::Undefined | Value::Null) {
4943 return;
4944 }
4945 // A throw from `return()` replaces nothing: the exception already being unwound is
4946 // the one that propagates.
4947 let _ = self.call_value(method, iterator, Vec::new());
4948 }
4949
4950 fn push_frame(
4951 &mut self,
4952 code: Gc<CompiledCode>,
4953 env: Gc<ClosureEnv>,
4954 this: Value,
4955 mut args: Vec<Value>,
4956 callee: Value,
4957 ) -> JsResult<()> {
4958 // Two bounds, and the byte budget is the one that decides in practice. The
4959 // reference's message is `stack overflow` on an `InternalError`, not V8's
4960 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4961 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4962 let frame_cost = Self::frame_cost(&code);
4963 let stack_base = self.stack_used();
4964 if self.frames.len() >= self.max_frames
4965 || stack_base.saturating_add(frame_cost) > self.stack_limit
4966 {
4967 return Err(Signal::Throw(
4968 self.make_error("InternalError", "stack overflow"),
4969 ));
4970 }
4971 let arg_count = code.code.args.len();
4972 // How many were actually passed, which `arguments.length` reports and
4973 // `assert(x)` depends on: a call with one argument must not look like a call
4974 // with one argument and an explicit `undefined`.
4975 let passed = args.len();
4976 // Missing arguments are `undefined` in their slots; extra ones are dropped
4977 // from the slots but still reachable through `arguments`.
4978 //
4979 // A call that passes no more than the declared parameters needs **no** copy:
4980 // after the resize below, `args[..passed]` *is* the passed values. Only the
4981 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4982 // the rare case. This used to copy every call: one `Value` clone per argument
4983 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4984 let passed_overflow = (passed > arg_count).then(|| {
4985 let mut values = self.take_values(passed, Value::Undefined);
4986 values[..passed].clone_from_slice(&args[..passed]);
4987 values
4988 });
4989 // Only when the counts differ, which for the overwhelmingly common call — as many
4990 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4991 // lengths is two length compares and nothing else, but this is the hottest few
4992 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4993 if passed != arg_count {
4994 args.resize(arg_count, Value::Undefined);
4995 args.truncate(arg_count);
4996 }
4997 let cell_count = code.code.var_ref_count as usize;
4998 let mut cells = Vec::with_capacity(cell_count);
4999 for _ in 0..cell_count {
5000 cells.push(self.new_cell(Value::Undefined));
5001 }
5002 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
5003 // A captured argument lives in its cell, not in the argument slot, so the
5004 // incoming value has to be moved there before the body runs.
5005 for (slot, cell) in code.arg_cell.iter().enumerate() {
5006 if *cell >= 0
5007 && let Some(value) = args.get(slot).cloned()
5008 {
5009 cells[*cell as usize].set(value);
5010 }
5011 }
5012 // Sloppy mode substitutes the global object for a missing receiver and boxes a
5013 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
5014 // reports `object`. Strict mode passes the value through untouched.
5015 let this = if code.code.strict {
5016 this
5017 } else if this.is_nullish() {
5018 Value::Object(self.realm.global.clone())
5019 } else if matches!(this, Value::Object(_)) {
5020 this
5021 } else {
5022 match crate::builtins::this_object(self, &this) {
5023 Ok(boxed) => Value::Object(boxed),
5024 Err(_) => this,
5025 }
5026 };
5027 let stack_depth = code.code.stack_size as usize + 1;
5028 // Taken before the `push` borrows `self.frames`, because the operand stack comes
5029 // out of the same recycle pool the locals did.
5030 let stack = self.take_values(stack_depth, Value::Undefined);
5031 self.frames.push(Frame {
5032 code,
5033 env,
5034 this,
5035 args,
5036 passed_count: passed,
5037 passed_overflow: passed_overflow.map(Box::new),
5038 locals,
5039 cells,
5040 local_vars: None,
5041 // Exactly the depth the compiler computed, so the operand stack never
5042 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
5043 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
5044 // the buffer between calls, so "exactly" costs nothing after the first one.
5045 stack,
5046 pc: 0,
5047 at: 0,
5048 callee,
5049 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
5050 cost: frame_cost,
5051 stack_base,
5052 tail: false,
5053 });
5054 Ok(())
5055 }
5056
5057 /// A value buffer of `len` slots, from the recycle pool when there is one.
5058 ///
5059 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
5060 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
5061 // A frame with no locals asks for nothing, and that is most frames: taking a
5062 // buffer out of the pool, clearing it and resizing it to zero is four operations
5063 // and a pool pop for an empty `Vec`, which is free to construct.
5064 if len == 0 {
5065 return Vec::new();
5066 }
5067 let mut buffer = self.free_values.pop().unwrap_or_default();
5068 buffer.clear();
5069 buffer.resize(len, fill);
5070 buffer
5071 }
5072
5073 /// Return a finished frame's value buffers for the next call to reuse.
5074 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
5075 for mut buffer in [
5076 std::mem::take(&mut frame.locals),
5077 frame
5078 .passed_overflow
5079 .take()
5080 .map(|buffer| *buffer)
5081 .unwrap_or_default(),
5082 std::mem::take(&mut frame.stack),
5083 ] {
5084 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
5085 // GC root: it kept every value the frame held reachable, which is invisible
5086 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
5087 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
5088 // exactly that within one run — the target `{}` of a finished IIFE was still
5089 // in its operand stack, in the pool.
5090 buffer.clear();
5091 // A buffer with no capacity is what `Vec::new` is; putting it back would just
5092 // fill the pool with nothing to offer.
5093 if free_values.len() < RECYCLE_SLOTS
5094 && buffer.capacity() > 0
5095 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
5096 {
5097 free_values.push(buffer);
5098 }
5099 }
5100 }
5101
5102 /// Pop a finished frame and keep its buffers.
5103 ///
5104 /// Every place that drops a frame goes through here: a recycled buffer is also where
5105 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
5106 /// nothing but the reuse.
5107 fn pop_frame(&mut self) -> Option<()> {
5108 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
5109 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
5110 let last = self.frames.len().checked_sub(1)?;
5111 Self::recycle(&mut self.free_values, &mut self.frames[last]);
5112 self.frames.truncate(last);
5113 Some(())
5114 }
5115
5116 /// Poll the host's interrupt handler, if one is installed.
5117 ///
5118 /// The counter is what keeps this off the hot path when nobody asked: the early return is
5119 /// one `Option` test, and with no handler installed the whole function is that test —
5120 /// `check_memory` next door already costs more, so this cannot be what shows up in a
5121 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
5122 #[inline]
5123 fn check_interrupt(&mut self) -> JsResult<()> {
5124 if self.interrupt.is_none() {
5125 return Ok(());
5126 }
5127 if self.interrupt_counter > 0 {
5128 self.interrupt_counter -= 1;
5129 return Ok(());
5130 }
5131 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
5132 // The closure is taken out for the duration so that a handler which re-enters the
5133 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
5134 let mut handler = self.interrupt.take().expect("checked above");
5135 let abort = handler();
5136 self.interrupt = Some(handler);
5137 if abort {
5138 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
5139 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
5140 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
5141 // documentation says.
5142 self.uncatchable = true;
5143 return Err(Signal::Throw(
5144 self.make_error("InternalError", "interrupted"),
5145 ));
5146 }
5147 Ok(())
5148 }
5149
5150 /// A memory checkpoint: does the heap still fit under its limit?
5151 ///
5152 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
5153 /// a `Cell` read and a predictable branch, and the point of asking that often is that
5154 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
5155 /// only at calls would let it run until the machine died, which is the exact failure
5156 /// `--memory-limit` exists to prevent.
5157 ///
5158 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
5159 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
5160 /// script that catches it, drops the reference and carries on is legitimate: measured
5161 /// on `qjs --memory-limit 1M`, the engine recovers.
5162 fn check_memory(&mut self) -> JsResult<()> {
5163 // One `Cell` read and a predictable branch when no limit is set, and an integer
5164 // compare when one is. Containers report their own growth as it happens
5165 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
5166 // walking it here was the first version and it was O(live) per 256 instructions,
5167 // which turned a 100k-element push loop into a five-minute one.
5168 let Some(limit) = self.heap.memory_limit() else {
5169 return Ok(());
5170 };
5171 let used = self.heap.used_bytes();
5172 if used <= limit {
5173 // Back under the limit — a collection or a dropped reference did it. The next
5174 // time it goes over is a new failure, not a repeat of this one.
5175 self.oom_reported_at = 0;
5176 return Ok(());
5177 }
5178 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5179 // block runs normally after `out of memory` — it allocates nothing, so nothing
5180 // fails. A check that re-fired on every instruction made the handler itself throw,
5181 // which is a dead end: the error became unobservable from script.
5182 //
5183 // Comparing against the total at the last report gives the same behaviour: the
5184 // handler runs while the total is unchanged, and the very next allocation over the
5185 // limit fails.
5186 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5187 {
5188 return Ok(());
5189 }
5190 self.oom_reported_at = used;
5191 Err(Signal::Throw(
5192 self.make_error("InternalError", "out of memory"),
5193 ))
5194 }
5195
5196 /// Fail before allocating `payload` bytes, if they would not fit.
5197 ///
5198 /// For the allocations whose size comes from script data — `new Array(n)`,
5199 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5200 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5201 /// answering NULL for the one big request.
5202 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5203 if self.heap.fits(payload) {
5204 return Ok(());
5205 }
5206 Err(Signal::Throw(
5207 self.make_error("InternalError", "out of memory"),
5208 ))
5209 }
5210
5211 /// Bytes of frame state the live call chain accounts for.
5212 pub fn stack_used(&self) -> usize {
5213 match self.frames.last() {
5214 Some(frame) => frame.stack_base + frame.cost,
5215 None => 0,
5216 }
5217 }
5218
5219 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5220 ///
5221 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5222 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5223 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5224 /// instead. That is the whole difference between the two models: it rations C stack, we
5225 /// ration frame state, and both quantities are dominated by the value slots — which is
5226 /// why the two depths come out comparable rather than merely proportional.
5227 fn frame_cost(code: &CompiledCode) -> usize {
5228 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5229 std::mem::size_of::<Frame>()
5230 + std::mem::size_of::<Value>() * slots
5231 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5232 }
5233
5234 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5235 ///
5236 /// Only names the eval created are here: a name the frame already declared statically
5237 /// is written through to its own slot instead, so this cannot shadow a real local.
5238 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5239 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5240 let (local_vars, phase) = self.visible_local_vars()?;
5241 if !local_vars.contains(name) {
5242 return None;
5243 }
5244 local_vars.get(name, phase)
5245 }
5246
5247 /// The variables a direct `eval` declared, as the code currently running sees them.
5248 ///
5249 /// Inside an eval that is the *caller's* set — the eval's own variable environment
5250 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5251 /// else it is the current frame's, falling back to the frame the closure was created
5252 /// in.
5253 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5254 ///
5255 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5256 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5257 /// refcount operations (the clone out of the frame, the drop at the end of the match)
5258 /// just to be asked `is_none`.
5259 fn has_visible_local_vars(&self) -> bool {
5260 let index = match self.eval_caller.flatten() {
5261 Some(caller) => caller,
5262 None => match self.frames.len().checked_sub(1) {
5263 Some(top) => top,
5264 None => return false,
5265 },
5266 };
5267 match self.frames.get(index) {
5268 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5269 None => false,
5270 }
5271 }
5272
5273 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5274 // While an `eval` runs, its own frame is on top but its variable environment is
5275 // the *caller's* — so the caller is what the lookup has to start from.
5276 let (index, phase) = match self.eval_caller.flatten() {
5277 Some(caller) => (
5278 caller,
5279 if self.in_parameter_list_at(caller) {
5280 0
5281 } else {
5282 1
5283 },
5284 ),
5285 None => (
5286 self.frames.len().checked_sub(1)?,
5287 if self.in_parameter_list() { 0 } else { 1 },
5288 ),
5289 };
5290 let frame = self.frames.get(index)?;
5291 // The frame's own variables, or — for an arrow, which has no variable environment
5292 // of its own — the one it was created in, which `ClosureEnv` carries.
5293 if let Some(local_vars) = frame.local_vars.clone() {
5294 return Some((local_vars, phase));
5295 }
5296 frame
5297 .env
5298 .local_vars
5299 .clone()
5300 .map(|local_vars| (local_vars, frame.env.local_phase))
5301 }
5302
5303 /// Whether the innermost frame is still evaluating its parameter list.
5304 ///
5305 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5306 /// and a closure created there may only see that much of [`LocalVars`].
5307 fn in_parameter_list(&self) -> bool {
5308 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5309 }
5310
5311 /// [`Interp::in_parameter_list`] for a specific frame.
5312 fn in_parameter_list_at(&self, frame: usize) -> bool {
5313 let Some(frame) = self.frames.get(frame) else {
5314 return false;
5315 };
5316 let code = &frame.code.code;
5317 if !code.has_parameter_expressions {
5318 return false;
5319 }
5320 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5321 // function as its body and let a direct `eval` act accordingly.
5322 if code.body_start == (0, 0) {
5323 return false;
5324 }
5325 match code.position_at(frame.at as u32) {
5326 Some(position) => position < code.body_start,
5327 None => false,
5328 }
5329 }
5330
5331 fn frame(&self) -> &Frame {
5332 self.frames.last().expect("a frame is live")
5333 }
5334
5335 fn frame_mut(&mut self) -> &mut Frame {
5336 self.frames.last_mut().expect("a frame is live")
5337 }
5338
5339 // -- slot access --------------------------------------------------------
5340
5341 /// Move a local's value out, leaving `undefined` in the slot.
5342 ///
5343 /// `None` for a captured slot: its value lives in a cell shared with every closure
5344 /// that closed over it, so it can never be exclusively ours and must not be taken.
5345 ///
5346 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5347 /// for every read and fatal for this one — a clone is exactly the second handle that
5348 /// rules out growing the string in place.
5349 fn take_loc(&mut self, slot: usize) -> Option<Value> {
5350 let frame = self.frames.last_mut()?;
5351 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5352 return None;
5353 }
5354 frame
5355 .locals
5356 .get_mut(slot)
5357 .map(|value| std::mem::replace(value, Value::Undefined))
5358 }
5359
5360 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5361 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5362 ///
5363 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5364 /// it** — the value is put back before the general path runs — so a `valueOf` that
5365 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5366 /// error as it would have without the fusion. This is why the in-place attempt is a
5367 /// `take` and not a `get`: an optimisation that changes what an exception observes is
5368 /// a wrong answer with a good excuse.
5369 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5370 // The take is `matches!`-guarded on the *right* operand only, and the taken value
5371 // is put back on every path that does not append. An earlier version wrote the two
5372 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5373 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5374 // through with its value already taken and dropped: the general path below then
5375 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5376 // A wrong answer, from an optimisation, with every test green.
5377 if matches!(right, Value::String(_))
5378 && let Some(taken) = self.take_loc(slot)
5379 {
5380 if let Value::String(mut left) = taken {
5381 let appended = match left.get_mut() {
5382 Some(string) => string.append_in_place(
5383 // The pattern is the one `matches!` just checked.
5384 match &right {
5385 Value::String(text) => text,
5386 _ => unreachable!("guarded above"),
5387 },
5388 ),
5389 None => None,
5390 };
5391 self.put_loc(slot, Value::String(left));
5392 if let Some(added) = appended {
5393 // The buffer grew where it stood, so the heap's running total has to
5394 // be told: `measure_used` would report the new length, and the two must
5395 // agree or the subtraction at free time leaves the counter wrong.
5396 self.heap.adjust_payload(added as isize);
5397 return Ok(());
5398 }
5399 } else {
5400 self.put_loc(slot, taken);
5401 }
5402 }
5403 // The two-number case, without an operand stack round trip. Everything below
5404 // this point is the *general* path: push both, call `binary_add`, pop the answer,
5405 // store it — five operations and two `Value` clones for what is one integer add.
5406 // `AddImmLoc` already answers this shape that way; the fusion above it was written
5407 // for string append and never got the numeric half, so `t += i` — a counting loop
5408 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5409 let left = self.get_loc(slot);
5410 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5411 self.put_loc(
5412 slot,
5413 match a.checked_add(*b) {
5414 Some(sum) => Value::Int(sum),
5415 None => Value::Float(*a as f64 + *b as f64),
5416 },
5417 );
5418 return Ok(());
5419 }
5420 self.push(left);
5421 self.push(right);
5422 self.binary_add()?;
5423 let value = self.pop();
5424 self.put_loc(slot, value);
5425 Ok(())
5426 }
5427
5428 fn get_arg(&self, slot: usize) -> Value {
5429 self.frame().read_arg(slot)
5430 }
5431
5432 fn put_arg(&mut self, slot: usize, value: Value) {
5433 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5434 if cell == -1 {
5435 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5436 *slot = value;
5437 }
5438 } else {
5439 self.frame().cells[cell as usize].set(value);
5440 }
5441 }
5442
5443 fn get_loc(&self, slot: usize) -> Value {
5444 // The cell mapping is `-1` for every slot that was not captured — which is all of
5445 // them in a function that creates no closure. `Frame::read_loc` tests that first,
5446 // so the common case is one array read and a clone: 20% of every loop iteration
5447 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5448 // sample of `dispatch:arith`).
5449 self.frame().read_loc(slot)
5450 }
5451
5452 fn put_loc(&mut self, slot: usize, value: Value) {
5453 // One borrow instead of three, and the cell check on the frame we already hold.
5454 let frame = self.frames.last_mut().expect("a frame is live");
5455 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5456 if cell < 0 {
5457 if let Some(slot) = frame.locals.get_mut(slot) {
5458 *slot = value;
5459 }
5460 } else if let Some(cell) = frame.cells.get(cell as usize) {
5461 cell.set(value);
5462 }
5463 }
5464
5465 // -- globals ------------------------------------------------------------
5466
5467 /// The name a global-slot operand refers to.
5468 fn global_name(&self, slot: usize) -> String {
5469 self.frame()
5470 .code
5471 .code
5472 .closure_vars
5473 .get(slot)
5474 .map(|c| c.name.clone())
5475 .unwrap_or_default()
5476 }
5477
5478 /// The facts about a global binding that decide where it lives.
5479 ///
5480 /// A script's globals split in two, and the split is observable: `var` and
5481 /// function declarations become properties of the global object (`globalThis.v`
5482 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5483 /// declarations live in the global *lexical* environment and are invisible there
5484 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5485 /// `is_lexical` flag means the answer is already in the bytecode.
5486 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5487 let name = self.global_name(slot);
5488 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5489 // while forwarding a reference through a nested function is built with the
5490 // flags cleared, so `const c` would look like an ordinary `var` from inside a
5491 // closure. Presence in the realm's lexical table is the same fact, recorded
5492 // once, and every slot sees it.
5493 let lexical = self.realm.globals.contains_key(&name);
5494 let is_const = self.realm.lexical_consts.contains(&name);
5495 (name, lexical, is_const)
5496 }
5497
5498 /// The value of `name` in the innermost active `with` object, if any.
5499 ///
5500 /// The active objects are the [`VarKind::With`] locals of every frame still running,
5501 /// innermost frame first and innermost block first within one. Walking frames rather
5502 /// than keeping a separate stack is what makes a closure called from inside a `with`
5503 /// see it, and what keeps the object alive only as long as the block is.
5504 /// The innermost active `with` object that has `name`, if any.
5505 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5506 let objects = self.eval_with.clone().unwrap_or_default();
5507 for object in objects {
5508 let key = self.string(name.to_string());
5509 if self
5510 .has_property(&key, &Value::Object(object.clone()))
5511 .ok()?
5512 {
5513 return Some(object);
5514 }
5515 }
5516 None
5517 }
5518
5519 /// Every active `with` object, innermost first.
5520 fn with_objects(&self) -> Vec<Gc<JsObject>> {
5521 let mut objects = Vec::new();
5522 for frame in self.frames.iter().rev() {
5523 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5524 if var.kind != js_compile::VarKind::With {
5525 continue;
5526 }
5527 // A captured binding lives in its cell and not in the slot list, so the
5528 // cell is consulted first — a closure created inside the block is exactly
5529 // what makes the object captured. Before the store runs the slot still
5530 // holds `undefined`, and a `with` object is always boxed, so a non-object
5531 // entry is simply not in scope yet.
5532 let value = frame
5533 .code
5534 .loc_cell
5535 .get(index)
5536 .copied()
5537 .filter(|cell| *cell >= 0)
5538 .and_then(|cell| frame.cells.get(cell as usize))
5539 .map(|cell| cell.get())
5540 .or_else(|| frame.locals.get(index).cloned());
5541 if let Some(Value::Object(object)) = value {
5542 objects.push(object);
5543 }
5544 }
5545 }
5546 objects
5547 }
5548
5549 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5550 for object in self.eval_with.clone().unwrap_or_default() {
5551 let key = self.string(name.to_string());
5552 if self.has_property(&key, &Value::Object(object.clone()))? {
5553 return Ok(Some(self.read_field(&Value::Object(object), name)?));
5554 }
5555 }
5556 Ok(None)
5557 }
5558
5559 /// Whether every scope between here and the global object is an ordinary one.
5560 ///
5561 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5562 /// bytecode resolved; when any is live the general path has to run in full order. When
5563 /// none is — every ordinary program — a global read is a property read and nothing
5564 /// else, and that is worth caching.
5565 fn scopes_are_plain(&self) -> bool {
5566 self.eval_caller.is_none()
5567 && self.eval_with.is_none()
5568 && self.eval_arguments.is_none()
5569 && self.eval_bindings.is_empty()
5570 && self.eval_scope.is_empty()
5571 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5572 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5573 // its `ClosureEnv`, so the test has to be the same one the general path makes.
5574 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5575 // upstream corpus caught and no unit test did.
5576 && !self.has_visible_local_vars()
5577 && self.frame().env.eval_scope.is_none()
5578 }
5579
5580 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5581 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5582 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5583 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5584 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5585 // borrow outlive the `&mut self` the lookup needs.
5586 //
5587 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5588 // forwarded through a nested function has its flags cleared, so the flag cannot
5589 // be believed.
5590 let code = self.frame().code.clone();
5591 let name = code
5592 .code
5593 .closure_vars
5594 .get(slot)
5595 .map(|c| c.name.as_str())
5596 .unwrap_or_default();
5597 let lexical = self.realm.globals.contains_key(name);
5598 // The common case, first: an ordinary global `var`, with a cache in front of the
5599 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5600 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5601 // cache hit and return without touching any of it.
5602 if !lexical && self.scopes_are_plain() {
5603 return self.get_plain_global(name, slot);
5604 }
5605 if name == "arguments"
5606 && let Some(arguments) = &self.eval_arguments
5607 {
5608 return Ok(arguments.clone());
5609 }
5610 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5611 // the objects live when the eval started are consulted before anything else. The
5612 // snapshot is taken at entry rather than scanning the frames on every read: a
5613 // block that has already finished still leaves its object in the slot, and a
5614 // bytecode read outside the block must not see it.
5615 if let Some(value) = self.with_lookup(name)? {
5616 return Ok(value);
5617 }
5618 // A name a **running** eval declared itself outranks the caller's bindings — that
5619 // is what makes a strict eval's `var` private to it. It has to come first here, and
5620 // first in `put_global`, or a nested eval would read the caller's variable while
5621 // writing its own: `eval("var o = 'str2'; eval('o')")` inside a function that also
5622 // has an `o`.
5623 for scope in self.eval_scope.iter().rev() {
5624 if let Some(value) = scope.get(name) {
5625 return Ok(value.clone());
5626 }
5627 }
5628 // A closure created by an `eval` resolves its free names against the bindings
5629 // that eval saw, even after the eval (and its frames) are gone.
5630 if let Some(cell) = self
5631 .frame()
5632 .env
5633 .eval_scope
5634 .as_ref()
5635 .and_then(|scope| scope.get(name))
5636 {
5637 let value = cell.get();
5638 if matches!(value, Value::Uninitialized) {
5639 return Err(self.throw_reference(name));
5640 }
5641 return Ok(value);
5642 }
5643 // A variable a direct `eval` declared shadows everything the compiler resolved,
5644 // including an enclosing function's binding: the eval put it in the caller's own
5645 // variable environment, which is nearer than any captured scope.
5646 if let Some((local_vars, phase)) = self.visible_local_vars()
5647 && let Some(cell) = local_vars.get(name, phase)
5648 {
5649 return Ok(cell.get());
5650 }
5651 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5652 // its local `a` wins over a global `a`.
5653 if let Some(value) = self.eval_binding_value(name) {
5654 return Ok(value);
5655 }
5656 // A binding declared by the strict `eval` currently running shadows anything
5657 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5658 if lexical {
5659 // A lexical global is a binding in a side table, so the dead zone is
5660 // visible and it is nowhere on the global object.
5661 if let Some(cell) = self.realm.globals.get(name) {
5662 let value = cell.get();
5663 if matches!(value, Value::Uninitialized) {
5664 return Err(self.throw_reference(name));
5665 }
5666 return Ok(value);
5667 }
5668 return Err(self.throw_reference(name));
5669 }
5670 // A `var` global is an ordinary property, so the prototype chain and the
5671 // global object's own builtins are all reachable through it.
5672 match self.get_property(&self.realm.global.clone(), name)? {
5673 Some(value) => Ok(value),
5674 None => Err(self.throw_reference(name)),
5675 }
5676 }
5677
5678 /// Read a plain global `var`: a cached own data property, or the full lookup.
5679 ///
5680 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5681 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5682 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5683 let object = self.realm.global.clone();
5684 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5685 if let Some(cached) = &self.global_cache[site]
5686 && object.upgrades_to(&cached.object)
5687 && let Some(value) = object.data_property_at(cached.index, name)
5688 {
5689 return Ok(value);
5690 }
5691 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5692 // chain exactly as before, then remember the answer if it is worth remembering.
5693 let Some(value) = self.get_property(&object, name)? else {
5694 return Err(self.throw_reference(name));
5695 };
5696 if let Some(index) = object.own_data_index(name) {
5697 self.global_cache[site] = Some(GlobalCache {
5698 object: object.downgrade(),
5699 index,
5700 });
5701 }
5702 Ok(value)
5703 }
5704
5705 /// Store to a global binding.
5706 ///
5707 /// Returns a signal when the store is refused: a `const` global may only be
5708 /// written by its initialiser, and a non-configurable `var` global may not be
5709 /// deleted but is always writable.
5710 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5711 let (name, lexical, is_const) = self.global_binding(slot);
5712
5713 // An assignment inside a `with` writes through to the object that supplies the
5714 // name, which for an `eval` means consulting the same chain `get_global` does.
5715 if let Some(owner) = self.with_owner(&name) {
5716 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5717 return Ok(());
5718 }
5719 // A *strict* eval has a variable environment of its own, so a name it declared
5720 // there shadows the caller's binding of the same name: in
5721 // `function f(){ "use strict"; var v = 0; eval("var v = 1") }` the outer `v` must
5722 // stay 0 (`eval-code/direct/var-env-var-strict-caller`). `eval_scope` is `Some`
5723 // only while such an eval runs, and holds only the names it declared, so this is
5724 // narrower than it looks.
5725 //
5726 // It sits ahead of the caller's bindings below on purpose: the *reads* take the
5727 // same order (`get_global`), and a store that disagreed with its own read would
5728 // write somewhere the eval cannot see.
5729 let closure_scope = self
5730 .frame()
5731 .env
5732 .eval_scope
5733 .as_ref()
5734 .and_then(|scope| scope.get(&name))
5735 .cloned();
5736 if let Some(cell) = closure_scope {
5737 cell.set(value);
5738 return Ok(());
5739 }
5740 for scope in self.eval_scope.iter_mut().rev() {
5741 if let Some(slot) = scope.get_mut(&name) {
5742 *slot = value;
5743 return Ok(());
5744 }
5745 }
5746 // A variable the running eval *declared* takes the write before any caller
5747 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5748 // environment even when an enclosing function has a `var c` of its own.
5749 if self.eval_caller.flatten().is_some()
5750 && let Some((local_vars, phase)) = self.visible_local_vars()
5751 && local_vars.contains(&name)
5752 && let Some(cell) = local_vars.get(&name, phase)
5753 {
5754 cell.set(value);
5755 return Ok(());
5756 }
5757 // A binding of the frame that called `eval` takes the write, which is what
5758 // makes `f("a = 3")` change the caller's `a`.
5759 if self.set_eval_binding(&name, &value)? {
5760 return Ok(());
5761 }
5762 // An *assignment* to a name nobody declared is not a declaration, so it falls
5763 // through to the global: strict mode raises `ReferenceError` for it, which is what
5764 // `eval("1 + (@not_def = 1)")` has to do.
5765 if lexical {
5766 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5767 // A lexical global starts out `Uninitialized` and only `init_global` ends
5768 // that, so a store reaching here is either a plain assignment to a slot
5769 // still in its dead zone — `x = 1; let x` at the top level, a
5770 // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5771 if matches!(cell.get(), Value::Uninitialized) {
5772 return Err(self.dead_zone_global(&name));
5773 }
5774 if is_const {
5775 return Err(self.read_only_global(&name));
5776 }
5777 cell.set(value);
5778 return Ok(());
5779 }
5780 // Writing an undeclared lexical global is a `ReferenceError` in strict
5781 // mode and a silent global creation otherwise; creating the cell here
5782 // keeps both paths from losing the value.
5783 let cell = self.new_cell(value);
5784 self.realm.globals.insert(name, cell);
5785 return Ok(());
5786 }
5787 // A variable a direct `eval` declared in this call shadows the global object, even
5788 // when the global already has a property of that name — `var c = "global"` at the
5789 // top level must not capture `eval("var c = 1")` inside a function.
5790 if let Some((local_vars, phase)) = self.visible_local_vars()
5791 && local_vars.contains(&name)
5792 && let Some(cell) = local_vars.get(&name, phase)
5793 {
5794 cell.set(value);
5795 return Ok(());
5796 }
5797 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5798 // remembered a global's slot index since M12b, but the *store* side never did: it
5799 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5800 // global object's whole table — which holds every builtin — on every assignment to
5801 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5802 // full global lookup per iteration; measured with a counter, `s` as a global made
5803 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5804 //
5805 // Re-validated exactly like the read: same object, same index, still the name, and
5806 // — the one extra check a store needs — still writable. A global that is an
5807 // accessor, non-writable, or inherited fails here and falls through to the full
5808 // path below, which reports the failure the way it always did.
5809 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5810 let global = self.realm.global.clone();
5811 if let Some(cached) = &self.global_cache[site]
5812 && global.upgrades_to(&cached.object)
5813 && global.write_data_at(cached.index, &name, value.clone())
5814 {
5815 return Ok(());
5816 }
5817 match global.own_property(&name) {
5818 // A `var` global is writable, so the store goes straight through — but
5819 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5820 // store (a non-writable or accessor-without-setter global) is a silent
5821 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5822 // split every other assignment has.
5823 Some(_) => {
5824 let on_failure = if self.current_strict() {
5825 DeleteFailure::Throw
5826 } else {
5827 DeleteFailure::Ignore
5828 };
5829 let result = self.set_property_with(&global, &name, value, on_failure);
5830 // Teach the cache the slot for a plain writable own data property, which is
5831 // what a declared `var` is. Without this the fast path above could never
5832 // fire for a global that is only ever *written* — its entry would have to
5833 // be put there by a read of the same slot, and a write-only loop has none.
5834 if result.is_ok()
5835 && let Some(index) = global.own_data_index(&name)
5836 {
5837 self.global_cache[site] = Some(GlobalCache {
5838 object: global.downgrade(),
5839 index,
5840 });
5841 }
5842 result
5843 }
5844 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5845 // declaration creates a *configurable* property, which is what makes it
5846 // deletable and is the one way a global differs from a declared `var`.
5847 // In strict mode the same store is a `ReferenceError` instead: that is the
5848 // whole point of strict mode, and creating the global silently meant
5849 // `"use strict"; x = 1` looked like it worked.
5850 None => {
5851 if self.current_strict() {
5852 return Err(self.throw_reference(&name));
5853 }
5854 // A direct eval declares here rather than on the global object: its
5855 // `var`s belong to the caller's variable environment. `declare_eval_local`
5856 // also covers a plain assignment to a variable an earlier eval made.
5857 if let Some(cell) = self.declare_eval_local(&name) {
5858 cell.set(value);
5859 return Ok(());
5860 }
5861 global.define_data(&name, value);
5862 Ok(())
5863 }
5864 }
5865 }
5866
5867 /// The value of a binding of the frame that called `eval`, if there is one.
5868 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5869 let binding = self
5870 .eval_bindings
5871 .iter()
5872 .find(|binding| binding.name == name)?;
5873 let owner = self.frames.get(binding.frame)?;
5874 let (slot, index) = (binding.slot, binding.index);
5875 Some(match slot {
5876 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5877 cell if cell >= 0 => owner
5878 .cells
5879 .get(cell as usize)
5880 .map(|cell| cell.get())
5881 .unwrap_or(Value::Undefined),
5882 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5883 },
5884 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5885 cell if cell >= 0 => owner
5886 .cells
5887 .get(cell as usize)
5888 .map(|cell| cell.get())
5889 .unwrap_or(Value::Undefined),
5890 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5891 },
5892 })
5893 }
5894
5895 /// Write to a binding of the frame that called `eval`.
5896 ///
5897 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5898 /// matched binding can still refuse the store, which is why this is fallible: a
5899 /// `const` is read-only everywhere, and a named function expression's own name is
5900 /// read-only in strict mode.
5901 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5902 let Some(binding) = self
5903 .eval_bindings
5904 .iter()
5905 .find(|binding| binding.name == name)
5906 else {
5907 return Ok(false);
5908 };
5909 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5910 let strict = self.current_strict();
5911 let Some(owner) = self.frames.get_mut(frame) else {
5912 return Ok(false);
5913 };
5914 match slot {
5915 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5916 cell if cell >= 0 => {
5917 if let Some(cell) = owner.cells.get(cell as usize) {
5918 cell.set(value.clone());
5919 }
5920 }
5921 _ => {
5922 if let Some(slot) = owner.args.get_mut(index) {
5923 *slot = value.clone();
5924 }
5925 }
5926 },
5927 EvalSlot::Local => {
5928 let declared = owner.code.code.vars.get(index);
5929 // A `const` is read-only even through `eval`. The realm records this for
5930 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5931 // the bytecode, so this is where it has to be enforced.
5932 if declared.is_some_and(|var| var.is_const) {
5933 return Err(self.read_only_local(name));
5934 }
5935 // The name of a named function expression is read-only too, but only
5936 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5937 // such a name is ignored, the same as a direct store would be.
5938 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5939 return if strict {
5940 Err(self.read_only_local(name))
5941 } else {
5942 Ok(true)
5943 };
5944 }
5945 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5946 cell if cell >= 0 => {
5947 if let Some(cell) = owner.cells.get(cell as usize) {
5948 cell.set(value.clone());
5949 }
5950 }
5951 _ => {
5952 if let Some(slot) = owner.locals.get_mut(index) {
5953 *slot = value.clone();
5954 }
5955 }
5956 }
5957 }
5958 }
5959 Ok(true)
5960 }
5961
5962 /// The `TypeError` an assignment to a read-only binding raises.
5963 fn read_only_local(&self, name: &str) -> Signal {
5964 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5965 }
5966
5967 /// Declare `name` as a variable of the frame that called the running `eval`.
5968 ///
5969 /// `None` when there is no direct eval in progress, or it was called from the top
5970 /// level — then the caller's variable environment *is* the global one and the
5971 /// existing path is right.
5972 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5973 let caller = self.eval_caller.flatten()?;
5974 // The bottom frame is the top-level script, whose variable environment *is* the
5975 // global one — so `eval("var x = 1")` at the top level still creates a global.
5976 if caller == 0 {
5977 return None;
5978 }
5979 // A name the eval's *own* variable environment already binds is not a new
5980 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5981 // `arguments`, and creating a second binding would leave the first — the one
5982 // closures read — untouched. A binding of an *outer* frame does not count: a
5983 // declaration shadows it rather than writing through.
5984 if self
5985 .eval_bindings
5986 .iter()
5987 .any(|binding| binding.name == name && binding.frame == caller)
5988 {
5989 return None;
5990 }
5991 let phase = if self.in_parameter_list_at(caller) {
5992 0
5993 } else {
5994 1
5995 };
5996 self.frame_local_vars(caller)?;
5997 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5998 if let Some(cell) = local_vars.get(name, 1) {
5999 return Some(cell);
6000 }
6001 let cell = self.new_cell(Value::Undefined);
6002 Some(local_vars.declare(name, phase, cell))
6003 }
6004
6005 /// Make sure `frame` has a `LocalVars`, creating it on demand.
6006 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
6007 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
6008 return Some(local_vars.clone());
6009 }
6010 let local_vars = Gc::new(self.heap, LocalVars::new());
6011 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
6012 Some(local_vars)
6013 }
6014
6015 /// Whether the realm already has a binding for `name`, lexically or as an *own*
6016 /// property of the global object. Used to decide whether a store inside an
6017 /// `eval` writes through to the realm or declares a binding of its own.
6018 ///
6019 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
6020 /// write to `Object.prototype.toString`, and must not shadow it either.
6021 fn global_knows(&mut self, name: &str) -> bool {
6022 if self.realm.globals.contains_key(name) {
6023 return true;
6024 }
6025 self.realm.global.own_property(name).is_some()
6026 }
6027
6028 /// Whether the code currently running is strict.
6029 ///
6030 /// Read off the frame's function, which is where the parser's answer ended up; a
6031 /// native function never runs strict-only checks, and there is no frame at all
6032 /// before the first script.
6033 pub fn current_strict(&self) -> bool {
6034 self.frames
6035 .last()
6036 .is_some_and(|frame| frame.code.code.strict)
6037 }
6038
6039 /// Initialise a declared global, which is what ends its dead zone.
6040 ///
6041 /// A `var` global becomes a property of the global object: writable, so a later
6042 /// assignment goes through, and non-configurable, so `delete` refuses.
6043 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
6044 let (name, lexical, _) = self.global_binding(slot);
6045 // A `var` declared by the strict `eval` currently running belongs to the
6046 // eval's scope, not to the global object: `eval("var v = 1")` must not make
6047 // `typeof v` answer `"number"` afterwards. A name the realm already has is
6048 // initialised in place, which is what a re-declaration inside eval does.
6049 if !self.eval_scope.is_empty() && !lexical && !self.global_knows(&name) {
6050 self.eval_scope
6051 .last_mut()
6052 .expect("checked above")
6053 .insert(name, value);
6054 return Ok(());
6055 }
6056 for scope in self.eval_scope.iter_mut().rev() {
6057 if let Some(slot) = scope.get_mut(&name) {
6058 *slot = value;
6059 return Ok(());
6060 }
6061 }
6062 if lexical {
6063 // The cell exists (created at declaration time) holding the dead-zone
6064 // marker; storing the value is what makes the binding readable.
6065 if let Some(cell) = self.realm.globals.get(&name).cloned() {
6066 cell.set(value);
6067 return Ok(());
6068 }
6069 let cell = self.new_cell(value);
6070 self.realm.globals.insert(name, cell);
6071 return Ok(());
6072 }
6073 let global = self.realm.global.clone();
6074 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
6075 // to answer `false` and leave the binding in place. `with_attributes` ties
6076 // `configurable` to `writable`, so the property is built field by field.
6077 global.define(
6078 &name,
6079 Property {
6080 value: Some(value),
6081 writable: true,
6082 enumerable: true,
6083 configurable: false,
6084 ..Property::default()
6085 },
6086 );
6087 Ok(())
6088 }
6089
6090 /// The `TypeError` a store to a `const` global raises.
6091 fn read_only_global(&self, name: &str) -> Signal {
6092 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6093 }
6094
6095 /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
6096 fn dead_zone_global(&self, name: &str) -> Signal {
6097 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
6098 }
6099
6100 // -- properties ---------------------------------------------------------
6101
6102 /// Read `object[key]`, following the prototype chain.
6103 ///
6104 /// An inherited accessor runs with the *receiver* as `this`, which is why the
6105 /// lookup returns the owner rather than just the value.
6106 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
6107 self.get_property_key(object, &PropertyKey::from(key))
6108 }
6109
6110 /// [`Interp::get_property`] with a key that may be a symbol.
6111 pub fn get_property_key(
6112 &mut self,
6113 object: &Gc<JsObject>,
6114 key: &PropertyKey,
6115 ) -> JsResult<Option<Value>> {
6116 self.get_property_key_for(object, None, key)
6117 }
6118
6119 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
6120 ///
6121 /// The receiver matters when the property is found on a *prototype*: a getter has to
6122 /// see the object the read started from. For a primitive that is the primitive
6123 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
6124 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
6125 /// the owner.
6126 pub fn get_property_key_for(
6127 &mut self,
6128 object: &Gc<JsObject>,
6129 receiver: Option<&Value>,
6130 key: &PropertyKey,
6131 ) -> JsResult<Option<Value>> {
6132 // A proxy answers for itself, before any of the shortcuts below: `new
6133 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
6134 // have.
6135 if object.proxy_state().is_some() {
6136 let receiver = receiver
6137 .cloned()
6138 .unwrap_or_else(|| Value::Object(object.clone()));
6139 return self.proxy_get(object, &receiver, key);
6140 }
6141 // A host class's `get_property` trap replaces the whole read, prototype walk
6142 // included — that is what makes a native accessor free rather than a JavaScript
6143 // getter call.
6144 if let Some(exotic) = object.exotic() {
6145 let receiver_value = receiver
6146 .cloned()
6147 .unwrap_or_else(|| Value::Object(object.clone()));
6148 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
6149 return Ok(Some(value));
6150 }
6151 // With no `get_property` trap, a `get_own_property` trap still answers for the
6152 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
6153 // and the hook lives exactly there. A key the trap reports as absent is still
6154 // looked for on the prototype, which is why the search resumes *above*.
6155 if let Some(property) = exotic.get_own_property(self, object, key)? {
6156 return match property {
6157 Some(property) => self.read_property(property, object, receiver),
6158 None => match lookup_key_above(object, key) {
6159 Some((_, property)) => self.read_property(property, object, receiver),
6160 None => Ok(None),
6161 },
6162 };
6163 }
6164 }
6165 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
6166 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
6167 // The `[[Get]]` short-circuit therefore belongs to this one arm.
6168 //
6169 // Constructibility is exactly the split the reference makes: `function f(){}` and
6170 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
6171 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
6172 // function" — it *is* the predicate, which is why no extra marker is needed.
6173 if let Some(text) = key.as_str()
6174 && (text == "caller" || text == "arguments")
6175 && object.is_constructor()
6176 && object.is_callable()
6177 && !object.is_bound_function()
6178 // …and only when the body is **sloppy**. A strict body reaches the
6179 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
6180 // whole `Function/15.3.5.4_2-*gs` family is written against
6181 // (`onlyStrict`, so every function in them is strict).
6182 && !object.function_is_strict()
6183 && object.own_property(text).is_none()
6184 {
6185 return Ok(Some(Value::Undefined));
6186 }
6187 // The element-vector and `length` shortcuts are string-only: an array index
6188 // has no symbol spelling.
6189 if let Some(text) = key.as_str() {
6190 if let Some(value) = self.own_element(object, text) {
6191 return Ok(Some(value));
6192 }
6193 // `length` is not stored as a property: an array's length is its element
6194 // count, and keeping one copy of it is what makes `push`/`pop` and
6195 // `a.length = n` agree.
6196 if let Some(length) = object.array_length()
6197 && text == "length"
6198 {
6199 // Not `Value::Int(length as i32)`: see [`length_value`].
6200 return Ok(Some(crate::object::length_value(length)));
6201 }
6202 }
6203 // A proxy or a hooked exotic object anywhere above `object` makes the static
6204 // table walk below wrong: a proxy's own table is *empty by design* (the properties
6205 // live on its target), so the walk skipped that link entirely and everything behind
6206 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6207 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6208 // -target-is-proxy.js` are the four.
6209 if Self::chain_needs_dispatch(object) {
6210 return self.walk_get(object, receiver, key);
6211 }
6212 match lookup_key(object, key) {
6213 Some((_, property)) => self.read_property(property, object, receiver),
6214 None => Ok(None),
6215 }
6216 }
6217
6218 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6219 /// answer for itself.
6220 ///
6221 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6222 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6223 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6224 /// an inherited getter the object the read started from.
6225 fn walk_get(
6226 &mut self,
6227 start: &Gc<JsObject>,
6228 receiver: Option<&Value>,
6229 key: &PropertyKey,
6230 ) -> JsResult<Option<Value>> {
6231 let receiver = receiver
6232 .cloned()
6233 .unwrap_or_else(|| Value::Object(start.clone()));
6234 let mut current = Some(start.clone());
6235 while let Some(holder) = current {
6236 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6237 // has to ask it, not read its (empty) own-property table. `Object.create(new
6238 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6239 // instead found nothing.
6240 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6241 return Ok(Some(value));
6242 }
6243 // A host class's `get_property` trap replaces the whole read for that holder,
6244 // prototype walk included — the same rule `get_property_key_for` applies to the
6245 // first object.
6246 if let Some(exotic) = holder.exotic()
6247 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6248 {
6249 return Ok(Some(value));
6250 }
6251 if let Some(property) = self.object_get_own_property(&holder, key)? {
6252 return self.read_property(property, &holder, Some(&receiver));
6253 }
6254 current = self.object_prototype_of(&holder)?;
6255 }
6256 Ok(None)
6257 }
6258
6259 /// Whether `object` or anything above it has properties that cannot be read out of a
6260 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6261 ///
6262 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6263 /// is the hot path for every property read; this is the check that decides whether it
6264 /// is safe to take it.
6265 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6266 object
6267 .chain()
6268 .iter()
6269 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
6270 }
6271
6272 /// The value a property read answers.
6273 ///
6274 /// One place rather than three, because an accessor has to run with the *receiver* as
6275 /// `this` whether the descriptor came from the property table, an exotic
6276 /// `get_own_property` trap, or a prototype above one.
6277 fn read_property(
6278 &mut self,
6279 property: Property,
6280 object: &Gc<JsObject>,
6281 receiver: Option<&Value>,
6282 ) -> JsResult<Option<Value>> {
6283 if property.is_accessor() {
6284 match &property.getter {
6285 Some(getter) if !matches!(getter, Value::Undefined) => {
6286 let receiver = receiver
6287 .cloned()
6288 .unwrap_or_else(|| Value::Object(object.clone()));
6289 self.call_value(getter.clone(), receiver, Vec::new())
6290 .map(Some)
6291 }
6292 // An accessor with no getter reads as `undefined`.
6293 _ => Ok(Some(Value::Undefined)),
6294 }
6295 } else {
6296 Ok(property.value)
6297 }
6298 }
6299
6300 /// `super.key` — start the search at `proto`, but report to `receiver`.
6301 ///
6302 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6303 /// found on the prototype of a class has to see the *instance* as `this`, and a
6304 /// plain property read off `proto` would lose that.
6305 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6306 let start = self.require_object(proto)?;
6307 let key = self.propkey(key)?;
6308 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6309 if matches!(proto, Value::Null) {
6310 return Ok(Value::Undefined);
6311 }
6312 match lookup_key(&start, &key) {
6313 Some((_, property)) if property.is_accessor() => match &property.getter {
6314 Some(getter) if !matches!(getter, Value::Undefined) => {
6315 self.call_value(getter.clone(), receiver.clone(), Vec::new())
6316 }
6317 _ => Ok(Value::Undefined),
6318 },
6319 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6320 None => Ok(Value::Undefined),
6321 }
6322 }
6323
6324 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6325 ///
6326 /// A setter found on the prototype runs with `receiver` as `this`; a data property
6327 /// is shadowed by a new own property on the receiver, the same rule an ordinary
6328 /// assignment follows.
6329 fn super_write(
6330 &mut self,
6331 receiver: &Value,
6332 proto: &Value,
6333 key: &Value,
6334 value: Value,
6335 ) -> JsResult<()> {
6336 let target = self.require_object(receiver)?;
6337 let key = self.propkey(key)?;
6338 if !matches!(proto, Value::Null)
6339 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6340 {
6341 if property.is_accessor() {
6342 if let Some(setter) = &property.setter
6343 && !matches!(setter, Value::Undefined)
6344 {
6345 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6346 }
6347 return Ok(());
6348 }
6349 // A data property on the prototype is writable or not; reading `owner` at
6350 // all is only for the attribute check.
6351 if !property.writable {
6352 return Err(self.type_error(format!("'{key}' is read-only")));
6353 }
6354 let _ = owner;
6355 }
6356 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6357 }
6358
6359 /// The object a `super` operation needs, or the `TypeError` the spec raises.
6360 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6361 match value.as_object() {
6362 Some(object) => Ok(object.clone()),
6363 None => Err(Signal::Throw(
6364 self.make_error("TypeError", "value is not an object"),
6365 )),
6366 }
6367 }
6368
6369 /// Build the class object `define_class` produces.
6370 ///
6371 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6372 /// whose prototype property is a fresh object inheriting from the parent's
6373 /// prototype, and whose own prototype is the parent constructor — which is what makes
6374 /// a static method inherited too.
6375 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6376 let ctor = self.pop();
6377 let parent = self.pop();
6378 let Value::Object(function) = &ctor else {
6379 return Err(Signal::Throw(
6380 self.make_error("TypeError", "class constructor must be a function"),
6381 ));
6382 };
6383 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6384 // but gives the instances no prototype at all.
6385 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6386 match &parent {
6387 Value::Null => (Some(self.realm.function_proto.clone()), None),
6388 Value::Object(parent_class) => {
6389 // `IsConstructor`, not `IsCallable`: §15.7.14 ClassDefinitionEvaluation
6390 // step 9 rejects a heritage without `[[Construct]]` *before* reading
6391 // `superclass.prototype`, so an arrow function and a generator — both
6392 // callable, neither constructible — are a `TypeError` and their
6393 // `prototype` getter must never run
6394 // (`subclass/superclass-arrow-function`, `…-generator-function`).
6395 if !parent_class.is_constructor() {
6396 return Err(Signal::Throw(
6397 self.make_error("TypeError", "parent class must be constructor"),
6398 ));
6399 }
6400 let proto = self.get_property(parent_class, "prototype")?;
6401 match proto {
6402 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6403 Some(Value::Null) => (Some(parent_class.clone()), None),
6404 _ => {
6405 return Err(Signal::Throw(self.make_error(
6406 "TypeError",
6407 "parent prototype must be an object or null",
6408 )));
6409 }
6410 }
6411 }
6412 _ => {
6413 return Err(Signal::Throw(
6414 self.make_error("TypeError", "parent class must be constructor"),
6415 ));
6416 }
6417 }
6418 } else {
6419 (
6420 Some(self.realm.function_proto.clone()),
6421 Some(self.realm.object_proto.clone()),
6422 )
6423 };
6424 let proto = self.new_object(parent_proto);
6425 function.set_proto(parent_ctor);
6426 // A class is not callable without `new`, and its `prototype` is not writable —
6427 // both follow from being a class and are what `class A {}; A()` throws on.
6428 function.set_class_constructor(true);
6429 function.set_home_object(None);
6430 self.set_function_name(&ctor, name);
6431 self.define_class_properties(function, &ctor, &proto)?;
6432 Ok((ctor, proto))
6433 }
6434
6435 /// Give the constructor its `prototype` and `length`, and the prototype its
6436 /// `constructor` back-pointer.
6437 fn define_class_properties(
6438 &mut self,
6439 function: &Gc<JsObject>,
6440 ctor: &Value,
6441 proto: &Gc<JsObject>,
6442 ) -> JsResult<()> {
6443 proto.define(
6444 "constructor",
6445 Property::with_attributes(ctor.clone(), true, false),
6446 );
6447 function.define(
6448 "prototype",
6449 Property::prototype_of(Value::Object(proto.clone()), false),
6450 );
6451 if let Some((code, _)) = bytecode_of(function) {
6452 let length = code.code.defined_args;
6453 function.define(
6454 "length",
6455 Property::name_or_length(Value::Int(length as i32)),
6456 );
6457 }
6458 Ok(())
6459 }
6460
6461 /// The own array element `key` names, if this object has one.
6462 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6463 // A typed array's elements live in its buffer, not in a property list: reading one
6464 // goes through the view's element type so a bounds check and a detached buffer are
6465 // both handled there.
6466 //
6467 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6468 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6469 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6470 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6471 // consulted. Testing with `array_index` rejected all three, which let a throwing
6472 // getter installed on `TypedArray.prototype["-1"]` run.
6473 if object.typed_array_parts().is_some() {
6474 let property_key = PropertyKey::from(key);
6475 let numeric = canonical_numeric_index(&property_key)?;
6476 if typed_array_index_is_valid(object, numeric) {
6477 return object.typed_array_element(numeric as usize);
6478 }
6479 // Canonical, but not a valid index: `undefined`, and *final*.
6480 return Some(Value::Undefined);
6481 }
6482 let index = array_index(key)?;
6483 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6484 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6485 // search early, which is why `Array.prototype[1] = 9` could not be seen through
6486 // `[1,,3][1]`.
6487 match object.array_get(index as usize) {
6488 Some(Value::Hole) | None => None,
6489 other => other,
6490 }
6491 }
6492
6493 /// Store `object[key] = value`, honouring setters and inherited properties.
6494 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6495 self.set_property_with(object, key, value, DeleteFailure::Throw)
6496 }
6497
6498 /// Store a property, choosing what to do when the object refuses.
6499 ///
6500 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6501 /// mode, which is the one place assignment differs by mode. Native code (the array
6502 /// methods, `JSON`) always asks for the throw.
6503 pub fn set_property_with(
6504 &mut self,
6505 object: &Gc<JsObject>,
6506 key: &str,
6507 value: Value,
6508 on_failure: DeleteFailure,
6509 ) -> JsResult<()> {
6510 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6511 }
6512
6513 /// [`Interp::set_property_with`] with a key that may be a symbol.
6514 pub fn set_property_with_key(
6515 &mut self,
6516 object: &Gc<JsObject>,
6517 key: &PropertyKey,
6518 value: Value,
6519 on_failure: DeleteFailure,
6520 ) -> JsResult<()> {
6521 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6522 }
6523
6524 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6525 ///
6526 /// The receiver split lives one level up, in
6527 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6528 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6529 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6530 /// stores into `object` itself, which is why the element branch below converts `V`
6531 /// before asking whether the index is valid: `V` may put it back in bounds
6532 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6533 fn set_property_with_key_receiver_aware(
6534 &mut self,
6535 object: &Gc<JsObject>,
6536 key: &PropertyKey,
6537 value: Value,
6538 on_failure: DeleteFailure,
6539 ) -> JsResult<()> {
6540 // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6541 // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6542 // Nothing about the receiver or the value changes that, so the whole operation is
6543 // one answer.
6544 //
6545 // Not implementing it explicitly left the ordinary algorithm in charge, and that
6546 // says "true" for names the namespace does not own as soon as the value matches or
6547 // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6548 // assignment stopped throwing (`await-ns-set-strict`).
6549 if object.module_namespace_marker() {
6550 return match on_failure {
6551 DeleteFailure::Ignore => Ok(()),
6552 DeleteFailure::Throw => Err(self.type_error(format!(
6553 "cannot assign to property '{key}' of a module namespace object"
6554 ))),
6555 };
6556 }
6557 // A proxy's `set` trap decides, and its `false` means the same thing an
6558 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6559 if object.proxy_state().is_some() {
6560 let receiver = Value::Object(object.clone());
6561 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6562 return match (accepted, on_failure) {
6563 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6564 (false, DeleteFailure::Throw) => {
6565 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6566 }
6567 };
6568 }
6569 }
6570 // A host class's `set_property` trap decides for itself. `Some(false)` is a
6571 // refusal and means exactly what a proxy's `false` means.
6572 if let Some(exotic) = object.exotic() {
6573 let receiver = Value::Object(object.clone());
6574 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6575 return match (accepted, on_failure) {
6576 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6577 (false, DeleteFailure::Throw) => {
6578 Err(self.type_error(format!("property '{key}' is read-only")))
6579 }
6580 };
6581 }
6582 }
6583 // The element and `length` shortcuts only exist for string keys: an array
6584 // index has no symbol spelling, and a symbol named `length` is an ordinary
6585 // property.
6586 let text = key.as_str();
6587 // A typed array's elements are a window onto its buffer: the store has to go
6588 // through the view's element type so the value is wrapped (or clamped) and so an
6589 // out-of-range or detached write is a silent no-op, as the spec says.
6590 //
6591 // The key test is `CanonicalNumericIndexString`, like every other index operation
6592 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6593 // does not exist, so they do nothing and leave no own property behind
6594 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6595 // path, which created a property named `"-0"`.
6596 //
6597 // The conversion comes **first**, before the index is checked at all, and that
6598 // order is observable twice over:
6599 //
6600 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6601 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6602 // then store the converted value;
6603 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6604 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6605 // run and its exception to escape.
6606 //
6607 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6608 // validity check, not a validity check that skips the conversion. The store itself
6609 // is a no-op when the index is invalid by then, which is why no extra guard is
6610 // needed around `typed_array_set`.
6611 if let Some(element) = object.typed_array_element_type()
6612 && let Some(numeric) = canonical_numeric_index(key)
6613 {
6614 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6615 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6616 // in `Interp`, because it is script-observable and the storage borrow inside
6617 // `typed_array_set` must not be held across it.
6618 let stored = self.element_value(element, value)?;
6619 if typed_array_index_is_valid(object, numeric)
6620 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6621 {
6622 return Err(self.type_error(reason));
6623 }
6624 return Ok(());
6625 }
6626 if let Some(text) = text
6627 && let Some(index) = array_index(text)
6628 && object.is_array()
6629 {
6630 // An accessor defined on an index lives in the property table while the
6631 // element slot is a hole, so the store has to go through the property first.
6632 // Writing the vector directly skipped the setter entirely.
6633 if let Some(existing) = object.own_property_key(key) {
6634 if existing.is_accessor() {
6635 return match existing.setter.clone() {
6636 Some(setter) if !matches!(setter, Value::Undefined) => {
6637 let receiver = Value::Object(object.clone());
6638 self.call_value(setter, receiver, vec![value]).map(|_| ())
6639 }
6640 _ => match on_failure {
6641 DeleteFailure::Throw => Err(self.type_error(format!(
6642 "cannot set property '{text}', it has only a getter"
6643 ))),
6644 DeleteFailure::Ignore => Ok(()),
6645 },
6646 };
6647 }
6648 if !existing.writable {
6649 return match on_failure {
6650 DeleteFailure::Throw => {
6651 Err(self.type_error(format!("'{text}' is read-only")))
6652 }
6653 DeleteFailure::Ignore => Ok(()),
6654 };
6655 }
6656 }
6657 {
6658 // Growing the array needs a writable `length`.
6659 if (index as usize) >= object.array_length().unwrap_or(0)
6660 && !object.length_writable()
6661 {
6662 return match on_failure {
6663 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6664 DeleteFailure::Ignore => Ok(()),
6665 };
6666 }
6667 // Adding an index past the end makes the array longer, which a
6668 // non-extensible array refuses.
6669 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6670 return match on_failure {
6671 DeleteFailure::Throw => Err(self.type_error(format!(
6672 "cannot add property '{key}', object is not extensible"
6673 ))),
6674 DeleteFailure::Ignore => Ok(()),
6675 };
6676 }
6677 if object.element_is_locked(index) {
6678 return match on_failure {
6679 DeleteFailure::Throw => {
6680 Err(self.type_error(format!("'{key}' is read-only")))
6681 }
6682 DeleteFailure::Ignore => Ok(()),
6683 };
6684 }
6685 // The element vector is only half of `[[Set]]` for an index: the
6686 // prototype chain is consulted first, and a setter there answers instead
6687 // of the element store. This branch used to write the element directly, so
6688 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6689 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6690 // the reference calls the setter and the array keeps no own index.
6691 //
6692 // An *exotic* prototype has no entry to find, because its indices live
6693 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6694 // then looked like "nothing on the chain" and the store created the
6695 // element, where the view's `[[Set]]` answers `true` and does nothing for
6696 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6697 // checks the array's `length` stays 0). So the dispatch comes first.
6698 if !object.has_own_key(key)
6699 && let Some(proto) = object.proto()
6700 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6701 {
6702 let receiver = Value::Object(object.clone());
6703 let accepted =
6704 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6705 return if accepted {
6706 Ok(())
6707 } else {
6708 match on_failure {
6709 DeleteFailure::Throw => {
6710 Err(self.type_error(format!("'{key}' is read-only")))
6711 }
6712 DeleteFailure::Ignore => Ok(()),
6713 }
6714 };
6715 }
6716 if let Some((owner, property)) = lookup_key(object, key)
6717 && !owner.ptr_eq(object)
6718 {
6719 match &property {
6720 property if property.is_accessor() => {
6721 match &property.setter {
6722 Some(setter) if !matches!(setter, Value::Undefined) => {
6723 let receiver = Value::Object(object.clone());
6724 self.call_value(setter.clone(), receiver, vec![value])?;
6725 }
6726 _ => {
6727 return match on_failure {
6728 DeleteFailure::Throw => Err(self.type_error(format!(
6729 "cannot set property '{text}', it has only a getter"
6730 ))),
6731 DeleteFailure::Ignore => Ok(()),
6732 };
6733 }
6734 }
6735 return Ok(());
6736 }
6737 property if !property.writable => {
6738 return match on_failure {
6739 DeleteFailure::Throw => {
6740 Err(self.type_error(format!("'{text}' is read-only")))
6741 }
6742 DeleteFailure::Ignore => Ok(()),
6743 };
6744 }
6745 _ => {}
6746 }
6747 }
6748 if object.array_set(self.heap, index as usize, value.clone()) {
6749 return Ok(());
6750 }
6751 // Past the dense limit the slot is too far out to be worth one `Value`
6752 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6753 // constant time by keeping the index as an ordinary property. The store
6754 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6755 // to a legal program.
6756 object.define_key(key, Property::with_attributes(value, true, true));
6757 // Extend, never shorten: the index may be *inside* the current length (a
6758 // huge `length` with a sparse store), and shortening would delete the
6759 // sparse properties above it — including the one just stored.
6760 if index as usize + 1 > object.array_length().unwrap_or(0) {
6761 object.array_set_length(self.heap, index as usize + 1);
6762 }
6763 return Ok(());
6764 }
6765 }
6766 if text == Some("length") && object.is_array() {
6767 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6768 // test. A `valueOf` that locks `length` on its second call therefore turns the
6769 // store into a refused write rather than a silent success
6770 // (`length/define-own-prop-length-coercion-order-set`).
6771 let rounded = self.coerce_array_length_twice(&value)?;
6772 if !object.length_writable() {
6773 return match on_failure {
6774 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6775 DeleteFailure::Ignore => Ok(()),
6776 };
6777 }
6778 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6779 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6780 // answered `NaN`, which left the assignment silently ignored
6781 // (`S15.4.5.2_A3_T2`).
6782 let _ = rounded;
6783 let length = self.to_js_number(&value)?;
6784 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6785 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6786 // `RangeError`s; the old code only tested "finite and non-negative" and then
6787 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6788 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6789 let valid = length.is_finite()
6790 && length >= 0.0
6791 && length.fract() == 0.0
6792 && length <= u32::MAX as f64;
6793 if !valid {
6794 return Err(self.range_error("invalid array length"));
6795 }
6796 {
6797 let length = length as usize;
6798 // `a.length = n` with `n` below a non-configurable element cannot
6799 // drop that element, so the whole assignment fails. The spec makes
6800 // this a `TypeError` rather than a silent no-op, in any mode.
6801 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6802 // Sloppy mode stops the truncation at the blocking element
6803 // instead of failing; strict mode raises.
6804 // Both modes stop at the blocking element; they differ in
6805 // whether that is reported. The reference truncates *then*
6806 // throws, so the array is left in the shortened state.
6807 object.array_truncate(self.heap, blocked + 1);
6808 return match on_failure {
6809 DeleteFailure::Throw => {
6810 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6811 }
6812 DeleteFailure::Ignore => Ok(()),
6813 };
6814 }
6815 object.array_set_length(self.heap, length);
6816 return Ok(());
6817 }
6818 }
6819 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6820 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6821 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6822 //
6823 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6824 // applying whatever came back is the same thing for an ordinary prototype and
6825 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6826 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6827 // answers "not mine, the receiver is not me" without touching the buffer. This
6828 // code used to find nothing owned by `o`, find no property on the view either,
6829 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6830 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6831 // `key-is-canonical-invalid-index-prototype-chain-set`).
6832 //
6833 // The read-only and accessor rules of step 1 are what make
6834 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6835 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6836 let own = match self.lookup_for_write(object, key)? {
6837 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6838 _ => None,
6839 };
6840 if let Some(property) = own {
6841 if property.is_accessor() {
6842 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6843 Some(setter) => {
6844 let receiver = Value::Object(object.clone());
6845 self.call_value(setter, receiver, vec![value])?;
6846 Ok(())
6847 }
6848 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6849 // Sloppy code swallows that refusal, strict code raises — the same
6850 // rule the read-only *data* property below follows, and skipping it
6851 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6852 // return silently. The reference answers `TypeError: 'x' is
6853 // read-only`.
6854 None => match on_failure {
6855 DeleteFailure::Throw => {
6856 Err(self.type_error(format!("'{key}' is read-only")))
6857 }
6858 DeleteFailure::Ignore => Ok(()),
6859 },
6860 };
6861 }
6862 // An own non-writable data property stops here: nothing may change it.
6863 if !property.writable {
6864 return match on_failure {
6865 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6866 DeleteFailure::Ignore => Ok(()),
6867 };
6868 }
6869 // An existing writable own property keeps its attributes: only the value
6870 // moves. Redefining instead would reset them, which is how a
6871 // non-configurable global `var` used to become deletable.
6872 if object.write_value_key(key, value.clone()) {
6873 return Ok(());
6874 }
6875 }
6876 // Step 2: hand the store to the prototype, with `object` as the receiver.
6877 if let Some(proto) = object.proto() {
6878 let receiver = Value::Object(object.clone());
6879 let accepted =
6880 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6881 return if accepted {
6882 Ok(())
6883 } else {
6884 match on_failure {
6885 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6886 DeleteFailure::Ignore => Ok(()),
6887 }
6888 };
6889 }
6890 // Step 3: create one, and a non-extensible object cannot.
6891 if !object.is_extensible() {
6892 return match on_failure {
6893 DeleteFailure::Throw => Err(self.type_error(format!(
6894 "cannot add property {key}, object is not extensible"
6895 ))),
6896 DeleteFailure::Ignore => Ok(()),
6897 };
6898 }
6899 object.define_data_key(key, value);
6900 Ok(())
6901 }
6902
6903 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6904 ///
6905 /// The distinction the fast path above does not need: it is called with the store's
6906 /// receiver already being the object it writes to. Here `object` is the one whose
6907 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6908 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6909 /// and not a write to `object`.
6910 ///
6911 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6912 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6913 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6914 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6915 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6916 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6917 ///
6918 /// Answers `false` where the spec says `false`; the caller turns that into the
6919 /// strict-mode `TypeError` or the sloppy-mode silence.
6920 fn ordinary_set_with_receiver(
6921 &mut self,
6922 object: &Gc<JsObject>,
6923 receiver: &Value,
6924 key: &PropertyKey,
6925 value: Value,
6926 on_failure: DeleteFailure,
6927 ) -> JsResult<bool> {
6928 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6929 if object.proxy_state().is_some() {
6930 return Ok(self
6931 .proxy_set(object, key, value, receiver)?
6932 .unwrap_or(true));
6933 }
6934 // A host class decides for itself, with the receiver the caller named.
6935 if let Some(exotic) = object.exotic()
6936 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6937 {
6938 return Ok(accepted);
6939 }
6940 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6941 // rather than the receiver, but the receiver may still *be* the view:
6942 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6943 // itself as receiver, and then the first half applies — convert `V` once, store
6944 // if the index is valid, answer `true` either way. The conversion is the observable
6945 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6946 //
6947 // Only the second half, a view that is *not* the receiver, skips the conversion
6948 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6949 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6950 // below with the value still unconverted.
6951 if object.typed_array_element_type().is_some()
6952 && let Some(numeric) = canonical_numeric_index(key)
6953 {
6954 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6955 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6956 return Ok(true);
6957 }
6958 if !typed_array_index_is_valid(object, numeric) {
6959 return Ok(true);
6960 }
6961 }
6962 let own = self.object_get_own_property(object, key)?;
6963 if let Some(own) = own {
6964 if own.is_accessor() {
6965 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6966 Some(setter) => {
6967 self.call_value(setter, receiver.clone(), vec![value])?;
6968 Ok(true)
6969 }
6970 None => Ok(false),
6971 };
6972 }
6973 // A non-writable data descriptor refuses, own or inherited. Either way the
6974 // receiver must not gain a shadowing property.
6975 if !own.writable {
6976 return Ok(false);
6977 }
6978 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6979 // created or written, and it is created as an ordinary data property.
6980 let Some(receiver_object) = receiver.as_object().cloned() else {
6981 return Ok(false);
6982 };
6983 return match self.object_get_own_property(&receiver_object, key)? {
6984 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6985 Some(existing) => self.object_define_own_property(
6986 &receiver_object,
6987 key,
6988 Property {
6989 value: Some(value),
6990 ..existing
6991 },
6992 ),
6993 None => {
6994 self.object_define_own_property(&receiver_object, key, Property::data(value))
6995 }
6996 };
6997 }
6998 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6999 if let Some(proto) = object.proto() {
7000 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
7001 }
7002 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
7003 // *default* data descriptor here, so control falls into step 2 exactly as if the
7004 // target had owned a writable property — which means the **receiver's** own
7005 // descriptor is asked for before the write. Skipping that question went straight to
7006 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
7007 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
7008 // exactly those calls).
7009 let Some(receiver_object) = receiver.as_object().cloned() else {
7010 return Ok(false);
7011 };
7012 match self.object_get_own_property(&receiver_object, key)? {
7013 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
7014 Some(existing) => self.object_define_own_property(
7015 &receiver_object,
7016 key,
7017 Property {
7018 value: Some(value),
7019 ..existing
7020 },
7021 ),
7022 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
7023 }
7024 }
7025
7026 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
7027 ///
7028 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
7029 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
7030 /// a virtual accessor gets its setter run without implementing `set_property` at all.
7031 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
7032 /// the prototype, so the walk resumes above the object.
7033 fn lookup_for_write(
7034 &mut self,
7035 object: &Gc<JsObject>,
7036 key: &PropertyKey,
7037 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
7038 let Some(exotic) = object.exotic() else {
7039 return Ok(lookup_key(object, key));
7040 };
7041 Ok(match exotic.get_own_property(self, object, key)? {
7042 Some(Some(property)) => Some((object.clone(), property)),
7043 Some(None) => lookup_key_above(object, key),
7044 None => lookup_key(object, key),
7045 })
7046 }
7047
7048 /// Delete `object[key]`.
7049 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
7050 self.delete_property_key(object, &PropertyKey::from(key))
7051 }
7052
7053 /// [`Interp::delete_property`] with a key that may be a symbol.
7054 pub fn delete_property_key(
7055 &mut self,
7056 object: &Gc<JsObject>,
7057 key: &PropertyKey,
7058 ) -> JsResult<bool> {
7059 // A proxy decides for itself, and may even throw; the invariant checks live in
7060 // `proxy_delete`.
7061 if let Some(answer) = self.proxy_delete(object, key)? {
7062 return Ok(answer);
7063 }
7064 // A host class's `delete_property` trap decides; `false` is a refusal, which the
7065 // caller reports as a failed delete.
7066 if let Some(exotic) = object.exotic()
7067 && let Some(answer) = exotic.delete_property(self, object, key)?
7068 {
7069 return Ok(answer);
7070 }
7071 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
7072 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
7073 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
7074 // one answers `false` because the elements are non-configurable. The prototype
7075 // chain is not consulted either, which is what makes a throwing getter on
7076 // `TypedArray.prototype["-1"]` stay unrun.
7077 if object.typed_array_parts().is_some()
7078 && object.proxy_state().is_none()
7079 && let Some(numeric) = canonical_numeric_index(key)
7080 {
7081 return Ok(!typed_array_index_is_valid(object, numeric));
7082 }
7083 let mapped_index = key.as_str().and_then(array_index);
7084 if let Some(index) = mapped_index
7085 && let Some(length) = object.array_length()
7086 && (index as usize) < length
7087 {
7088 // An accessor defined on an index lives in the property table rather than the
7089 // element vector, so both have to be cleared: `delete` after
7090 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
7091 object.delete_key(key);
7092 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
7093 // index stops answering `in`.
7094 if object.element_is_undeletable(index) {
7095 return Ok(false);
7096 }
7097 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
7098 // so a later `defineProperty(arguments, "0", {value})` writes to the object
7099 // and no longer through to the parameter. A refused delete leaves the
7100 // mapping alone.
7101 object.drop_mapped_argument(index as usize);
7102 object.array_set(self.heap, index as usize, Value::Hole);
7103 return Ok(true);
7104 }
7105 // An array's `length` is a non-configurable own property that lives outside the
7106 // property table, so `delete_key` finds nothing and reports success — `Reflect
7107 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
7108 // §10.4.4.1 step 3 refuses it.
7109 if key.as_str() == Some("length") && object.array_length().is_some() {
7110 return Ok(false);
7111 }
7112 // The same for an object that is not an array: only a delete that actually
7113 // removed the property ends the alias.
7114 let deleted = object.delete_key(key);
7115 if deleted && let Some(index) = mapped_index {
7116 object.drop_mapped_argument(index as usize);
7117 }
7118 Ok(deleted)
7119 }
7120
7121 // -- proxy traps --------------------------------------------------------
7122 //
7123 // A proxy's internal methods all look the same: ask the handler for the trap, call it
7124 // with the target and the operation's own arguments, then check the answer against
7125 // the target. The checks are not decoration — they are what stops a proxy from
7126 // reporting a `non-configurable` property as missing, which would let a frozen object
7127 // be rewritten by standing in front of it.
7128
7129 /// The target and handler of `object`, or `None` when it is not a proxy.
7130 ///
7131 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
7132 /// one has to fail: the slots the traps would have been read from are gone.
7133 pub(crate) fn proxy_parts(
7134 &mut self,
7135 object: &Gc<JsObject>,
7136 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
7137 let Some(state) = object.proxy_state() else {
7138 return Ok(None);
7139 };
7140 let state = state.borrow();
7141 match (&state.target, &state.handler) {
7142 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
7143 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
7144 }
7145 }
7146
7147 /// Call `handler[name]`, or answer `None` when the trap is absent.
7148 ///
7149 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
7150 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
7151 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
7152 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
7153 /// one per trap plus the `target-is-proxy` variants.
7154 ///
7155 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
7156 /// this cannot simply be "any non-callable means no trap".
7157 fn proxy_trap(
7158 &mut self,
7159 handler: &Value,
7160 name: &str,
7161 args: Vec<Value>,
7162 ) -> JsResult<Option<Value>> {
7163 let Value::Object(table) = handler else {
7164 return Err(self.type_error("proxy handler is not an object"));
7165 };
7166 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
7167 match trap {
7168 Value::Undefined | Value::Null => Ok(None),
7169 Value::Object(function) if function.is_callable() => {
7170 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
7171 Ok(Some(answer))
7172 }
7173 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
7174 }
7175 }
7176
7177 /// Whether the target's own property `key` is one it refuses to lose.
7178 ///
7179 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
7180 /// its value behind the target's back.
7181 ///
7182 /// A **method**, not a free function, because §10.5.1's invariants say
7183 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
7184 /// property table directly finds nothing (a proxy's table is empty by design), so every
7185 /// invariant check silently passed for a proxy target. That is what
7186 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
7187 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
7188 /// where an array's elements and its `length` — both fixed, both outside the table —
7189 /// are covered.
7190 fn fixed_property(
7191 &mut self,
7192 target: &Gc<JsObject>,
7193 key: &PropertyKey,
7194 ) -> JsResult<Option<Property>> {
7195 Ok(self
7196 .object_get_own_property(target, key)?
7197 .filter(|property| !property.configurable))
7198 }
7199
7200 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7201 fn proxy_get(
7202 &mut self,
7203 object: &Gc<JsObject>,
7204 receiver: &Value,
7205 key: &PropertyKey,
7206 ) -> JsResult<Option<Value>> {
7207 let Some((target, handler)) = self.proxy_parts(object)? else {
7208 return Ok(None);
7209 };
7210 let key_value = self.key_value(key);
7211 let Some(result) = self.proxy_trap(
7212 &handler,
7213 "get",
7214 vec![Value::Object(target.clone()), key_value, receiver.clone()],
7215 )?
7216 else {
7217 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7218 // inherited getter still sees the proxy.
7219 return Ok(Some(
7220 self.get_property_key_for(&target, Some(receiver), key)?
7221 .unwrap_or(Value::Undefined),
7222 ));
7223 };
7224 if let Some(fixed) = self.fixed_property(&target, key)? {
7225 if fixed.is_accessor() {
7226 // A fixed accessor with no getter must read as `undefined`.
7227 let has_getter = fixed
7228 .getter
7229 .as_ref()
7230 .is_some_and(|getter| !matches!(getter, Value::Undefined));
7231 if !has_getter && !matches!(result, Value::Undefined) {
7232 return Err(self.type_error(format!(
7233 "proxy 'get' must report undefined for the non-configurable property '{key}'"
7234 )));
7235 }
7236 } else if !fixed.writable {
7237 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7238 if !fixed_value.same_value(&result) {
7239 return Err(self.type_error(format!(
7240 "proxy 'get' disagrees with the non-configurable property '{key}'"
7241 )));
7242 }
7243 }
7244 }
7245 Ok(Some(result))
7246 }
7247
7248 /// `[[Set]]` on a proxy.
7249 ///
7250 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7251 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7252 /// read-only store has.
7253 fn proxy_set(
7254 &mut self,
7255 object: &Gc<JsObject>,
7256 key: &PropertyKey,
7257 value: Value,
7258 receiver: &Value,
7259 ) -> JsResult<Option<bool>> {
7260 let Some((target, handler)) = self.proxy_parts(object)? else {
7261 return Ok(None);
7262 };
7263 let key_value = self.key_value(key);
7264 let Some(result) = self.proxy_trap(
7265 &handler,
7266 "set",
7267 vec![
7268 Value::Object(target.clone()),
7269 key_value,
7270 value.clone(),
7271 receiver.clone(),
7272 ],
7273 )?
7274 else {
7275 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7276 // given — not the target. `OrdinarySet` step 3 is
7277 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7278 // object whose prototype is a typed array has to reach the proxy's own
7279 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7280 // calls and expects exactly one. Storing on the target instead put the value
7281 // in the target and never consulted the trap.
7282 let accepted = self.ordinary_set_with_receiver(
7283 &target,
7284 receiver,
7285 key,
7286 value,
7287 DeleteFailure::Ignore,
7288 )?;
7289 return Ok(Some(accepted));
7290 };
7291 if !result.to_boolean() {
7292 return Ok(Some(false));
7293 }
7294 if let Some(fixed) = self.fixed_property(&target, key)? {
7295 if fixed.is_accessor() {
7296 let has_setter = fixed
7297 .setter
7298 .as_ref()
7299 .is_some_and(|setter| !matches!(setter, Value::Undefined));
7300 if !has_setter {
7301 return Err(self.type_error(format!(
7302 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7303 )));
7304 }
7305 } else if !fixed.writable {
7306 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7307 if !fixed_value.same_value(&value) {
7308 return Err(self.type_error(format!(
7309 "proxy 'set' changed the non-configurable property '{key}'"
7310 )));
7311 }
7312 }
7313 }
7314 // A new property cannot appear on a target that refuses new properties.
7315 if self.object_get_own_property(&target, key)?.is_none()
7316 && !self.object_is_extensible(&target)?
7317 {
7318 return Err(self.type_error(format!(
7319 "proxy 'set' added '{key}' to a non-extensible target"
7320 )));
7321 }
7322 Ok(Some(true))
7323 }
7324
7325 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7326 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7327 let Some((target, handler)) = self.proxy_parts(object)? else {
7328 return Ok(None);
7329 };
7330 let key_value = self.key_value(key);
7331 let Some(result) = self.proxy_trap(
7332 &handler,
7333 "has",
7334 vec![Value::Object(target.clone()), key_value],
7335 )?
7336 else {
7337 return Ok(Some(self.has_own_or_inherited(&target, key)?));
7338 };
7339 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7340 return Err(self.type_error(format!(
7341 "proxy 'has' denied the non-configurable property '{key}'"
7342 )));
7343 }
7344 // A non-extensible target cannot grow, so every own property it *has* is fixed.
7345 if !result.to_boolean()
7346 && !self.object_is_extensible(&target)?
7347 && self.object_get_own_property(&target, key)?.is_some()
7348 {
7349 return Err(self.type_error(format!(
7350 "proxy 'has' denied the own property '{key}' of a non-extensible target"
7351 )));
7352 }
7353 Ok(Some(result.to_boolean()))
7354 }
7355
7356 /// `[[Delete]]` on a proxy.
7357 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7358 let Some((target, handler)) = self.proxy_parts(object)? else {
7359 return Ok(None);
7360 };
7361 let key_value = self.key_value(key);
7362 let Some(result) = self.proxy_trap(
7363 &handler,
7364 "deleteProperty",
7365 vec![Value::Object(target.clone()), key_value],
7366 )?
7367 else {
7368 return Ok(Some(self.delete_property_key(&target, key)?));
7369 };
7370 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7371 return Err(self.type_error(format!(
7372 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7373 )));
7374 }
7375 if result.to_boolean()
7376 && !self.object_is_extensible(&target)?
7377 && self.object_get_own_property(&target, key)?.is_some()
7378 {
7379 return Err(self.type_error(format!(
7380 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7381 )));
7382 }
7383 Ok(Some(result.to_boolean()))
7384 }
7385
7386 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7387 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7388 let Some((target, handler)) = self.proxy_parts(object)? else {
7389 return Ok(None);
7390 };
7391 let Some(result) =
7392 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7393 else {
7394 // No trap: the target's own keys, already in the order an object reports.
7395 return Ok(Some(self.object_own_property_keys(&target)?));
7396 };
7397 // `CreateListFromArrayLike` with the string-or-symbol restriction.
7398 let list = self.list_from_array_like(&result, true)?;
7399 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7400 for value in list {
7401 let key = self.propkey(&value)?;
7402 if keys.contains(&key) {
7403 return Err(self.type_error(format!(
7404 "proxy 'ownKeys' returned the duplicate key '{key}'"
7405 )));
7406 }
7407 keys.push(key);
7408 }
7409 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7410 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7411 // table is empty, which made every check below vacuous.
7412 let target_keys = self.object_own_property_keys(&target)?;
7413 let extensible = self.object_is_extensible(&target)?;
7414 for key in &target_keys {
7415 if keys.contains(key) {
7416 continue;
7417 }
7418 if self.fixed_property(&target, key)?.is_some() {
7419 return Err(self.type_error(format!(
7420 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7421 )));
7422 }
7423 if !extensible {
7424 return Err(self.type_error(format!(
7425 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7426 )));
7427 }
7428 }
7429 if !extensible {
7430 // §10.5.11 step 12: the lists must match one for one, in any order.
7431 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7432 {
7433 return Err(
7434 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7435 );
7436 }
7437 }
7438 Ok(Some(keys))
7439 }
7440
7441 /// `[[GetOwnProperty]]` on a proxy.
7442 fn proxy_get_own_property(
7443 &mut self,
7444 object: &Gc<JsObject>,
7445 key: &PropertyKey,
7446 ) -> JsResult<Option<Option<Property>>> {
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 "getOwnPropertyDescriptor",
7454 vec![Value::Object(target.clone()), key_value],
7455 )?
7456 else {
7457 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7458 // property table. Two things ride on that choice: a target that is itself a
7459 // proxy has to re-dispatch (its own table is empty, so reading it reported
7460 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7461 // indices and `length` live outside the table and need the ordinary synthesis.
7462 // `object_get_own_property` does both.
7463 return Ok(Some(self.object_get_own_property(&target, key)?));
7464 };
7465 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7466 // `ToPropertyDescriptor` runs, because that operation would box the primitive
7467 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7468 // empty descriptor instead of refusing.
7469 if !matches!(result, Value::Undefined | Value::Object(_)) {
7470 return Err(self.type_error(
7471 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7472 ));
7473 }
7474 let target_desc = self.object_get_own_property(&target, key)?;
7475 let extensible = self.object_is_extensible(&target)?;
7476 let Some(descriptor) = (match result {
7477 Value::Undefined => None,
7478 _ => Some(self.property_from_descriptor(&result)?),
7479 }) else {
7480 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7481 // descriptor is configurable *and* the target can still grow back.
7482 if let Some(target_desc) = &target_desc {
7483 if !target_desc.configurable {
7484 return Err(self.type_error(format!(
7485 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7486 )));
7487 }
7488 if !extensible {
7489 return Err(self.type_error(format!(
7490 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7491 )));
7492 }
7493 }
7494 return Ok(Some(None));
7495 };
7496 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7497 // which is a stronger requirement than "the target is not contradicting it" — the
7498 // four branches below are each one test262 case.
7499 if !descriptor.configurable {
7500 let Some(target_desc) = &target_desc else {
7501 return Err(self.type_error(format!(
7502 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7503 )));
7504 };
7505 if target_desc.configurable {
7506 return Err(self.type_error(format!(
7507 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7508 )));
7509 }
7510 let target_is_data = !target_desc.is_accessor();
7511 let result_is_data = !descriptor.is_accessor();
7512 if result_is_data && !target_is_data {
7513 return Err(self.type_error(format!(
7514 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7515 )));
7516 }
7517 if target_is_data && !target_desc.writable {
7518 if !result_is_data {
7519 return Err(self.type_error(format!(
7520 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7521 )));
7522 }
7523 if descriptor.writable {
7524 return Err(self.type_error(format!(
7525 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7526 )));
7527 }
7528 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7529 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7530 if !fixed_value.same_value(&reported) {
7531 return Err(self.type_error(format!(
7532 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7533 )));
7534 }
7535 }
7536 // Step 16.d: a reported *read-only* data property needs a real read-only data
7537 // property behind it. Missing this let a trap bolt a frozen property onto a
7538 // writable target intent (`resultdesc-is-not-configurable-not-writable-
7539 // targetdesc-is-writable`).
7540 if result_is_data && !descriptor.writable {
7541 if !target_is_data {
7542 return Err(self.type_error(format!(
7543 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7544 )));
7545 }
7546 if target_desc.writable {
7547 return Err(self.type_error(format!(
7548 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7549 )));
7550 }
7551 }
7552 if descriptor.is_accessor() {
7553 // Step 16.e: a getter the target does not have may not be invented, and
7554 // vice versa.
7555 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7556 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7557 (Some(a), Some(b)) => a.same_value(b),
7558 _ => false,
7559 };
7560 if !same(&target_desc.getter, &descriptor.getter)
7561 || !same(&target_desc.setter, &descriptor.setter)
7562 {
7563 return Err(self.type_error(format!(
7564 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7565 )));
7566 }
7567 }
7568 }
7569 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7570 // where the target's own is locked. Without it a handler could advertise
7571 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7572 // that believed it would try to redefine something it cannot.
7573 if descriptor.configurable
7574 && let Some(target_desc) = &target_desc
7575 && !target_desc.configurable
7576 {
7577 return Err(self.type_error(format!(
7578 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7579 )));
7580 }
7581 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7582 // through the trap either, however well-formed the descriptor is. This is the
7583 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7584 // the frozen target does not own.
7585 if !extensible {
7586 let Some(target_desc) = &target_desc else {
7587 return Err(self.type_error(format!(
7588 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7589 )));
7590 };
7591 if target_desc.is_accessor() == descriptor.is_accessor() {
7592 let target_is_data = !target_desc.is_accessor();
7593 let result_is_data = !descriptor.is_accessor();
7594 if target_is_data && !target_desc.writable && descriptor.writable {
7595 return Err(self.type_error(format!(
7596 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7597 )));
7598 }
7599 if !result_is_data && !target_is_data {
7600 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7601 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7602 (Some(a), Some(b)) => a.same_value(b),
7603 _ => false,
7604 };
7605 if !same(&target_desc.getter, &descriptor.getter)
7606 || !same(&target_desc.setter, &descriptor.setter)
7607 {
7608 return Err(self.type_error(format!(
7609 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7610 )));
7611 }
7612 }
7613 }
7614 }
7615 Ok(Some(Some(descriptor)))
7616 }
7617
7618 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7619 ///
7620 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7621 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7622 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7623 /// for a data property. `Property` cannot express "this field is absent", so the whole
7624 /// property path is skipped and the descriptor is assembled here field by field.
7625 ///
7626 /// `current` is the property the trap reported, used only to tell a data property from
7627 /// an accessor.
7628 pub fn proxy_seal_property(
7629 &mut self,
7630 object: &Gc<JsObject>,
7631 key: &PropertyKey,
7632 frozen: bool,
7633 current: &Property,
7634 ) -> JsResult<bool> {
7635 let Some((_target, handler)) = self.proxy_parts(object)? else {
7636 return Err(self.type_error("not a proxy"));
7637 };
7638 let descriptor = self.new_object(None);
7639 descriptor.define_data("configurable", Value::Bool(false));
7640 if frozen && !current.is_accessor() {
7641 descriptor.define_data("writable", Value::Bool(false));
7642 }
7643 let key_value = self.key_value(key);
7644 let target = object
7645 .proxy_state()
7646 .and_then(|state| state.borrow().target.clone());
7647 let Some(target) = target else {
7648 return Err(self.type_error("cannot use a proxy that has been revoked"));
7649 };
7650 let Some(result) = self.proxy_trap(
7651 &handler,
7652 "defineProperty",
7653 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7654 )?
7655 else {
7656 // No trap means the definition belongs to the target; `false` is its answer.
7657 return Ok(false);
7658 };
7659 Ok(result.to_boolean())
7660 }
7661
7662 /// `[[DefineOwnProperty]]` on a proxy.
7663 fn proxy_define_property(
7664 &mut self,
7665 object: &Gc<JsObject>,
7666 key: &PropertyKey,
7667 property: Property,
7668 ) -> JsResult<Option<bool>> {
7669 let Some((target, handler)) = self.proxy_parts(object)? else {
7670 return Ok(None);
7671 };
7672 let key_value = self.key_value(key);
7673 let descriptor = self.descriptor_from_property(&property);
7674 let Some(result) = self.proxy_trap(
7675 &handler,
7676 "defineProperty",
7677 vec![Value::Object(target.clone()), key_value, descriptor],
7678 )?
7679 else {
7680 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7681 // going" answer and `object_define_own_property` turns it into exactly that
7682 // forwarding — see the note there. (Reading it as "not a proxy" would define
7683 // the property on the proxy object itself, whose table is empty and which no
7684 // read ever consults.)
7685 return Ok(None);
7686 };
7687 if !result.to_boolean() {
7688 return Ok(Some(false));
7689 }
7690 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7691 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7692 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7693 // and treating them alike made four cases pass a descriptor the target contradicts.
7694 let target_desc = self.object_get_own_property(&target, key)?;
7695 let extensible = self.object_is_extensible(&target)?;
7696 let named = property
7697 .descriptor_fields
7698 .unwrap_or(crate::object::DescriptorFields {
7699 value: false,
7700 writable: false,
7701 enumerable: false,
7702 configurable: false,
7703 get: false,
7704 set: false,
7705 });
7706 if named.configurable && !property.configurable {
7707 let Some(target_desc) = &target_desc else {
7708 return Err(self.type_error(format!(
7709 "proxy 'defineProperty' invented the non-configurable '{key}'"
7710 )));
7711 };
7712 if target_desc.configurable {
7713 return Err(self.type_error(format!(
7714 "proxy 'defineProperty' made '{key}' non-configurable"
7715 )));
7716 }
7717 }
7718 // Step 11's other half: reporting that a property was made *configurable* needs a
7719 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7720 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7721 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7722 // target`).
7723 if named.configurable
7724 && property.configurable
7725 && let Some(target_desc) = &target_desc
7726 && !target_desc.configurable
7727 {
7728 return Err(
7729 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7730 );
7731 }
7732 // Step 12: a property cannot be reported *made writable* when the target's copy is
7733 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7734 // the trap is allowed to claim a definition it did not perform, as long as the
7735 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7736 // legal, and refusing it broke the commonest way to seed a proxy).
7737 if named.writable
7738 && property.writable
7739 && let Some(target_desc) = &target_desc
7740 && !target_desc.writable
7741 {
7742 return Err(self.type_error(format!(
7743 "proxy 'defineProperty' made the read-only '{key}' writable"
7744 )));
7745 }
7746 // Step 13: making a property read-only needs an existing read-only property.
7747 if named.writable
7748 && !property.writable
7749 && let Some(target_desc) = &target_desc
7750 && !target_desc.is_accessor()
7751 && target_desc.writable
7752 {
7753 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7754 }
7755 // Step 14: a non-writable, non-configurable property's value is fixed.
7756 if named.value
7757 && let Some(target_desc) = &target_desc
7758 && !target_desc.is_accessor()
7759 && !target_desc.writable
7760 && !target_desc.configurable
7761 {
7762 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7763 let reported = property.value.clone().unwrap_or(Value::Undefined);
7764 if !fixed_value.same_value(&reported) {
7765 return Err(self.type_error(format!(
7766 "proxy 'defineProperty' changed the value of '{key}'"
7767 )));
7768 }
7769 }
7770 // Step 15: a non-extensible target cannot grow.
7771 if target_desc.is_none() && !extensible {
7772 return Err(self.type_error(format!(
7773 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7774 )));
7775 }
7776 Ok(Some(true))
7777 }
7778
7779 /// `[[GetPrototypeOf]]` on a proxy.
7780 fn proxy_get_prototype_of(
7781 &mut self,
7782 object: &Gc<JsObject>,
7783 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7784 let Some((target, handler)) = self.proxy_parts(object)? else {
7785 return Ok(None);
7786 };
7787 let Some(result) = self.proxy_trap(
7788 &handler,
7789 "getPrototypeOf",
7790 vec![Value::Object(target.clone())],
7791 )?
7792 else {
7793 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7794 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7795 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7796 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7797 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7798 return Ok(Some(self.object_prototype_of(&target)?));
7799 };
7800 let proto = match &result {
7801 Value::Null => None,
7802 Value::Object(proto) => Some(proto.clone()),
7803 _ => {
7804 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7805 }
7806 };
7807 if !self.object_is_extensible(&target)? {
7808 let actual = self.object_prototype_of(&target)?;
7809 if !same_proto(proto.as_ref(), actual.as_ref()) {
7810 return Err(self.type_error(
7811 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7812 ));
7813 }
7814 }
7815 Ok(Some(proto))
7816 }
7817
7818 /// `[[SetPrototypeOf]]` on a proxy.
7819 fn proxy_set_prototype_of(
7820 &mut self,
7821 object: &Gc<JsObject>,
7822 proto: Option<Gc<JsObject>>,
7823 ) -> JsResult<Option<bool>> {
7824 let Some((target, handler)) = self.proxy_parts(object)? else {
7825 return Ok(None);
7826 };
7827 let proto_value = match &proto {
7828 Some(proto) => Value::Object(proto.clone()),
7829 None => Value::Null,
7830 };
7831 let Some(result) = self.proxy_trap(
7832 &handler,
7833 "setPrototypeOf",
7834 vec![Value::Object(target.clone()), proto_value],
7835 )?
7836 else {
7837 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7838 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7839 // its stored prototype overwritten behind its back.
7840 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7841 };
7842 if result.to_boolean()
7843 && !self.object_is_extensible(&target)?
7844 && !same_proto(
7845 Some(&proto).and_then(|p| p.clone()).as_ref(),
7846 self.object_prototype_of(&target)?.as_ref(),
7847 )
7848 {
7849 return Err(self.type_error(
7850 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7851 ));
7852 }
7853 Ok(Some(result.to_boolean()))
7854 }
7855
7856 /// `[[IsExtensible]]` on a proxy.
7857 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7858 let Some((target, handler)) = self.proxy_parts(object)? else {
7859 return Ok(None);
7860 };
7861 let Some(result) = self.proxy_trap(
7862 &handler,
7863 "isExtensible",
7864 vec![Value::Object(target.clone())],
7865 )?
7866 else {
7867 return Ok(Some(self.object_is_extensible(&target)?));
7868 };
7869 // The answer is not the proxy's to invent: it must agree with the target, or a
7870 // script could learn `false` while the target keeps accepting new properties.
7871 if result.to_boolean() != self.object_is_extensible(&target)? {
7872 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7873 }
7874 Ok(Some(result.to_boolean()))
7875 }
7876
7877 /// `[[PreventExtensions]]` on a proxy.
7878 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7879 let Some((target, handler)) = self.proxy_parts(object)? else {
7880 return Ok(None);
7881 };
7882 let Some(result) = self.proxy_trap(
7883 &handler,
7884 "preventExtensions",
7885 vec![Value::Object(target.clone())],
7886 )?
7887 else {
7888 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7889 // its answer can be `false`.
7890 return Ok(Some(self.object_prevent_extensions(&target)?));
7891 };
7892 if result.to_boolean() && self.object_is_extensible(&target)? {
7893 return Err(self.type_error(
7894 "proxy 'preventExtensions' reported success but the target is still extensible",
7895 ));
7896 }
7897 Ok(Some(result.to_boolean()))
7898 }
7899
7900 /// `[[Call]]` on a proxy, through the `apply` trap.
7901 fn proxy_apply(
7902 &mut self,
7903 object: &Gc<JsObject>,
7904 this: Value,
7905 args: Vec<Value>,
7906 ) -> JsResult<Option<Value>> {
7907 let Some((target, handler)) = self.proxy_parts(object)? else {
7908 return Ok(None);
7909 };
7910 // The trap gets the arguments as one array, which is the shape the spec passes
7911 // and the shape `apply` traps are written against (`args[0]` is the first one).
7912 let arguments = self.new_array(args.clone());
7913 let this_for_trap = this.clone();
7914 let Some(result) = self.proxy_trap(
7915 &handler,
7916 "apply",
7917 vec![
7918 Value::Object(target.clone()),
7919 this_for_trap,
7920 Value::Object(arguments),
7921 ],
7922 )?
7923 else {
7924 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7925 };
7926 Ok(Some(result))
7927 }
7928
7929 /// `[[Construct]]` on a proxy, through the `construct` trap.
7930 fn proxy_construct(
7931 &mut self,
7932 object: &Gc<JsObject>,
7933 args: Vec<Value>,
7934 new_target: &Value,
7935 ) -> JsResult<Option<Value>> {
7936 let Some((target, handler)) = self.proxy_parts(object)? else {
7937 return Ok(None);
7938 };
7939 if !target.is_callable() {
7940 return Err(self.type_error("proxy target is not a constructor"));
7941 }
7942 let arguments = self.new_array(args.clone());
7943 let Some(result) = self.proxy_trap(
7944 &handler,
7945 "construct",
7946 vec![
7947 Value::Object(target.clone()),
7948 Value::Object(arguments),
7949 new_target.clone(),
7950 ],
7951 )?
7952 else {
7953 return Ok(Some(self.construct(
7954 Value::Object(target),
7955 new_target.clone(),
7956 args,
7957 )?));
7958 };
7959 if !matches!(result, Value::Object(_)) {
7960 return Err(self.type_error("proxy 'construct' must return an object"));
7961 }
7962 Ok(Some(result))
7963 }
7964
7965 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7966 pub(crate) fn has_own_or_inherited(
7967 &mut self,
7968 object: &Gc<JsObject>,
7969 key: &PropertyKey,
7970 ) -> JsResult<bool> {
7971 // The object itself first: it may be a proxy, and then the answer is its trap's.
7972 if let Some(answer) = self.proxy_has(object, key)? {
7973 return Ok(answer);
7974 }
7975 // An integer-indexed exotic object answers a canonical numeric index from
7976 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7977 // prototype chain. That is observable twice: a view the buffer has been resized
7978 // away from has no indices, so `2 in view` is `false` even when
7979 // `Object.getPrototypeOf(view)[2]` exists (what
7980 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7981 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7982 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7983 // goes through here, which is why the same rule is repeated in `has_property_key`
7984 // rather than living only there.
7985 if object.typed_array_parts().is_some()
7986 && let Some(numeric) = canonical_numeric_index(key)
7987 {
7988 return Ok(typed_array_index_is_valid(object, numeric));
7989 }
7990 // A host class answers `in` for its own keys, which may live nowhere in a property
7991 // table — `"x" in point` is true because the class says so, not because a property
7992 // exists.
7993 if let Some(exotic) = object.exotic()
7994 && let Some(answer) = exotic.has_property(self, object, key)?
7995 {
7996 return Ok(answer);
7997 }
7998 // `has_own` rather than `own_property_key`: an array's elements and its derived
7999 // `length` are invisible to the property table, and `Array.prototype` is an array.
8000 // A host class's `get_own_property` counts too, because the reference's
8001 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
8002 // lives — a class with only `get_own_property` answers `in` through it.
8003 if self.exotic_has_own(object, key)? {
8004 return Ok(true);
8005 }
8006 // A hole is *not* the end of the search: the chain may still have the key, which
8007 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
8008 for ancestor in object.chain() {
8009 // A proxy further up the chain answers for itself.
8010 if let Some(answer) = self.proxy_has(&ancestor, key)? {
8011 return Ok(answer);
8012 }
8013 // Same for a host class: a prototype may be one, and `in` reaches it.
8014 if let Some(exotic) = ancestor.exotic()
8015 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
8016 {
8017 return Ok(answer);
8018 }
8019 if self.exotic_has_own(&ancestor, key)? {
8020 return Ok(true);
8021 }
8022 }
8023 Ok(false)
8024 }
8025
8026 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
8027 /// trap included.
8028 ///
8029 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
8030 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
8031 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
8032 if let Some(exotic) = object.exotic()
8033 && let Some(answer) = exotic.get_own_property(self, object, key)?
8034 {
8035 return Ok(answer.is_some());
8036 }
8037 Ok(has_own(object, key))
8038 }
8039
8040 /// `CreateListFromArrayLike`, optionally restricted to property keys.
8041 ///
8042 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
8043 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
8044 /// `TypeError` instead of a property named `"1.5"`.
8045 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
8046 let object = self.object_from(value)?;
8047 let length = self
8048 .get_property(&object, "length")?
8049 .map(|value| value.to_number())
8050 .unwrap_or(0.0);
8051 if !length.is_finite() || length < 0.0 {
8052 return Err(self.type_error("invalid array-like length"));
8053 }
8054 let length = length as usize;
8055 let mut items = Vec::with_capacity(length.min(1024));
8056 for index in 0..length {
8057 let item = self
8058 .get_property(&object, &index.to_string())?
8059 .unwrap_or(Value::Undefined);
8060 if keys_only && matches!(&item, Value::Symbol(_)) {
8061 items.push(item);
8062 continue;
8063 }
8064 if keys_only && !matches!(&item, Value::String(_)) {
8065 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
8066 }
8067 items.push(item);
8068 }
8069 Ok(items)
8070 }
8071
8072 /// A `Property` from the descriptor object a trap returned.
8073 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
8074 let object = self.object_from(value)?;
8075 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
8076 interp.get_property(&object, name)
8077 };
8078 let getter = field(self, "get")?;
8079 let setter = field(self, "set")?;
8080 let accessor = getter.is_some() || setter.is_some();
8081 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
8082 Ok(interp
8083 .get_property(&object, name)?
8084 .is_some_and(|value| value.to_boolean()))
8085 };
8086 let enumerable = boolean(self, "enumerable")?;
8087 let configurable = boolean(self, "configurable")?;
8088 if accessor {
8089 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
8090 return Err(
8091 self.type_error("a descriptor cannot be both a data property and an accessor")
8092 );
8093 }
8094 Ok(Property {
8095 getter: getter.or(Some(Value::Undefined)),
8096 setter: setter.or(Some(Value::Undefined)),
8097 enumerable,
8098 configurable,
8099 writable: false,
8100 value: None,
8101 descriptor_fields: None,
8102 })
8103 } else {
8104 Ok(Property {
8105 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
8106 writable: boolean(self, "writable")?,
8107 enumerable,
8108 configurable,
8109 getter: None,
8110 setter: None,
8111 descriptor_fields: None,
8112 })
8113 }
8114 }
8115
8116 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
8117 fn descriptor_from_property(&mut self, property: &Property) -> Value {
8118 let object = self.new_object(None);
8119 // A partial descriptor names only some fields, and the trap must see exactly those:
8120 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
8121 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
8122 // case, where every field is present.
8123 let fields = property.descriptor_fields;
8124 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
8125 fields.is_none_or(|fields| field(&fields))
8126 };
8127 if property.is_accessor() {
8128 let getter = property.getter.clone().unwrap_or(Value::Undefined);
8129 let setter = property.setter.clone().unwrap_or(Value::Undefined);
8130 object.define_data("get", getter);
8131 object.define_data("set", setter);
8132 } else {
8133 if names(|fields| fields.value) {
8134 let value = property.value.clone().unwrap_or(Value::Undefined);
8135 object.define_data("value", value);
8136 }
8137 if names(|fields| fields.writable) {
8138 object.define_data("writable", Value::Bool(property.writable));
8139 }
8140 }
8141 if names(|fields| fields.enumerable) {
8142 object.define_data("enumerable", Value::Bool(property.enumerable));
8143 }
8144 if names(|fields| fields.configurable) {
8145 object.define_data("configurable", Value::Bool(property.configurable));
8146 }
8147 Value::Object(object)
8148 }
8149
8150 // -- calling ------------------------------------------------------------
8151
8152 /// Call `callee` with `this` and `args`.
8153 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
8154 let Value::Object(function) = &callee else {
8155 // `typeof x === "function"` is not enough to make `x()` legal: only a
8156 // callable object is. `null` and `undefined` need no special wording
8157 // here — their `ToString` already reads the way the reference's does.
8158 let what = format!("{} is not a function", callee.to_js_string());
8159 return Err(Signal::Throw(self.make_error("TypeError", &what)));
8160 };
8161 // A proxy of a function is called through its `apply` trap. It has no
8162 // `ObjectKind::Function` of its own, so this has to come before the dispatch
8163 // below, and a proxy of a non-function has nothing to forward to.
8164 if function.proxy_state().is_some() {
8165 return match self.proxy_apply(function, this, args)? {
8166 Some(result) => Ok(result),
8167 None => Err(Signal::Throw(
8168 self.make_error("TypeError", "proxy target is not callable"),
8169 )),
8170 };
8171 }
8172 let callable = function.with(|data| match &data.kind {
8173 ObjectKind::Function(callable) => match callable {
8174 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
8175 // The `Rc` is cloned out so the borrow of this object's data is released
8176 // before the closure runs: the closure may touch the same object.
8177 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
8178 Callable::Bound {
8179 target,
8180 this,
8181 args: leading,
8182 } => Some(NativeCall::Bound {
8183 target: target.clone(),
8184 this: this.clone(),
8185 leading: leading.clone(),
8186 }),
8187 Callable::Bytecode { code, env } => {
8188 Some(NativeCall::Bytecode(code.clone(), env.clone()))
8189 }
8190 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
8191 Callable::PromiseResolve(promise) => {
8192 Some(NativeCall::PromiseResolve(promise.clone()))
8193 }
8194 Callable::PromiseReject(promise) => {
8195 Some(NativeCall::PromiseReject(promise.clone()))
8196 }
8197 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8198 state: state.clone(),
8199 }),
8200 Callable::ThenShim {
8201 handler,
8202 resolve,
8203 reject,
8204 fulfilled,
8205 } => Some(NativeCall::ThenShim {
8206 handler: handler.clone(),
8207 resolve: resolve.clone(),
8208 reject: reject.clone(),
8209 fulfilled: *fulfilled,
8210 }),
8211 Callable::AwaitResume {
8212 coroutine,
8213 promise,
8214 kind,
8215 } => Some(NativeCall::AwaitResume {
8216 coroutine: coroutine.clone(),
8217 promise: promise.clone(),
8218 kind: *kind,
8219 }),
8220 Callable::CombinatorSettle {
8221 state,
8222 index,
8223 fulfilled,
8224 } => Some(NativeCall::CombinatorSettle {
8225 state: state.clone(),
8226 index: *index,
8227 fulfilled: *fulfilled,
8228 }),
8229 Callable::FinallyShim {
8230 callback,
8231 fulfilled,
8232 constructor,
8233 } => Some(NativeCall::FinallyShim {
8234 callback: callback.clone(),
8235 fulfilled: *fulfilled,
8236 constructor: constructor.clone(),
8237 }),
8238 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8239 Callable::CompletedReturn {
8240 generator,
8241 promise,
8242 rejected,
8243 } => Some(NativeCall::CompletedReturn {
8244 generator: generator.clone(),
8245 promise: promise.clone(),
8246 rejected: *rejected,
8247 }),
8248 Callable::YieldResult {
8249 generator,
8250 promise,
8251 done,
8252 } => Some(NativeCall::YieldResult {
8253 generator: generator.clone(),
8254 promise: promise.clone(),
8255 done: *done,
8256 }),
8257 Callable::DisposeStep {
8258 remaining,
8259 promise,
8260 error,
8261 rejected,
8262 awaited,
8263 needs_await,
8264 } => Some(NativeCall::DisposeStep {
8265 remaining: remaining.clone(),
8266 promise: promise.clone(),
8267 error: error.clone(),
8268 rejected: *rejected,
8269 awaited: *awaited,
8270 needs_await: *needs_await,
8271 }),
8272 Callable::GeneratorResume {
8273 generator,
8274 promise,
8275 kind,
8276 } => Some(NativeCall::GeneratorResume {
8277 generator: generator.clone(),
8278 promise: promise.clone(),
8279 kind: *kind,
8280 }),
8281 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8282 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8283 Callable::SettlePromise {
8284 promise,
8285 value,
8286 rejected,
8287 } => Some(NativeCall::SettlePromise {
8288 promise: promise.clone(),
8289 value: value.clone(),
8290 rejected: *rejected,
8291 }),
8292 },
8293 _ => None,
8294 });
8295 match callable {
8296 Some(NativeCall::Host(func)) => {
8297 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8298 // function by name rather than stopping at the caller.
8299 let frame_less = function
8300 .own_property("_frame_less")
8301 .and_then(|property| property.value)
8302 .is_some_and(|value| value.to_boolean());
8303 let outer = if frame_less {
8304 None
8305 } else {
8306 self.native_frames
8307 .push((function.clone(), self.frames.len()));
8308 Some(self.current_native.replace(function.clone()))
8309 };
8310 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8311 // constructor reads it through `current_new_target` because it is handed
8312 // `undefined` for `this`. Taking the parked value here is what stops a
8313 // *plain* call made from inside a constructor body from seeing the
8314 // enclosing `new.target`.
8315 let parked = self.pending_new_target.take();
8316 let result = {
8317 let outer_new_target = std::mem::replace(
8318 &mut self.active_new_target,
8319 parked.unwrap_or(Value::Undefined),
8320 );
8321 let result = {
8322 let mut body = func.borrow_mut();
8323 body(self, this, &args)
8324 };
8325 self.active_new_target = outer_new_target;
8326 result
8327 };
8328 if !frame_less {
8329 self.native_frames.pop();
8330 self.current_native = outer.flatten();
8331 }
8332 result
8333 }
8334 Some(NativeCall::Native(func)) => {
8335 // A function marked `_frame_less` is one the reference implements
8336 // without a call frame — `eval` is the only one so far.
8337 let frame_less = function
8338 .own_property("_frame_less")
8339 .and_then(|property| property.value)
8340 .is_some_and(|value| value.to_boolean());
8341 let outer = if frame_less {
8342 None
8343 } else {
8344 self.native_frames
8345 .push((function.clone(), self.frames.len()));
8346 Some(self.current_native.replace(function.clone()))
8347 };
8348 let parked = self.pending_new_target.take();
8349 let outer_new_target = std::mem::replace(
8350 &mut self.active_new_target,
8351 parked.unwrap_or(Value::Undefined),
8352 );
8353 let result = func(self, this, &args);
8354 self.active_new_target = outer_new_target;
8355 if !frame_less {
8356 self.native_frames.pop();
8357 self.current_native = outer.flatten();
8358 }
8359 result
8360 }
8361 Some(NativeCall::Revoker(slots)) => {
8362 // Idempotent: revoking twice answers `undefined` again rather than
8363 // complaining, which is what the spec says and what a `finally` block
8364 // relies on.
8365 let mut state = slots.borrow_mut();
8366 state.target = None;
8367 state.handler = None;
8368 Ok(Value::Undefined)
8369 }
8370 Some(NativeCall::PromiseResolve(promise)) => {
8371 // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8372 // else, so a resolve after a reject does nothing *and* a resolve after a
8373 // resolve-with-thenable does nothing — the promise is still `Pending` then,
8374 // because the adoption is a queued job.
8375 let value = args.first().cloned().unwrap_or(Value::Undefined);
8376 if !self.claim_resolution(&promise) {
8377 return Ok(Value::Undefined);
8378 }
8379 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8380 // the resolve function performs `RejectPromise` and returns `undefined`.
8381 // (`ResolvePromise` itself throws as well, so the engine's own callers see
8382 // it; only this wrapper swallows it.)
8383 let _ = self.resolve_promise_with(&promise, value);
8384 Ok(Value::Undefined)
8385 }
8386 Some(NativeCall::PromiseReject(promise)) => {
8387 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8388 // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8389 if !self.claim_resolution(&promise) {
8390 return Ok(Value::Undefined);
8391 }
8392 self.reject_promise(&promise, reason);
8393 Ok(Value::Undefined)
8394 }
8395 Some(NativeCall::ThenShim {
8396 handler,
8397 resolve,
8398 reject,
8399 fulfilled,
8400 }) => {
8401 // `PerformPromiseThen` with a capability: run the handler, then settle
8402 // through the capability's own pair. A throw from the handler is the
8403 // rejection, and a throw from the capability's `resolve` is not caught —
8404 // exactly the spec's `?`.
8405 let value = args.first().cloned().unwrap_or(Value::Undefined);
8406 match handler {
8407 Some(handler) => {
8408 match self.call_value(handler, Value::Undefined, vec![value]) {
8409 Ok(result) => {
8410 self.call_value(resolve, Value::Undefined, vec![result])?;
8411 }
8412 Err(Signal::Throw(reason)) => {
8413 self.call_value(reject, Value::Undefined, vec![reason])?;
8414 }
8415 Err(signal) => return Err(signal),
8416 }
8417 }
8418 None => {
8419 let handler = if fulfilled { resolve } else { reject };
8420 self.call_value(handler, Value::Undefined, vec![value])?;
8421 }
8422 }
8423 Ok(Value::Undefined)
8424 }
8425 Some(NativeCall::CapabilityExecutor { state }) => {
8426 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8427 // slot holds a value yet. The test is on the *values*, not on a call count —
8428 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8429 // called-twice`'s first case does exactly that), while a second call after a
8430 // real pair is the `TypeError`.
8431 let defined = |name: &str| {
8432 state
8433 .own_property(name)
8434 .and_then(|property| property.value)
8435 .is_some_and(|value| !matches!(value, Value::Undefined))
8436 };
8437 if defined("resolve") || defined("reject") {
8438 return Err(self.type_error("promise capability executor called twice"));
8439 }
8440 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8441 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8442 state.define_data("resolve", resolve);
8443 state.define_data("reject", reject);
8444 Ok(Value::Undefined)
8445 }
8446 Some(NativeCall::CombinatorSettle {
8447 state,
8448 index,
8449 fulfilled,
8450 }) => {
8451 let value = args.first().cloned().unwrap_or(Value::Undefined);
8452 self.settle_combinator(&state, index, fulfilled, value)?;
8453 Ok(Value::Undefined)
8454 }
8455 Some(NativeCall::AwaitResume {
8456 coroutine,
8457 promise,
8458 kind,
8459 }) => {
8460 // Resume *inline*, in the reaction that delivered the value. Deferring it
8461 // by another job inserts a tick between every `await` and its
8462 // continuation, which reorders `await` against unrelated `then` chains —
8463 // `f().then(g)` then runs before `f`'s own next statement.
8464 self.drive_async(
8465 &coroutine,
8466 &promise,
8467 kind,
8468 args.first().cloned().unwrap_or(Value::Undefined),
8469 )
8470 .map(|()| Value::Undefined)
8471 }
8472 Some(NativeCall::ReturnValue(value)) => Ok(value),
8473 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8474 Some(NativeCall::FinallyShim {
8475 callback,
8476 fulfilled,
8477 constructor,
8478 }) => {
8479 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8480 // own value is discarded; what the caller sees is the *original* outcome,
8481 // delayed until `PromiseResolve(C, result)` has settled.
8482 //
8483 // Two details are observable and both have a test:
8484 //
8485 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8486 // `PerformPromiseThen`. A callback that returns a thenable with its own
8487 // `then` must have that `then` called
8488 // (`resolved-observable-then-calls` counts it);
8489 // * only the **fulfil** handler is supplied. A returned promise that
8490 // *rejects* rejects the whole `finally`, rather than having its failure
8491 // swallowed and the original value passed through.
8492 let original = args.first().cloned().unwrap_or(Value::Undefined);
8493 let result = match &callback {
8494 Some(callback) => {
8495 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8496 }
8497 None => Value::Undefined,
8498 };
8499 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8500 // constructor is reused rather than rewrapped, which is what keeps
8501 // `mp1.finally(() => mp2)` from gaining a layer.
8502 let resolved = self.promise_resolve_for(&constructor, result)?;
8503 let thunk = if fulfilled {
8504 Callable::ReturnValue(original)
8505 } else {
8506 Callable::ThrowValue(original)
8507 };
8508 // `length: 0` and `name: ""`, and **not** a constructor — the three things
8509 // `resolved-observable-then-calls-argument` reads off the thunk while it has
8510 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8511 // function with no `length` at all.
8512 let thunk = self.builtin_function("", 0, thunk);
8513 let then = self.read_field(&resolved, "then")?;
8514 if !matches!(&then, Value::Object(object) if object.is_callable()) {
8515 return Err(self.type_error("then is not a function"));
8516 }
8517 self.call_value(then, resolved, vec![Value::Object(thunk)])
8518 }
8519 Some(NativeCall::DisposeStep {
8520 remaining,
8521 promise,
8522 error,
8523 rejected,
8524 awaited,
8525 needs_await,
8526 }) => {
8527 let error = if rejected {
8528 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8529 self.merge_dispose_error(reason, error)
8530 } else {
8531 error
8532 };
8533 self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8534 Ok(Value::Undefined)
8535 }
8536 Some(NativeCall::ModuleBinding(cell)) => {
8537 // §10.4.6.8 `[[Get]]` step 4: a binding that has not been initialised yet
8538 // throws rather than reading `undefined`. A namespace can be observed
8539 // before its module has finished evaluating — a cycle, or
8540 // `Object.freeze(ns)` in the importer — and every read of the still-dead
8541 // `let` must be a `ReferenceError`
8542 // (`module-code/namespace/internals/get-str-found-uninit` and seven
8543 // siblings).
8544 let value = cell.get();
8545 if matches!(value, Value::Uninitialized) {
8546 return Err(Signal::Throw(
8547 self.make_error("ReferenceError", "module binding is not initialized"),
8548 ));
8549 }
8550 Ok(value)
8551 }
8552 Some(NativeCall::CompletedReturn {
8553 generator,
8554 promise,
8555 rejected,
8556 }) => {
8557 let value = args.first().cloned().unwrap_or(Value::Undefined);
8558 let outcome = if rejected {
8559 AsyncOutcome::Error(value)
8560 } else {
8561 AsyncOutcome::Value(self.iterator_result(value, true)?)
8562 };
8563 self.settle_async_request(&generator, &promise, outcome)?;
8564 Ok(Value::Undefined)
8565 }
8566 Some(NativeCall::YieldResult {
8567 generator,
8568 promise,
8569 done,
8570 }) => {
8571 let value = args.first().cloned().unwrap_or(Value::Undefined);
8572 let result = self.iterator_result(value, done)?;
8573 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8574 Ok(Value::Undefined)
8575 }
8576 Some(NativeCall::GeneratorResume {
8577 generator,
8578 promise,
8579 kind,
8580 }) => {
8581 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8582 // tick and reorders the generator against other chains.
8583 self.step_async_generator(
8584 &generator,
8585 &promise,
8586 kind,
8587 args.first().cloned().unwrap_or(Value::Undefined),
8588 )
8589 .map(|()| Value::Undefined)
8590 }
8591 Some(NativeCall::SettlePromise {
8592 promise,
8593 value,
8594 rejected,
8595 }) => {
8596 if rejected {
8597 self.reject_promise(&promise, value);
8598 } else {
8599 self.fulfill_promise(&promise, value);
8600 }
8601 Ok(Value::Undefined)
8602 }
8603 Some(NativeCall::Bound {
8604 target,
8605 this: bound_this,
8606 leading,
8607 }) => {
8608 let mut all = leading;
8609 all.extend(args);
8610 self.call_value(target, bound_this, all)
8611 }
8612 Some(NativeCall::Bytecode(code, env)) => {
8613 if code.code.kind.is_generator() {
8614 return self.new_generator(callee, this, args);
8615 }
8616 if code.code.kind.is_async() {
8617 // Same coroutine machinery as a generator; the difference is only in
8618 // what the completion does — see `new_async_function`.
8619 return self.new_async_function(callee, this, args);
8620 }
8621 self.execute(code, env, this, args, callee)
8622 }
8623 None => Err(Signal::Throw(
8624 self.make_error("TypeError", "not a function"),
8625 )),
8626 }
8627 }
8628
8629 /// Give a freshly built function its own `prototype` object.
8630 ///
8631 /// Every function that can be used with `new` carries one, and its
8632 /// `constructor` points back at the function — a reference cycle, which is
8633 /// exactly what the collector's cycle pass exists to reclaim.
8634 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8635 self.install_function_prototype_with(function, None);
8636 }
8637
8638 /// [`Interp::install_function_prototype`] with an explicit parent for the new
8639 /// `prototype` object.
8640 ///
8641 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8642 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8643 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8644 /// `None` means `%Object.prototype%`.
8645 fn install_function_prototype_with(
8646 &mut self,
8647 function: &Gc<JsObject>,
8648 parent: Option<Gc<JsObject>>,
8649 ) {
8650 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8651 let prototype = self.new_object(Some(parent));
8652 let constructor = Value::Object(function.clone());
8653 prototype.define(
8654 "constructor",
8655 Property::with_attributes(constructor, true, false),
8656 );
8657 let value = Value::Object(prototype);
8658 function.define("prototype", Property::prototype_of(value, true));
8659 }
8660
8661 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8662 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8663 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8664 ///
8665 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8666 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8667 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8668 /// is `[]` there.
8669 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8670 let prototype = self.new_object(Some(parent));
8671 let value = Value::Object(prototype);
8672 function.define("prototype", Property::prototype_of(value, true));
8673 }
8674
8675 /// The `[[Prototype]]` a newly created generator object gets:
8676 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8677 ///
8678 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8679 /// function's `prototype` is writable, so a script can replace it with anything, and
8680 /// only an *object* is consulted.
8681 fn generator_instance_proto(
8682 &mut self,
8683 function: &Gc<JsObject>,
8684 default: Gc<JsObject>,
8685 ) -> JsResult<Gc<JsObject>> {
8686 match self.get_property(function, "prototype")? {
8687 Some(Value::Object(prototype)) => Ok(prototype),
8688 _ => Ok(default),
8689 }
8690 }
8691
8692 /// A getter or setter that reads or writes the reference cell behind a mapped
8693 /// `arguments` index.
8694 ///
8695 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8696 /// count — which is what the collector treats as "a reference from outside the
8697 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8698 /// accessor is reachable, which is the same lifetime the arguments object has.
8699 ///
8700 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8701 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8702 /// parameter value and the arguments object reaches the closure, never the other
8703 /// way round. Nothing the collector has to see is hidden.
8704 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8705 let name = if is_setter { "set" } else { "get" };
8706 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8707 if is_setter {
8708 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8709 Ok(Value::Undefined)
8710 } else {
8711 Ok(cell.get())
8712 }
8713 };
8714 self.new_host_function(name, 1, Box::new(func))
8715 }
8716
8717 /// The object `special_object` builds.
8718 ///
8719 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8720 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8721 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8722 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8723 /// write through `arguments` does not reach the parameter.
8724 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8725 match magic {
8726 0 | 1 => {
8727 let args = self.frame().passed().to_vec();
8728 let proto = self.realm.object_proto.clone();
8729 let object = self.new_object(Some(proto));
8730 // The marker `Object.prototype.toString` needs: an arguments object is an
8731 // ordinary object apart from reporting `[object Arguments]`, and that has
8732 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8733 // show up ahead of them in a key listing anyway — it is non-enumerable.
8734 self.internal_set(&object, "_class", self.string("Arguments"));
8735 // `length` is writable and configurable but neither enumerable nor a
8736 // plain data property: `Object.keys(arguments)` lists the indices only,
8737 // which is how `{...arguments}` copies them without the length.
8738 object.define(
8739 "length",
8740 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8741 );
8742 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8743 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8744 // change `a`, and assigning `a` has to change `arguments[0]`.
8745 //
8746 // The shared storage is the parameter's reference cell. The compiler
8747 // gives every parameter of such a function one (see
8748 // `provide_body_arguments`), and the cell outlives the frame, so this
8749 // keeps working after the arguments object escapes.
8750 //
8751 // The index becomes an accessor rather than a data property. A mapped
8752 // index reports as a plain writable/enumerable data property through
8753 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8754 // the getter/setter pair is only the plumbing underneath.
8755 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8756 let frame = self.frame();
8757 frame
8758 .code
8759 .arg_cell
8760 .iter()
8761 .map(|cell| {
8762 (*cell >= 0)
8763 .then(|| frame.cells.get(*cell as usize).cloned())
8764 .flatten()
8765 })
8766 .collect()
8767 } else {
8768 Vec::new()
8769 };
8770 // Tell the object which indices are mapped, so
8771 // `Object.getOwnPropertyDescriptor` can report them as the data
8772 // properties the spec describes instead of the accessors that
8773 // implement the aliasing.
8774 if magic == 1 {
8775 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8776 for cell in &mapped_cells {
8777 table.push(cell.clone());
8778 }
8779 object.set_mapped_arguments(table);
8780 }
8781 for (index, value) in args.into_iter().enumerate() {
8782 match mapped_cells.get(index).cloned().flatten() {
8783 Some(cell) => {
8784 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8785 let setter = self.new_mapped_arguments_accessor(cell, true);
8786 object.define(
8787 &index.to_string(),
8788 Property::accessor_with(
8789 Some(Value::Object(getter)),
8790 Some(Value::Object(setter)),
8791 true,
8792 ),
8793 );
8794 }
8795 None => object.define_data(&index.to_string(), value),
8796 }
8797 }
8798 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8799 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8800 // non-enumerable and non-configurable. It is not a nicety — it is the only
8801 // documented way to reach `%ThrowTypeError%`:
8802 //
8803 // Object.getOwnPropertyDescriptor(function(){"use strict";
8804 // return arguments;}(), "callee").get
8805 //
8806 // and the whole `ThrowTypeError/` directory is written against that
8807 // expression. Without it 13 cases failed with `cannot read property 'get'
8808 // of undefined`, which reads like a test harness bug rather than a missing
8809 // accessor.
8810 //
8811 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8812 // writable data property holding the function being called, and
8813 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8814 // `hasOwnProperty("callee")` hold there.
8815 if magic == 1 {
8816 let callee = self.frame().callee.clone();
8817 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8818 object.define("callee", Property::with_attributes(callee, true, false));
8819 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8820 && object.own_property("callee").is_none()
8821 {
8822 object.define(
8823 "callee",
8824 Property {
8825 getter: Some(Value::Object(thrower.clone())),
8826 setter: Some(Value::Object(thrower)),
8827 enumerable: false,
8828 configurable: false,
8829 ..Property::default()
8830 },
8831 );
8832 }
8833 // An arguments object is iterable: `[...arguments]` and
8834 // `for (const a of arguments)` both work, through the *array* iterator
8835 // because the object is array-like. Without this the whole spread form
8836 // reported "not iterable".
8837 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8838 let values = self
8839 .realm
8840 .array_proto
8841 .own_property("values")
8842 .and_then(|property| property.value);
8843 if let Some(values) = values {
8844 object.define_key(
8845 &iterator_key,
8846 Property::with_attributes(values, true, false),
8847 );
8848 }
8849 Ok(Value::Object(object))
8850 }
8851 // `this.active_func`: the constructor `super()` resolves against.
8852 //
8853 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8854 // own, so it inherits this from the function it was written in along with `this`
8855 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8856 // the constructor and is called back later (`iter.return = () => super()`) has
8857 // the constructor nowhere on the stack. The compiler therefore reads it out of
8858 // a closure variable of the enclosing function, exactly as the reference does
8859 // with its `this_active_func` local.
8860 2 => Ok(self
8861 .current_callee()
8862 .map_or(Value::Undefined, Value::Object)),
8863 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8864 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8865 // its own either, so the lookup walks out to the nearest non-arrow frame for
8866 // the same reason as `this.active_func` above — without that, `super()` inside
8867 // an arrow passed `undefined` as the new target and the parent constructor was
8868 // then rejected for being invoked without `new`.
8869 3 => Ok(self
8870 .eval_new_target
8871 .clone()
8872 .unwrap_or_else(|| self.frame().new_target.clone())),
8873 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8874 // An arrow has none of its own, so the lookup walks out to the enclosing
8875 // method — which is why `super` works inside an arrow inside a method.
8876 4 => Ok(self
8877 .frames
8878 .iter()
8879 .rev()
8880 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8881 .map_or(Value::Undefined, Value::Object)),
8882 // `import.meta`: the innermost module body's meta object. Outside a module
8883 // the compiler never emits this, so an empty fallback is unreachable rather
8884 // than permissive.
8885 6 => {
8886 let name = self.module_stack.last().cloned();
8887 let meta = name
8888 .and_then(|name| self.modules.get(&name).cloned())
8889 .and_then(|module| module.with(|r| r.import_meta.clone()));
8890 Ok(meta.map_or(Value::Undefined, Value::Object))
8891 }
8892 other => Err(Signal::Throw(self.make_error(
8893 "InternalError",
8894 &format!("special_object {other} is not implemented yet"),
8895 ))),
8896 }
8897 }
8898
8899 /// `[[HomeObject]]` of the innermost function that has one, if any.
8900 ///
8901 /// An arrow has none, so the search walks out to the enclosing method — the same
8902 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8903 /// inside a method.
8904 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8905 self.frames
8906 .iter()
8907 .rev()
8908 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8909 }
8910
8911 /// The dispose method a `using` declaration should snapshot, or an error.
8912 ///
8913 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8914 /// is what makes a resource that only knows the synchronous protocol usable in both
8915 /// forms.
8916 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8917 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8918 if value.is_nullish() {
8919 return Ok(Value::Undefined);
8920 }
8921 let Some(object) = value.as_object() else {
8922 return Err(self.type_error("not an object"));
8923 };
8924 let mut method = if await_form {
8925 let found = self.get_property_key(
8926 object,
8927 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8928 )?;
8929 match found {
8930 Some(found) if !found.is_nullish() => Some(found),
8931 _ => self
8932 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8933 }
8934 } else {
8935 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8936 };
8937 let Some(found) = method.take() else {
8938 return Err(self.type_error("value is not disposable"));
8939 };
8940 if found.is_nullish() {
8941 return Err(self.type_error("value is not disposable"));
8942 }
8943 let callable = found.as_object().is_some_and(|object| object.is_callable());
8944 if !callable {
8945 return Err(self.type_error("dispose method is not a function"));
8946 }
8947 Ok(found)
8948 }
8949
8950 /// Call one resource's disposer, folding a failure into `error_state`.
8951 ///
8952 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8953 /// because a captured `using` binding lives in its reference cell and the local slot is
8954 /// stale — a closure over the resource is legal and must not change what is disposed.
8955 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8956 let value = self.get_loc(slot);
8957 let method = self.get_loc(slot + 1);
8958 // A resource that was never initialised — its declaration threw — or that is
8959 // `null`/`undefined` has nothing to dispose.
8960 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8961 return Ok(error_state);
8962 }
8963 if matches!(method, Value::Undefined | Value::Uninitialized) {
8964 return Ok(error_state);
8965 }
8966 match self.call_value(method, value, Vec::new()) {
8967 Ok(_) => Ok(error_state),
8968 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8969 Err(other) => Err(other),
8970 }
8971 }
8972
8973 /// Combine a disposal failure with whatever was already going wrong.
8974 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8975 if matches!(error_state, Value::Uninitialized) {
8976 return new_error;
8977 }
8978 self.new_suppressed_error(new_error, error_state)
8979 }
8980
8981 /// A `SuppressedError` instance built straight from its prototype.
8982 ///
8983 /// Not through the constructor: a script that rewrites
8984 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8985 /// error wrapping.
8986 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8987 let proto = self
8988 .realm
8989 .suppressed_error_proto
8990 .clone()
8991 .unwrap_or_else(|| self.realm.error_proto.clone());
8992 let object = self.new_object(Some(proto));
8993 object.define("error", Property::with_attributes(error, true, true));
8994 object.define(
8995 "suppressed",
8996 Property::with_attributes(suppressed, true, true),
8997 );
8998 object.define(
8999 "message",
9000 Property::with_attributes(self.string("SuppressedError"), true, true),
9001 );
9002 self.internal_set(&object, "_class", self.string("Error"));
9003 self.add_stack(&object);
9004 Value::Object(object)
9005 }
9006
9007 /// Call `callee`, or push its frame and let the main loop run it.
9008 ///
9009 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
9010 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
9011 /// continues, so `function f(){ return f() }` costs heap and stops at
9012 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
9013 /// is entered directly, and natives do not re-enter JavaScript in this
9014 /// milestone.
9015 ///
9016 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
9017 /// because the returning frame will.
9018 /// The elements of an array-like value, as a call argument list.
9019 ///
9020 /// `apply` accepts any array-like, not only a real array: the reference reads
9021 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
9022 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
9023 ///
9024 /// Used by the paths that take a *length* from script data — the typed-array
9025 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
9026 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
9027 /// `RangeError` rather than a silently clamped count.
9028 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
9029 let number = self.to_js_number(value)?;
9030 if number.is_nan() {
9031 return Ok(0);
9032 }
9033 let number = number.trunc();
9034 if number < 0.0 || number > 9_007_199_254_740_991.0 {
9035 return Err(self.range_error("invalid length"));
9036 }
9037 Ok(number as usize)
9038 }
9039
9040 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
9041 /// other callers that take an argument list from script data.
9042 ///
9043 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
9044 /// constructor and `Array.from` need `ToIndex` instead (see
9045 /// [`Interp::to_index`]), which is why they do not go through here.
9046 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
9047 let Some(object) = value.as_object().cloned() else {
9048 if value.is_nullish() {
9049 // `f.apply(this, null)` passes no arguments at all.
9050 return Ok(Vec::new());
9051 }
9052 return Err(self.type_error("createListFromArrayLike called on non-object"));
9053 };
9054 let length = match self.get_property(&object, "length")? {
9055 Some(length) => length.to_number(),
9056 None => 0.0,
9057 };
9058 if !length.is_finite() || length <= 0.0 {
9059 return Ok(Vec::new());
9060 }
9061 let length = (length as usize).min(1_000_000);
9062 let mut args = Vec::with_capacity(length);
9063 for index in 0..length {
9064 let element = self.get_property(&object, &index.to_string())?;
9065 args.push(element.unwrap_or(Value::Undefined));
9066 }
9067 Ok(args)
9068 }
9069
9070 /// Turn a call to a generator function into a generator object.
9071 ///
9072 /// The frame is built exactly as an ordinary call would build it, then detached and
9073 /// stored in the generator before any body instruction runs — which is what makes
9074 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
9075 /// is `initial_yield`, the first instruction of every suspending body.
9076 pub fn new_generator(
9077 &mut self,
9078 function: Value,
9079 this: Value,
9080 args: Vec<Value>,
9081 ) -> JsResult<Value> {
9082 let Some(object) = function.as_object().cloned() else {
9083 return Err(self.type_error("not a generator function"));
9084 };
9085 let Some((code, env)) = bytecode_of(&object) else {
9086 return Err(self.type_error("not a generator function"));
9087 };
9088 let is_async = code.code.kind.is_async();
9089 self.push_frame(code, env, this, args, function)?;
9090 let frame = self.frames.pop().expect("push_frame just pushed it");
9091 // A fresh generator is *suspended at start*: the body has not run, so a
9092 // `return`/`throw` on it finishes without executing anything.
9093 let mut state = GeneratorState {
9094 frame: Some(frame),
9095 phase: GeneratorPhase::SuspendedStart,
9096 parked_on_await: false,
9097 parked_on_yield_star: false,
9098 requests: std::collections::VecDeque::new(),
9099 async_busy: false,
9100 is_async,
9101 };
9102 // Run to the first suspension. For a generator that is `initial_yield`, so no
9103 // body code runs; for a malformed body it would be the first `yield`.
9104 // An `async function*` answers an async generator: same coroutine, but its
9105 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
9106 let default_proto = if is_async {
9107 self.realm
9108 .async_generator_proto
9109 .clone()
9110 .unwrap_or_else(|| self.realm.generator_proto.clone())
9111 } else {
9112 self.realm.generator_proto.clone()
9113 };
9114 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
9115 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
9116 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
9117 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
9118 let proto = self.generator_instance_proto(&object, default_proto)?;
9119 let generator = self.new_object(Some(proto));
9120 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
9121 Ok(_) => {}
9122 Err(error) => return Err(error),
9123 }
9124 generator.with_mut(|data| {
9125 data.kind = ObjectKind::Generator(Box::new(state));
9126 });
9127 Ok(Value::Object(generator))
9128 }
9129
9130 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9131 ///
9132 /// Returns the `{value, done}` object itself rather than the pair, because a
9133 /// `yield*` suspension already has one — the inner iterator's own result — and the
9134 /// protocol says to hand that straight through rather than nest it.
9135 /// Advance a generator and report *why* it parked.
9136 ///
9137 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
9138 /// "hand this value to the caller" — but an async generator does: an `await` has to
9139 /// settle before it can answer, while a `yield` is the answer.
9140 fn resume_generator_detailed(
9141 &mut self,
9142 generator: &Gc<JsObject>,
9143 kind: ResumeKind,
9144 value: Value,
9145 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9146 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
9147 ObjectKind::Generator(state) => {
9148 let is_async = state.is_async;
9149 Some(std::mem::replace(
9150 state.as_mut(),
9151 GeneratorState {
9152 frame: None,
9153 phase: GeneratorPhase::Executing,
9154 parked_on_await: false,
9155 parked_on_yield_star: false,
9156 requests: std::collections::VecDeque::new(),
9157 // **Busy while the body runs**, so a `next()` called *from inside*
9158 // the body queues instead of being served. §27.6.3.7
9159 // `AsyncGeneratorResumeNext` returns immediately for the state
9160 // "executing", and the request is served once the body suspends;
9161 // with `false` here the re-entrant call found an empty frame and
9162 // rejected (`request-queue-order-state-executing`).
9163 async_busy: is_async,
9164 is_async,
9165 },
9166 ))
9167 }
9168 _ => None,
9169 }) else {
9170 return Err(self.type_error("not a generator"));
9171 };
9172 let result = self.step_generator(&mut state, kind, value);
9173 // Requests queued *while* the body ran live on the placeholder, because the real
9174 // state is out of the object for the duration. They have to be folded back in
9175 // before the placeholder is overwritten, or the promise they carry never settles.
9176 let queued = generator.with_mut(|data| match &mut data.kind {
9177 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
9178 _ => std::collections::VecDeque::new(),
9179 });
9180 state.requests.extend(queued);
9181 generator.with_mut(|data| {
9182 data.kind = ObjectKind::Generator(Box::new(state));
9183 });
9184 result
9185 }
9186
9187 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9188 ///
9189 /// Returns the `{value, done}` object itself rather than the pair, because a
9190 /// `yield*` suspension already has one — the inner iterator's own result — and the
9191 /// protocol says to hand that straight through rather than nest it.
9192 pub fn resume_generator(
9193 &mut self,
9194 generator: &Gc<JsObject>,
9195 kind: ResumeKind,
9196 value: Value,
9197 ) -> JsResult<Value> {
9198 let (value, done, ready, _reason) =
9199 self.resume_generator_detailed(generator, kind, value)?;
9200 if ready {
9201 return Ok(value);
9202 }
9203 self.iterator_result(value, done)
9204 }
9205
9206 /// `next`/`return`/`throw` on an async generator, which answer a promise.
9207 ///
9208 /// The body is the same coroutine a sync generator runs; what changes is that an
9209 /// `await` inside it has to settle before the method can answer, so the step is
9210 /// driven off the job queue rather than returning inline.
9211 pub fn resume_async_generator(
9212 &mut self,
9213 generator: &Gc<JsObject>,
9214 kind: ResumeKind,
9215 value: Value,
9216 ) -> JsResult<Value> {
9217 let promise = self.new_promise();
9218 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9219 // that order, and the second value must reach the *second* `yield`.
9220 let idle = generator.with_mut(|data| match &mut data.kind {
9221 ObjectKind::Generator(state) => {
9222 state.requests.push_back(AsyncRequest {
9223 kind,
9224 value,
9225 promise: promise.clone(),
9226 });
9227 !state.async_busy
9228 }
9229 _ => false,
9230 });
9231 if idle {
9232 self.next_async_request(generator)?;
9233 }
9234 Ok(Value::Object(promise))
9235 }
9236
9237 /// Serve the front queued request, if the generator is free to run one.
9238 ///
9239 /// A finished generator answers from the queue without running anything:
9240 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9241 /// first, and `throw(e)` rejects.
9242 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9243 enum Front {
9244 Idle,
9245 Run(ResumeKind, Value, Gc<JsObject>),
9246 Finished(ResumeKind, Value, Gc<JsObject>),
9247 }
9248 let front = generator.with_mut(|data| match &mut data.kind {
9249 ObjectKind::Generator(state) => {
9250 let Some(request) = state.requests.front() else {
9251 return Front::Idle;
9252 };
9253 // Busy means a request is still in flight — awaiting inside the body, not
9254 // finished. Serving another now would interleave two requests.
9255 if state.async_busy && state.phase != GeneratorPhase::Completed {
9256 return Front::Idle;
9257 }
9258 let kind = request.kind;
9259 let value = request.value.clone();
9260 let promise = request.promise.clone();
9261 state.async_busy = true;
9262 if state.phase == GeneratorPhase::Completed {
9263 Front::Finished(kind, value, promise)
9264 } else {
9265 Front::Run(kind, value, promise)
9266 }
9267 }
9268 _ => Front::Idle,
9269 });
9270 match front {
9271 Front::Idle => Ok(()),
9272 Front::Run(kind, value, promise) => {
9273 self.step_async_generator(generator, &promise, kind, value)
9274 }
9275 Front::Finished(kind, value, promise) => match kind {
9276 ResumeKind::Throw => {
9277 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9278 }
9279 ResumeKind::Next | ResumeKind::Start => {
9280 let result = self.iterator_result(Value::Undefined, true)?;
9281 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9282 }
9283 ResumeKind::Return => {
9284 // `js_async_generator_completed_return`: the value is awaited before it
9285 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9286 // finished generator answers `1`, not a promise.
9287 let resolved = match self.promise_resolve_intrinsic(value) {
9288 Ok(resolved) => resolved,
9289 Err(Signal::Throw(reason)) => {
9290 return self.settle_async_request(
9291 generator,
9292 &promise,
9293 AsyncOutcome::Error(reason),
9294 );
9295 }
9296 Err(other) => return Err(other),
9297 };
9298 let done = JsObject::function(
9299 self.heap,
9300 Some(self.realm.function_proto.clone()),
9301 Callable::CompletedReturn {
9302 generator: generator.clone(),
9303 promise: promise.clone(),
9304 rejected: false,
9305 },
9306 );
9307 let failed = JsObject::function(
9308 self.heap,
9309 Some(self.realm.function_proto.clone()),
9310 Callable::CompletedReturn {
9311 generator: generator.clone(),
9312 promise: promise.clone(),
9313 rejected: true,
9314 },
9315 );
9316 let Value::Object(resolved) = resolved else {
9317 return self.settle_async_request(
9318 generator,
9319 &promise,
9320 AsyncOutcome::Error(Value::Undefined),
9321 );
9322 };
9323 self.perform_then(
9324 &resolved,
9325 Some(Value::Object(done)),
9326 Some(Value::Object(failed)),
9327 )?;
9328 Ok(())
9329 }
9330 },
9331 }
9332 }
9333
9334 /// Settle the front request and start the next one.
9335 ///
9336 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9337 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9338 /// generator would strand every later request.
9339 fn settle_async_request(
9340 &mut self,
9341 generator: &Gc<JsObject>,
9342 promise: &Gc<JsObject>,
9343 outcome: AsyncOutcome,
9344 ) -> JsResult<()> {
9345 let settled = generator.with_mut(|data| match &mut data.kind {
9346 ObjectKind::Generator(state) => {
9347 let front = state.requests.front();
9348 debug_assert!(
9349 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9350 "a request settled outside its turn"
9351 );
9352 state.requests.pop_front();
9353 state.async_busy = false;
9354 true
9355 }
9356 _ => false,
9357 });
9358 if settled {
9359 match outcome {
9360 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9361 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9362 }
9363 }
9364 self.next_async_request(generator)
9365 }
9366
9367 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9368 ///
9369 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9370 /// disposer runs **synchronously** — the reference starts it before returning, which
9371 /// a test can observe by logging after the call — and the rest follow once their
9372 /// predecessor settles.
9373 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9374 let promise = self.new_promise();
9375 // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9376 // any resource at all, because every `await using` resource has the async-dispose
9377 // hint — including the null/undefined ones that have nothing to call. If none of them
9378 // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9379 // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9380 // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9381 let needs_await = !resources.is_empty();
9382 let mut pairs = Vec::with_capacity(resources.len());
9383 for (value, method) in resources {
9384 let pair = self.new_array(vec![value, method]);
9385 pairs.push(Value::Object(pair));
9386 }
9387 let remaining = self.new_array(pairs);
9388 self.dispose_step(
9389 &remaining,
9390 &promise,
9391 Value::Uninitialized,
9392 false,
9393 needs_await,
9394 )?;
9395 Ok(Value::Object(promise))
9396 }
9397
9398 /// One link of the `disposeAsync` chain.
9399 ///
9400 /// Loops while the disposers finish synchronously, and parks on the first thenable it
9401 /// meets — pushing itself back in as the continuation, with the accumulated error
9402 /// carried along so a later failure can still be folded into the `SuppressedError`.
9403 fn dispose_step(
9404 &mut self,
9405 remaining: &Gc<JsObject>,
9406 promise: &Gc<JsObject>,
9407 mut error: Value,
9408 awaited: bool,
9409 needs_await: bool,
9410 ) -> JsResult<()> {
9411 loop {
9412 let length = remaining.array_length().unwrap_or(0);
9413 if length == 0 {
9414 // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9415 // still has to happen. Re-entering this same step past an already-fulfilled
9416 // promise is exactly one tick, and it keeps the folding of `error` in one place.
9417 if needs_await && !awaited {
9418 let finished = self.new_array(Vec::new());
9419 let thunk = JsObject::function(
9420 self.heap,
9421 Some(self.realm.function_proto.clone()),
9422 Callable::DisposeStep {
9423 remaining: finished.clone(),
9424 promise: promise.clone(),
9425 error,
9426 rejected: false,
9427 awaited: true,
9428 needs_await: false,
9429 },
9430 );
9431 let tick = self.promise_resolve_value(Value::Undefined)?;
9432 if let Value::Object(tick) = tick {
9433 self.perform_then(
9434 &tick,
9435 Some(Value::Object(thunk.clone())),
9436 Some(Value::Object(thunk)),
9437 )?;
9438 }
9439 return Ok(());
9440 }
9441 if matches!(error, Value::Uninitialized) {
9442 self.fulfill_promise(promise, Value::Undefined);
9443 } else {
9444 self.reject_promise(promise, error);
9445 }
9446 return Ok(());
9447 }
9448 let Some(Value::Object(pair)) = remaining
9449 .array_get(length - 1)
9450 .filter(|v| !matches!(v, Value::Hole))
9451 else {
9452 remaining.array_truncate(self.heap, length - 1);
9453 continue;
9454 };
9455 remaining.array_truncate(self.heap, length - 1);
9456 let value = pair.array_get(0).unwrap_or(Value::Undefined);
9457 let Some(Value::Object(method)) = pair.array_get(1) else {
9458 continue;
9459 };
9460 if !method.is_callable() {
9461 continue;
9462 }
9463 match self.call_value(Value::Object(method), value, Vec::new()) {
9464 Ok(result) => {
9465 if !self.is_thenable(&result)? {
9466 // Finished synchronously; the next disposer is the next iteration.
9467 continue;
9468 }
9469 let awaited = match self.promise_resolve_value(result) {
9470 Ok(awaited) => awaited,
9471 Err(Signal::Throw(reason)) => {
9472 self.reject_promise(promise, reason);
9473 return Ok(());
9474 }
9475 Err(other) => return Err(other),
9476 };
9477 let Value::Object(awaited) = awaited else {
9478 continue;
9479 };
9480 let ok = JsObject::function(
9481 self.heap,
9482 Some(self.realm.function_proto.clone()),
9483 Callable::DisposeStep {
9484 remaining: remaining.clone(),
9485 promise: promise.clone(),
9486 error: error.clone(),
9487 rejected: false,
9488 awaited: true,
9489 needs_await,
9490 },
9491 );
9492 let failed = JsObject::function(
9493 self.heap,
9494 Some(self.realm.function_proto.clone()),
9495 Callable::DisposeStep {
9496 remaining: remaining.clone(),
9497 promise: promise.clone(),
9498 error,
9499 rejected: true,
9500 awaited: true,
9501 needs_await,
9502 },
9503 );
9504 self.perform_then(
9505 &awaited,
9506 Some(Value::Object(ok)),
9507 Some(Value::Object(failed)),
9508 )?;
9509 return Ok(());
9510 }
9511 Err(Signal::Throw(thrown)) => {
9512 error = self.merge_dispose_error(thrown, error);
9513 }
9514 Err(other) => return Err(other),
9515 }
9516 }
9517 }
9518
9519 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9520 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9521 let Value::Object(object) = value else {
9522 return Ok(false);
9523 };
9524 Ok(matches!(
9525 self.get_property(object, "then")?,
9526 Some(Value::Object(then)) if then.is_callable()
9527 ))
9528 }
9529
9530 /// One step of an async generator, settling `promise` with an `{value, done}` result.
9531 fn step_async_generator(
9532 &mut self,
9533 generator: &Gc<JsObject>,
9534 promise: &Gc<JsObject>,
9535 kind: ResumeKind,
9536 value: Value,
9537 ) -> JsResult<()> {
9538 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9539 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9540 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9541 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9542 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9543 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9544 // out of the same read, one as a rejection and one as a rethrow.
9545 //
9546 // Narrow on purpose: only a value that is *already a promise* is inspected, so
9547 // nothing changes for `return 1` and the extra read is a plain data-property
9548 // lookup on the intrinsic case.
9549 if kind == ResumeKind::Return
9550 && let Value::Object(object) = &value
9551 && self.promise_state(object).is_some()
9552 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9553 {
9554 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9555 }
9556 let stepped = self.resume_generator_detailed(generator, kind, value);
9557 let (value, done, ready, reason) = match stepped {
9558 Ok(stepped) => stepped,
9559 Err(Signal::Throw(reason)) => {
9560 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9561 }
9562 Err(other) => return Err(other),
9563 };
9564 // Only an `await` has to wait before the method can answer.
9565 if !done && reason == Some(SuspendKind::Await) {
9566 let awaited = match self.promise_resolve_value(value) {
9567 Ok(awaited) => awaited,
9568 Err(Signal::Throw(reason)) => {
9569 return self.settle_async_request(
9570 generator,
9571 promise,
9572 AsyncOutcome::Error(reason),
9573 );
9574 }
9575 Err(other) => return Err(other),
9576 };
9577 let Value::Object(awaited) = awaited else {
9578 return Ok(());
9579 };
9580 let resumed = JsObject::function(
9581 self.heap,
9582 Some(self.realm.function_proto.clone()),
9583 Callable::GeneratorResume {
9584 generator: generator.clone(),
9585 promise: promise.clone(),
9586 kind: ResumeKind::Next,
9587 },
9588 );
9589 let raised = JsObject::function(
9590 self.heap,
9591 Some(self.realm.function_proto.clone()),
9592 Callable::GeneratorResume {
9593 generator: generator.clone(),
9594 promise: promise.clone(),
9595 kind: ResumeKind::Throw,
9596 },
9597 );
9598 self.perform_then(
9599 &awaited,
9600 Some(Value::Object(resumed)),
9601 Some(Value::Object(raised)),
9602 )?;
9603 return Ok(());
9604 }
9605 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9606 // completes it — both arrive as the settled value rather than as the promise
9607 // object. A plain value skips the round trip, which is also what keeps `yield 1`
9608 // from costing an extra tick.
9609 let awaits_value = self.is_thenable(&value)?;
9610 if awaits_value {
9611 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9612 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9613 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9614 // no `PromiseResolve` appears, so that path keeps the shortcut.
9615 let awaited = match if done {
9616 self.promise_resolve_intrinsic(value)
9617 } else {
9618 self.promise_resolve_value(value)
9619 } {
9620 Ok(awaited) => awaited,
9621 Err(Signal::Throw(reason)) => {
9622 return self.settle_async_request(
9623 generator,
9624 promise,
9625 AsyncOutcome::Error(reason),
9626 );
9627 }
9628 Err(other) => return Err(other),
9629 };
9630 let Value::Object(awaited) = awaited else {
9631 return Ok(());
9632 };
9633 // A rejected yield throws *at the yield* inside the body, so the rejection
9634 // resumes the generator rather than the method's promise.
9635 let answer = JsObject::function(
9636 self.heap,
9637 Some(self.realm.function_proto.clone()),
9638 Callable::YieldResult {
9639 generator: generator.clone(),
9640 promise: promise.clone(),
9641 done,
9642 },
9643 );
9644 let raise = JsObject::function(
9645 self.heap,
9646 Some(self.realm.function_proto.clone()),
9647 Callable::GeneratorResume {
9648 generator: generator.clone(),
9649 promise: promise.clone(),
9650 kind: ResumeKind::Throw,
9651 },
9652 );
9653 self.perform_then(
9654 &awaited,
9655 Some(Value::Object(answer)),
9656 Some(Value::Object(raise)),
9657 )?;
9658 return Ok(());
9659 }
9660 let result = if ready {
9661 // `yield*` handed back the inner iterator's own result object.
9662 value
9663 } else {
9664 self.iterator_result(value, done)?
9665 };
9666 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9667 }
9668
9669 /// The `{value, done}` object an iterator method answers with.
9670 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9671 let result = self.new_object(Some(self.realm.object_proto.clone()));
9672 result.define_data("value", value);
9673 result.define_data("done", Value::Bool(done));
9674 Ok(Value::Object(result))
9675 }
9676
9677 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9678 fn step_generator(
9679 &mut self,
9680 state: &mut GeneratorState,
9681 kind: ResumeKind,
9682 value: Value,
9683 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9684 match state.phase {
9685 GeneratorPhase::Executing => {
9686 return Err(self.type_error("cannot invoke a running generator"));
9687 }
9688 GeneratorPhase::Completed => {
9689 // A finished generator answers every resumption without running.
9690 return Ok(match kind {
9691 ResumeKind::Throw => return Err(Signal::Throw(value)),
9692 ResumeKind::Return => (value, true, false, None),
9693 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9694 });
9695 }
9696 GeneratorPhase::SuspendedStart => {
9697 if kind != ResumeKind::Next && kind != ResumeKind::Start {
9698 // The body never started, so there is nothing to unwind or return
9699 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9700 state.frame = None;
9701 state.phase = GeneratorPhase::Completed;
9702 return Ok(match kind {
9703 ResumeKind::Throw => return Err(Signal::Throw(value)),
9704 _ => (value, true, false, None),
9705 });
9706 }
9707 }
9708 GeneratorPhase::SuspendedYield => {}
9709 }
9710
9711 let Some(mut frame) = state.frame.take() else {
9712 return Ok((Value::Undefined, true, false, None));
9713 };
9714 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9715 // number that says which method resumed it; the emitted `if_false` branches on
9716 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9717 let mut raised = None;
9718 match kind {
9719 ResumeKind::Next | ResumeKind::Start => {
9720 if state.phase == GeneratorPhase::SuspendedYield {
9721 frame.stack.push(value);
9722 // An `await` resumes with its value alone; only a `yield` gets the
9723 // magic number that says which of `next`/`return` resumed it.
9724 if !state.parked_on_await {
9725 frame.stack.push(Value::Int(RESUME_NEXT));
9726 }
9727 }
9728 }
9729 ResumeKind::Return => {
9730 // A `return` on a not-yet-started generator is handled above, so this is
9731 // always a real resumption.
9732 frame.stack.push(value);
9733 frame.stack.push(Value::Int(RESUME_RETURN));
9734 }
9735 ResumeKind::Throw => {
9736 // At a `yield*` the exception is *data* for the delegation: the compiled
9737 // code resumes with the value and magic `2` and calls the inner iterator's
9738 // `throw`. Everywhere else it is raised at the suspension point, so the
9739 // body's own handler sees it.
9740 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9741 frame.stack.push(value);
9742 frame.stack.push(Value::Int(RESUME_THROW));
9743 } else {
9744 raised = Some(value);
9745 }
9746 }
9747 }
9748 state.phase = GeneratorPhase::Executing;
9749
9750 let depth = self.frames.len();
9751 self.frames.push(frame);
9752 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9753 // happened at the `yield`.
9754 if let Some(mut exception) = raised {
9755 if self.catch_here(&mut exception).is_none() {
9756 self.pop_frame();
9757 state.phase = GeneratorPhase::Completed;
9758 return Err(Signal::Throw(exception));
9759 }
9760 }
9761
9762 // Only the generator's *own* frame ends the generator. The body may call ordinary
9763 // functions, and those push frames of their own: a `Step::Return` from one of them
9764 // is a nested call finishing, not the generator completing. Miscounting that is
9765 // silent — the generator reports the callee's value as its own result and marks
9766 // itself done — so the depth comparison is load-bearing, not defensive.
9767 let own_frame = depth + 1;
9768 loop {
9769 match self.step() {
9770 Ok(Step::Continue) => {}
9771 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9772 let mut frame = self.frames.pop().expect("a frame is live");
9773 // `yield` left the value on the stack; `initial_yield` left nothing.
9774 let yielded = if reason == SuspendKind::Initial {
9775 Value::Undefined
9776 } else {
9777 frame.stack.pop().unwrap_or(Value::Undefined)
9778 };
9779 state.frame = Some(frame);
9780 state.parked_on_await = reason == SuspendKind::Await;
9781 state.parked_on_yield_star =
9782 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9783 state.phase = if reason == SuspendKind::Initial {
9784 GeneratorPhase::SuspendedStart
9785 } else {
9786 GeneratorPhase::SuspendedYield
9787 };
9788 // `yield*` hands the inner iterator's own result object straight
9789 // back, so the caller sees one `{value, done}` rather than a nested
9790 // one — which is why the third field says "already a result".
9791 return Ok((
9792 yielded,
9793 false,
9794 reason == SuspendKind::YieldStar,
9795 Some(reason),
9796 ));
9797 }
9798 Ok(Step::Suspend(_)) => {
9799 // A `yield` in a frame other than the generator's would mean a
9800 // generator body entered as an ordinary call, which
9801 // `call_or_push` prevents.
9802 self.unwind_to(depth);
9803 state.phase = GeneratorPhase::Completed;
9804 return Err(Signal::Throw(self.make_error(
9805 "InternalError",
9806 "a generator body ran as an ordinary call",
9807 )));
9808 }
9809 Ok(Step::Return(value)) => {
9810 self.pop_frame();
9811 if self.frames.len() > depth {
9812 // A nested call finished: hand the value back to its caller and
9813 // keep running the generator body.
9814 self.frames
9815 .last_mut()
9816 .expect("a caller is live")
9817 .stack
9818 .push(value);
9819 continue;
9820 }
9821 state.phase = GeneratorPhase::Completed;
9822 // The reference closes the generator's closure variables here; ours
9823 // live in cells the frame owned, which the drop below releases.
9824 return Ok((value, true, false, None));
9825 }
9826 Err(Signal::Throw(exception)) => {
9827 // The frame that threw gets the first chance to catch, exactly as in
9828 // the ordinary call loop; a frame above the generator's is popped and
9829 // the exception carries on down.
9830 let mut exception = exception;
9831 loop {
9832 if self.frames.len() <= depth {
9833 // The generator's own frame is gone, so nothing here caught it.
9834 state.phase = GeneratorPhase::Completed;
9835 return Err(Signal::Throw(exception));
9836 }
9837 if self.catch_here(&mut exception).is_some() {
9838 break;
9839 }
9840 self.pop_frame();
9841 }
9842 }
9843 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9844 }
9845 }
9846 }
9847
9848 /// Pop frames until `depth` are left, keeping their buffers.
9849 fn unwind_to(&mut self, depth: usize) {
9850 while self.frames.len() > depth {
9851 self.pop_frame();
9852 }
9853 }
9854 fn call_or_push(
9855 &mut self,
9856 callee: Value,
9857 this: Value,
9858 args: Vec<Value>,
9859 ) -> JsResult<Option<Value>> {
9860 if let Value::Object(function) = &callee
9861 && let Some((code, env)) = bytecode_of(function)
9862 {
9863 // Calling a generator function does not run anything: it captures the
9864 // arguments in a frame and hands back the generator object.
9865 if code.code.kind.is_generator() {
9866 return self.new_generator(callee, this, args).map(Some);
9867 }
9868 // An async function answers a promise and runs its body as a coroutine, so it
9869 // takes the same path as a plain call into it.
9870 if code.code.kind.is_async() {
9871 return self.new_async_function(callee, this, args).map(Some);
9872 }
9873 self.push_frame(code, env, this, args, callee)?;
9874 return Ok(None);
9875 }
9876 self.call_value(callee, this, args).map(Some)
9877 }
9878
9879 /// `new callee(args)`.
9880 ///
9881 /// A constructor differs from a plain call in three ways: it gets a fresh object
9882 /// as `this` whose prototype is the constructor's `prototype` property, its
9883 /// return value is *replaced* by that object unless it returns an object itself,
9884 /// and a native constructor is expected to initialise the object it is given
9885 /// rather than build one.
9886 pub fn construct(
9887 &mut self,
9888 callee: Value,
9889 new_target: Value,
9890 args: Vec<Value>,
9891 ) -> JsResult<Value> {
9892 // `new` on a bound function constructs its *target*, prepending the arguments
9893 // the bind fixed and ignoring the bound `this` — a bound function is a
9894 // constructor only when its target is one, and `new` always makes a fresh
9895 // object of the target's prototype rather than reusing the bound receiver.
9896 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9897 // ran the body with `this === null` and threw on `this.x = a`.
9898 let mut callee = callee;
9899 let mut new_target = new_target;
9900 let mut args = args;
9901 loop {
9902 let Some(object) = callee.as_object().cloned() else {
9903 return Err(Signal::Throw(
9904 self.make_error("TypeError", "not a constructor"),
9905 ));
9906 };
9907 // A proxy of a function constructs through its `construct` trap, and the
9908 // trap's answer is the result directly — no fresh object is made here.
9909 if object.proxy_state().is_some() {
9910 return match self.proxy_construct(&object, args, &new_target)? {
9911 Some(result) => Ok(result),
9912 None => Err(Signal::Throw(
9913 self.make_error("TypeError", "proxy target is not a constructor"),
9914 )),
9915 };
9916 }
9917 // A generator function has no `[[Construct]]`, and the reference names it in
9918 // the message: `new (function* G(){})()` reports "G is not a constructor".
9919 if object.with(|data| match &data.kind {
9920 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9921 code.code.kind.is_generator()
9922 }
9923 _ => false,
9924 }) {
9925 let name = object
9926 .own_property("name")
9927 .and_then(|property| property.value)
9928 .map(|value| value.to_js_string())
9929 .unwrap_or_default();
9930 return Err(Signal::Throw(
9931 self.make_error("TypeError", &format!("{name} is not a constructor")),
9932 ));
9933 }
9934 let bound = object.with(|data| match &data.kind {
9935 ObjectKind::Function(Callable::Bound {
9936 target,
9937 args: leading,
9938 ..
9939 }) => Some((target.clone(), leading.clone())),
9940 _ => None,
9941 });
9942 let Some((target, leading)) = bound else {
9943 // Not a bound function, so this object is the callee. §7.2.4
9944 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9945 // refusals above cover only the built-ins the reference also refuses by
9946 // name. Everything else — a method, an arrow, an async function — has no
9947 // `[[Construct]]` either, and answering "yes" here made
9948 // `new (Array.prototype.map)` build an object instead of throwing.
9949 if !object.is_constructor() {
9950 let name = object
9951 .own_property("name")
9952 .and_then(|property| property.value)
9953 .map(|value| value.to_js_string())
9954 .unwrap_or_default();
9955 return Err(Signal::Throw(
9956 self.make_error("TypeError", &format!("{name} is not a constructor")),
9957 ));
9958 }
9959 break;
9960 };
9961 let mut all = leading;
9962 all.extend(args);
9963 args = all;
9964 // A bound function that is its own `new.target` stands in for its target:
9965 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9966 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9967 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9968 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9969 _ => false,
9970 };
9971 if same_wrapper {
9972 new_target = target.clone();
9973 }
9974 callee = target;
9975 }
9976 let Value::Object(function) = &callee else {
9977 unreachable!("the loop above only breaks on an object");
9978 };
9979 // The fresh object's prototype comes from `new.target`, not from the callee: a
9980 // derived constructor reaches here through `super()`, and the instance must be a
9981 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9982 // an object inheriting `D.prototype` rather than `C.prototype`.
9983 let prototype_source = match new_target.as_object() {
9984 Some(target) => target.clone(),
9985 None => function.clone(),
9986 };
9987 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9988 // has validated its arguments. Pre-building one here would read
9989 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9990 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9991 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9992 let is_native = function.native_creates_own_instance();
9993 let this = if is_native {
9994 Value::Undefined
9995 } else {
9996 let prototype = self.get_property(&prototype_source, "prototype")?;
9997 let prototype = match prototype {
9998 Some(Value::Object(proto)) => Some(proto),
9999 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
10000 // object, the answer is the realm's *intrinsic* prototype for this
10001 // constructor, not `%Object.prototype%`.
10002 _ => {
10003 // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
10004 // and that is a `TypeError` for a revoked proxy. Without it, `new
10005 // revokedProxy()` quietly produced an `%Object.prototype%` instance —
10006 // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
10007 // trap, so it is already revoked when this fallback runs.
10008 if prototype_source.proxy_state().is_some() {
10009 self.proxy_parts(&prototype_source)?;
10010 }
10011 let fallback = self.get_property(function, "prototype")?;
10012 match fallback {
10013 Some(Value::Object(proto)) => Some(proto),
10014 _ => Some(self.realm.object_proto.clone()),
10015 }
10016 }
10017 };
10018 Value::Object(self.new_object(prototype))
10019 };
10020 // `new.target` inside the body is the constructor that was written, so a bound
10021 // function's target sees itself rather than the bound wrapper.
10022 //
10023 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
10024 // `?`, so assigning `None` after the call would be skipped and the failed
10025 // `new.target` would stay visible to every later native call. The symptom was a
10026 // native constructor refusing a plain call — `var s = Symbol(); new
10027 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
10028 // "FinalizationRegistry is not a constructor".
10029 let outer_new_target = self.pending_new_target.replace(new_target);
10030 let callee = callee.clone();
10031 let result = self.call_value(callee, this.clone(), args);
10032 self.pending_new_target = outer_new_target;
10033 let result = result?;
10034 // A constructor that returns an object overrides `this`; any other return value
10035 // (including `undefined`) is ignored — **except** in a derived constructor, where
10036 // §15.7.1 step 12 makes a non-object return a `TypeError`
10037 // (`Function/internals/Construct/derived-return-val`).
10038 let derived = function.with(|data| match &data.kind {
10039 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
10040 code.code.is_derived_constructor
10041 }
10042 _ => false,
10043 });
10044 Ok(match result {
10045 Value::Object(_) => result,
10046 // A bare `return;` answers `undefined`, which is **legal** even in a derived
10047 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
10048 Value::Undefined => this,
10049 _ if derived => {
10050 return Err(Signal::Throw(self.make_error(
10051 "TypeError",
10052 "derived constructor may only return an object or undefined",
10053 )));
10054 }
10055 _ => this,
10056 })
10057 }
10058
10059 /// `new.target` for the call currently being made.
10060 ///
10061 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
10062 /// it as `this`), but a *host* constructor that builds its own instance is handed
10063 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
10064 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
10065 /// it here.
10066 ///
10067 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
10068 /// receives for a plain call.
10069 pub fn current_new_target(&self) -> Value {
10070 self.active_new_target.clone()
10071 }
10072
10073 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
10074 ///
10075 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
10076 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
10077 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
10078 let constructor = self.realm.errors.get("AggregateError").cloned();
10079 let Some(constructor) = constructor else {
10080 return self.make_error("AggregateError", message);
10081 };
10082 let list = self.new_array(errors);
10083 match self.construct(
10084 Value::Object(constructor.clone()),
10085 Value::Object(constructor),
10086 vec![Value::Object(list), self.string(message)],
10087 ) {
10088 Ok(value) => value,
10089 // A user could have replaced `AggregateError` with something that throws; the
10090 // engine still owes the caller a rejection, so it falls back rather than
10091 // turning `Promise.any`'s rejection into a throw.
10092 Err(_) => self.make_error("AggregateError", message),
10093 }
10094 }
10095
10096 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
10097 ///
10098 /// The error classes themselves arrive with the builtins milestone; what
10099 /// matters here is that the thrown value stringifies the way a script printing
10100 /// the caught value expects.
10101 ///
10102 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
10103 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
10104 /// rely on when they print a caught value.
10105 pub fn make_error(&self, name: &str, message: &str) -> Value {
10106 let proto = self
10107 .realm
10108 .errors
10109 .get(name)
10110 .map(|constructor| self.prototype_of(constructor))
10111 .unwrap_or_else(|| self.realm.error_proto.clone());
10112 let error = self.new_object(Some(proto));
10113 // `name` and `message` are own properties of the instance, which is what
10114 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
10115 // `Error`.
10116 error.define(
10117 "name",
10118 Property::with_attributes(self.string(name), true, false),
10119 );
10120 error.define(
10121 "message",
10122 Property::with_attributes(self.string(message), true, false),
10123 );
10124 // The internal class, which is what tells a printer this is an error rather than a
10125 // plain object with `name` and `message` properties. The constructor path sets it
10126 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
10127 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
10128 // literally `"Error"` in both places — the *name* is read from `name`, which is why
10129 // a `RangeError` still prints as `RangeError`.
10130 self.internal_set(&error, "_class", self.string("Error"));
10131 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
10132 // answered `false` from `Error.isError` while a constructed one answered `true`,
10133 // because only the constructor set the slot. The reference answers `true` for both
10134 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
10135 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
10136 // tests `typeof stack === "string"` to decide on a trailing newline, so every
10137 // engine-thrown error lost its blank line.
10138 self.internal_set(&error, "_error_data", Value::Bool(true));
10139 // The trace is captured where the error is *made*, which is where the reference
10140 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
10141 // way out, so a caught engine error already has its stack even if the handler
10142 // never rethrows it.
10143 self.add_stack(&error);
10144 Value::Object(error)
10145 }
10146
10147 /// Give an error object its `stack` property, from the current frame stack.
10148 ///
10149 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
10150 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
10151 /// `stack` a script set, is not rewritten.
10152 pub fn add_stack(&self, object: &Gc<JsObject>) {
10153 self.add_stack_skipping(object, 0);
10154 }
10155
10156 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
10157 ///
10158 /// An `Error` constructor passes 1: the reference builds those traces with
10159 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
10160 /// constructor itself, while a `RangeError` raised inside `toISOString` does
10161 /// report `at toISOString (native)`.
10162 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
10163 if object.has_own("stack") {
10164 return;
10165 }
10166 // The trace is *captured* here but not installed as a property: `stack` is an
10167 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
10168 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
10169 // is kept in a hidden slot and the getter materialises it on first read.
10170 //
10171 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
10172 // shows it — this is the same discipline `_error_data` and `_class` follow.
10173 let trace = self.stack_trace_skipping(skip);
10174 let text = self.string(trace);
10175 self.internal_set(object, "_stack_trace", text);
10176 }
10177
10178 /// The function object currently being called, if any.
10179 ///
10180 /// A native function is a bare `fn` pointer, so it cannot capture which class
10181 /// it belongs to; it reads that from the callee instead. This is also what a
10182 /// stack trace would use.
10183 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
10184 // A native has no frame of its own — it is recorded in `current_native` — so asking
10185 // `frames` answered with the *bytecode caller's* callee. `Error`'s constructor reads
10186 // the class off this, and every plain call therefore built an `Error`:
10187 // `EvalError(1)` had the name `"Error"` (`try/S12.14_A19_T1`).
10188 //
10189 // Only while the native is the innermost thing running. It stays recorded while the
10190 // native drives *through* user code — `Iterator.prototype.take` calls the `next` a
10191 // script wrote — and answering with it there gave that user code the native's callee:
10192 // `super()` looked up the native's prototype instead of its own constructor's.
10193 // `native_frames` records `frames.len()` from before the native ran, so an equal
10194 // length means nothing has been pushed since.
10195 if let Some(native) = &self.current_native
10196 && self
10197 .native_frames
10198 .last()
10199 .is_some_and(|(_, depth)| *depth == self.frames.len())
10200 {
10201 return Some(native.clone());
10202 }
10203 match &self.frames.last()?.callee {
10204 Value::Object(object) => Some(object.clone()),
10205 _ => None,
10206 }
10207 }
10208
10209 /// The `prototype` property of a constructor, falling back to
10210 /// `Object.prototype` for anything that is not shaped like one.
10211 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
10212 constructor
10213 .own_property("prototype")
10214 .and_then(|property| property.value)
10215 .and_then(|value| value.as_object().cloned())
10216 .unwrap_or_else(|| self.realm.object_proto.clone())
10217 }
10218
10219 /// Throw a `TypeError` carrying `message`.
10220 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
10221 Signal::Throw(self.make_error("TypeError", message.as_ref()))
10222 }
10223
10224 /// Throw a `RangeError` carrying `message`.
10225 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
10226 Signal::Throw(self.make_error("RangeError", message.as_ref()))
10227 }
10228
10229 /// A `ReferenceError`, as the value to throw.
10230 ///
10231 /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10232 /// and its siblings report a `ReferenceError` there, which is what
10233 /// `adopt|defer|move/throws-if-disposed` assert.
10234 pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10235 Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10236 }
10237
10238 /// The `ReferenceError` a read of an uninitialised binding raises.
10239 /// The name of the binding `slot` refers to, for an error message.
10240 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10241 match kind {
10242 VarSlot::Loc => self
10243 .frame()
10244 .code
10245 .code
10246 .vars
10247 .get(slot)
10248 .map(|v| v.name.clone()),
10249 VarSlot::Closure => self
10250 .frame()
10251 .code
10252 .code
10253 .closure_vars
10254 .get(slot)
10255 .map(|c| c.name.clone()),
10256 }
10257 .unwrap_or_default()
10258 }
10259
10260 /// Whether `slot` names a `const` binding, which rejects every store after its
10261 /// initialiser.
10262 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10263 match kind {
10264 VarSlot::Loc => self
10265 .frame()
10266 .code
10267 .code
10268 .vars
10269 .get(slot)
10270 .is_some_and(|v| v.is_const),
10271 VarSlot::Closure => self
10272 .frame()
10273 .code
10274 .code
10275 .closure_vars
10276 .get(slot)
10277 .is_some_and(|c| c.is_const),
10278 }
10279 }
10280
10281 /// The `TypeError` a store to a `const` binding raises.
10282 ///
10283 /// `const` is enforced here rather than at compile time because the binding can be
10284 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10285 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10286 /// both halves of what "checked store" means: the dead zone is over, and the
10287 /// binding is writable.
10288 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10289 let name = self.binding_name(slot, kind);
10290 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10291 }
10292
10293 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10294 let name = match kind {
10295 VarSlot::Loc => self
10296 .frame()
10297 .code
10298 .code
10299 .vars
10300 .get(slot)
10301 .map(|v| v.name.clone()),
10302 VarSlot::Closure => self
10303 .frame()
10304 .code
10305 .code
10306 .closure_vars
10307 .get(slot)
10308 .map(|c| c.name.clone()),
10309 }
10310 .unwrap_or_default();
10311 // The reference has a wording of its own for `this`, because the dead zone it sits
10312 // in is the derived constructor's rather than a `let`'s: `constructor(){ return; }`
10313 // reports `this is not initialized`.
10314 let message = if name == "this" {
10315 "this is not initialized".to_string()
10316 } else {
10317 format!("cannot access '{name}' before initialization")
10318 };
10319 Signal::Throw(self.make_error("ReferenceError", &message))
10320 }
10321
10322 /// The reference a `make_*_ref` opcode builds, from the object it produced.
10323 fn reference_target(&mut self, offset: usize) -> JsResult<RefTarget> {
10324 match self.peek(offset) {
10325 Value::Object(object) => object.reference().ok_or_else(|| {
10326 self.type_error("a reference operation on something that is not a reference")
10327 }),
10328 _ => Err(self.type_error("a reference operation on a non-object")),
10329 }
10330 }
10331
10332 /// `ResolveBinding(name)` for a name the compiler could only resolve statically as "a
10333 /// global".
10334 ///
10335 /// Three answers, in the order §9.1.1.4 asks them:
10336 ///
10337 /// * a local a direct `eval` declared in this frame — the innermost variable
10338 /// environment, so it wins;
10339 /// * an existing global binding or an existing property of the global object;
10340 /// * nothing, which is an **unresolvable** reference (base `undefined`) rather than a
10341 /// failure: reading it throws and a sloppy write creates the global.
10342 fn global_reference(&mut self, name: &crate::value::Wtf8) -> JsResult<RefTarget> {
10343 if let Some((local_vars, phase)) = self.visible_local_vars() {
10344 let key = name.to_string_lossy();
10345 if local_vars.contains(&key)
10346 && let Some(cell) = local_vars.get(&key, phase)
10347 {
10348 return Ok(RefTarget::Cell(cell));
10349 }
10350 }
10351 let key = PropertyKey::String(name.clone());
10352 let global = self.realm.global.clone();
10353 let has = self.has_own_or_inherited(&global, &key)?;
10354 Ok(RefTarget::Property {
10355 base: if has {
10356 Value::Object(global)
10357 } else {
10358 Value::Undefined
10359 },
10360 name: key,
10361 })
10362 }
10363
10364 fn throw_reference(&self, name: &str) -> Signal {
10365 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10366 }
10367
10368 // -- the instruction loop -----------------------------------------------
10369
10370 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10371 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10372 // measured at 16% of a tight arithmetic loop's total time.
10373 #[inline(always)]
10374 fn step(&mut self) -> JsResult<Step> {
10375 // The instruction is already decoded (see [`crate::insn`]), so this is an index
10376 // and a `Copy` read rather than a table lookup plus a width switch. Only the
10377 // borrow lives across the boundary; nothing is cloned.
10378 // **One** borrow of the frame: fetch the record, then advance in the same scope.
10379 // The obvious version borrowed it three times (`last` to read, `last_mut` to
10380 // write, and once more inside the handler), and each is a bounds check plus an
10381 // `Option` unwrap — on the one path every instruction takes.
10382 let Some((insn, next)) = ({
10383 let frame = self
10384 .frames
10385 .last_mut()
10386 .expect("step() is only called with a live frame");
10387 // Past the last instruction is a normal return: the compiler ends a function
10388 // with `return`, and a jump to the end of a block lands here.
10389 let insn = frame.insns().get(frame.pc).copied();
10390 match insn {
10391 None => None,
10392 Some(insn) => {
10393 // A fused record stands for the next few instructions, so the next
10394 // `pc` is its width ahead — the instructions it replaces are never
10395 // dispatched. `at` is the byte offset a stack trace reports; it stays
10396 // an offset because the line table is keyed by bytes.
10397 frame.at = insn.offset as usize;
10398 frame.pc += insn.width();
10399 Some((insn, frame.pc))
10400 }
10401 }
10402 }) else {
10403 return Ok(Step::Return(Value::Undefined));
10404 };
10405 self.check_memory()?;
10406 self.check_interrupt()?;
10407 if insn.fused == crate::insn::Fused::None {
10408 self.execute_instruction(insn.op, insn.a, insn.b, next)
10409 } else {
10410 self.execute_fused(insn)
10411 }
10412 }
10413
10414 /// Run a fused instruction: several bytecode instructions in one dispatch.
10415 ///
10416 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10417 /// it cannot throw and cannot allocate — and anything else falls back to the real
10418 /// instructions, in their real order, so an exception leaves the operand stack
10419 /// exactly as it would have been.
10420 #[inline]
10421 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10422 use crate::insn::Fused;
10423 let slot = insn.a as usize;
10424 match insn.fused {
10425 // `x = k`: `push k; put_loc x`.
10426 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10427 // `x += k`: `get_loc x; push k; add; put_loc x`.
10428 Fused::AddImmLoc => {
10429 let delta = insn.b as i32;
10430 match self.get_loc(slot) {
10431 Value::Int(left) => {
10432 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10433 // that built two `Value`s, called a function, and matched on them
10434 // again to reach this same `checked_add`. It is the innermost
10435 // operation of every accumulator in every program.
10436 let answer = match left.checked_add(delta) {
10437 Some(sum) => Value::Int(sum),
10438 None => Value::Float(left as f64 + delta as f64),
10439 };
10440 self.put_loc(slot, answer);
10441 }
10442 other => {
10443 self.push(other);
10444 self.push(Value::Int(delta));
10445 self.binary_add()?;
10446 let value = self.pop();
10447 self.put_loc(slot, value);
10448 }
10449 }
10450 }
10451 // `x += "literal"` and `x += y`: the two shapes that can append in place.
10452 Fused::AddAtomLoc => {
10453 let text = self.atom_wtf8(insn.b as usize);
10454 let right = self.string_wtf8(text);
10455 self.add_into_loc(slot, right)?;
10456 }
10457 Fused::AddLocLoc => {
10458 let source = (insn.a & 0xFFFF) as usize;
10459 let target = (insn.a >> 16) as usize;
10460 let right = self.get_loc(source);
10461 self.add_into_loc(target, right)?;
10462 }
10463 Fused::AddArgLoc => {
10464 let source = (insn.a & 0xFFFF) as usize;
10465 let target = (insn.a >> 16) as usize;
10466 let right = self.get_arg(source);
10467 self.add_into_loc(target, right)?;
10468 }
10469 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10470 Fused::PostIncLoc => match self.get_loc(slot) {
10471 Value::Int(left) => {
10472 let answer = match left.checked_add(1) {
10473 Some(sum) => Value::Int(sum),
10474 None => Value::Float(left as f64 + 1.0),
10475 };
10476 self.put_loc(slot, answer);
10477 }
10478 other => {
10479 self.push(other);
10480 let raw = self.pop();
10481 let (old, updated) = self.advance_numeric(raw, true)?;
10482 self.push(old);
10483 self.push(updated);
10484 let value = self.pop();
10485 self.put_loc(slot, value);
10486 self.pop();
10487 }
10488 },
10489 // `if (!(x < arg)) goto target`: a loop header.
10490 //
10491 // The comparison is computed rather than replayed on the operand stack. That
10492 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10493 // that throws: the effects happen in the same order, and a handler truncates
10494 // the stack down to its marker, so the intermediate values are unobservable.
10495 Fused::LtLocArgJump => {
10496 let loc = (insn.a >> 16) as usize;
10497 let arg = (insn.a & 0xFFFF) as usize;
10498 let left = self.get_loc(loc);
10499 let right = self.get_arg(arg);
10500 let taken = match (&left, &right) {
10501 (Value::Int(left), Value::Int(right)) => !(left < right),
10502 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10503 };
10504 if taken {
10505 self.frame_mut().pc = insn.b as usize;
10506 }
10507 }
10508 // `i < k` in a loop header, where `k` is an integer literal.
10509 Fused::LtLocImmJump => {
10510 let left = self.get_loc(insn.a as usize);
10511 let right = Value::Int(insn.imm as i32);
10512 let taken = match &left {
10513 Value::Int(left) => !(*left < insn.imm as i32),
10514 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10515 };
10516 if taken {
10517 self.frame_mut().pc = insn.b as usize;
10518 }
10519 }
10520 Fused::None => unreachable!("only called for a fused record"),
10521 }
10522 Ok(Step::Continue)
10523 }
10524
10525 /// Run records that cannot call script, cannot throw and cannot change frames.
10526 ///
10527 /// Returns `Some(value)` when the function ran off the end of its instructions (a
10528 /// normal return), and `None` when it stopped in front of an instruction the slow path
10529 /// has to handle — `pc` is written back either way, so `step` resumes at the right
10530 /// place.
10531 ///
10532 /// **The invariant is the whole point.** Every arm here is restricted to work that
10533 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10534 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10535 /// that the memory limit has to see. An opcode whose operands turn out to need any of
10536 /// that **stops the loop** instead of trying, so the slow path gets the instruction
10537 /// untouched and with its operands still on the stack. That is why the fallback is a
10538 /// `break` and not a duplicated slow arm: a second implementation of the same
10539 /// semantics is how a wrong answer gets in with no test noticing.
10540 ///
10541 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10542 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10543 fn run_fast(&mut self) -> JsResult<Option<Value>> {
10544 use crate::insn::Fused;
10545 // The outer loop exists only so a `Call` can come back through here: once a
10546 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10547 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10548 // frame. Re-entering re-reads both from whichever frame is now on top. Every
10549 // other exit from the inner loop returns, so this costs one loop per call.
10550 'outer: loop {
10551 // One reference-count bump per *slow* instruction (a call, an allocation, a
10552 // property access), never one per instruction — that distinction is worth
10553 // two orders of magnitude and was measured as such.
10554 let (code, mut pc) = {
10555 let frame = self.frame();
10556 (frame.code.clone(), frame.pc)
10557 };
10558 let insns = &code.insns;
10559 loop {
10560 let Some(insn) = insns.get(pc).copied() else {
10561 self.frame_mut().pc = pc;
10562 return Ok(Some(Value::Undefined));
10563 };
10564 match insn.fused {
10565 // `x = k`
10566 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10567 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10568 // object — stops the loop so `binary_add` can decide.
10569 Fused::AddImmLoc => {
10570 let slot = insn.a as usize;
10571 let delta = insn.b as i32;
10572 let Value::Int(left) = self.get_loc(slot) else {
10573 return Ok(self.stop(pc));
10574 };
10575 let sum = match left.checked_add(delta) {
10576 Some(sum) => Value::Int(sum),
10577 None => Value::Float(left as f64 + delta as f64),
10578 };
10579 self.put_loc(slot, sum);
10580 }
10581 // `x += "literal"` / `x += y`: the operand is a string, so the append
10582 // either allocates one or grows one. Both are the slow path's business;
10583 // the fusion's job is only to make the *slot* the sole owner, which is what
10584 // `execute_fused` needs and what `get_loc` alone destroys.
10585 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10586 return Ok(self.stop(pc));
10587 }
10588 // `x++` on an integer, old value dropped.
10589 Fused::PostIncLoc => {
10590 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10591 // value is read in place and overwritten in place, so the reference
10592 // count it held is released by the same assignment that stores the
10593 // new one. `get_loc` plus `put_loc` did two borrows, two table
10594 // lookups and a clone, and this arm is the whole body of a counting
10595 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10596 let slot = insn.a as usize;
10597 let frame = self.frames.last_mut().expect("a frame is live");
10598 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10599 let target = if cell < 0 {
10600 frame.locals.get_mut(slot)
10601 } else {
10602 None
10603 };
10604 let Some(target) = target else {
10605 return Ok(self.stop(pc));
10606 };
10607 let Value::Int(left) = *target else {
10608 return Ok(self.stop(pc));
10609 };
10610 *target = match left.checked_add(1) {
10611 Some(sum) => Value::Int(sum),
10612 None => Value::Float(left as f64 + 1.0),
10613 };
10614 }
10615 // A loop header, `if (!(x < arg)) goto target`, with both sides already
10616 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10617 // bound stayed small integers.
10618 Fused::LtLocArgJump => {
10619 let loc = (insn.a >> 16) as usize;
10620 let arg = (insn.a & 0xFFFF) as usize;
10621 // One borrow for both slots: this arm *is* the whole loop of a
10622 // `for (i = 0; i < n; i++)` with an argument bound, so a second
10623 // `frames.last()` here is paid on every iteration. Measured 7.5% on
10624 // `dispatch:empty-loop`.
10625 let (left, right) = {
10626 let frame = self.frame();
10627 (frame.read_loc(loc), frame.read_arg(arg))
10628 };
10629 // Heavily measured: the bound is very often a `Float` even when the
10630 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10631 // `JSON.parse` or a division is one — so requiring both sides to be
10632 // `Int` sent every iteration of those loops down the slow path. The
10633 // comparison below is the same one `relational` makes for two numbers.
10634 if !is_number(&left) || !is_number(&right) {
10635 return Ok(self.stop(pc));
10636 }
10637 // `if_false` branches on the comparison being false, which is **not**
10638 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10639 // `>=` is also false and would keep it running forever. Clippy wants the
10640 // negation folded; that would be a wrong answer.
10641 let ordered = left.to_number() < right.to_number();
10642 let take_branch = !ordered;
10643 if take_branch {
10644 pc = insn.b as usize;
10645 continue;
10646 }
10647 }
10648 // The same header with a literal bound: `if (!(x < k)) goto target`.
10649 // The bound is an immediate, so only the counter needs a type test.
10650 #[allow(clippy::neg_cmp_op_on_partial_ord)]
10651 Fused::LtLocImmJump => {
10652 let left = self.get_loc(insn.a as usize);
10653 if !is_number(&left) {
10654 return Ok(self.stop(pc));
10655 }
10656 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10657 if take_branch {
10658 pc = insn.b as usize;
10659 continue;
10660 }
10661 }
10662 Fused::None => match insn.op {
10663 // -- branches ---------------------------------------------------
10664 // A jump is an assignment now, because the target is an instruction
10665 // index. No arithmetic, no resolution table.
10666 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10667 let target = insn.a as usize;
10668 // A **back-edge** is a loop, and it is the only place an
10669 // instruction-level checkpoint can stop one: `for(;;){}` compiles
10670 // to a jump to itself and never leaves this loop, so the
10671 // per-instruction checks in `step` never run. That is exactly the
10672 // hole this arm closes — a host's `JS_SetInterruptHandler` did
10673 // nothing to a `for(;;){}` until it did, which is what
10674 // `tests/c/embed.c` is for.
10675 //
10676 // Polling here rather than on every instruction in this loop is
10677 // also the reference's choice (`OP_goto` calls
10678 // `js_poll_interrupts`), and it costs one compare per branch
10679 // instead of one decrement per instruction.
10680 if target <= pc {
10681 self.frame_mut().pc = target;
10682 self.check_memory()?;
10683 self.check_interrupt()?;
10684 }
10685 pc = target;
10686 continue;
10687 }
10688 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10689 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10690 let taken = self.pop().to_boolean();
10691 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10692 if taken == want {
10693 pc = insn.a as usize;
10694 continue;
10695 }
10696 }
10697 // -- slot access -------------------------------------------------
10698 // A load's slot is already an operand (see `insn::implicit_operand`);
10699 // a captured one goes through its cell, which runs no script.
10700 Opcode::GetLoc
10701 | Opcode::GetLoc8
10702 | Opcode::GetLoc0
10703 | Opcode::GetLoc1
10704 | Opcode::GetLoc2
10705 | Opcode::GetLoc3 => {
10706 let value = self.get_loc(insn.a as usize);
10707 self.push(value);
10708 }
10709 Opcode::PutLoc
10710 | Opcode::PutLoc8
10711 | Opcode::PutLoc0
10712 | Opcode::PutLoc1
10713 | Opcode::PutLoc2
10714 | Opcode::PutLoc3 => {
10715 let value = self.pop();
10716 self.put_loc(insn.a as usize, value);
10717 }
10718 Opcode::GetArg
10719 | Opcode::GetArg0
10720 | Opcode::GetArg1
10721 | Opcode::GetArg2
10722 | Opcode::GetArg3 => {
10723 let value = self.get_arg(insn.a as usize);
10724 self.push(value);
10725 }
10726 Opcode::PutArg
10727 | Opcode::PutArg0
10728 | Opcode::PutArg1
10729 | Opcode::PutArg2
10730 | Opcode::PutArg3 => {
10731 let value = self.pop();
10732 self.put_arg(insn.a as usize, value);
10733 }
10734 // `a[i]` with an integer index on a dense array: see `fast_array_get`
10735 // for why a non-hole own element is exactly the slow path's answer.
10736 // The two operands are *peeked*, so a miss leaves the stack as the
10737 // slow path expects to find it.
10738 Opcode::GetArrayEl => {
10739 // One lookup, not two. The guard used `if …is_some()` and the arm
10740 // then called it again to get the value — two `peek`s, two
10741 // `array_get`s and two `Value` clones for one element.
10742 // `fast_array_get` was 13.1% of `array:indexed`, and the same
10743 // double call was the first version of the `get_field` fast path.
10744 let Some(value) = self.fast_array_get() else {
10745 return Ok(self.stop(pc));
10746 };
10747 // `a[i]` consumes both operands and leaves the element in their
10748 // place: one `truncate` and one write, no `pop`/`push` pair.
10749 let frame = self.frame_mut();
10750 frame.stack.truncate(frame.stack.len() - 2);
10751 frame.stack.push(value);
10752 }
10753 // `a[i] = v` on a dense array with an integer index: see
10754 // `fast_array_set` for why the whole store is one step.
10755 Opcode::PutArrayEl if self.fast_array_set() => {}
10756 // `o.x` resolved from the inline cache without leaving the loop.
10757 //
10758 // The cache is keyed by `(receiver identity, atom, site)` and a
10759 // monomorphic read re-validates the same chain every iteration, so
10760 // each one used to cost a `stop(pc)` — a write of `pc` into the
10761 // frame, a return out of this loop, a re-dispatch through `step` and
10762 // a re-entry. `property:monomorphic` spent 18% in
10763 // `read_field_cached` and 21% in `push`, both across that boundary.
10764 //
10765 // The site is `pc + width`, which is exactly the `next` the slow arm
10766 // passes — the two must agree or every fast lookup misses and
10767 // re-records the same entry forever.
10768 //
10769 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10770 // slow arm finds the receiver where it expects it.
10771 // `name` resolved from the global-variable cache inside the loop.
10772 //
10773 // Same shape as `get_field` above and for the same reason: `get_var`
10774 // was not in the fast loop, so reading a global — which `fib` does
10775 // once per recursive call, for its own name — cost a `stop(pc)`, a
10776 // return out of the loop, a `step` re-dispatch and a re-entry, before
10777 // `get_global` even started its `scopes_are_plain` checks.
10778 //
10779 // Everything here is exactly `get_global`'s first branch: not lexical,
10780 // no `eval` scope, cache hit. Anything else leaves the stack untouched
10781 // and lets the slow arm decide.
10782 Opcode::GetVar => {
10783 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10784 return Ok(self.stop(pc));
10785 };
10786 self.push(value);
10787 }
10788 Opcode::GetField | Opcode::GetField2 => {
10789 let Some(value) =
10790 self.fast_field_get(insn.a as usize, pc + insn.width())
10791 else {
10792 return Ok(self.stop(pc));
10793 };
10794 if insn.op == Opcode::GetField2 {
10795 // `get_field2` keeps the receiver for the `call_method` that
10796 // follows.
10797 self.push(value);
10798 } else {
10799 // `get_field` replaces the receiver, so this is one store over
10800 // the top slot rather than a `pop` and a `push`: the length
10801 // never changes, so neither `Vec` arm has a capacity check or a
10802 // drop to run beyond the one the overwrite itself does.
10803 let frame = self.frame_mut();
10804 match frame.stack.last_mut() {
10805 Some(slot) => *slot = value,
10806 None => return Ok(self.stop(pc)),
10807 }
10808 }
10809 }
10810 // -- constants ---------------------------------------------------
10811 Opcode::PushMinus1
10812 | Opcode::Push0
10813 | Opcode::Push1
10814 | Opcode::Push2
10815 | Opcode::Push3
10816 | Opcode::Push4
10817 | Opcode::Push5
10818 | Opcode::Push6
10819 | Opcode::Push7
10820 | Opcode::PushI8
10821 | Opcode::PushI16
10822 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10823 // -- stack shuffling ---------------------------------------------
10824 Opcode::Drop => {
10825 self.pop();
10826 }
10827 // -- arithmetic on two integers ----------------------------------
10828 //
10829 // The operands are *looked at* before they are popped, so a non-integer
10830 // pair leaves the stack exactly as the slow path expects to find it.
10831 Opcode::Add if self.numeric_pair() => {
10832 let right = self.pop();
10833 let left = self.pop();
10834 // Exactly [`add_numbers`], which is what the slow arm reaches.
10835 let answer = match (&left, &right) {
10836 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10837 Some(sum) => Value::Int(sum),
10838 None => Value::Float(*a as f64 + *b as f64),
10839 },
10840 _ => Value::Float(left.to_number() + right.to_number()),
10841 };
10842 self.push(answer);
10843 }
10844 Opcode::Sub
10845 | Opcode::And
10846 | Opcode::Or
10847 | Opcode::Xor
10848 | Opcode::Shl
10849 | Opcode::Sar
10850 | Opcode::Shr
10851 if self.numeric_pair() =>
10852 {
10853 let right = self.pop();
10854 let left = self.pop();
10855 let answer =
10856 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10857 self.push(answer);
10858 }
10859 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10860 if self.numeric_pair() =>
10861 {
10862 let right = self.pop();
10863 let left = self.pop();
10864 let answer = self
10865 .relational(insn.op, left, right)
10866 .expect("numbers cannot throw");
10867 self.push(answer);
10868 }
10869 // -- calls -------------------------------------------------------
10870 //
10871 // A plain call: `callee(arg0, …, argN) -> result`.
10872 //
10873 // This arm exists because of one measurement. `call:recursion` had
10874 // **20.4% of its profile in `execute_instruction`** — the *slow*
10875 // executor — and `fib`'s recursive call is the only thing in that
10876 // function which is not a fast arm. Every call therefore left this
10877 // loop via `stop()`, went through `step()`'s dispatch and
10878 // `execute_instruction`'s match over every opcode, and came back here
10879 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10880 //
10881 // Two things make it safe to do here rather than only in the slow path:
10882 //
10883 // * the caller's `pc` is stored *before* the call, which is what
10884 // `step` does too — so when the callee returns, the caller resumes
10885 // after the call and not at it;
10886 // * `check_memory` runs, because `step` calls it once per instruction
10887 // and a call allocates a frame, its locals and its cells. Skipping
10888 // the checkpoint here would let a `--memory-limit` script overshoot
10889 // by one call per instruction.
10890 Opcode::Call
10891 | Opcode::Call0
10892 | Opcode::Call1
10893 | Opcode::Call2
10894 | Opcode::Call3 => {
10895 let argc = self.argc_operand(insn.op, insn.a);
10896 let next = pc + insn.width();
10897 {
10898 let frame = self
10899 .frames
10900 .last_mut()
10901 .expect("run_fast() is only called with a live frame");
10902 // `at` is what a stack trace reports for this frame, so a throw
10903 // inside the callee has to see the call site and not whatever
10904 // the last `stop()` left there.
10905 frame.at = insn.offset as usize;
10906 frame.pc = next;
10907 }
10908 self.check_memory()?;
10909 self.check_interrupt()?;
10910 let args = self.pop_n(argc);
10911 let callee = self.pop();
10912 // A plain call has no receiver; the callee decides what to do with
10913 // `undefined` (a sloppy function substitutes the global object).
10914 if let Some(result) =
10915 self.call_or_push(callee, Value::Undefined, args)?
10916 {
10917 // Native, host, generator, async, bound — no frame was pushed,
10918 // so this loop is still describing the right function. `pc`
10919 // is advanced by the loop tail like every other arm; only the
10920 // frame's copy had to be written here, and it already was.
10921 self.push(result);
10922 } else {
10923 // A bytecode callee: its frame is on top now, and `insns` and
10924 // `pc` both belong to the caller. Start over on the new frame.
10925 continue 'outer;
10926 }
10927 }
10928 // -- return ------------------------------------------------------
10929 Opcode::Return => {
10930 let value = self.pop();
10931 self.frame_mut().pc = pc + insn.width();
10932 return Ok(Some(value));
10933 }
10934 Opcode::ReturnUndef => {
10935 self.frame_mut().pc = pc + insn.width();
10936 return Ok(Some(Value::Undefined));
10937 }
10938 // Everything else needs the slow path.
10939 _ => return Ok(self.stop(pc)),
10940 },
10941 }
10942 pc += insn.width();
10943 }
10944 }
10945 }
10946
10947 /// Whether the top two operand-stack values are both numbers.
10948 ///
10949 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10950 /// cannot run script, so the arm may not throw and may not change frames.
10951 fn numeric_pair(&self) -> bool {
10952 is_number(&self.peek(0)) && is_number(&self.peek(1))
10953 }
10954
10955 /// `a[i]` for a dense array and an integer index, without the string round trip.
10956 ///
10957 /// The slow path answers this by turning `i` into a string (`propkey` →
10958 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10959 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10960 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10961 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10962 /// without even the cheap `Int` formatting.
10963 ///
10964 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10965 /// unambiguously the one the slow path would give:
10966 ///
10967 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10968 /// `2^32-1` is the length, not an index),
10969 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10970 /// typed array or an ordinary object, all of which have their own rules),
10971 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10972 /// starts walking the prototype chain, and `a[i]` on a hole must find
10973 /// `Array.prototype[i]` if it exists rather than `undefined`.
10974 ///
10975 /// The last condition is the one that makes this safe rather than merely fast: an own
10976 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10977 /// `get_var` answered from the global-variable cache, or `None`.
10978 ///
10979 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10980 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10981 /// records nothing — the slow arm is about to walk the chain and record it.
10982 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10983 let frame = self.frame();
10984 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10985 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10986 // `GlobalRef` forwarded through a nested function has its flags cleared.
10987 if self.realm.globals.contains_key(name) {
10988 return None;
10989 }
10990 if !self.scopes_are_plain() {
10991 return None;
10992 }
10993 let object = &self.realm.global;
10994 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10995 let cached = self.global_cache[site].as_ref()?;
10996 if !object.upgrades_to(&cached.object) {
10997 return None;
10998 }
10999 object.data_property_at(cached.index, name)
11000 }
11001
11002 /// `o.x` answered entirely from the inline cache, or `None`.
11003 ///
11004 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
11005 /// about to do exactly that and recording it twice would rebuild the chain for every
11006 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
11007 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
11008 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
11009 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
11010 // an object receiver is a reference-count bump that the answer never needs.
11011 let frame = self.frame();
11012 let object = frame.stack.last()?;
11013 let Value::Object(target) = object else {
11014 return None;
11015 };
11016 // A proxy traps the lookup, so no cache entry ever describes it.
11017 if target.proxy_state().is_some() {
11018 return None;
11019 }
11020 let key = frame.code.atom_keys.get(atom)?;
11021 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
11022 if cached.key != *key {
11023 return None;
11024 }
11025 Self::cached_hit(target, cached)
11026 }
11027
11028 fn fast_array_get(&self) -> Option<Value> {
11029 let Value::Int(index) = self.peek(0) else {
11030 return None;
11031 };
11032 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
11033 // set for an `i32`.
11034 if index < 0 {
11035 return None;
11036 }
11037 let Value::Object(object) = self.peek(1) else {
11038 return None;
11039 };
11040 match object.array_get(index as usize) {
11041 Some(value) if !matches!(value, Value::Hole) => Some(value),
11042 _ => None,
11043 }
11044 }
11045
11046 /// `a[i] = v` on a dense array with an integer index, as one store.
11047 ///
11048 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
11049 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
11050 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
11051 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
11052 /// reference at the time it was measured (14.7x).
11053 ///
11054 /// Every condition here is one the slow path would also have to satisfy before
11055 /// storing into the element vector:
11056 ///
11057 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
11058 /// accepts as an index;
11059 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
11060 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
11061 /// one inside a recorded descriptor, reports `false` and the caller stops.
11062 ///
11063 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
11064 /// writes the own element too once `array_set` says it did.
11065 fn fast_array_set(&mut self) -> bool {
11066 // Every test runs *before* anything is popped: a refusal has to leave the stack
11067 // exactly as the slow path expects to find it. Popping first and reporting the
11068 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
11069 // then ran the slow path with nothing to write.
11070 let Value::Int(index) = self.peek(1) else {
11071 return false;
11072 };
11073 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
11074 if index < 0 {
11075 return false;
11076 }
11077 // Only a real array: a typed array's elements live in its buffer, a string-like
11078 // object has no element vector, and `array_set` on either does nothing.
11079 let Value::Object(object) = self.peek(2) else {
11080 return false;
11081 };
11082 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
11083 return false;
11084 }
11085 // A non-extensible array reports `false` here, but the *slow* path has to decide
11086 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
11087 // that with the key and the stack still intact.
11088 if !object.is_extensible() {
11089 return false;
11090 }
11091 // Inside the logical length, so the store cannot change `length`. Combined with
11092 // extensibility above, the only growth left for `array_set` is filling a hole in
11093 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
11094 // shape this fast path exists for. A store past the length would grow the array,
11095 // and whether that is allowed is the slow path's question.
11096 if index as usize >= object.array_length().unwrap_or(0) {
11097 return false;
11098 }
11099 // Only an *own element* can take the inline store. A hole is not an own property,
11100 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
11101 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
11102 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
11103 // the one case this path used to swallow.
11104 //
11105 // The cost is small: `array:indexed` only reads after a 64-element fill, and
11106 // `array:push` appends past the length, which this path already refused.
11107 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
11108 {
11109 return false;
11110 }
11111 // The bound `array_set` refuses past. Checking it here keeps that arm from having
11112 // to report a failure after the operands are gone.
11113 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
11114 return false;
11115 }
11116 let value = self.pop();
11117 self.pop();
11118 self.pop();
11119 object.array_store(self.heap, index as usize, value)
11120 }
11121
11122 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
11123 fn stop(&mut self, pc: usize) -> Option<Value> {
11124 self.frame_mut().pc = pc;
11125 None
11126 }
11127
11128 fn push(&mut self, value: Value) {
11129 self.frame_mut().stack.push(value);
11130 }
11131
11132 fn pop(&mut self) -> Value {
11133 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
11134 }
11135
11136 fn pop_n(&mut self, count: usize) -> Vec<Value> {
11137 let frame = self.frame_mut();
11138 let start = frame.stack.len().saturating_sub(count);
11139 frame.stack.split_off(start)
11140 }
11141
11142 fn peek(&self, back: usize) -> Value {
11143 let frame = self.frame();
11144 frame
11145 .stack
11146 .get(frame.stack.len().wrapping_sub(1 + back))
11147 .cloned()
11148 .unwrap_or(Value::Undefined)
11149 }
11150
11151 #[allow(clippy::too_many_lines)]
11152 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
11153 use Opcode::*;
11154 match op {
11155 // -- constants and stack shuffling -----------------------------
11156 Nop => {}
11157 PushMinus1 => self.push(Value::Int(-1)),
11158 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
11159 let value = match op {
11160 Push0 => 0,
11161 Push1 => 1,
11162 Push2 => 2,
11163 Push3 => 3,
11164 Push4 => 4,
11165 Push5 => 5,
11166 Push6 => 6,
11167 _ => 7,
11168 };
11169 self.push(Value::Int(value));
11170 }
11171 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
11172 PushBigintI32 => {
11173 // The immediate form of a `BigInt` literal; the reference has the same
11174 // split between this and a constant-pool entry.
11175 let value = crate::bigint::BigInt::from_i64(a as i64);
11176 self.push(self.bigint(value));
11177 }
11178 PushTrue => self.push(Value::Bool(true)),
11179 PushFalse => self.push(Value::Bool(false)),
11180 PushEmptyString => self.push(self.string("")),
11181 Undefined => self.push(Value::Undefined),
11182 Null => self.push(Value::Null),
11183 Object => {
11184 let proto = self.realm.object_proto.clone();
11185 self.push(Value::Object(self.new_object(Some(proto))));
11186 }
11187 PushThis => {
11188 let this = self.frame().this.clone();
11189 self.push(this);
11190 }
11191 PushConst | PushConst8 => {
11192 let value = self.constant(a as usize)?;
11193 self.push(value);
11194 }
11195 PushAtomValue => {
11196 let text = self.atom_wtf8(a as usize);
11197 self.push(self.string_wtf8(text));
11198 }
11199 Dup => {
11200 let value = self.peek(0);
11201 self.push(value);
11202 }
11203 Dup2 => {
11204 // `a b -> a b a b`
11205 let b = self.peek(0);
11206 let a = self.peek(1);
11207 self.push(a);
11208 self.push(b);
11209 }
11210 Dup3 => {
11211 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
11212 // prototype and key while reading the current value through them.
11213 let c = self.peek(0);
11214 let b = self.peek(1);
11215 let a = self.peek(2);
11216 self.push(a);
11217 self.push(b);
11218 self.push(c);
11219 }
11220 Swap => {
11221 // `a b -> b a`
11222 let bottom = self.pop();
11223 let top = self.pop();
11224 self.push(bottom);
11225 self.push(top);
11226 }
11227 Perm3 => {
11228 // `a b c -> b a c`, the reference's reordering for a spread method
11229 // call: `obj func array` becomes the `func this array` that `apply`
11230 // takes.
11231 let c = self.pop();
11232 let b = self.pop();
11233 let a = self.pop();
11234 self.push(b);
11235 self.push(a);
11236 self.push(c);
11237 }
11238 Dup1 => {
11239 let value = self.peek(1);
11240 self.push(value);
11241 }
11242 Drop => {
11243 self.pop();
11244 }
11245 Nip => {
11246 // `a b -> b`
11247 let top = self.pop();
11248 self.pop();
11249 self.push(top);
11250 }
11251 Perm4 => {
11252 // `obj prop a b -> a obj prop b`, the reference's reordering for a
11253 // postfix update of a computed element: it puts the *old* value
11254 // underneath the receiver and key so `put_array_el` can consume them
11255 // and leave the old value as the expression's result.
11256 let d = self.pop();
11257 let c = self.pop();
11258 let b = self.pop();
11259 let a = self.pop();
11260 self.push(c);
11261 self.push(a);
11262 self.push(b);
11263 self.push(d);
11264 }
11265 Insert2 => {
11266 // `obj a -> a obj a`
11267 let value = self.pop();
11268 let object = self.pop();
11269 self.push(value.clone());
11270 self.push(object);
11271 self.push(value);
11272 }
11273 Insert3 => {
11274 // `obj prop a -> a obj prop a`
11275 let value = self.pop();
11276 let key = self.pop();
11277 let object = self.pop();
11278 self.push(value.clone());
11279 self.push(object);
11280 self.push(key);
11281 self.push(value);
11282 }
11283 Insert4 => {
11284 // `this obj prop a -> a this obj prop a`
11285 //
11286 // `put_super_value` consumes all four and yields nothing, so the copy
11287 // underneath is what leaves the assignment an expression value.
11288 let value = self.pop();
11289 let key = self.pop();
11290 let object = self.pop();
11291 let receiver = self.pop();
11292 self.push(value.clone());
11293 self.push(receiver);
11294 self.push(object);
11295 self.push(key);
11296 self.push(value);
11297 }
11298 Swap2 => {
11299 // `a b c d -> c d a b`
11300 let d = self.pop();
11301 let c = self.pop();
11302 let b = self.pop();
11303 let a = self.pop();
11304 self.push(c);
11305 self.push(d);
11306 self.push(a);
11307 self.push(b);
11308 }
11309 Rot3l => {
11310 // `x a b -> a b x`
11311 let b = self.pop();
11312 let a = self.pop();
11313 let x = self.pop();
11314 self.push(a);
11315 self.push(b);
11316 self.push(x);
11317 }
11318 Rot3r => {
11319 // `a b c -> c a b`
11320 let c = self.pop();
11321 let b = self.pop();
11322 let a_value = self.pop();
11323 self.push(c);
11324 self.push(a_value);
11325 self.push(b);
11326 }
11327
11328 Rest => {
11329 // `...rest` in a parameter list: the arguments from index `a` on, as a
11330 // real array. It takes nothing off the stack — the arguments are in the
11331 // frame, not on it.
11332 let frame = self.frame();
11333 let from = a as usize;
11334 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11335 let array = self.new_array(collected);
11336 self.push(Value::Object(array));
11337 }
11338
11339 // -- slots ------------------------------------------------------
11340 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11341 let slot = self.slot_operand(op, a);
11342 let value = self.get_loc(slot);
11343 self.push(value);
11344 }
11345 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11346 let slot = self.slot_operand(op, a);
11347 let value = self.pop();
11348 self.put_loc(slot, value);
11349 }
11350 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11351 let slot = self.slot_operand(op, a);
11352 let value = self.pop();
11353 self.put_loc(slot, value.clone());
11354 self.push(value);
11355 }
11356 // The `_check` forms are the temporal dead zone: they throw when the
11357 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11358 // *reads*, so only the two writes may pop — mishandling that quietly
11359 // consumes the value the caller pushed just before.
11360 GetLocCheck => {
11361 let slot = self.slot_operand(op, a);
11362 let value = self.get_loc(slot);
11363 if matches!(value, Value::Uninitialized) {
11364 return Err(self.dead_zone(slot, VarSlot::Loc));
11365 }
11366 self.push(value);
11367 }
11368 PutLocCheck | SetLocCheck => {
11369 let slot = self.slot_operand(op, a);
11370 let value = self.pop();
11371 // The dead zone is a property of the **slot**, not of the value being
11372 // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11373 // initialised yet. Testing the value instead — which is never
11374 // `Uninitialized` in practice — let every such store through, so the check
11375 // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11376 // (`get_loc_check`) were already asking the slot, which is why
11377 // `print(x); let x` threw while `x = 1; let x` did not.
11378 if matches!(self.get_loc(slot), Value::Uninitialized) {
11379 return Err(self.dead_zone(slot, VarSlot::Loc));
11380 }
11381 // The initialiser goes through `put_loc`, not this, so any store that
11382 // reaches here is a later assignment — which a `const` refuses.
11383 if self.is_read_only(slot, VarSlot::Loc) {
11384 return Err(self.read_only(slot, VarSlot::Loc));
11385 }
11386 if op == SetLocCheck {
11387 self.put_loc(slot, value.clone());
11388 self.push(value);
11389 } else {
11390 self.put_loc(slot, value);
11391 }
11392 }
11393 PutLocCheckInit => {
11394 // The one store that *initialises* a lexical slot: `this` in a derived
11395 // constructor, which only exists after `super()` has run. A second
11396 // initialisation is the error the reference reports as
11397 // "'this' can be initialized only once".
11398 let slot = self.slot_operand(op, a);
11399 let value = self.pop();
11400 if !matches!(self.get_loc(slot), Value::Uninitialized) {
11401 return Err(Signal::Throw(self.make_error(
11402 "ReferenceError",
11403 "'this' can be initialized only once",
11404 )));
11405 }
11406 self.put_loc(slot, value);
11407 }
11408 CheckCtor => {
11409 // A class constructor may only run under `new`, which is what makes
11410 // `class A {}; A()` a TypeError.
11411 if matches!(self.frame().new_target, Value::Undefined) {
11412 return Err(Signal::Throw(self.make_error(
11413 "TypeError",
11414 "class constructors must be invoked with 'new'",
11415 )));
11416 }
11417 }
11418 InitCtor => {
11419 // The body a derived class gets when it declares no constructor:
11420 // forward every argument to the parent constructor, keeping `new.target`.
11421 if matches!(self.frame().new_target, Value::Undefined) {
11422 return Err(Signal::Throw(self.make_error(
11423 "TypeError",
11424 "class constructors must be invoked with 'new'",
11425 )));
11426 }
11427 let Some(callee) = self.current_callee() else {
11428 return Err(Signal::Throw(
11429 self.make_error("TypeError", "no constructor to inherit from"),
11430 ));
11431 };
11432 let parent = callee.proto().map_or(Value::Null, Value::Object);
11433 let new_target = self.frame().new_target.clone();
11434 let args = self.frame().passed().to_vec();
11435 let result = self.construct(parent, new_target, args)?;
11436 self.push(result);
11437 }
11438 SetLocUninitialized => {
11439 let slot = self.slot_operand(op, a);
11440 self.put_loc(slot, Value::Uninitialized);
11441 }
11442 CloseLoc => {
11443 // "Close" a binding: give it a *fresh* cell holding the current
11444 // value. Closures created before this point keep the old cell and the
11445 // ones created after see the new one, which is what makes every
11446 // iteration of `for (let i ...)` capture its own `i`, and what freezes
11447 // a block-scoped binding when the block ends.
11448 //
11449 // Clearing the slot instead (which this used to do) broke both: a
11450 // closure over a captured block variable read `undefined`, and a loop
11451 // terminated after one iteration.
11452 let slot = self.slot_operand(op, a);
11453 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11454 if index >= 0 {
11455 let current = self.frame().cells[index as usize].get();
11456 let fresh = self.new_cell(current);
11457 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11458 *cell = fresh;
11459 }
11460 }
11461 }
11462 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11463 let slot = self.slot_operand(op, a);
11464 let value = self.get_arg(slot);
11465 self.push(value);
11466 }
11467 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11468 let slot = self.slot_operand(op, a);
11469 let value = self.pop();
11470 self.put_arg(slot, value);
11471 }
11472 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11473 let slot = self.slot_operand(op, a);
11474 let value = self.pop();
11475 self.put_arg(slot, value.clone());
11476 self.push(value);
11477 }
11478
11479 // -- closure variables ------------------------------------------
11480 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11481 let slot = self.slot_operand(op, a);
11482 // A name a direct `eval` created shadows the binding the compiler chose.
11483 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11484 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11485 // and only a runtime lookup can know that.
11486 if let Some(cell) = self.eval_created_local(slot) {
11487 self.push(cell.get());
11488 return self.step();
11489 }
11490 let value = self.cell_value(slot)?;
11491 self.push(value);
11492 }
11493 GetVarRefCheck => {
11494 let slot = self.slot_operand(op, a);
11495 let value = self.cell_value(slot)?;
11496 if matches!(value, Value::Uninitialized) {
11497 return Err(self.dead_zone(slot, VarSlot::Closure));
11498 }
11499 self.push(value);
11500 }
11501 PutVarRefCheckInit => {
11502 // The captured-form twin of `PutLocCheckInit`. Both exist because `super()`
11503 // may be written inside an arrow, and there `this` is a var-ref rather than
11504 // a local.
11505 let slot = self.slot_operand(op, a);
11506 let value = self.pop();
11507 // The wording differs from the local form because the reference reaches
11508 // this case through `get_var_ref_checkthis`, which reports the dead zone
11509 // rather than the double initialisation.
11510 if !matches!(self.cell_value(slot)?, Value::Uninitialized) {
11511 return Err(Signal::Throw(
11512 self.make_error("ReferenceError", "this is not initialized"),
11513 ));
11514 }
11515 self.set_cell(slot, value)?;
11516 }
11517 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11518 let slot = self.slot_operand(op, a);
11519 let value = self.pop();
11520 if let Some(cell) = self.eval_created_local(slot) {
11521 cell.set(value);
11522 return self.step();
11523 }
11524 // Same two rules as `PutLocCheck`: a checked store to a captured binding
11525 // asks the cell about the dead zone, then refuses a `const` whose
11526 // initialiser has already run.
11527 if op == PutVarRefCheck {
11528 let current = self.cell_value(slot)?;
11529 if matches!(current, Value::Uninitialized) {
11530 return Err(self.dead_zone(slot, VarSlot::Closure));
11531 }
11532 if self.is_read_only(slot, VarSlot::Closure) {
11533 return Err(self.read_only(slot, VarSlot::Closure));
11534 }
11535 }
11536 self.set_cell(slot, value)?;
11537 }
11538 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11539 let slot = self.slot_operand(op, a);
11540 let value = self.pop();
11541 if let Some(cell) = self.eval_created_local(slot) {
11542 cell.set(value.clone());
11543 self.push(value);
11544 return self.step();
11545 }
11546 self.set_cell(slot, value.clone())?;
11547 self.push(value);
11548 }
11549
11550 // -- globals ----------------------------------------------------
11551 GetVar => {
11552 let value = self.get_global(a as usize)?;
11553 self.push(value);
11554 }
11555 GetVarUndef => {
11556 let slot = a as usize;
11557 // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11558 // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11559 // and `GetValue`s it, and only the unresolvable case is forgiven).
11560 //
11561 // The distinction is made by asking whether a binding exists at all: a name
11562 // in the realm's lexical table is declared, so a `ReferenceError` from
11563 // reading it is the dead zone talking. Swallowing every error made
11564 // `eval("typeof x; let x;")` print `"undefined"`.
11565 let declared = self.realm.globals.contains_key(&self.global_name(slot));
11566 let value = if declared {
11567 self.get_global(slot)?
11568 } else {
11569 match self.get_global(slot) {
11570 Ok(value) => value,
11571 Err(Signal::Throw(_)) => Value::Undefined,
11572 Err(other) => return Err(other),
11573 }
11574 };
11575 self.push(value);
11576 }
11577 DeleteVar => {
11578 // `delete name` for a name that is not a declared binding. A lexical
11579 // global lives in the reference table and cannot be deleted; anything
11580 // reachable only as a property of the global object is *implicit* —
11581 // `x = 1` with no declaration — and goes away if it is configurable,
11582 // which is what `delete` on an implicit global answers.
11583 let name = self.atom_text(a as usize);
11584 let global = self.realm.global.clone();
11585 let deleted = if self.realm.globals.contains_key(&name) {
11586 false
11587 } else if global.own_property(&name).is_some() {
11588 self.delete_property(&global, &name)?
11589 } else {
11590 true
11591 };
11592 self.push(Value::Bool(deleted));
11593 }
11594 PutVar => {
11595 let value = self.pop();
11596 self.put_global(a as usize, value)?;
11597 }
11598 PutVarInit => {
11599 let slot = a as usize;
11600 let value = self.pop();
11601 self.init_global(slot, value)?;
11602 }
11603
11604 // -- arithmetic -------------------------------------------------
11605 Add => self.binary_add()?,
11606 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11607 let raw_right = self.pop();
11608 let raw_left = self.pop();
11609 // Two numbers need no `ToPrimitive` at all, which is every `x - y` and
11610 // `flags | mask` in real code.
11611 if is_number(&raw_left) && is_number(&raw_right) {
11612 self.push(arithmetic(op, raw_left, raw_right)?);
11613 } else {
11614 // §13.15.3 steps 1–3: **both** operands are made primitive before the
11615 // disjointness check, left first. Getting the order wrong was observable
11616 // — `ToPrimitive` on the right ran first, so a `valueOf` log read `b,a`
11617 // and a throw from the *left* operand never happened
11618 // (`S11.10.1_A2.3_T1`, `order-of-evaluation`).
11619 //
11620 // Doing the check on the *primitives* rather than on the raw values is
11621 // the second half: `Object(5n) & Object(3n)` has a bigint on neither
11622 // side of the stack yet, so the old check sent it down the `ToNumber`
11623 // path and raised "cannot convert bigint to number"
11624 // (`bigint-non-primitive`).
11625 let left = self.primitive_of(raw_left)?;
11626 let right = self.primitive_of(raw_right)?;
11627 // BigInt arithmetic is a separate path, and not only for the type of
11628 // the result: `ToNumber` of a bigint throws, so mixing the two must be
11629 // an error rather than a silent conversion.
11630 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11631 let value = self.bigint_arithmetic(op, left, right)?;
11632 self.push(value);
11633 } else {
11634 let right = self.numeric(right)?;
11635 let left = self.numeric(left)?;
11636 self.push(arithmetic(op, left, right)?);
11637 }
11638 }
11639 }
11640 Neg => {
11641 let raw = self.pop();
11642 match raw {
11643 // A bigint negates exactly, however wide it is.
11644 Value::BigInt(big) => {
11645 let negated = big.negate();
11646 self.push(self.bigint(negated));
11647 }
11648 other => {
11649 let value = self.numeric_operand(other)?;
11650 if let Value::BigInt(big) = &value {
11651 let negated = big.negate();
11652 self.push(self.bigint(negated));
11653 } else {
11654 self.push(negate(value));
11655 }
11656 }
11657 }
11658 }
11659 Plus => {
11660 let value = self.pop();
11661 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11662 // unary plus is defined to produce a *number*, which a bigint cannot
11663 // become without loss. It used to fall through to `NaN`.
11664 if matches!(value, Value::BigInt(_)) {
11665 return Err(self.type_error("cannot convert bigint to number"));
11666 }
11667 let numeric = self.numeric_of(value)?;
11668 self.push(numeric);
11669 }
11670 Inc => {
11671 let raw = self.pop();
11672 let (_, updated) = self.advance_numeric(raw, true)?;
11673 self.push(updated);
11674 }
11675 Dec => {
11676 let raw = self.pop();
11677 let (_, updated) = self.advance_numeric(raw, false)?;
11678 self.push(updated);
11679 }
11680 PostInc | PostDec => {
11681 // `x -> x x+1`: the *new* value ends up on top, so the store the
11682 // compiler emits right after (`put_var`) writes the incremented
11683 // one, while the old value stays underneath for the expression's
11684 // own result. Getting this backwards makes `i++` a no-op, which
11685 // turns `while (i < 3)` into an infinite loop.
11686 let raw = self.pop();
11687 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11688 self.push(old);
11689 self.push(updated);
11690 }
11691 Not => {
11692 let raw = self.pop();
11693 match raw {
11694 // `~x` on a bigint is `-x - 1`, exact at any width.
11695 Value::BigInt(big) => {
11696 let inverted = big.bitnot();
11697 self.push(self.bigint(inverted));
11698 }
11699 other => {
11700 let value = self.numeric_operand(other)?;
11701 if let Value::BigInt(big) = &value {
11702 let inverted = big.bitnot();
11703 self.push(self.bigint(inverted));
11704 } else {
11705 self.push(Value::Int(!value.to_int32()));
11706 }
11707 }
11708 }
11709 }
11710 Lnot => {
11711 let value = self.pop();
11712 self.push(Value::Bool(!value.to_boolean()));
11713 }
11714
11715 // -- comparison -------------------------------------------------
11716 Lt | Lte | Gt | Gte => {
11717 let right = self.pop();
11718 let left = self.pop();
11719 let answer = self.relational(op, left, right)?;
11720 self.push(answer);
11721 }
11722 Eq | Neq => {
11723 let right = self.pop();
11724 let left = self.pop();
11725 let equal = self.abstract_equals(left, right)?;
11726 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11727 }
11728 StrictEq => {
11729 let right = self.pop();
11730 let left = self.pop();
11731 self.push(Value::Bool(left.strict_equals(&right)));
11732 }
11733 StrictNeq => {
11734 let right = self.pop();
11735 let left = self.pop();
11736 self.push(Value::Bool(!left.strict_equals(&right)));
11737 }
11738 IsUndefined => {
11739 // `=== undefined`, which is what a destructuring default tests. It is
11740 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11741 let value = self.pop();
11742 self.push(Value::Bool(matches!(value, Value::Undefined)));
11743 }
11744 IsUndefinedOrNull => {
11745 let value = self.pop();
11746 self.push(Value::Bool(value.is_nullish()));
11747 }
11748 Typeof => {
11749 let value = self.pop();
11750 self.push(self.string(value.type_of()));
11751 }
11752 ToObject => {
11753 // A destructuring *object* pattern starts here, which is why
11754 // `var {} = null` throws. Only `undefined` and `null` are refused; a
11755 // primitive is boxed.
11756 let value = self.pop();
11757 let object = self.object_from(&value)?;
11758 self.push(Value::Object(object));
11759 }
11760 Instanceof => {
11761 let constructor = self.pop();
11762 let object = self.pop();
11763 // `InstanceofOperator`, not `OrdinaryHasInstance`: the operator consults
11764 // `Symbol.hasInstance` first and throws for a right-hand side that is not an
11765 // object (step 1) or not callable (step 4). Calling `instance_of` directly
11766 // skipped both the protocol and the two `TypeError`s.
11767 let answer = self.instance_of_operator(&object, &constructor)?;
11768 self.push(Value::Bool(answer));
11769 }
11770 In => {
11771 let object = self.pop();
11772 let key = self.pop();
11773 let answer = self.has_property(&key, &object)?;
11774 self.push(Value::Bool(answer));
11775 }
11776 WithHasVar => {
11777 // `obj -> bool`: does this `with` object bind the name?
11778 //
11779 // §9.1.1.2.1 `HasBinding` for an Object Environment Record is **not**
11780 // `HasProperty`: step 2 skips the property entirely when the object's
11781 // `Symbol.unscopables` lists it. So `globalThis[Symbol.unscopables] = {v:
11782 // true}` makes `with (globalThis) { v }` read the *outer* `v`, which is what
11783 // the thirty-odd `unscopables-with` cases assert.
11784 //
11785 // One instruction rather than a hand-expanded sequence of `in`, a
11786 // `Symbol.unscopables` lookup and a second `in`: the same question is asked
11787 // by both the read/write guard and `delete`, and a compiler-side expansion
11788 // would be about ten instructions per name per `with` object.
11789 let object = self.pop();
11790 let name = self.atom_text(a as usize);
11791 let bound = self.with_has_binding(&object, &name)?;
11792 self.push(Value::Bool(bound));
11793 }
11794 WithGetVar => {
11795 // `obj -> value`: the second half of `GetBindingValue`.
11796 let object = self.pop();
11797 let name = self.atom_text(a as usize);
11798 let value = self.with_get_binding(&object, &name)?;
11799 self.push(value);
11800 }
11801 WithPutVar => {
11802 // `obj value ->`: the second half of `SetMutableBinding`. The operand order
11803 // is `put_field`'s (value on top), not the reference's, so that the
11804 // read-modify-write shapes (`perm3`/`insert2`) can be shared with the
11805 // member-expression forms.
11806 let value = self.pop();
11807 let object = self.pop();
11808 let name = self.atom_text(a as usize);
11809 self.with_put_binding(&object, &name, value)?;
11810 }
11811
11812 // -- control flow -----------------------------------------------
11813 Goto | Goto8 | Goto16 => {
11814 self.frame_mut().pc = a as usize;
11815 }
11816 IfTrue | IfTrue8 => {
11817 let value = self.pop();
11818 if value.to_boolean() {
11819 self.frame_mut().pc = a as usize;
11820 }
11821 }
11822 IfFalse | IfFalse8 => {
11823 let value = self.pop();
11824 if !value.to_boolean() {
11825 self.frame_mut().pc = a as usize;
11826 }
11827 }
11828 Catch => {
11829 // Pushes the handler target onto the value stack; `unwind` finds it.
11830 self.push(Value::CatchOffset(a));
11831 }
11832 Gosub => {
11833 self.push(Value::ReturnAddress(next as u32));
11834 self.frame_mut().pc = a as usize;
11835 }
11836 Ret => {
11837 let value = self.pop();
11838 match value {
11839 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11840 _ => {
11841 return Err(Signal::Throw(
11842 self.make_error("InternalError", "invalid return address"),
11843 ));
11844 }
11845 }
11846 }
11847 NipCatch => {
11848 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11849 // including the marker, keeping the top value.
11850 let top = self.pop();
11851 loop {
11852 match self.pop() {
11853 Value::CatchOffset(_) | Value::Undefined => break,
11854 _ => {}
11855 }
11856 if self.frame().stack.is_empty() {
11857 break;
11858 }
11859 }
11860 self.push(top);
11861 }
11862 Throw => {
11863 let value = self.pop();
11864 return Err(Signal::Throw(value));
11865 }
11866 ThrowError => {
11867 let name = self.atom_text(a as usize);
11868 let (class, message) = match b {
11869 0 => ("TypeError", format!("'{name}' is read-only")),
11870 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11871 2 => ("ReferenceError", format!("'{name}' is not initialized")),
11872 // `delete super.x` is a syntax-level mistake the reference reports
11873 // with this wording, not a property-access failure.
11874 3 => (
11875 "ReferenceError",
11876 "unsupported reference to 'super'".to_string(),
11877 ),
11878 4 => (
11879 "TypeError",
11880 "iterator does not have a throw method".to_string(),
11881 ),
11882 5 => (
11883 "ReferenceError",
11884 "invalid assignment left-hand side".to_string(),
11885 ),
11886 _ => ("TypeError", format!("invalid operation on '{name}'")),
11887 };
11888 return Err(Signal::Throw(self.make_error(class, &message)));
11889 }
11890 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11891 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11892 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11893 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11894 Await => return Ok(Step::Suspend(SuspendKind::Await)),
11895 ReturnAsync => {
11896 // The reference's `return_async` returns `undefined` and lets the resume
11897 // machinery pick the real value off `sp[-1]`, which is how it tells a
11898 // completion from a suspension. Carrying the value explicitly says the
11899 // same thing without the implicit stack slot.
11900 let value = self.pop();
11901 return Ok(Step::Return(value));
11902 }
11903 Return => {
11904 let value = self.pop();
11905 return Ok(Step::Return(value));
11906 }
11907 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11908
11909 // -- calls ------------------------------------------------------
11910 Call | Call0 | Call1 | Call2 | Call3 => {
11911 let argc = self.argc_operand(op, a);
11912 let args = self.pop_n(argc);
11913 let callee = self.pop();
11914 // A plain call has no receiver; the callee decides what to do with
11915 // `undefined` (a sloppy function substitutes the global object).
11916 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11917 self.push(result);
11918 }
11919 }
11920 CallConstructor => {
11921 // `constructor this_obj args… -> object`. The duplicated
11922 // constructor is `new.target`; this milestone does not expose it,
11923 // so the extra copy is simply consumed here.
11924 let argc = a as usize;
11925 let args = self.pop_n(argc);
11926 let new_target = self.pop();
11927 let callee = self.pop();
11928 let result = self.construct(callee, new_target, args)?;
11929 self.push(result);
11930 }
11931 CallMethod => {
11932 let argc = a as usize;
11933 let args = self.pop_n(argc);
11934 let callee = self.pop();
11935 let this = self.pop();
11936 if let Some(result) = self.call_or_push(callee, this, args)? {
11937 self.push(result);
11938 }
11939 }
11940 Apply => {
11941 // `func this array -> result`, the spread-call form: the compiler
11942 // builds one array of arguments, and all that is left here is to
11943 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11944 let array = self.pop();
11945 let this = self.pop();
11946 let callee = self.pop();
11947 let args = self.array_like_to_args(&array)?;
11948 if a & 1 != 0 {
11949 let result = self.construct(callee, this, args)?;
11950 self.push(result);
11951 } else if let Some(result) = self.call_or_push(callee, this, args)? {
11952 self.push(result);
11953 }
11954 }
11955 TailCall | TailCallMethod => {
11956 // `tail_call` is `call` whose result is returned immediately — the
11957 // reference jumps straight to `done` instead of storing the value and
11958 // running on. The callee still gets its own frame, so deep tail
11959 // recursion hits the stack limit exactly like plain recursion does;
11960 // marking this frame lets the return path unwind without needing
11961 // instructions after the call.
11962 let argc = if op == TailCallMethod {
11963 a as usize
11964 } else {
11965 self.argc_operand(op, a)
11966 };
11967 let args = self.pop_n(argc);
11968 let callee = self.pop();
11969 let this = if op == TailCallMethod {
11970 self.pop()
11971 } else {
11972 Value::Undefined
11973 };
11974 if let Value::Object(function) = &callee
11975 && let Some((code, env)) = bytecode_of(function)
11976 {
11977 // A generator or async body is not run here at all: calling it only
11978 // *creates* the generator/coroutine, so it must not inherit this
11979 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11980 // onto `f`'s frame, and the first `yield`/`await` then reported
11981 // "a generator body ran as an ordinary call".
11982 if code.code.kind.is_generator() || code.code.kind.is_async() {
11983 let value = self.call_value(callee, this, args)?;
11984 return Ok(Step::Return(value));
11985 }
11986 self.frame_mut().tail = true;
11987 self.push_frame(code, env, this, args, callee)?;
11988 return Ok(Step::Continue);
11989 }
11990 // A native callee has no frame to reuse, so its value is simply
11991 // returned.
11992 let value = self.call_value(callee, this, args)?;
11993 return Ok(Step::Return(value));
11994 }
11995
11996 // -- objects ----------------------------------------------------
11997 SpecialObject => {
11998 let value = self.special_object(a)?;
11999 self.push(value);
12000 }
12001 PrivateSymbol => {
12002 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
12003 // symbol each time it is evaluated, which is why the compiler evaluates it
12004 // once (at class definition) and stores it in a class-scope binding.
12005 let name = self.atom_text(a as usize);
12006 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
12007 self.push(Value::Symbol(symbol));
12008 }
12009 GetPrivateField => {
12010 // `obj symbol -> value`. A missing private field is a TypeError, which is what
12011 // makes `#x` inaccessible on any object not built by this class.
12012 let symbol = self.pop();
12013 let object = self.pop();
12014 let value = self.read_private_field(&object, &symbol)?;
12015 self.push(value);
12016 }
12017 PutPrivateField => {
12018 // `obj value symbol ->`, and the store is a plain assignment to a property the
12019 // class already created, so there is no setter to consult.
12020 let symbol = self.pop();
12021 let value = self.pop();
12022 let object = self.pop();
12023 self.write_private_field(&object, &symbol, value)?;
12024 }
12025 DefinePrivateField => {
12026 // `obj symbol value -> obj`: a field initialiser creates the property, and
12027 // redefining one is a TypeError ("already exists").
12028 let value = self.pop();
12029 let symbol = self.pop();
12030 let object = self.pop();
12031 self.define_private_field(&object, &symbol, value)?;
12032 self.push(object);
12033 }
12034 PrivateIn => {
12035 // `obj key -> bool`: `#x in o`. The second operand decides which question is
12036 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
12037 // is a field, so this is an own-property test; a *function* is a method or
12038 // accessor, so this is a brand check.
12039 let key = self.pop();
12040 let object = self.pop();
12041 let Some(target) = object.as_object() else {
12042 return Err(Signal::Throw(
12043 self.make_error("TypeError", "invalid 'in' operand"),
12044 ));
12045 };
12046 let present = match &key {
12047 Value::Object(_) => self.check_brand(target, &key)?,
12048 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
12049 };
12050 self.push(Value::Bool(present));
12051 }
12052 AddBrand => {
12053 // `obj home ->`: create the class brand on `home` if it has none, then give
12054 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
12055 // class definition: only the prototype's copy of the symbol is wanted.
12056 let home = self.pop();
12057 let object = self.pop();
12058 self.add_brand(&object, &home)?;
12059 }
12060 CheckBrand => {
12061 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
12062 // Both stay, because the caller needs them — `nip` halves a read into its
12063 // value and `call_method` uses the pair as receiver and callee.
12064 let function = self.peek(0);
12065 let object = self.peek(1);
12066 let Some(target) = object.as_object() else {
12067 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12068 };
12069 if !self.check_brand(target, &function)? {
12070 return Err(Signal::Throw(
12071 self.make_error("TypeError", "invalid brand on object"),
12072 ));
12073 }
12074 }
12075 GetLength => {
12076 // `get_length` is the `.length` read; an array and a string answer
12077 // from their own length, anything else from the property.
12078 let target = self.pop();
12079 let value = match &target {
12080 Value::Object(object) => match object.array_length() {
12081 Some(length) => crate::object::length_value(length),
12082 None => self.read_field(&target, "length")?,
12083 },
12084 Value::String(text) => Value::Int(text.utf16_len() as i32),
12085 _ => self.read_field(&target, "length")?,
12086 };
12087 self.push(value);
12088 }
12089 GetField | GetField2 => {
12090 let object = self.pop();
12091 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
12092 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
12093 // just below is what lets the borrow outlive the `&mut self` the lookup
12094 // needs — one refcount bump instead of a key clone plus its drop, on the
12095 // hottest property path there is: every `o.x` and every `o.m()` receiver.
12096 let code = self.frame().code.clone();
12097 let key = &code.atom_keys[a as usize];
12098 let value = self.read_field_cached(&object, key, next)?;
12099 if op == GetField2 {
12100 self.push(object);
12101 }
12102 self.push(value);
12103 }
12104 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
12105 let key = self.pop();
12106 let object = self.pop();
12107 // §7.1.1 `GetValue` step 3 orders these two conversions: `ToObject(V.[[Base]])`
12108 // first, then `ToPropertyKey(V.[[ReferencedName]])`. So a nullish base is a
12109 // `TypeError` and the key is **never coerced** — `null[{toString(){throw}}]`
12110 // throws the TypeError, not the key's exception
12111 // (`S11.3.1_A6_T1`). A write has the opposite order, which is why
12112 // `PutArrayEl` deliberately does not do this.
12113 //
12114 // Only nullish is checked here, and the full boxing is still left to
12115 // `read_field_key`: a string base has an index fast path that turning it
12116 // into a `String` object up front would throw away.
12117 if object.is_nullish() {
12118 return Err(Signal::Throw(self.make_error(
12119 "TypeError",
12120 &format!("cannot read property of {}", object.to_js_string()),
12121 )));
12122 }
12123 let key = self.propkey(&key)?;
12124 let value = self.read_field_key(&object, &key)?;
12125 if matches!(op, GetArrayEl2 | GetArrayEl3) {
12126 self.push(object);
12127 }
12128 if op == GetArrayEl3 {
12129 // The key goes back in its *value* form, which the compiler stores
12130 // into the target of a destructuring assignment.
12131 self.push(match &key {
12132 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12133 PropertyKey::String(text) => self.string_wtf8(text.clone()),
12134 });
12135 }
12136 self.push(value);
12137 }
12138 PutField => {
12139 let value = self.pop();
12140 let object = self.pop();
12141 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
12142 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
12143 // only reads. `this.value = …` is the write half of the hottest loop in
12144 // `property:method-call`, and `own_property_key` was 4.8% of the case.
12145 let code = self.frame().code.clone();
12146 let key = &code.atom_keys[a as usize];
12147 self.write_field_key(&object, key, value)?;
12148 }
12149 PutArrayEl => {
12150 let value = self.pop();
12151 let key = self.pop();
12152 let object = self.pop();
12153 let key = self.propkey(&key)?;
12154 self.write_field_key(&object, &key, value)?;
12155 }
12156 DefineField => {
12157 let value = self.pop();
12158 let object = self.pop();
12159 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
12160 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
12161 // three U+FFFD — a property under a different name from the one
12162 // `o["\uD800"]` reads.
12163 let code = self.frame().code.clone();
12164 let key = code.atom_keys[a as usize].clone();
12165 // No naming here. `{m: function(){}}` is named by the *compiler*, which
12166 // emits `set_name` — and only where `NamedEvaluation` applies, so
12167 // `{m: (0, function(){})}` stays anonymous. Naming every function that
12168 // reaches a property definition got that case wrong, and the compiler is
12169 // the only place that can tell the two apart.
12170 self.define_field(&object, &key, value)?;
12171 self.push(object);
12172 }
12173 DefineArrayEl => {
12174 // `obj key value -> obj key`. The *value* form of the key is what goes
12175 // back on the stack — the compiler stores it into the pattern's binding —
12176 // so the symbol is not stringified on the way through.
12177 //
12178 // `define_field` and not `write_field_key`: this is `CreateDataProperty`,
12179 // and only the define algorithm gives `{ ['__proto__']: v }` an ordinary
12180 // own property. Going through `[[Set]]` found `Object.prototype`'s
12181 // `__proto__` accessor on the prototype chain and *changed the prototype*
12182 // instead, and it would have called a user setter from a literal
12183 // (`computed-__proto__`, `__proto__-duplicate-computed`).
12184 let value = self.pop();
12185 let key_value = self.pop();
12186 let object = self.peek(0);
12187 let key = self.propkey(&key_value)?;
12188 self.define_field(&object, &key, value)?;
12189 self.push(key_value);
12190 }
12191 SetHomeObject => {
12192 // `obj func -> obj func`: records the object a method was defined on so
12193 // `super` inside it resolves against that object's prototype.
12194 let function = self.peek(0);
12195 let home = self.peek(1);
12196 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
12197 function.set_home_object(Some(home.clone()));
12198 }
12199 }
12200 Regexp => {
12201 // `pattern flags -> regexp`. A literal compiles here rather than through the
12202 // constructor, which is both what the reference's dedicated opcode is for
12203 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
12204 let flags = self.pop();
12205 let pattern = self.pop();
12206 let pattern = self.checked_to_wtf8(&pattern)?;
12207 let flags = self.to_js_string(&flags)?;
12208 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
12209 self.push(Value::Object(object));
12210 }
12211 UsingDisposeInit => {
12212 // The error state a disposal accumulates into. Uninitialised means "no
12213 // failure yet"; anything else is the exception being propagated.
12214 self.push(Value::Uninitialized);
12215 }
12216 UsingCheck => {
12217 // `value -> value, method`: validate and snapshot the disposer now, so a
12218 // later change to `Symbol.dispose` cannot change what gets called, and so a
12219 // value that is not disposable fails before the body runs.
12220 let value = self.pop();
12221 let method = self.using_method_for(&value, a as u8 == 1)?;
12222 self.push(value);
12223 self.push(method);
12224 }
12225 UsingDispose => {
12226 // `error_state -> error_state'`: dispose the variable at `slot` — its value
12227 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
12228 // the pending error.
12229 let slot = self.slot_operand(op, a);
12230 let error_state = self.pop();
12231 let merged = self.using_dispose_once(slot, error_state)?;
12232 self.push(merged);
12233 }
12234 UsingDisposeMerge => {
12235 let new_error = self.pop();
12236 let error_state = self.pop();
12237 let merged = self.merge_dispose_error(new_error, error_state);
12238 self.push(merged);
12239 }
12240 UsingDisposeEnd => {
12241 // A disposal that failed replaces the block's normal completion, so the
12242 // error state becomes a real throw here rather than at the call site.
12243 let error_state = self.pop();
12244 if !matches!(error_state, Value::Uninitialized) {
12245 return Err(Signal::Throw(error_state));
12246 }
12247 }
12248 // -- references -------------------------------------------------
12249 //
12250 // §6.2.5's Reference, as a value the operand stack can carry. Only emitted
12251 // where a direct `eval` could declare a shadowing `var` between the read and
12252 // the store (§13.15.3 resolves the lvalue once), so nothing hot goes through
12253 // here.
12254 MakeLocRef | MakeArgRef | MakeVarRefRef | MakeVarRef => {
12255 let name = self.atom_wtf8(a as usize);
12256 let target = match op {
12257 // A *global*: the name is looked up afresh, because an `eval` earlier in
12258 // this very function may already have declared it as a local, and
12259 // because an implicit global may not exist at all.
12260 MakeVarRef => self.global_reference(&name)?,
12261 // A slot. `eval_created_local` is the same override an ordinary
12262 // `get_var_ref` makes, so `eval("var x = 9"); x *= (…)` reads the eval's
12263 // `x` while `x *= (eval("var x = 2"), 4)` reads the outer one — the
12264 // difference is only *when* the reference was taken.
12265 // A slot. Three cases, and the first two are easy to confuse:
12266 //
12267 // * a *local* or *argument* — its cell number is in `loc_cell`/`arg_cell`,
12268 // not the slot itself, and `resolve` has already forced it to be
12269 // captured so a cell exists;
12270 // * a *global* reached through the closure table — the cell there is a
12271 // placeholder (`is_global_slot`), so the binding has to be reached by
12272 // name after all;
12273 // * anything else in the closure table — a real cell, but a direct `eval`
12274 // may have shadowed the name with a fresh local, and that shadow is what
12275 // an ordinary read would find.
12276 MakeVarRefRef if self.is_global_slot(b as usize) => {
12277 self.global_reference(&name)?
12278 }
12279 _ => {
12280 let slot = b as usize;
12281 let cell = match op {
12282 MakeLocRef => self
12283 .frame()
12284 .code
12285 .loc_cell
12286 .get(slot)
12287 .copied()
12288 .filter(|cell| *cell >= 0)
12289 .and_then(|cell| self.frame().cells.get(cell as usize).cloned()),
12290 MakeArgRef => self
12291 .frame()
12292 .code
12293 .arg_cell
12294 .get(slot)
12295 .copied()
12296 .filter(|cell| *cell >= 0)
12297 .and_then(|cell| self.frame().cells.get(cell as usize).cloned()),
12298 _ => self.eval_created_local(slot),
12299 };
12300 match cell.or_else(|| self.frame().env.cells.get(slot).cloned()) {
12301 Some(cell) => RefTarget::Cell(cell),
12302 None => {
12303 return Err(Signal::Throw(self.make_error(
12304 "InternalError",
12305 "a reference to a slot with no cell",
12306 )));
12307 }
12308 }
12309 }
12310 };
12311 let object = self.new_object(None);
12312 object.set_reference(target);
12313 self.push(Value::Object(object));
12314 }
12315 GetRefValue => {
12316 // `[ref] -> [ref, value]`: the reference stays, exactly like a `get_field2`,
12317 // so a second half can store through it.
12318 let reference = self.reference_target(0)?;
12319 let value = match reference {
12320 RefTarget::Cell(cell) => cell.get(),
12321 RefTarget::Property { base, name } => {
12322 // An unresolvable reference is a name that is on neither the global
12323 // binding table nor the global object, and reading one is a
12324 // `ReferenceError` in every mode (§6.2.5.5).
12325 if matches!(base, Value::Undefined) {
12326 return Err(self.throw_reference(
12327 &name
12328 .as_wtf8()
12329 .map(|t| t.to_string_lossy().into_owned())
12330 .unwrap_or_default(),
12331 ));
12332 }
12333 self.get_property_key(
12334 base.as_object().ok_or_else(|| {
12335 self.type_error("a reference base must be an object")
12336 })?,
12337 &name,
12338 )?
12339 .unwrap_or(Value::Undefined)
12340 }
12341 };
12342 self.push(value);
12343 }
12344 PutRefValue => {
12345 // `[ref, value] -> []`.
12346 let value = self.pop();
12347 let reference = self.reference_target(0)?;
12348 self.pop();
12349 match reference {
12350 RefTarget::Cell(cell) => cell.set(value),
12351 RefTarget::Property { base, name } => {
12352 if matches!(base, Value::Undefined) {
12353 // Sloppy code creates the global; strict code refuses
12354 // (§9.1.1.4.6 `SetMutableBinding` on an unresolvable name).
12355 if self.current_strict() {
12356 return Err(self.throw_reference(
12357 &name
12358 .as_wtf8()
12359 .map(|t| t.to_string_lossy().into_owned())
12360 .unwrap_or_default(),
12361 ));
12362 }
12363 let global = self.realm.global.clone();
12364 self.set_property_with_key(
12365 &global,
12366 &name,
12367 value,
12368 DeleteFailure::Ignore,
12369 )?;
12370 } else {
12371 let object = base.as_object().ok_or_else(|| {
12372 self.type_error("a reference base must be an object")
12373 })?;
12374 self.set_property_with_key(object, &name, value, DeleteFailure::Throw)?;
12375 }
12376 }
12377 }
12378 }
12379 UsingDisposeAsync => {
12380 // `error_state -> error_state, promise`: the disposer is called here and
12381 // its result wrapped, so the `await` the compiler emits next is what
12382 // actually waits. Calling it and dropping the result lost every failure
12383 // from an `async [Symbol.asyncDispose]` — the rejection had no handler and
12384 // no path back into the error state
12385 // (`throws-error-as-is-if-only-one-error-during-disposal`).
12386 let slot = self.slot_operand(op, a);
12387 let error_state = self.pop();
12388 let value = self.get_loc(slot);
12389 let method = self.get_loc(slot + 1);
12390 let promise = if value.is_nullish()
12391 || matches!(value, Value::Uninitialized)
12392 || matches!(method, Value::Undefined | Value::Uninitialized)
12393 {
12394 // Nothing to dispose: `await undefined` is a no-op, as it is in the
12395 // reference (`sp[0] = JS_UNDEFINED`).
12396 Value::Undefined
12397 } else {
12398 let result = self.call_value(method, value, Vec::new())?;
12399 self.promise_resolve_value(result)?
12400 };
12401 self.push(error_state);
12402 self.push(promise);
12403 }
12404 GetSuper => {
12405 // `obj -> obj's prototype`: the starting point of a `super` lookup.
12406 let object = self.pop();
12407 let proto = match &object {
12408 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
12409 _ => Value::Null,
12410 };
12411 self.push(proto);
12412 }
12413 GetSuperValue => {
12414 // `receiver proto key -> value`, searching from `proto` but reporting to
12415 // `receiver`, which is what `super.g` must do for a getter to see `this`.
12416 //
12417 // Three values in, one out: the receiver is *consumed*, not left under the
12418 // result. Leaving it there was invisible for `super.x` in `return` or
12419 // statement position (the result is what gets popped) and corrupted the
12420 // frame everywhere else — `print(super.x)` left the class where the call
12421 // opcode looks for the receiver and called the class itself.
12422 let key = self.pop();
12423 let proto = self.pop();
12424 let receiver = self.pop();
12425 let value = self.super_read(&receiver, &proto, &key)?;
12426 self.push(value);
12427 }
12428 PutSuperValue => {
12429 // `receiver proto key value ->`: a store that starts at `proto` but
12430 // assigns to `receiver`.
12431 let value = self.pop();
12432 let key = self.pop();
12433 let proto = self.pop();
12434 let receiver = self.pop();
12435 self.super_write(&receiver, &proto, &key, value)?;
12436 }
12437 DefineClass => {
12438 // `parent ctor -> ctor proto`: the constructor becomes the class and a
12439 // fresh prototype object lands on top for the methods to go on.
12440 let name = self.atom_text(a as usize);
12441 let (ctor, proto) = self.define_class(&name, b)?;
12442 self.push(ctor);
12443 self.push(Value::Object(proto));
12444 }
12445 DefineClassComputed => {
12446 // `parent ctor key -> ctor proto key`: the computed name stays put so
12447 // `define_field`-style consumers can still read it.
12448 let key = self.pop();
12449 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12450 let (ctor, proto) = self.define_class(&name, b)?;
12451 self.push(ctor);
12452 self.push(Value::Object(proto));
12453 self.push(key);
12454 }
12455 DefineMethod => {
12456 let function = self.pop();
12457 let object = self.pop();
12458 // The exact key, like `define_field`: a quoted method key may hold an
12459 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
12460 // that `o["\uD800"]` finds.
12461 let code = self.frame().code.clone();
12462 let key = code.atom_keys[a as usize].clone();
12463 // A method's `[[HomeObject]]` is the object it was defined on, which is
12464 // what `super` inside it resolves against.
12465 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12466 function.set_home_object(Some(object.clone()));
12467 }
12468 let name = match key.as_wtf8() {
12469 Some(text) => text.clone(),
12470 // A symbol atom — one of the well-known symbols, which the lexer keeps
12471 // as an atom rather than a runtime value. Its name is the bracketed
12472 // description, like any other symbol key.
12473 None => symbol_key_name(&key),
12474 };
12475 self.set_function_name_wtf8(&function, &accessor_prefixed(&name, b));
12476 if let Some(array) = object.as_object()
12477 && !define_function_property(array, &key, function, b)
12478 {
12479 return Err(self.type_error("property is not configurable"));
12480 }
12481 self.push(object);
12482 }
12483 DefineMethodComputed => {
12484 let function = self.pop();
12485 let key = self.pop();
12486 let object = self.pop();
12487 let key = self.propkey(&key)?;
12488 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
12489 // the name: `super` inside a computed method resolves through it. Without
12490 // this, `class B extends A { [k]() { return super.m() } }` read the
12491 // home object as null and threw.
12492 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12493 function.set_home_object(Some(object.clone()));
12494 }
12495 // A symbol key names the method `[description]`, or `""` without one —
12496 // §7.3.24, the same rule [`Interp::function_name_from_key`] applies to
12497 // `set_name_computed`. Falling back to `to_string` here named every
12498 // `{ [sym](){} }` method `Symbol()` instead.
12499 match &key {
12500 PropertyKey::Symbol(_) => {
12501 // The accessor prefix still applies: `get [Symbol.iterator](){}`
12502 // is named `"get [Symbol.iterator]"`.
12503 let name = accessor_prefixed(&symbol_key_name(&key), a);
12504 self.set_function_name_wtf8(&function, &name);
12505 }
12506 PropertyKey::String(text) => {
12507 let name = accessor_prefixed(text, a);
12508 self.set_function_name_wtf8(&function, &name);
12509 }
12510 }
12511 if let Some(array) = object.as_object()
12512 && !define_function_property(array, &key, function, a)
12513 {
12514 return Err(self.type_error("property is not configurable"));
12515 }
12516 self.push(object);
12517 }
12518 SetProto => {
12519 // `{ __proto__: v }` — §13.2.5.1 step 6: nothing is defined and nothing is
12520 // changed unless `v` is an object or `null`. A primitive was taken as "no
12521 // prototype" instead, so `{ __proto__: undefined }` came out with `null`
12522 // where the answer is an ordinary object
12523 // (`__proto__-value-non-object`).
12524 let proto = self.pop();
12525 let object = self.pop();
12526 if matches!(proto, Value::Null | Value::Object(_))
12527 && let Some(target) = object.as_object()
12528 {
12529 target.set_proto(proto.as_object().cloned());
12530 }
12531 self.push(object);
12532 }
12533 CopyDataProperties => {
12534 let exclusion = self.pop();
12535 let source = self.pop();
12536 let target = self.peek(0);
12537 self.copy_properties(&target, &source, &exclusion)?;
12538 self.push(source);
12539 self.push(exclusion);
12540 }
12541 ToPropkey => {
12542 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12543 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12544 // ordinary `"Symbol(b)"` property.
12545 let value = self.pop();
12546 let key = match self.propkey(&value)? {
12547 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12548 PropertyKey::String(text) => self.string_wtf8(text),
12549 };
12550 self.push(key);
12551 }
12552 SetName => {
12553 let function = self.peek(0);
12554 let name = self.atom_wtf8(a as usize);
12555 self.set_function_name_wtf8(&function, &name);
12556 }
12557 SetNameComputed => {
12558 let key = self.peek(1);
12559 let function = self.peek(0);
12560 let name = self.function_name_from_key(&key)?;
12561 self.set_function_name_wtf8(&function, &name);
12562 }
12563
12564 // -- arrays -----------------------------------------------------
12565 ArrayFrom => {
12566 let count = a as usize;
12567 let elements = self.pop_n(count);
12568 let array = self.new_array(elements);
12569 self.push(Value::Object(array));
12570 }
12571 Append => {
12572 // `array index iterable -> array new_index`
12573 let iterable = self.pop();
12574 self.pop();
12575 let array = self.peek(0);
12576 let added = self.append_enumerate(&array, &iterable)?;
12577 self.push(Value::Int(added));
12578 }
12579
12580 // -- iteration --------------------------------------------------
12581 ForInStart => {
12582 let value = self.pop();
12583 let record = self.for_in_record(&value)?;
12584 self.push(Value::Object(record));
12585 }
12586 ForInNext => {
12587 // `record -> record key done`. The flag is *done*, not "found":
12588 // the compiler tests it with `if_false` to jump back into the body,
12589 // so reporting `true` while keys remain would end the loop at once.
12590 let record = self.peek(0);
12591 match self.for_in_advance(&record)? {
12592 Some(key) => {
12593 let text = self.string(key);
12594 self.push(text);
12595 self.push(Value::Bool(false));
12596 }
12597 None => {
12598 self.push(Value::Undefined);
12599 self.push(Value::Bool(true));
12600 }
12601 }
12602 }
12603 ForOfStart => {
12604 let value = self.pop();
12605 let iterator = self.get_iterator(&value)?;
12606 self.push(iterator.object);
12607 self.push(iterator.next);
12608 self.push(Value::CatchOffset(0));
12609 }
12610 ForOfNext => {
12611 // `iter next catch_offset -> iter next catch_offset value done`.
12612 //
12613 // The operand is how many values sit *above* the iterator triple: a
12614 // destructuring rest element keeps its target array and running index
12615 // there while draining the iterator, so the triple is not at the top.
12616 let extra = a as usize;
12617 let iterator_slot = 2 + extra;
12618 // An exhausted iterator is replaced by `undefined` (see below), so a
12619 // second step must not call `next` again — `Array.from` and a
12620 // destructuring pattern both keep stepping past the end.
12621 let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12622 Ok((Value::Undefined, true))
12623 } else {
12624 let iterator = Iterator {
12625 object: self.peek(iterator_slot),
12626 next: self.peek(1 + extra),
12627 };
12628 self.iterator_step(&iterator)
12629 };
12630 let (value, done) = match stepped {
12631 Ok(stepped) => stepped,
12632 Err(signal) => {
12633 // An exception from `next()` is not an abrupt completion of the
12634 // *body*, so §7.4.6 does not apply and the iterator must not be
12635 // closed: `[ , ] = iterable` with a throwing `next` expects
12636 // `returnCount === 0`. Clearing the slot is how the reference says
12637 // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12638 // returns -1), and it is also what makes the destructor below — the
12639 // exception path's `catch_offset 0` close — a no-op here.
12640 self.clear_iterator_slot(iterator_slot);
12641 return Err(signal);
12642 }
12643 };
12644 if done {
12645 // The result's `value` is meaningless once the iterator is done:
12646 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12647 // rather than binding the generator's return value.
12648 let top = self.frame().stack.len() - 1 - iterator_slot;
12649 self.frame_mut().stack[top] = Value::Undefined;
12650 self.push(Value::Undefined);
12651 self.push(Value::Bool(true));
12652 } else {
12653 self.push(value);
12654 self.push(Value::Bool(false));
12655 }
12656 }
12657 IteratorNext => {
12658 // `iter next catch val -> iter next catch val'`: replace the argument with
12659 // the result of `next(val)`. The triple below stays put, which is why the
12660 // three instructions of the `yield*` loop all address the stack the same way.
12661 let value = self.pop();
12662 let object = self.peek(2);
12663 let next = self.peek(1);
12664 let result = self.call_value(next, object, vec![value])?;
12665 self.push(result);
12666 }
12667 IteratorCall => {
12668 // `iter next catch val -> iter next catch val' flag`.
12669 //
12670 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12671 // The flag is `true` when the method was missing, which is how the
12672 // caller learns that the inner iterator cannot take part in the
12673 // unwinding.
12674 let value = self.pop();
12675 let object = self.peek(2);
12676 let key = if a & 1 != 0 { "throw" } else { "return" };
12677 let method = self.read_field(&object, key)?;
12678 if matches!(method, Value::Undefined | Value::Null) {
12679 self.push(value);
12680 self.push(Value::Bool(true));
12681 } else {
12682 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12683 let result = self.call_value(method, object, argument)?;
12684 self.push(result);
12685 self.push(Value::Bool(false));
12686 }
12687 }
12688 IteratorCheckObject => {
12689 if !matches!(self.peek(0), Value::Object(_)) {
12690 return Err(Signal::Throw(
12691 self.make_error("TypeError", "iterator must return an object"),
12692 ));
12693 }
12694 }
12695 IteratorClose => {
12696 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12697 // calling the iterator's `return` so it can release whatever it holds.
12698 //
12699 // The catch offset goes first, so an exception from `return` is not caught
12700 // by the loop being abandoned. This used to pop the three operands and call
12701 // nothing at all, which made `break` out of a `for of` invisible to an
12702 // iterator with a `return` method.
12703 self.pop();
12704 self.pop();
12705 let iterator = self.pop();
12706 if !matches!(iterator, Value::Undefined) {
12707 let method = self.read_field(&iterator, "return")?;
12708 if !matches!(method, Value::Undefined | Value::Null) {
12709 let result = self.call_value(method, iterator.clone(), Vec::new())?;
12710 // §7.4.6: a `return` that answers a non-object is a TypeError.
12711 if !matches!(result, Value::Object(_)) {
12712 return Err(Signal::Throw(
12713 self.make_error("TypeError", "iterator must return an object"),
12714 ));
12715 }
12716 }
12717 }
12718 }
12719 Import => {
12720 // `import(specifier, options)`: the options slot is on top. Both are
12721 // `GetValue`-ed by the compiler, which is why this pops values rather than
12722 // references — and why the validation of `options` (§13.3.10.1 step 10)
12723 // happens inside `dynamic_import`, where its failures can be turned into a
12724 // rejection instead of a throw.
12725 let options = self.pop();
12726 let specifier = self.pop();
12727 let promise = self.dynamic_import(specifier, options)?;
12728 self.push(promise);
12729 }
12730 ForAwaitOfStart => {
12731 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12732 // `Symbol.iterator` fallback.
12733 let value = self.pop();
12734 let iterator = self.get_async_iterator(&value)?;
12735 self.push(iterator.object);
12736 self.push(iterator.next);
12737 self.push(Value::CatchOffset(0));
12738 }
12739 ForAwaitOfNext => {
12740 // `for await` steps the iterator and leaves the *result* wrapped in a
12741 // promise, so the `await` the compiler emits right after this can suspend
12742 // on it. Unwrapping happens in `iterator_get_value_done`.
12743 let extra = a as usize;
12744 let iterator_slot = 2 + extra;
12745 // The enumerator marker is **disabled for the step**, and
12746 // `iterator_get_value_done` puts it back once the result has survived the
12747 // awaiting. Both halves are load-bearing for the async case:
12748 //
12749 // * a rejection is not "the body threw", so the loop must not close the
12750 // iterator *again* — the wrapper already did;
12751 // * but until the result arrives the record is live, so a later failure
12752 // still has to close it.
12753 //
12754 // The reference says the same in one line each
12755 // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12756 // offset so that exceptions do not close the iterator */`).
12757 self.clear_iterator_slot(extra);
12758 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12759 Value::Undefined
12760 } else {
12761 let iterator = Iterator {
12762 object: self.peek(iterator_slot),
12763 next: self.peek(1 + extra),
12764 };
12765 let next = iterator.next.clone();
12766 self.call_value(next, iterator.object, Vec::new())?
12767 };
12768 let promise = self.promise_resolve_value(result)?;
12769 self.push(promise);
12770 }
12771 IteratorGetValueDone => {
12772 // `result -> value done`. A missing result object means the iterator was
12773 // already exhausted, which the loop treats as `done`.
12774 let result = self.pop();
12775 // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12776 // from here on the record is closeable again.
12777 {
12778 let depth = self.frame().stack.len();
12779 if depth >= 2 {
12780 self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12781 }
12782 }
12783 let done = match &result {
12784 Value::Object(object) => self
12785 .get_property(object, "done")?
12786 .is_some_and(|value| value.to_boolean()),
12787 _ => true,
12788 };
12789 if done {
12790 // Clear the iterator object so the `iterator_close` the loop emits on
12791 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12792 // on normal completion, and this is where a normal completion is
12793 // recognised — the same trick `for_of_next` uses, which also replaces
12794 // the slot with `undefined`.
12795 //
12796 // The layout is fixed because only `for await` emits this opcode:
12797 // `iter next catch [result]`, so the iterator is three below the top.
12798 let depth = self.frame().stack.len();
12799 if depth >= 3 {
12800 self.frame_mut().stack[depth - 3] = Value::Undefined;
12801 }
12802 self.push(Value::Undefined);
12803 self.push(Value::Bool(true));
12804 } else {
12805 let Value::Object(object) = &result else {
12806 self.push(Value::Undefined);
12807 self.push(Value::Bool(true));
12808 return Ok(Step::Continue);
12809 };
12810 let value = self
12811 .get_property(object, "value")?
12812 .unwrap_or(Value::Undefined);
12813 self.push(value);
12814 self.push(Value::Bool(false));
12815 }
12816 }
12817
12818 Delete => {
12819 // `delete obj[key]`, where the key was just pushed. Deleting an array
12820 // index leaves a *hole* rather than closing the gap, and a
12821 // non-configurable property answers `false` and stays.
12822 let key = self.pop();
12823 let target = self.pop();
12824 let key = self.propkey(&key)?;
12825 let text_label = key.as_str().unwrap_or("").to_string();
12826 let deleted = match &target {
12827 Value::Object(object) => {
12828 let object = object.clone();
12829 self.delete_property_key(&object, &key)?
12830 }
12831 // A string's `length` and its index properties are
12832 // non-configurable, so deleting one answers `false`.
12833 Value::String(text) => {
12834 !(text_label == "length"
12835 || array_index(&text_label)
12836 .is_some_and(|index| (index as usize) < text.utf16_len()))
12837 }
12838 // "delete null.a" is a TypeError, not a no-op: the operator needs an
12839 // object to delete from, and only a *boxable* primitive has one.
12840 Value::Undefined | Value::Null => {
12841 return Err(Signal::Throw(
12842 self.make_error("TypeError", "cannot convert to object"),
12843 ));
12844 }
12845 // Any other primitive has no own properties; deleting nothing
12846 // succeeds.
12847 _ => true,
12848 };
12849 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12850 // `TypeError` rather than a `false` result. Sloppy mode silently reports
12851 // the refusal, which is why the same statement throws here but not there.
12852 if !deleted && self.current_strict() {
12853 return Err(Signal::Throw(
12854 self.make_error("TypeError", "cannot delete property"),
12855 ));
12856 }
12857 self.push(Value::Bool(deleted));
12858 }
12859
12860 // -- exceptions and bookkeeping ---------------------------------
12861 Fclosure | Fclosure8 => {
12862 let value = self.closure(a as usize)?;
12863 self.push(value);
12864 }
12865
12866 other => {
12867 let name = other.info().name;
12868 return Err(Signal::Throw(self.make_error(
12869 "InternalError",
12870 &format!("{name} is not implemented yet"),
12871 )));
12872 }
12873 }
12874 Ok(Step::Continue)
12875 }
12876
12877 // -- operand helpers ----------------------------------------------------
12878
12879 /// The slot index an operand names, taking short forms into account.
12880 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12881 use Opcode::*;
12882 match op {
12883 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12884 | SetVarRef0 => 0,
12885 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12886 | SetVarRef1 => 1,
12887 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12888 | SetVarRef2 => 2,
12889 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12890 | SetVarRef3 => 3,
12891 _ => a as usize,
12892 }
12893 }
12894
12895 /// The argument count of a call, taking `call0`…`call3` into account.
12896 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12897 use Opcode::*;
12898 match op {
12899 Call0 => 0,
12900 Call1 => 1,
12901 Call2 => 2,
12902 Call3 => 3,
12903 _ => a as usize,
12904 }
12905 }
12906
12907 /// The atom's name as a property key.
12908 ///
12909 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12910 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12911 /// `String::clone` was a heap allocation and a copy — per property access.
12912 /// The atom at `index`, as a property key.
12913 ///
12914 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12915 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12916 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12917 /// 5.3% of `property:monomorphic`.
12918 /// The atom's text, exactly — including an unpaired surrogate.
12919 ///
12920 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12921 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12922 /// `atom_text` below is for the other kind of use, where the atom is a key in the
12923 /// engine's own tables.
12924 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12925 self.frame()
12926 .code
12927 .code
12928 .atoms
12929 .get(index)
12930 .map(|atom| match atom {
12931 Atom::Str(text) => text.clone(),
12932 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12933 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12934 Atom::Null => crate::value::Wtf8::new(String::new()),
12935 })
12936 .unwrap_or_default()
12937 }
12938
12939 fn atom_text(&self, index: usize) -> String {
12940 self.frame()
12941 .code
12942 .code
12943 .atoms
12944 .get(index)
12945 .map(|atom| match atom {
12946 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12947 // compare it to an identifier, and a surrogate-bearing name is reachable
12948 // through `atom_wtf8` where it matters.
12949 Atom::Str(text) => text.to_string_lossy().into_owned(),
12950 Atom::Index(value) => value.to_string(),
12951 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12952 // `throw_error`, `delete super.x`) never read it.
12953 Atom::Null => String::new(),
12954 })
12955 .unwrap_or_default()
12956 }
12957
12958 fn constant(&mut self, index: usize) -> JsResult<Value> {
12959 let constant = self.frame().code.code.cpool.get(index).cloned();
12960 Ok(match &constant {
12961 Some(Constant::Number(number)) => Value::Float(*number),
12962 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12963 Some(Constant::BigInt { digits, radix }) => {
12964 match crate::bigint::BigInt::from_radix(digits, *radix) {
12965 Some(big) => self.bigint(big),
12966 // A literal the parser accepted is always parseable; a failure here
12967 // would be a compiler bug, so it reads as an `InternalError`.
12968 None => {
12969 return Err(Signal::Throw(
12970 self.make_error("InternalError", "unparseable bigint literal"),
12971 ));
12972 }
12973 }
12974 }
12975 Some(Constant::Function(_)) => {
12976 return Err(Signal::Throw(
12977 self.make_error("InternalError", "a bare function constant"),
12978 ));
12979 }
12980 // A tagged template's call site: a frozen array of the cooked chunks with a
12981 // frozen `raw` array beside it, which is what `String.raw` reads back.
12982 //
12983 // §13.2.8.1 caches it on the realm: `runTemplate()` called twice must hand the
12984 // tag the *same* object, and only a registry gives that. The site is
12985 // (code object, constant index) — see [`Realm::template_map`].
12986 Some(Constant::Template { site, cooked, raw }) => {
12987 // Weakly held, and reaped when the map gets crowded: a program that calls
12988 // `eval` with a tagged template in a loop compiles a fresh site each time,
12989 // and keeping a strong handle would grow this map without bound. Losing an
12990 // expired entry costs nothing — nothing is using the object it named.
12991 if let Some(cached) = self
12992 .realm
12993 .template_map
12994 .get(site)
12995 .and_then(|weak| weak.upgrade())
12996 {
12997 return Ok(Value::Object(cached));
12998 }
12999 let cooked_values: Vec<Value> = cooked
13000 .iter()
13001 .map(|chunk| match chunk {
13002 Some(text) => self.string_wtf8(text.clone()),
13003 None => Value::Undefined,
13004 })
13005 .collect();
13006 let raw_values: Vec<Value> =
13007 raw.iter().map(|text| self.string(text.clone())).collect();
13008 let raw_array = self.new_array(raw_values);
13009 let template = self.new_array(cooked_values);
13010 template.define(
13011 "raw",
13012 Property::with_attributes(Value::Object(raw_array.clone()), false, false),
13013 );
13014 // `SetIntegrityLevel(…, frozen)`, not just a refusal of new properties: the
13015 // template object's indices have to be non-writable and non-configurable, and
13016 // so does `length`. `set_extensible(false)` alone left every index writable,
13017 // which is what `template-object` checks with `verifyProperty`.
13018 // An array of template strings cannot be a proxy, so neither call can be
13019 // refused — `freeze_object` is `?` rather than best-effort on purpose.
13020 crate::builtins::object::freeze_object(self, &raw_array)?;
13021 crate::builtins::object::freeze_object(self, &template)?;
13022 if self.realm.template_map.len() > 256 {
13023 self.realm
13024 .template_map
13025 .retain(|_, weak| weak.upgrade().is_some());
13026 }
13027 self.realm.template_map.insert(*site, template.downgrade());
13028 Value::Object(template)
13029 }
13030 _ => Value::Undefined,
13031 })
13032 }
13033
13034 /// The reference cell a closure-variable slot names.
13035 ///
13036 /// Two kinds of binding share this addressing: a genuine closure variable
13037 /// (captured from an enclosing function) lives in this frame's environment,
13038 /// while a *declared global* lives in the realm so that a script, a function
13039 /// declaration and their uses all see one binding. A plain `Global` — an
13040 /// undeclared name that may be satisfied by the global object — has no cell at
13041 /// all, which is how `typeof x` still works for a name that does not exist.
13042 /// The reference cell a closure-variable slot names.
13043 ///
13044 /// The environment is resolved once, when the closure is built, and this is
13045 /// just the lookup afterwards. A *declared global* is in there too, pointing at
13046 /// the realm's cell, so a script, a hoisted function declaration and their uses
13047 /// all share one binding. A plain `Global` — a name the script never declared —
13048 /// is read and written through `get_var`/`put_var` by name instead, which is
13049 /// what lets the global object satisfy it.
13050 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
13051 self.frame().env.cells.get(slot).cloned()
13052 }
13053
13054 /// Whether `slot` refers to a global binding through the reference table.
13055 ///
13056 /// A global's cell in the closure environment only exists so the slot has
13057 /// something to point at; the binding itself lives on the global object (a `var`)
13058 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
13059 /// be routed, not performed on the placeholder.
13060 fn is_global_slot(&self, slot: usize) -> bool {
13061 self.frame()
13062 .code
13063 .code
13064 .closure_vars
13065 .get(slot)
13066 .is_some_and(|c| {
13067 // A module's declarations and imports are *not* globals: their cells are
13068 // the module environment's, filled by the host, so the placeholder routing
13069 // must not apply to them.
13070 matches!(
13071 c.closure_type,
13072 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
13073 )
13074 })
13075 }
13076
13077 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
13078 if self.is_global_slot(slot) {
13079 return self.get_global(slot);
13080 }
13081 Ok(self
13082 .var_ref_cell(slot)
13083 .map(|cell| cell.get())
13084 .unwrap_or(Value::Undefined))
13085 }
13086
13087 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
13088 // A function declaration is hoisted by storing into a global reference before
13089 // the body runs, so this path is also what puts it on the global object.
13090 if self.is_global_slot(slot) {
13091 return self.put_global(slot, value);
13092 }
13093 if let Some(cell) = self.var_ref_cell(slot) {
13094 cell.set(value);
13095 }
13096 Ok(())
13097 }
13098
13099 // -- closures -----------------------------------------------------------
13100
13101 /// Build the closure for the function constant `index`.
13102 ///
13103 /// Every entry in the child's closure table names where its binding lives in
13104 /// *this* frame: a local or argument slot that was marked captured, or a cell
13105 /// this frame is itself holding. That is how a variable three functions deep
13106 /// stays one binding.
13107 fn closure(&mut self, index: usize) -> JsResult<Value> {
13108 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
13109 else {
13110 return Err(Signal::Throw(
13111 self.make_error("InternalError", "fclosure of a non-function"),
13112 ));
13113 };
13114 let mut cells = Vec::with_capacity(function.closure_vars.len());
13115 for closure_var in &function.closure_vars {
13116 let cell = match closure_var.closure_type {
13117 ClosureType::Arg => {
13118 let slot = closure_var.var_idx as usize;
13119 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
13120 }
13121 ClosureType::Local => {
13122 let slot = closure_var.var_idx as usize;
13123 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
13124 }
13125 ClosureType::Ref | ClosureType::GlobalRef => {
13126 // A `Ref` names a cell in this frame's own closure table; a
13127 // `GlobalRef` also starts there, then resolves by name below.
13128 let slot = closure_var.var_idx as usize;
13129 if let Some(cell) = self.frame().env.cells.get(slot) {
13130 cells.push(cell.clone());
13131 continue;
13132 }
13133 -1
13134 }
13135 _ => -1,
13136 };
13137 if cell >= 0 {
13138 let cell = self.frame().cells[cell as usize].clone();
13139 cells.push(cell);
13140 continue;
13141 }
13142 // A global: the cell is created on demand and shared through the realm,
13143 // so every function sees one binding.
13144 let name = closure_var.name.clone();
13145 let cell = match self.realm.globals.get(&name) {
13146 Some(cell) => cell.clone(),
13147 None => {
13148 let cell = self.new_cell(Value::Undefined);
13149 self.realm.globals.insert(name.clone(), cell.clone());
13150 cell
13151 }
13152 };
13153 cells.push(cell);
13154 }
13155 let name = function.name.clone();
13156 // `.length` is the arity before any default or rest parameter, not the number
13157 // of slots a pattern parameter needs.
13158 let length = function.defined_args;
13159 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
13160 // function and an arrow function do not. A *method* also does not, but that is not
13161 // known here — the method is marked when the `[[HomeObject]]` is attached (see
13162 // `set_home_object`), which is the moment it becomes a method.
13163 let function_kind = function.kind;
13164 let constructible =
13165 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
13166 let code = Gc::new(self.heap, CompiledCode::new(*function));
13167 // A closure built inside an `eval` inherits the eval's view of the enclosing
13168 // bindings, so it can still read them once the eval has returned.
13169 let eval_scope = self
13170 .active_eval_scope
13171 .clone()
13172 .or_else(|| self.frame().env.eval_scope.clone());
13173 // A closure sees the variables a direct `eval` declared in the frame it was
13174 // created in — the ones declared before *and after* it, so the same object is
13175 // shared; only the phase bounds which of them are visible.
13176 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
13177 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
13178 let env = Gc::new(
13179 self.heap,
13180 ClosureEnv {
13181 cells,
13182 eval_scope,
13183 local_vars,
13184 local_phase,
13185 },
13186 );
13187 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
13188 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
13189 // the only thing that carries `Symbol.toStringTag`, so without it
13190 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
13191 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
13192 let proto = match function_kind {
13193 js_compile::bytecode::FunctionKind::AsyncGenerator => self
13194 .realm
13195 .async_generator_function_proto
13196 .clone()
13197 .or_else(|| self.realm.function_proto.clone().into()),
13198 js_compile::bytecode::FunctionKind::Generator => self
13199 .realm
13200 .generator_function_proto
13201 .clone()
13202 .or_else(|| self.realm.function_proto.clone().into()),
13203 js_compile::bytecode::FunctionKind::Async => self
13204 .realm
13205 .async_function_proto
13206 .clone()
13207 .or_else(|| self.realm.function_proto.clone().into()),
13208 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
13209 };
13210 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
13211 object.set_constructible(constructible);
13212 object.define(
13213 "length",
13214 Property::name_or_length(Value::Int(length as i32)),
13215 );
13216 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
13217 // that checks the own-property descriptor fails if the property is missing.
13218 object.define("name", Property::name_or_length(self.string(name)));
13219 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
13220 // when `[[Construct]]` is created, so an async function and an arrow function have
13221 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
13222 // function) an own `prototype` property, which `builtin.js` checks for absence.
13223 //
13224 // A **generator** function is the exception that is not constructible: it still
13225 // gets a `prototype` field, because that object is what a generator *instance*
13226 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
13227 // made `function* g(){}; g.prototype` `undefined` and every generator share
13228 // `%GeneratorPrototype%` as its direct prototype.
13229 if constructible {
13230 self.install_function_prototype(&object);
13231 } else if matches!(
13232 function_kind,
13233 js_compile::bytecode::FunctionKind::Generator
13234 | js_compile::bytecode::FunctionKind::AsyncGenerator
13235 ) {
13236 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
13237 self.realm.generator_proto.clone()
13238 } else {
13239 self.realm
13240 .async_generator_proto
13241 .clone()
13242 .unwrap_or_else(|| self.realm.generator_proto.clone())
13243 };
13244 self.install_generator_prototype(&object, parent);
13245 }
13246 Ok(Value::Object(object))
13247 }
13248
13249 // -- conversions used by the operators ----------------------------------
13250
13251 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
13252 // `+x` is `ToNumber`, which for a string parses it and for an object runs
13253 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
13254 // string, which then behaves differently in every later comparison.
13255 match value {
13256 Value::Int(_) | Value::Float(_) => Ok(value),
13257 other => Ok(Value::Float(self.to_js_number(&other)?)),
13258 }
13259 }
13260
13261 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
13262 ///
13263 /// Returns the *converted* old value and the new one, because the two callers need
13264 /// different halves: `++x` yields the new value, while `x++` yields the old one and
13265 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
13266 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
13267 /// boolean.
13268 ///
13269 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
13270 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
13271 /// a bigint algorithm then ran exactly once.
13272 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
13273 if let Value::BigInt(big) = &value {
13274 let one = crate::bigint::BigInt::from_i64(1);
13275 let next = if up { big.add(&one) } else { big.sub(&one) };
13276 return Ok((value, self.bigint(next)));
13277 }
13278 let old = self.numeric_operand(value)?;
13279 if let Value::BigInt(big) = &old {
13280 let one = crate::bigint::BigInt::from_i64(1);
13281 let next = if up { big.add(&one) } else { big.sub(&one) };
13282 return Ok((old, self.bigint(next)));
13283 }
13284 let new = if up {
13285 increment(old.clone())
13286 } else {
13287 decrement(old.clone())
13288 };
13289 Ok((old, new))
13290 }
13291
13292 /// `ToNumeric` for a unary or update operand: `ToPrimitive(number)`, then either branch.
13293 ///
13294 /// The unary operators are defined on `Numeric`, not on `Number`: `-x` and `~x` are
13295 /// `Numeric::unaryMinus`/`bitwiseNOT`, which a bigint answers exactly. [`Interp::numeric`]
13296 /// is `ToNumber` and collapses a bigint to a float, so an operand that is a *wrapper
13297 /// object* — `-Object(5n)` — lost its bigint-ness before the operator ever saw it and
13298 /// raised "cannot convert bigint to number". A primitive bigint never took that path
13299 /// (`Neg`/`Not` matched `Value::BigInt` first), which is why only the boxed form broke.
13300 fn numeric_operand(&mut self, value: Value) -> JsResult<Value> {
13301 let primitive = match value {
13302 Value::Int(_) | Value::Float(_) | Value::BigInt(_) => value,
13303 other => self.to_primitive(other, Hint::Number)?,
13304 };
13305 match primitive {
13306 Value::BigInt(_) => Ok(primitive),
13307 other => self.numeric(other),
13308 }
13309 }
13310
13311 fn numeric(&mut self, value: Value) -> JsResult<Value> {
13312 // `ToNumber` on an object runs `ToPrimitive` first, which is how
13313 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
13314 // heard at all. Reading the object's own tag instead (`other.to_number()`)
13315 // turned the whole operand into `NaN` and swallowed the exception.
13316 match value {
13317 Value::Int(_) | Value::Float(_) => Ok(value),
13318 other => Ok(Value::Float(self.to_js_number(&other)?)),
13319 }
13320 }
13321
13322 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
13323 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
13324 match value {
13325 Value::BigInt(big) => Ok((**big).clone()),
13326 // The reference words this the same way for every operator, so a failing
13327 // script reads identically; the operator itself adds nothing a caller can use.
13328 _ => Err(Signal::Throw(
13329 self.make_error("TypeError", "cannot convert bigint to number"),
13330 )),
13331 }
13332 }
13333
13334 /// Arithmetic where at least one operand is a `BigInt`.
13335 ///
13336 /// The two numeric types never mix, so a bigint paired with anything else is an error
13337 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
13338 /// that the relational operators handle it separately.
13339 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13340 use Opcode::*;
13341 let a = self.bigint_operand(&left)?;
13342 let b = self.bigint_operand(&right)?;
13343 let result = match op {
13344 Add => a.add(&b),
13345 Sub => a.sub(&b),
13346 Mul => a.mul(&b),
13347 Div | Mod => {
13348 let Some((quotient, remainder)) = a.div_rem(&b) else {
13349 return Err(Signal::Throw(
13350 self.make_error("RangeError", "division by zero"),
13351 ));
13352 };
13353 if op == Div { quotient } else { remainder }
13354 }
13355 Pow => {
13356 let Some(value) = a.pow(&b) else {
13357 return Err(Signal::Throw(self.make_error(
13358 "RangeError",
13359 "BigInt exponent must be non-negative and not absurdly large",
13360 )));
13361 };
13362 value
13363 }
13364 And => a.bitand(&b),
13365 Or => a.bitor(&b),
13366 Xor => a.bitxor(&b),
13367 Shl | Sar => {
13368 // A shift count is a `BigInt` here, and both directions are exact; a
13369 // negative count would be the other direction, which the spec forbids.
13370 let Some(count) = b.to_i64() else {
13371 return Err(Signal::Throw(
13372 self.make_error("RangeError", "BigInt shift count is too large"),
13373 ));
13374 };
13375 if count < 0 {
13376 return Err(Signal::Throw(self.make_error(
13377 "RangeError",
13378 "BigInt shift count must be non-negative",
13379 )));
13380 }
13381 if op == Shl {
13382 a.shl(count as u64)
13383 } else {
13384 a.shr(count as u64)
13385 }
13386 }
13387 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
13388 _ => {
13389 return Err(Signal::Throw(self.make_error(
13390 "TypeError",
13391 "BigInts have no unsigned right shift, use >> instead",
13392 )));
13393 }
13394 };
13395 Ok(self.bigint(result))
13396 }
13397
13398 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
13399 ///
13400 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
13401 /// is on the mathematical values, and nothing is rounded first.
13402 /// `<`, `<=`, `>`, `>=`.
13403 ///
13404 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
13405 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
13406 /// It is a `?`-returning function for exactly that reason: an object operand can run
13407 /// script, and script can throw. The old version compared `to_number` of the raw
13408 /// values, which answered `false` for every object instead of calling `valueOf` —
13409 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
13410 /// never ran.
13411 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13412 // The hot arm first: `i < n` with both sides already integers. No conversion, no
13413 // call, nothing that can throw.
13414 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13415 let ordering = Some(left.cmp(right));
13416 return Ok(ordering_answer(op, ordering));
13417 }
13418 // Anything that can run script has to be converted first, in this order.
13419 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
13420 {
13421 (
13422 self.to_primitive(left, Hint::Number)?,
13423 self.to_primitive(right, Hint::Number)?,
13424 )
13425 } else {
13426 (left, right)
13427 };
13428 let ordering = match (&left, &right) {
13429 // The loop condition `i < n` is integer against integer, and it runs once
13430 // per iteration of every loop in every program. Without this arm it took the
13431 // `to_number` path twice, which is a `match` plus a conversion each.
13432 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
13433 // **Code unit** order, not code point order. They differ exactly where a
13434 // surrogate pair meets a BMP character above U+E000: `"\uDC00" > "\uD800"` is
13435 // true because 0xDC00 > 0xD800, while comparing code points would have turned
13436 // both lone surrogates into U+FFFD and called them equal
13437 // (`greater-than/S11.8.2_A4.12_T1`).
13438 (Value::String(a), Value::String(b)) => Some(compare_code_units(a, b)),
13439 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
13440 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
13441 // is true even though `2.5` has no bigint form.
13442 // §7.2.13 step 3.d-3.e: a bigint against a string goes through
13443 // `StringToBigInt`, **not** `ToNumber` — `"9007199254740993" > 9007199254740992n`
13444 // is true because both sides stay exact integers, which converting the string to
13445 // a double would destroy. A string that is not an integer literal makes the
13446 // whole comparison `undefined`, i.e. `false` for every relational operator.
13447 (Value::BigInt(a), Value::String(text)) => {
13448 string_to_bigint(&text.to_string_lossy()).map(|b| a.cmp(&b))
13449 }
13450 (Value::String(text), Value::BigInt(b)) => {
13451 string_to_bigint(&text.to_string_lossy()).map(|a| b.cmp(&a).reverse())
13452 }
13453 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
13454 let b = self.number_operand(other)?;
13455 if b.is_nan() {
13456 None
13457 } else {
13458 compare_bigint_and_f64(a, b)
13459 }
13460 }
13461 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
13462 let a = self.number_operand(other)?;
13463 if a.is_nan() {
13464 None
13465 } else {
13466 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
13467 }
13468 }
13469 // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
13470 // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
13471 // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
13472 _ => self
13473 .to_js_number(&left)?
13474 .partial_cmp(&self.to_js_number(&right)?),
13475 };
13476 Ok(ordering_answer(op, ordering))
13477 }
13478
13479 /// `ToNumber(V)`, refusing a Symbol instead of answering `NaN`.
13480 ///
13481 /// §7.1.4 throws for a Symbol, and the relational operators inherit that: `3n < Symbol()`
13482 /// is a `TypeError`, not `false`. `Value::to_number` is a total function — it has to be,
13483 /// because it is also what `Number(x)` uses — so the check lives here.
13484 fn number_operand(&self, value: &Value) -> JsResult<f64> {
13485 if matches!(value, Value::Symbol(_)) {
13486 return Err(self.type_error("cannot convert symbol to number"));
13487 }
13488 Ok(value.to_number())
13489 }
13490
13491 fn binary_add(&mut self) -> JsResult<()> {
13492 let right = self.pop();
13493 let left = self.pop();
13494 // Two integers add without any of the machinery below: no `ToPrimitive` (an
13495 // `Int` is already primitive), no string check, no bigint check, no allocation.
13496 // `x += 1` in a loop is the single most common instruction sequence in real
13497 // script, and it used to walk every one of those checks before reaching the
13498 // same `checked_add`.
13499 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13500 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
13501 return Ok(());
13502 }
13503 let left = self.primitive_of(left)?;
13504 let right = self.primitive_of(right)?;
13505 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
13506 // that check comes before the bigint one: `"" + 1n` is a string, not a
13507 // mixed-type error.
13508 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
13509 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
13510 // `TypeError`, the one place a symbol and a string do not mix.
13511 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
13512 // between a copy and a rope from their lengths, and a rope is what turns
13513 // `text += "abc"` in a loop from quadratic into linear.
13514 if let (Value::String(left), Value::String(right)) = (&left, &right) {
13515 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
13516 // reports as `InternalError: string too long`.
13517 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
13518 return Err(Signal::Throw(
13519 self.make_error("InternalError", "string too long"),
13520 ));
13521 };
13522 self.push(Value::String(Gc::new(self.heap, joined)));
13523 return Ok(());
13524 }
13525 // At least one operand was not a string, so `ToString` it. This rejects a
13526 // symbol, which is the one place a symbol and a string do not mix.
13527 let left = self.checked_to_wtf8(&left)?;
13528 let right = self.checked_to_wtf8(&right)?;
13529 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
13530 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
13531 let text = left.concat(&right);
13532 self.push(self.string_wtf8(text));
13533 return Ok(());
13534 }
13535 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
13536 // not a conversion.
13537 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
13538 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
13539 self.push(value);
13540 return Ok(());
13541 }
13542 let left = self.numeric(left)?;
13543 let right = self.numeric(right)?;
13544 self.push(add_numbers(left, right));
13545 Ok(())
13546 }
13547
13548 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
13549 self.to_primitive(value, Hint::Default)
13550 }
13551
13552 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
13553 ///
13554 /// The order depends on the hint: the "number" order tries `valueOf` first and
13555 /// `toString` second, the "string" order the other way round, and the default
13556 /// hint uses the number order. A result that is still an object is a `TypeError`,
13557 /// because no built-in `valueOf`/`toString` returns one.
13558 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
13559 let Value::Object(object) = &value else {
13560 return Ok(value);
13561 };
13562 // A Date overrides the default hint to mean "string", which is what
13563 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
13564 // this, `"" + new Date()` would print the milliseconds, not the date.
13565 let hint = if hint == Hint::Default && is_date_object(self, object) {
13566 Hint::String
13567 } else {
13568 hint
13569 };
13570 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
13571 // handed the hint as a string. This is the hook a Date uses for its default hint
13572 // and a script uses to take over conversion entirely.
13573 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
13574 // `GetMethod`, not "is it a callable object": the property has to be read and then
13575 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
13576 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
13577 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
13578 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
13579 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
13580 // callable.
13581 match self.get_property_key(object, &key)? {
13582 None | Some(Value::Undefined) | Some(Value::Null) => {}
13583 Some(Value::Object(function)) if function.is_callable() => {
13584 let hint = match hint {
13585 Hint::String => "string",
13586 Hint::Number => "number",
13587 Hint::Default => "default",
13588 };
13589 let hint = self.string(hint);
13590 let result = self.call_value(
13591 Value::Object(function),
13592 Value::Object(object.clone()),
13593 vec![hint],
13594 )?;
13595 if !matches!(result, Value::Object(_)) {
13596 return Ok(result);
13597 }
13598 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
13599 }
13600 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
13601 }
13602 let order: [&str; 2] = match hint {
13603 Hint::String => ["toString", "valueOf"],
13604 Hint::Number | Hint::Default => ["valueOf", "toString"],
13605 };
13606 let receiver = object.clone();
13607 for method in order {
13608 if let Some(function) = self.get_property(&receiver, method)?
13609 && matches!(&function, Value::Object(object) if object.is_callable())
13610 {
13611 let result =
13612 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13613 if !matches!(result, Value::Object(_)) {
13614 return Ok(result);
13615 }
13616 }
13617 }
13618 Err(self.type_error("cannot convert object to primitive value"))
13619 }
13620
13621 /// `ToString` with the object case going through `ToPrimitive`.
13622 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13623 if matches!(value, Value::Object(_)) {
13624 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13625 return Ok(primitive.to_js_string());
13626 }
13627 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13628 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13629 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13630 // check here broke `String(Symbol())` and 45 cases that print a symbol.
13631 Ok(value.to_js_string())
13632 }
13633
13634 /// `ToString(value)`, with §7.1.19's symbol refusal.
13635 ///
13636 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13637 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13638 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13639 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13640 if matches!(value, Value::Symbol(_)) {
13641 return Err(self.type_error("cannot convert a Symbol to a string"));
13642 }
13643 if matches!(value, Value::Object(_)) {
13644 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13645 if matches!(primitive, Value::Symbol(_)) {
13646 return Err(self.type_error("cannot convert a Symbol to a string"));
13647 }
13648 return Ok(primitive.to_js_string());
13649 }
13650 Ok(value.to_js_string())
13651 }
13652
13653 /// `ToString` that keeps the string's code units instead of flattening them.
13654 ///
13655 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13656 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13657 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13658 if matches!(value, Value::Symbol(_)) {
13659 return Err(Signal::Throw(
13660 self.make_error("TypeError", "cannot convert symbol to string"),
13661 ));
13662 }
13663 // An object runs `ToPrimitive` first, which may itself produce a symbol.
13664 let value = self.to_primitive(value.clone(), Hint::String)?;
13665 match value {
13666 Value::Symbol(_) => Err(Signal::Throw(
13667 self.make_error("TypeError", "cannot convert symbol to string"),
13668 )),
13669 Value::String(text) => Ok(text.wtf8().clone()),
13670 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13671 }
13672 }
13673
13674 /// `ToNumber` with the object case going through `ToPrimitive`.
13675 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13676 let value = if matches!(value, Value::Object(_)) {
13677 self.to_primitive(value.clone(), Hint::Number)?
13678 } else {
13679 value.clone()
13680 };
13681 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13682 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13683 // `NaN` to stay total, and the operators check for the bigint themselves — but
13684 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13685 // refuse, and answering `NaN` made them silently wrong instead.
13686 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13687 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13688 match value {
13689 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13690 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13691 other => Ok(other.to_number()),
13692 }
13693 }
13694
13695 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13696 /// [`ElementType::write`].
13697 ///
13698 /// This is separated from the write because both conversions are observable script —
13699 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13700 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13701 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13702 /// setters, and a plain `a[i] = v`.
13703 pub(crate) fn element_value(
13704 &mut self,
13705 element: crate::builtins::typedarray::ElementType,
13706 value: Value,
13707 ) -> JsResult<Value> {
13708 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13709 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13710 let primitive = match &value {
13711 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13712 _ => value,
13713 };
13714 if element.is_bigint() {
13715 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13716 Ok(Value::BigInt(Gc::new(self.heap, big)))
13717 } else {
13718 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13719 Ok(Value::Float(self.to_js_number(&primitive)?))
13720 }
13721 }
13722
13723 /// `ToPropertyKey`: what a computed member access uses as its key.
13724 ///
13725 /// A symbol is returned as itself, never stringified — that is what keeps
13726 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13727 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13728 match value {
13729 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13730 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13731 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13732 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13733 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13734 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13735 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13736 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13737 other.to_js_string(),
13738 ))),
13739 },
13740 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13741 }
13742 }
13743
13744 /// `ToPropertyKey` for the callers that can only use a string key.
13745 ///
13746 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13747 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13748 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13749 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13750 /// program continues with a value nobody asked for.
13751 /// `SetFunctionName`'s name for a computed key, which is not `ToPropertyKey`.
13752 ///
13753 /// §7.3.24 step 1: when the key is a **Symbol**, the name is `"[" + description + "]"`
13754 /// — or the empty string when the symbol has no description. Going through
13755 /// `ToPropertyKey` instead gave `Symbol(test262)` and `Symbol()`, so every
13756 /// `{ [sym](){} }` method had the wrong `name` (`fn-name-fn` and its generated
13757 /// relatives, in both `expressions/object` and `statements/class`).
13758 ///
13759 /// Everything else is an ordinary `ToPropertyKey` — a string key keeps its code units,
13760 /// which is what makes `{ "\uD800": function () {} }.name` the lone surrogate.
13761 fn function_name_from_key(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13762 if let Value::Symbol(symbol) = value {
13763 return Ok(match symbol.description() {
13764 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
13765 None => crate::value::Wtf8::default(),
13766 });
13767 }
13768 self.propkey_of(value)
13769 }
13770
13771 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13772 use crate::value::Wtf8;
13773 Ok(match value {
13774 // A string key keeps its code units. Going through a lossy `String` would make
13775 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13776 Value::String(text) => text.wtf8().clone(),
13777 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13778 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13779 // falling back to its `ToString` would print `[object Object]`.
13780 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13781 Value::String(text) => text.wtf8().clone(),
13782 other => Wtf8::new(other.to_js_string()),
13783 },
13784 other => Wtf8::new(other.to_js_string()),
13785 })
13786 }
13787
13788 // -- object operations used by instructions -----------------------------
13789
13790 /// Read `object[key]`, returning `undefined` when the property is missing.
13791 ///
13792 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13793 /// primitive (looking through its prototype) as well as an object — which is what
13794 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13795 /// argument needs too.
13796 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13797 self.read_field_key(object, &PropertyKey::from(key))
13798 }
13799
13800 /// [`Interp::read_field`] with a key that may be a symbol.
13801 ///
13802 /// A symbol key never reaches the string shortcuts: a string's `length` and its
13803 /// indices are string properties, and a symbol named `length` is a different
13804 /// property that a string primitive cannot have.
13805 /// [`Interp::read_field_key`], with an inline cache in front of it.
13806 ///
13807 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13808 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13809 /// without this the engine walked the chain and compared ~40 property names on each
13810 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13811 ///
13812 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13813 /// missing property. Those answers depend on running code or on state the guard below
13814 /// does not cover, and a wrong answer here is far more expensive than a lookup.
13815 ///
13816 /// A hit is re-validated against the *whole* walked chain, not just the level that
13817 /// answered: the receiver and every prototype down to that level must still be the same
13818 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13819 /// property-table *lengths* — which is what catches a property appearing on an
13820 /// intermediate prototype and shadowing the cached one.
13821 pub fn read_field_cached(
13822 &mut self,
13823 object: &Value,
13824 key: &PropertyKey,
13825 slot: usize,
13826 ) -> JsResult<Value> {
13827 let index = Self::field_cache_slot(object, key, slot);
13828 let Value::Object(target) = object else {
13829 return self.read_field_key(object, key);
13830 };
13831 if target.proxy_state().is_some() {
13832 return self.read_field_key(object, key);
13833 }
13834 if let Some(cached) = &self.field_cache[index]
13835 && cached.key == *key
13836 && let Some(value) = Self::cached_hit(target, cached)
13837 {
13838 return Ok(value);
13839 }
13840 let value = self.read_field_key(object, key)?;
13841 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13842 Ok(value)
13843 }
13844
13845 /// Whether a cache entry still describes this lookup, and if so the value.
13846 ///
13847 /// The guard is the whole point of the entry: identity plus property-table length for
13848 /// every level walked. Re-checked per level rather than once at the receiving end,
13849 /// because a shadowing property can appear anywhere along the chain.
13850 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13851 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13852 // starts with: a clone is a reference-count bump and a drop, and for
13853 // `property:monomorphic` every single hit takes only this arm.
13854 let (weak, len) = cached.chain[0].as_ref()?;
13855 if !target.upgrades_to(weak) {
13856 return None;
13857 }
13858 if cached.level == 0 {
13859 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13860 return target.cached_property_at(cached.index, &cached.key, *len);
13861 }
13862 if target.props_len() != *len {
13863 return None;
13864 }
13865 let mut level = 1;
13866 let mut current = target.proto()?;
13867 loop {
13868 let (weak, len) = cached.chain[level].as_ref()?;
13869 if !current.upgrades_to(weak) || current.props_len() != *len {
13870 return None;
13871 }
13872 if level == cached.level as usize {
13873 // The level that answered: the value is only reusable while the key is
13874 // still there and still a plain data property.
13875 return current.cached_data_property(cached.index, &cached.key);
13876 }
13877 current = current.proto()?;
13878 level += 1;
13879 }
13880 }
13881
13882 /// Build a cache entry for a lookup that just went through the slow path.
13883 ///
13884 /// Records the chain only when the answer came from a plain data property at a level
13885 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13886 /// costs the next lookup the walk it would have cost anyway.
13887 fn record_field_lookup(
13888 target: &Gc<JsObject>,
13889 key: &PropertyKey,
13890 _value: Value,
13891 ) -> Option<FieldCache> {
13892 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13893 [None, None, None];
13894 let mut current = target.clone();
13895 for level in 0..MAX_CACHED_CHAIN {
13896 chain[level] = Some((current.downgrade(), current.props_len()));
13897 if let Some((found, _)) = current.own_property_index(key) {
13898 // `own_property_index` declines an accessor and a hole, which is exactly
13899 // the set that must not be cached.
13900 return Some(FieldCache {
13901 key: key.clone(),
13902 index: found,
13903 level: level as u8,
13904 chain,
13905 });
13906 }
13907 current = current.proto()?;
13908 }
13909 None
13910 }
13911
13912 /// Which cache slot a lookup uses.
13913 ///
13914 /// Mixes the object's address, the name and the site, so that two properties of one
13915 /// object, and one property of two objects, land in different slots — which is what lets
13916 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13917 /// other iteration.
13918 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13919 let mut hash = match object {
13920 Value::Object(object) => object.address(),
13921 _ => 0,
13922 };
13923 hash = hash
13924 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13925 .rotate_left(17)
13926 .wrapping_add(key.hash_code());
13927 hash = hash.wrapping_add(site.wrapping_mul(31));
13928 // The table is a power of two, so the low bits are the slot.
13929 hash & (FIELD_CACHE_SLOTS - 1)
13930 }
13931
13932 /// Read `key` from `object`, without the inline cache.
13933 ///
13934 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13935 /// prototype chain, while the cached form answers an own data property from memory.
13936 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13937 let text = key.as_str().unwrap_or("");
13938 let Value::Object(object) = object else {
13939 // Reading a property of `undefined`/`null` is the classic TypeError.
13940 if object.is_nullish() {
13941 return Err(Signal::Throw(self.make_error(
13942 "TypeError",
13943 &format!("cannot read property '{key}' of {}", object.to_js_string()),
13944 )));
13945 }
13946 // A string has `length` and index access without being boxed.
13947 if let Value::String(value) = object {
13948 if text == "length" {
13949 return Ok(Value::Int(value.utf16_len() as i32));
13950 }
13951 if let Some(index) = array_index(text) {
13952 return Ok(match value.wtf8().unit_at(index as usize) {
13953 Some(unit) => self.string_wtf8(unit),
13954 None => Value::Undefined,
13955 });
13956 }
13957 }
13958 // A property of a primitive is looked up on its prototype: this is what
13959 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13960 let prototype = match object {
13961 Value::String(_) => self.realm.string_proto.clone(),
13962 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13963 Value::Bool(_) => self.realm.boolean_proto.clone(),
13964 // A symbol's methods live on `Symbol.prototype`, reached the same way —
13965 // `sym.description` reads through the prototype, not off the symbol.
13966 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13967 // …and a bigint's on `BigInt.prototype`, which is how
13968 // `(255n).toString(16)` reaches its method.
13969 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13970 _ => None,
13971 };
13972 if let Some(prototype) = prototype
13973 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13974 {
13975 return Ok(value);
13976 }
13977 return Ok(Value::Undefined);
13978 };
13979 Ok(self
13980 .get_property_key(object, key)?
13981 .unwrap_or(Value::Undefined))
13982 }
13983
13984 /// The `#name` a private symbol stands for, for error messages.
13985 ///
13986 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13987 /// was made from.
13988 fn private_name(symbol: &Value) -> Option<String> {
13989 match symbol {
13990 Value::Symbol(symbol) if symbol.is_private() => Some(
13991 symbol
13992 .description()
13993 .map(|text| text.to_string())
13994 .unwrap_or_default(),
13995 ),
13996 _ => None,
13997 }
13998 }
13999
14000 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
14001 ///
14002 /// Every private-field opcode takes the symbol the class stored in its own scope; a
14003 /// non-symbol here would be a compiler bug, and the reference guards it with
14004 /// `JS_ThrowTypeErrorNotASymbol`.
14005 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
14006 match symbol {
14007 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
14008 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
14009 }
14010 }
14011
14012 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
14013 ///
14014 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
14015 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
14016 /// would hit if the parser did not reject it first.
14017 fn define_private_field(
14018 &mut self,
14019 object: &Value,
14020 symbol: &Value,
14021 value: Value,
14022 ) -> JsResult<()> {
14023 let key = self.private_key(symbol)?;
14024 let Some(target) = object.as_object() else {
14025 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14026 };
14027 if !target.is_extensible() {
14028 return Err(Signal::Throw(
14029 self.make_error("TypeError", "object is not extensible"),
14030 ));
14031 }
14032 if target.own_property_key(&key).is_some() {
14033 let name = Self::private_name(symbol).unwrap_or_default();
14034 return Err(Signal::Throw(self.make_error(
14035 "TypeError",
14036 &format!("private class field '{name}' already exists"),
14037 )));
14038 }
14039 target.define_data_key(&key, value);
14040 Ok(())
14041 }
14042
14043 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
14044 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
14045 let key = self.private_key(symbol)?;
14046 let Some(target) = object.as_object() else {
14047 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14048 };
14049 match target.own_property_key(&key) {
14050 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
14051 None => {
14052 let name = Self::private_name(symbol).unwrap_or_default();
14053 Err(Signal::Throw(self.make_error(
14054 "TypeError",
14055 &format!("private class field '{name}' does not exist"),
14056 )))
14057 }
14058 }
14059 }
14060
14061 /// `JS_SetPrivateField`: the store half of the same rule.
14062 fn write_private_field(
14063 &mut self,
14064 object: &Value,
14065 symbol: &Value,
14066 value: Value,
14067 ) -> JsResult<()> {
14068 let key = self.private_key(symbol)?;
14069 let Some(target) = object.as_object() else {
14070 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14071 };
14072 if target.write_value_key(&key, value) {
14073 return Ok(());
14074 }
14075 let name = Self::private_name(symbol).unwrap_or_default();
14076 Err(Signal::Throw(self.make_error(
14077 "TypeError",
14078 &format!("private class field '{name}' does not exist"),
14079 )))
14080 }
14081
14082 /// The `in` half: does `object` have this private field?
14083 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
14084 ///
14085 /// The symbol is created once per class — the first `add_brand` on a given home object
14086 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
14087 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
14088 /// emit for the *instance* brand passes null because all it wants is the symbol.
14089 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
14090 let Some(home_object) = home.as_object() else {
14091 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14092 };
14093 let symbol = match home_object.private_brand() {
14094 Some(symbol) => symbol,
14095 None => {
14096 let symbol = Gc::new(
14097 self.heap,
14098 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
14099 );
14100 home_object.set_private_brand(symbol.clone());
14101 symbol
14102 }
14103 };
14104 let Some(target) = object.as_object() else {
14105 // Not an object: nothing to brand. The reference does the same, and `undefined`
14106 // here would otherwise turn a field initialiser into a TypeError.
14107 return Ok(());
14108 };
14109 if !target.is_extensible() {
14110 return Err(Signal::Throw(
14111 self.make_error("TypeError", "object is not extensible"),
14112 ));
14113 }
14114 if target.carries_brand(&symbol) {
14115 return Err(Signal::Throw(
14116 self.make_error("TypeError", "private method is already present"),
14117 ));
14118 }
14119 target.add_brand(symbol);
14120 Ok(())
14121 }
14122
14123 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
14124 ///
14125 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
14126 /// decides whether to throw.
14127 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
14128 let Some(function) = function.as_object() else {
14129 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14130 };
14131 let Some(home) = function.home_object() else {
14132 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14133 };
14134 let Some(brand) = home.private_brand() else {
14135 return Err(Signal::Throw(
14136 self.make_error("TypeError", "expecting <brand> private field"),
14137 ));
14138 };
14139 Ok(object.carries_brand(&brand))
14140 }
14141
14142 /// `CreateDataPropertyOrThrow(object, key, value)` — §7.3.3.
14143 ///
14144 /// What a property definition does: `[[DefineOwnProperty]]` with all three attributes
14145 /// true. Not `[[Set]]`, which walks the prototype chain and may run a setter there.
14146 fn define_field(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
14147 if let Some(target) = object.as_object() {
14148 // `CreateDataProperty` cannot reshape a non-configurable own property: its
14149 // descriptor asks for `writable` and `configurable`, and a non-configurable
14150 // property may become neither (`class C { static ['prototype'] = 1 }` is a
14151 // `TypeError`, since the constructor's `prototype` is both). The general define
14152 // path only validates *partial* descriptors — see the note there — so this has
14153 // to be said here.
14154 if self
14155 .object_get_own_property(target, key)?
14156 .is_some_and(|existing| {
14157 !existing.configurable && (existing.is_accessor() || !existing.writable)
14158 })
14159 {
14160 return Err(Signal::Throw(self.make_error(
14161 "TypeError",
14162 &format!(
14163 "cannot define property '{key}' of {}",
14164 Value::Object(target.clone()).to_js_string()
14165 ),
14166 )));
14167 }
14168 // Only an *array* stores into the element vector. A numeric key
14169 // on an ordinary object is an ordinary property, which is what
14170 // makes `{1: 'a'}` iterate as a key rather than disappear.
14171 let stored = target.is_array()
14172 && key.as_str().and_then(array_index).is_some_and(|index| {
14173 target.array_set(self.heap, index as usize, value.clone())
14174 });
14175 if !stored {
14176 // `CreateDataPropertyOrThrow`, not a raw table insert: a class
14177 // field is defined with `[[DefineOwnProperty]]`, so a frozen
14178 // receiver throws (`class Test { f = Object.freeze(this); g = 1 }`
14179 // must fail on `g`) and a **proxy** receiver runs its
14180 // `defineProperty` trap (`class-field-is-observable-by-proxy`
14181 // counts the trap's calls). `define_data_key` writes straight into
14182 // the table, which did neither.
14183 // `?` and not `unwrap_or(false)`: a proxy's `defineProperty` trap
14184 // may *throw*, and that exception is the answer
14185 // (`public-class-field-initialization-is-visible-to-proxy` throws
14186 // a `Test262Error` from the trap and expects it, not a `TypeError`).
14187 let defined =
14188 self.object_define_own_property(target, key, Property::data(value))?;
14189 if !defined {
14190 let target = Value::Object(target.clone());
14191 return Err(Signal::Throw(self.make_error(
14192 "TypeError",
14193 &format!(
14194 "cannot define property '{key}' of {}",
14195 target.to_js_string()
14196 ),
14197 )));
14198 }
14199 }
14200 }
14201 Ok(())
14202 }
14203
14204 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
14205 let Value::Object(object) = object else {
14206 // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
14207 // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
14208 // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
14209 // `undefined` still throw, with their own message.
14210 if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
14211 return Ok(());
14212 }
14213 return Err(Signal::Throw(self.make_error(
14214 "TypeError",
14215 &format!("cannot set property '{key}' of {}", object.to_js_string()),
14216 )));
14217 };
14218 // The write half of the property inline cache, in effect: an own, writable,
14219 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
14220 // decide — no prototype walk (an own property shadows the chain before a setter
14221 // there could matter), no extensibility check (the object already has the key),
14222 // and no `[[DefineOwnProperty]]`.
14223 //
14224 // `this.value = …` inside a method is the whole write side of
14225 // `property:method-call`, and it was reaching `set_property_with_key` with its
14226 // proxy test, its typed-array test, its array-index test and finally a linear
14227 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
14228 //
14229 // Every disqualifier is checked here: a proxy traps the set, an array index and
14230 // `length` live outside the property table, and a typed array's element is stored
14231 // through its view's element type.
14232 if object.proxy_state().is_none()
14233 && !object.is_array()
14234 && object.typed_array_element_type().is_none()
14235 && object.write_value_key(key, value.clone())
14236 {
14237 return Ok(());
14238 }
14239 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
14240 let on_failure = if self.frame().code.code.strict {
14241 DeleteFailure::Throw
14242 } else {
14243 DeleteFailure::Ignore
14244 };
14245 self.set_property_with_key(object, key, value, on_failure)
14246 }
14247
14248 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
14249 ///
14250 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
14251 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
14252 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
14253 /// `Number.parseInt(sym)` — so those callers use this instead.
14254 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
14255 if matches!(value, Value::Symbol(_)) {
14256 return Err(Signal::Throw(
14257 self.make_error("TypeError", "cannot convert symbol to string"),
14258 ));
14259 }
14260 // An object runs `ToPrimitive` first, which may itself produce a symbol —
14261 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
14262 let value = self.to_primitive(value.clone(), Hint::String)?;
14263 if matches!(value, Value::Symbol(_)) {
14264 return Err(Signal::Throw(
14265 self.make_error("TypeError", "cannot convert symbol to string"),
14266 ));
14267 }
14268 Ok(value.to_js_string())
14269 }
14270
14271 /// `ToPropertyKey` for a builtin that takes a key argument.
14272 ///
14273 /// Fallible: a key whose `toString` throws has to propagate that error, both for
14274 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
14275 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
14276 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
14277 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
14278 self.propkey(value)
14279 }
14280
14281 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
14282 ///
14283 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
14284 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
14285 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
14286 /// `RangeError` — and why this cannot be a plain `ToNumber`.
14287 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
14288 ///
14289 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
14290 /// then a `RangeError` when they disagree. Two conversions rather than one is
14291 /// observable: a `valueOf` that runs the first time can make `length` non-writable
14292 /// before the second, which turns the store into a refused write
14293 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
14294 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
14295 let first = self.array_length_of(value)?;
14296 let second = self.array_length_of(value)?;
14297 debug_assert_eq!(first, second);
14298 Ok(first)
14299 }
14300
14301 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
14302 ///
14303 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
14304 /// conversion can say so; a caller that needs the spec's two uses that instead.
14305 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
14306 let number = match value {
14307 Value::Int(number) => *number as f64,
14308 Value::Float(number) => *number,
14309 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
14310 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
14311 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
14312 // reference answers 0.
14313 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
14314 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
14315 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
14316 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
14317 _ => {
14318 // The primitive comes back through this same conversion, so a wrapper of a
14319 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
14320 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
14321 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
14322 return self.array_length_of(&primitive);
14323 }
14324 };
14325 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
14326 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
14327 // is a `RangeError`, not `0`.
14328 if !number.is_finite()
14329 || number.fract() != 0.0
14330 || !(0.0..=u32::MAX as f64).contains(&number)
14331 {
14332 return Err(self.range_error("invalid array length"));
14333 }
14334 Ok(number as u32)
14335 }
14336
14337 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
14338 /// `Object.getOwnPropertySymbols` put in their result array.
14339 pub fn key_value(&self, key: &PropertyKey) -> Value {
14340 match key {
14341 PropertyKey::String(text) => self.string_wtf8(text.clone()),
14342 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
14343 }
14344 }
14345
14346 /// Fill in a String exotic object: `_value`, `length` and the index properties.
14347 ///
14348 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
14349 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
14350 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
14351 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
14352 /// the two paths had drifted; this is the one both now use.
14353 ///
14354 /// The indices are *code units*, so an astral character occupies two of them — the
14355 /// same rule `s.length` and `s[i]` follow.
14356 /// Give an already-created object the internal slot that makes it a wrapper of
14357 /// `value`, so the primitive's prototype methods work on it.
14358 ///
14359 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
14360 /// which are wrappers of their own type holding the empty value.
14361 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
14362 self.internal_set(object, "_value", value);
14363 }
14364
14365 pub(crate) fn init_string_wrapper(
14366 &mut self,
14367 object: &Gc<JsObject>,
14368 text: &Gc<crate::value::JsString>,
14369 ) {
14370 object.define(
14371 "length",
14372 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
14373 );
14374 for index in 0..text.utf16_len() {
14375 if let Some(unit) = text.wtf8().unit_at(index) {
14376 object.define(
14377 &index.to_string(),
14378 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
14379 Property::with_attributes(self.string_wtf8(unit), false, true),
14380 );
14381 }
14382 }
14383 object.define_key(
14384 &self.internal_slot("_value"),
14385 Property::with_attributes(Value::String(text.clone()), false, false),
14386 );
14387 }
14388
14389 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
14390 ///
14391 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
14392 /// throws. The wrapper carries its primitive in `_value` — the same slot
14393 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
14394 /// on a boxed value no constructor ever built.
14395 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14396 let (prototype, primitive) = match value {
14397 Value::Object(object) => return Ok(object.clone()),
14398 Value::String(text) => {
14399 let object = self.new_object(self.realm.string_proto.clone());
14400 self.init_string_wrapper(&object, text);
14401 return Ok(object);
14402 }
14403 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
14404 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
14405 // A symbol and a bigint box into wrappers whose methods live on
14406 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
14407 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
14408 // branch below instead produced an object with *no* prototype, so those
14409 // methods were unreachable on a box.
14410 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
14411 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
14412 Value::Undefined | Value::Null => {
14413 return Err(Signal::Throw(self.make_error(
14414 "TypeError",
14415 &format!("cannot convert {} to object", value.to_js_string()),
14416 )));
14417 }
14418 _ => (None, value.clone()),
14419 };
14420 let object = self.new_object(prototype);
14421 self.internal_set(&object, "_value", primitive);
14422 Ok(object)
14423 }
14424
14425 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
14426 ///
14427 /// Split out for a reader that has to create the object *before* it knows what it wraps:
14428 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
14429 /// written before its primitive, so the placeholder has to exist first and be filled in
14430 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
14431 /// than a second in the deserialiser.
14432 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
14433 let prototype = match value {
14434 Value::String(_) => self.realm.string_proto.clone(),
14435 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14436 Value::Bool(_) => self.realm.boolean_proto.clone(),
14437 Value::Symbol(_) => self.realm.symbol_proto.clone(),
14438 Value::BigInt(_) => self.realm.bigint_proto.clone(),
14439 _ => {
14440 return Err(Signal::Throw(self.make_error(
14441 "TypeError",
14442 &format!("cannot box {}", value.to_js_string()),
14443 )));
14444 }
14445 };
14446 object.set_proto(prototype);
14447 if let Value::String(text) = value {
14448 self.init_string_wrapper(object, text);
14449 return Ok(());
14450 }
14451 self.internal_set(object, "_value", value.clone());
14452 Ok(())
14453 }
14454
14455 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
14456 ///
14457 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
14458 /// through the `Symbol` function object, so the registry is reachable as a method rather
14459 /// than only from `builtins::symbol`.
14460 pub fn symbol_for(&mut self, key: &str) -> Value {
14461 if let Some(existing) = self.realm.symbol_registry.get(key) {
14462 return existing.clone();
14463 }
14464 let symbol = crate::builtins::symbol::symbol_value(
14465 self,
14466 crate::value::JsSymbol::registered(key.to_string()),
14467 );
14468 self.realm
14469 .symbol_registry
14470 .insert(key.to_string(), symbol.clone());
14471 symbol
14472 }
14473
14474 /// `a == b`, the coercing comparison.
14475 ///
14476 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
14477 /// which is what makes `[] == ""` true: `[]` becomes `""` via
14478 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
14479 /// because the conversion is allowed to call script code, so the two primitive
14480 /// operands are handed back to it.
14481 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
14482 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
14483 return Ok(left.loose_equals(&right));
14484 }
14485 // `null == undefined` holds even though neither is an object.
14486 if matches!(left, Value::Undefined | Value::Null)
14487 && matches!(right, Value::Undefined | Value::Null)
14488 {
14489 return Ok(true);
14490 }
14491 if matches!(left, Value::Undefined | Value::Null)
14492 || matches!(right, Value::Undefined | Value::Null)
14493 {
14494 return Ok(false);
14495 }
14496 // Two objects compare by identity. Only an object *against a primitive* is
14497 // converted, which is why `{} == {}` is false while `[] == ""` is true.
14498 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
14499 return Ok(a.ptr_eq(b));
14500 }
14501 let left = self.to_primitive(left, Hint::Default)?;
14502 let right = self.to_primitive(right, Hint::Default)?;
14503 Ok(left.loose_equals(&right))
14504 }
14505
14506 /// `HasBinding(N)` for an Object Environment Record whose binding object is `object`.
14507 ///
14508 /// §9.1.1.2.1: `HasProperty` **and then** not listed in the object's
14509 /// `Symbol.unscopables`. The `unscopables` object is read with a plain `Get`, so a
14510 /// getter on it runs exactly once per lookup — `with/with-get-unscopables-once` counts
14511 /// the calls.
14512 fn with_has_binding(&mut self, object: &Value, name: &str) -> JsResult<bool> {
14513 let key = PropertyKey::from(name);
14514 if !self.has_property_value(object, &key)? {
14515 return Ok(false);
14516 }
14517 let unscopables_key = self.realm.well_known_key(WellKnown::Unscopables);
14518 let unscopables = self.read_field_key(object, &unscopables_key)?;
14519 let Value::Object(_) = unscopables else {
14520 // `undefined` (the usual case) or a primitive: nothing is excluded.
14521 return Ok(true);
14522 };
14523 let excluded = self.read_field_key(&unscopables, &key)?;
14524 Ok(!excluded.to_boolean())
14525 }
14526
14527 /// `GetBindingValue(N, S)` for an Object Environment Record: §9.1.1.2.4.
14528 ///
14529 /// `HasProperty` is asked a **second** time — the guard already asked it — because the
14530 /// object may have changed in between: `GetBindingValue` step 2 is a fresh lookup, and
14531 /// a proxy sees two `has` traps plus the `get`. The `unscopables` step is *not*
14532 /// repeated: that belongs to `HasBinding`, not to `GetBindingValue`.
14533 ///
14534 /// When the property has gone, strict code throws and sloppy code reads `undefined`
14535 /// from the environment (step 2's `S` is the strictness of the *running* code, not of
14536 /// the declaration).
14537 fn with_get_binding(&mut self, object: &Value, name: &str) -> JsResult<Value> {
14538 let key = PropertyKey::from(name);
14539 if !self.has_property_value(object, &key)? {
14540 if self.frame().code.code.strict {
14541 return Err(self.throw_reference(name));
14542 }
14543 return Ok(Value::Undefined);
14544 }
14545 self.read_field_key(object, &key)
14546 }
14547
14548 /// `SetMutableBinding(N, V, S)` for an Object Environment Record: §9.1.1.2.5.
14549 ///
14550 /// Same second `HasProperty`, and the same strict-mode `ReferenceError` when the
14551 /// property is gone — before the store, which is what makes
14552 /// `set-mutable-binding-binding-deleted-with-typed-array-in-proto-chain-strict-mode`
14553 /// a `ReferenceError` rather than whatever the failed store would have thrown.
14554 fn with_put_binding(&mut self, object: &Value, name: &str, value: Value) -> JsResult<()> {
14555 let key = PropertyKey::from(name);
14556 if !self.has_property_value(object, &key)? && self.frame().code.code.strict {
14557 return Err(self.throw_reference(name));
14558 }
14559 self.write_field_key(object, &key, value)
14560 }
14561
14562 /// `HasProperty(O, P)` on a `Value`, without the `in`-operator error for a primitive.
14563 fn has_property_value(&mut self, object: &Value, key: &PropertyKey) -> JsResult<bool> {
14564 match object {
14565 Value::Object(target) => self.has_property_key(target, key),
14566 // `with` boxes its object when the statement is entered (`to_object`), so a
14567 // primitive cannot arrive here; `false` is the honest answer rather than a
14568 // panic if it ever does.
14569 _ => Ok(false),
14570 }
14571 }
14572
14573 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
14574 let Value::Object(object) = object else {
14575 return Err(Signal::Throw(
14576 self.make_error("TypeError", "cannot use 'in' on a non-object"),
14577 ));
14578 };
14579 let key = self.propkey(key)?;
14580 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
14581 // trap. One implementation, so an array's derived `length` and its inherited holes
14582 // cannot be right in one caller and wrong in another.
14583 self.has_own_or_inherited(object, &key)
14584 }
14585
14586 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
14587 ///
14588 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
14589 /// whole reason the operator is a hook rather than a prototype walk.
14590 ///
14591 /// §13.10.2 `InstanceofOperator(O, C)`, which is stricter than
14592 /// [`Interp::ordinary_instance_of`]: step 1 throws when `C` is not an object at all
14593 /// (`true instanceof true`) and step 4 throws when it is an object but not callable
14594 /// (`1 instanceof Math`). Both used to answer `false`, which is `OrdinaryHasInstance`'s
14595 /// rule (its step 2) and not this operator's — so nine `expressions/instanceof` cases
14596 /// expected a `TypeError` and got a value.
14597 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14598 // Step 1, before any method lookup.
14599 if constructor.as_object().is_none() {
14600 return Err(Signal::Throw(self.make_error(
14601 "TypeError",
14602 "right-hand side of 'instanceof' is not an object",
14603 )));
14604 }
14605 let Value::Object(function) = constructor else {
14606 unreachable!("just checked");
14607 };
14608 // Step 2. A primitive `C` cannot reach here, so `get_property_key` on the object is
14609 // the whole of it.
14610 let key = self.realm.well_known_key(WellKnown::HasInstance);
14611 let method = self.get_property_key(function, &key)?;
14612 if let Some(method) = method
14613 && !matches!(method, Value::Undefined)
14614 {
14615 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
14616 return Ok(answer.to_boolean());
14617 }
14618 // Step 4.
14619 if !function.is_callable() {
14620 return Err(Signal::Throw(self.make_error(
14621 "TypeError",
14622 "right-hand side of 'instanceof' is not callable",
14623 )));
14624 }
14625 // Step 5.
14626 self.instance_of(object, constructor)
14627 }
14628
14629 /// `OrdinaryHasInstance`: the prototype walk on its own.
14630 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14631 self.instance_of(object, constructor)
14632 }
14633
14634 /// `IsArray`: an array, or a proxy whose target is one.
14635 ///
14636 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
14637 /// makes `Array.isArray(new Proxy([], {}))` true.
14638 pub fn is_array_value(&self, value: &Value) -> bool {
14639 match value {
14640 Value::Object(object) => {
14641 if let Some(state) = object.proxy_state() {
14642 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
14643 }
14644 object.is_array()
14645 }
14646 _ => false,
14647 }
14648 }
14649
14650 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
14651 ///
14652 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
14653 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
14654 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
14655 /// see [`Interp::enqueue_job_function`].
14656 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
14657 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
14658 // the handler is reported rather than lost — the same reason a `then` reaction needs a
14659 // promise to settle.
14660 let promise = self.new_promise();
14661 self.fulfill_promise(&promise, Value::Undefined);
14662 self.jobs.push_back(Job::Reaction {
14663 handler: Some(function),
14664 argument: Value::Undefined,
14665 rejected: false,
14666 promise,
14667 });
14668 Ok(())
14669 }
14670
14671 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
14672 ///
14673 /// Four of its steps were missing or wrong, and each one is a test262 case in
14674 /// `Function/prototype/Symbol.hasInstance/`:
14675 ///
14676 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
14677 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
14678 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
14679 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
14680 /// `prototype` of its own, so without this step the walk below gives `false`;
14681 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
14682 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
14683 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14684 let Value::Object(function) = constructor else {
14685 return Ok(false);
14686 };
14687 if !function.is_callable() {
14688 return Ok(false);
14689 }
14690 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
14691 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
14692 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
14693 if let Some((target, this)) = function.bound_target_and_this() {
14694 let object = if this.as_object().is_some() {
14695 this
14696 } else {
14697 object.clone()
14698 };
14699 return self.instance_of(&object, &target);
14700 }
14701 let Value::Object(target) = object else {
14702 return Ok(false);
14703 };
14704 let prototype = self.get_property(function, "prototype")?;
14705 let Some(Value::Object(prototype)) = prototype else {
14706 return Err(Signal::Throw(self.make_error(
14707 "TypeError",
14708 "function has non-object prototype in instanceof check",
14709 )));
14710 };
14711 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
14712 // which is also what makes `proxyOfInstance instanceof C` work.
14713 let mut current = Some(target.clone());
14714 while let Some(object) = current {
14715 if object.ptr_eq(&prototype) {
14716 return Ok(true);
14717 }
14718 current = self.object_prototype_of(&object)?;
14719 }
14720 Ok(false)
14721 }
14722
14723 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
14724 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
14725 if let Some(proto) = self.proxy_get_prototype_of(object)? {
14726 return Ok(proto);
14727 }
14728 if let Some(exotic) = object.exotic()
14729 && let Some(proto) = exotic.get_prototype(self, object)?
14730 {
14731 return Ok(proto);
14732 }
14733 Ok(object.proto())
14734 }
14735
14736 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
14737 pub fn object_set_prototype_of(
14738 &mut self,
14739 object: &Gc<JsObject>,
14740 proto: Option<Gc<JsObject>>,
14741 ) -> JsResult<bool> {
14742 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
14743 return Ok(answer);
14744 }
14745 if let Some(exotic) = object.exotic()
14746 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
14747 {
14748 return Ok(answer);
14749 }
14750 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
14751 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
14752 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
14753 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
14754 if self
14755 .internal_get(object, "_immutable_proto")
14756 .is_some_and(|flag| flag.to_boolean())
14757 && !same_proto(object.proto().as_ref(), proto.as_ref())
14758 {
14759 return Ok(false);
14760 }
14761 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
14762 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
14763 // inheriting from itself, which every later prototype walk then had to defend
14764 // against — and `Reflect.setPrototypeOf` reported success for an operation the
14765 // language says is impossible.
14766 if let Some(proto) = &proto {
14767 let mut current = Some(proto.clone());
14768 let mut guard = 0;
14769 while let Some(node) = current {
14770 if node.ptr_eq(object) {
14771 // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
14772 // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
14773 // while `Reflect.setPrototypeOf` reports it
14774 // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
14775 return Ok(false);
14776 }
14777 guard += 1;
14778 if guard > 1000 {
14779 break;
14780 }
14781 current = node.proto();
14782 }
14783 }
14784 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14785 // re-setting it to the *same* one is a no-op `true`. Missing this made
14786 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14787 // actually reparent the object — and it is what
14788 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14789 // forwarding path has nothing else left to refuse it.
14790 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14791 return Ok(false);
14792 }
14793 object.set_proto(proto);
14794 Ok(true)
14795 }
14796
14797 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14798 ///
14799 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14800 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14801 /// already one.
14802 /// `HasProperty(O, P)`.
14803 ///
14804 /// One implementation, shared with the `in` operator. It used to be a second copy that
14805 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14806 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14807 /// proxy ran the wrong hook and could even disagree with `in`. The
14808 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14809 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14810 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14811 self.has_own_or_inherited(object, key)
14812 }
14813
14814 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14815 ///
14816 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14817 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14818 /// boolean as well, and it needs the receiver to be the one the caller named.
14819 pub fn set_property_with_key_receiver(
14820 &mut self,
14821 object: &Gc<JsObject>,
14822 key: &PropertyKey,
14823 value: Value,
14824 receiver: Option<&Value>,
14825 on_failure: DeleteFailure,
14826 ) -> JsResult<bool> {
14827 let receiver = receiver
14828 .cloned()
14829 .unwrap_or_else(|| Value::Object(object.clone()));
14830 if object.proxy_state().is_some() {
14831 return match self.proxy_set(object, key, value, &receiver)? {
14832 Some(accepted) => Ok(accepted),
14833 None => Ok(true),
14834 };
14835 }
14836 // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14837 // receiver. This has to be answered here as well as in the storing path below,
14838 // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14839 if object.module_namespace_marker() {
14840 return Ok(false);
14841 }
14842 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14843 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14844 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14845 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14846 //
14847 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14848 //
14849 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14850 // * an *invalid* index with a different receiver answers `true` and does nothing,
14851 // not even converting `V` (`valueOfCalls` stays 0);
14852 // * a valid index with a different receiver falls through to
14853 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14854 // value lands on the **receiver**, unconverted, and can be refused by a
14855 // non-extensible receiver, an accessor, or a read-only index there.
14856 //
14857 // The last one used to write into the view itself, which left `target[0]` changed
14858 // and `receiver[0]` untouched — backwards.
14859 if object.typed_array_element_type().is_some()
14860 && let Some(numeric) = canonical_numeric_index(key)
14861 {
14862 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14863 if same {
14864 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14865 return Ok(true);
14866 }
14867 if !typed_array_index_is_valid(object, numeric) {
14868 return Ok(true);
14869 }
14870 let Some(receiver) = receiver.as_object().cloned() else {
14871 return Ok(false);
14872 };
14873 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
14874 if existing.is_accessor() || !existing.writable {
14875 return Ok(false);
14876 }
14877 let property = Property {
14878 value: Some(value),
14879 ..existing
14880 };
14881 return self.object_define_own_property(&receiver, key, property);
14882 }
14883 return self.object_define_own_property(&receiver, key, Property::data(value));
14884 }
14885 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
14886 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
14887 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
14888 // `Reflect.set` to *report* the refusal instead of raising.
14889 //
14890 // A receiver that is not the object turns the whole operation into
14891 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
14892 // `[[Set]]` rather than a lookup — that is what makes
14893 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
14894 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
14895 // writes to `object`, so it cannot express that and is only used when the two are
14896 // the same.
14897 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14898 if !same {
14899 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14900 }
14901 // Same receiver: the plain path below writes into `object`, which is right, but it
14902 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14903 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
14904 if let Some(existing) = self.object_get_own_property(object, key)? {
14905 if existing.is_accessor() {
14906 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
14907 Some(setter) => {
14908 self.call_value(setter, receiver, vec![value])?;
14909 Ok(true)
14910 }
14911 None => Ok(false),
14912 };
14913 }
14914 if !existing.writable {
14915 return Ok(false);
14916 }
14917 }
14918 // Otherwise it is an ordinary create-or-write into `object` itself.
14919 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14920 Ok(true)
14921 }
14922
14923 /// `[[IsExtensible]]`, with the proxy trap when there is one.
14924 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14925 if let Some(answer) = self.proxy_is_extensible(object)? {
14926 return Ok(answer);
14927 }
14928 if let Some(exotic) = object.exotic()
14929 && let Some(answer) = exotic.is_extensible(self, object)?
14930 {
14931 return Ok(answer);
14932 }
14933 Ok(object.is_extensible())
14934 }
14935
14936 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
14937 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14938 if let Some(answer) = self.proxy_prevent_extensions(object)? {
14939 return Ok(answer);
14940 }
14941 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
14942 //
14943 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
14944 //
14945 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
14946 // created with an explicit length, because the buffer can still move it. That is
14947 // what makes `Object.freeze` refuse every such view, including a zero-length one
14948 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14949 // plain buffer is allowed.
14950 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14951 && buffer
14952 .array_buffer_storage()
14953 .is_some_and(|storage| storage.borrow().is_resizable())
14954 {
14955 return Err(
14956 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14957 );
14958 }
14959 if let Some(exotic) = object.exotic()
14960 && let Some(answer) = exotic.prevent_extensions(self, object)?
14961 {
14962 return Ok(answer);
14963 }
14964 object.set_extensible(false);
14965 Ok(true)
14966 }
14967
14968 fn copy_properties(
14969 &mut self,
14970 target: &Value,
14971 source: &Value,
14972 exclusion: &Value,
14973 ) -> JsResult<()> {
14974 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14975 // does contribute: its index properties are own, enumerable and writable, which
14976 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14977 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14978 // is a no-op.
14979 let Some(target) = target.as_object() else {
14980 return Ok(());
14981 };
14982 let source_object = match source {
14983 Value::Object(object) => object.clone(),
14984 Value::String(text) => {
14985 // Untaken keys are the string's indices, which are code units.
14986 for index in 0..text.utf16_len() {
14987 if let Some(unit) = text.wtf8().unit_at(index) {
14988 target.define_data(&index.to_string(), self.string_wtf8(unit));
14989 }
14990 }
14991 return Ok(());
14992 }
14993 _ => return Ok(()),
14994 };
14995 // An object *rest* element passes the keys already taken by the literal part as
14996 // an array of **key values**; a spread passes `null`, which excludes nothing. The
14997 // array is read by its elements rather than by its own property names, and the
14998 // values stay `PropertyKey`s: a computed key can be a symbol, and
14999 // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
15000 // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
15001 // strings made a symbol exclusion a no-op.
15002 let mut excluded: Vec<PropertyKey> = Vec::new();
15003 if let Value::Object(list) = exclusion
15004 && let Some(length) = list.array_length()
15005 {
15006 for index in 0..length {
15007 if let Some(value) = list.array_get(index) {
15008 excluded.push(self.propkey(&value)?);
15009 }
15010 }
15011 }
15012 let source = &source_object;
15013 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
15014 // Reading the property table directly made every spread of a proxy empty.
15015 let keys = self.object_own_property_keys(source)?;
15016 for as_key in keys {
15017 // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
15018 // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
15019 // Skipping them silently lost every symbol on every spread and every object
15020 // rest element (`obj-rest-order`).
15021 //
15022 if excluded.contains(&as_key) {
15023 continue;
15024 }
15025 let enumerable = self
15026 .object_get_own_property(source, &as_key)?
15027 .is_some_and(|property| property.enumerable);
15028 if !enumerable {
15029 continue;
15030 }
15031 let value = self
15032 .get_property_key(source, &as_key)?
15033 .unwrap_or(Value::Undefined);
15034 target.define_data_key(&as_key, value);
15035 }
15036 Ok(())
15037 }
15038
15039 // -- iteration ---------------------------------------------------------
15040
15041 /// One object's own keys in enumeration order: array indices ascending, then the
15042 /// rest in insertion order.
15043 ///
15044 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
15045 /// whether the key is enumerable, which the caller resolves per key because an
15046 /// array's elements are not in the same store as its named properties.
15047 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
15048 // An index can arrive twice, once from the array's element store and once from
15049 // its property map, so the numeric keys go through a map that keeps the
15050 // enumerable answer if either source gave one.
15051 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
15052 for (key, enumerable) in &own {
15053 if let Some(index) = key.as_str().and_then(array_index) {
15054 let entry = numeric.entry(index).or_insert(false);
15055 *entry = *entry || *enumerable;
15056 }
15057 }
15058 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
15059 .into_iter()
15060 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
15061 .collect();
15062 ordered.extend(
15063 own.into_iter()
15064 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
15065 );
15066 ordered
15067 }
15068
15069 /// Build the key list a `for-in` loop walks.
15070 ///
15071 /// The order is the specification's: own properties before inherited ones, and
15072 /// within one object the integer-like keys in ascending numeric order ahead of the
15073 /// string keys in insertion order. A shadowed key only appears once, and a key that
15074 /// is a non-enumerable own property anywhere nearer is skipped entirely.
15075 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
15076 let record = self.new_object(None);
15077 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
15078 // A proxy supplies its own key list, and — the reason this is not just another
15079 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
15080 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
15081 // descriptor there.
15082 if let Value::Object(object) = value
15083 && object.proxy_state().is_some()
15084 {
15085 let own = self
15086 .proxy_own_keys(object)?
15087 .unwrap_or_else(|| object.own_property_keys());
15088 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
15089 let mut numeric: Vec<u32> = Vec::new();
15090 let mut rest: Vec<PropertyKey> = Vec::new();
15091 for key in own {
15092 match key.as_str().and_then(array_index) {
15093 Some(index) => numeric.push(index),
15094 None => rest.push(key),
15095 }
15096 }
15097 numeric.sort_unstable();
15098 ordered.extend(
15099 numeric
15100 .into_iter()
15101 .map(|index| PropertyKey::from(index.to_string())),
15102 );
15103 ordered.extend(rest);
15104 for (index, key) in ordered.into_iter().enumerate() {
15105 record.define_data(&index.to_string(), self.key_value(&key));
15106 }
15107 record.define_data("__index", Value::Int(0));
15108 // The mark that makes `for_in_advance` re-ask the proxy per key.
15109 record.define_data("__proxy", Value::Object(object.clone()));
15110 return Ok(record);
15111 }
15112 if let Value::Object(object) = value {
15113 let mut chain = vec![object.clone()];
15114 chain.extend(object.chain());
15115 // Every own string key the walk has seen, enumerable or not. A
15116 // non-enumerable own property still hides a same-named enumerable one
15117 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
15118 // keeps `x` out of the loop even when the prototype has one.
15119 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
15120 for object in chain {
15121 // A namespace's bindings are materialised by `[[GetOwnProperty]]`, and a
15122 // binding still in its dead zone throws there (§10.4.6.8). Enumerating
15123 // through the raw table skipped that, so `for (var k in ns)` on a namespace
15124 // whose module was still evaluating saw the keys and read `undefined`
15125 // (`namespace/internals/enumerate-binding-uninit`).
15126 if object.module_namespace_marker() {
15127 for key in object.own_property_keys() {
15128 self.object_get_own_property(&object, &key)?;
15129 }
15130 }
15131 let mut own: Vec<(crate::value::Wtf8, bool)> = object
15132 .own_property_keys()
15133 .iter()
15134 .filter_map(|key| key.as_wtf8().cloned())
15135 .map(|key| {
15136 let enumerable = object
15137 .own_property(&key.to_string_lossy())
15138 .map(|property| property.enumerable)
15139 .unwrap_or(false);
15140 (key, enumerable)
15141 })
15142 .collect();
15143 if let Some(length) = object.array_length() {
15144 own.retain(|(key, _)| key.as_str() != Some("length"));
15145 for index in 0..length {
15146 // A dense element is enumerable; a **hole** is not there at all —
15147 // and a hole is also what an index with a recorded descriptor
15148 // leaves behind, in which case the table entry above already
15149 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
15150 // defines index 0 non-enumerable and `for…in` must skip it).
15151 if let Some(value) = object.array_get(index)
15152 && !matches!(value, Value::Hole)
15153 {
15154 own.push((crate::value::Wtf8::new(index.to_string()), true));
15155 }
15156 }
15157 }
15158 // Integer-like keys come first in ascending order, then the rest in
15159 // insertion order — and the ordering is *per object*, not for the chain
15160 // as a whole: one pass over every collected key lifted a prototype's
15161 // `"4"` above the target's own `x`/`y`, which is not the order
15162 // `for…in` reports.
15163 for (key, enumerable) in Self::order_own_keys(own) {
15164 if visited.contains(&key) {
15165 continue;
15166 }
15167 visited.push(key.clone());
15168 if enumerable {
15169 keys.push(key);
15170 }
15171 }
15172 }
15173 }
15174 for (index, key) in keys.into_iter().enumerate() {
15175 record.define_data(&index.to_string(), self.string_wtf8(key));
15176 }
15177 record.define_data("__index", Value::Int(0));
15178 Ok(record)
15179 }
15180
15181 /// The next key of a `for…in` record, `None` when the loop is done.
15182 ///
15183 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
15184 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
15185 /// the loop reaches it, so a handler that stops reporting a key partway through drops
15186 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
15187 /// key the handler had already withdrawn.
15188 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
15189 let Value::Object(record) = record else {
15190 return Ok(None);
15191 };
15192 let proxy = record
15193 .own_property("__proxy")
15194 .and_then(|property| property.value);
15195 loop {
15196 let index = record
15197 .own_property("__index")
15198 .and_then(|property| property.value)
15199 .map(|value| value.to_int32())
15200 .unwrap_or(0);
15201 let Some(candidate) = record
15202 .own_property(&index.to_string())
15203 .and_then(|property| property.value)
15204 else {
15205 return Ok(None);
15206 };
15207 record.define_data("__index", Value::Int(index + 1));
15208 let text = candidate.to_js_string();
15209 let Some(Value::Object(proxy)) = &proxy else {
15210 return Ok(Some(text));
15211 };
15212 // The candidate is already a key string here, so the lookup does not need a
15213 // second `ToPropertyKey` conversion.
15214 let key = PropertyKey::from(text.as_str());
15215 let live = match self.proxy_get_own_property(proxy, &key)? {
15216 Some(descriptor) => descriptor,
15217 // Not a proxy after all, or it lost its state: fall back to the target.
15218 None => proxy.own_property_key(&key),
15219 };
15220 if live.is_some_and(|property| property.enumerable) {
15221 return Ok(Some(text));
15222 }
15223 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
15224 // next one.
15225 }
15226 }
15227
15228 /// The iterator for `for-of`: the object and its `next` method.
15229 ///
15230 /// An object that already carries a `next` method is used as it is — that is what
15231 /// `arr.values()` returns — and only arrays and strings get the built-in
15232 /// sequence iterator.
15233 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
15234 ///
15235 /// Callers that must choose between the iterable and the array-like protocol — the
15236 /// typed-array constructor is the main one — need to ask *before* committing to one.
15237 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
15238 let key = self.realm.well_known_key(WellKnown::Iterator);
15239 let method = self.read_field_key(value, &key)?;
15240 if matches!(method, Value::Undefined | Value::Null) {
15241 return Ok(false);
15242 }
15243 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15244 return Err(Signal::Throw(
15245 self.make_error("TypeError", "Symbol.iterator is not callable"),
15246 ));
15247 }
15248 Ok(true)
15249 }
15250
15251 /// Collect everything an iterable yields.
15252 ///
15253 /// The cap is a guard against a generator that never ends: an unbounded collect would
15254 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
15255 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
15256 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
15257 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
15258 const MAX_ITEMS: usize = 1 << 24;
15259 let iterator = self.get_iterator(value)?;
15260 let mut out = Vec::new();
15261 loop {
15262 let (element, done) = self.iterator_step(&iterator)?;
15263 if done {
15264 return Ok(out);
15265 }
15266 out.push(element);
15267 if out.len() > MAX_ITEMS {
15268 // Close before refusing: the walk is being abandoned, so the iterator's
15269 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
15270 // unrun and a locked resource unreleased.
15271 self.close_iterator_after_throw(&iterator)?;
15272 return Err(self.range_error("iterable is too long to collect"));
15273 }
15274 }
15275 }
15276
15277 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
15278 ///
15279 /// A native constructor calls this once it has validated its arguments, which is the
15280 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
15281 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
15282 /// never reached. The prototype comes from `new.target` when it is an object, and from
15283 /// `default_proto` otherwise.
15284 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
15285 let proto = self.ctor_prototype(default_proto)?;
15286 Ok(self.new_object(Some(proto)))
15287 }
15288
15289 /// An **array** whose prototype comes from `new.target`.
15290 ///
15291 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
15292 /// instance from `new.target.prototype`, and building a plain array instead made every
15293 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
15294 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
15295 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
15296 Ok(JsObject::array(self.heap, Some(proto), 0))
15297 }
15298
15299 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
15300 ///
15301 /// The `Option` form is for the constructors that build their instance in a helper which
15302 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
15303 /// from `await`'s internal promise, and only the first has a `new.target`.
15304 fn ctor_prototype_opt(
15305 &mut self,
15306 default_proto: Option<Gc<JsObject>>,
15307 ) -> JsResult<Option<Gc<JsObject>>> {
15308 // `active_new_target`: by the time a native constructor runs, `call_value` has
15309 // already consumed the parked value.
15310 let Some(target) = self
15311 .active_new_target
15312 .as_object()
15313 .cloned()
15314 .map(Value::Object)
15315 else {
15316 return Ok(default_proto);
15317 };
15318 let Some(target) = target.as_object().cloned() else {
15319 return Ok(default_proto);
15320 };
15321 match self.get_property(&target, "prototype")? {
15322 Some(Value::Object(proto)) => Ok(Some(proto)),
15323 _ => Ok(default_proto),
15324 }
15325 }
15326
15327 /// `new.target.prototype`, or `default_proto` when this is a plain call.
15328 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
15329 let Some(target) = self.active_new_target.as_object().cloned() else {
15330 return Ok(default_proto);
15331 };
15332 match self.get_property(&target, "prototype")? {
15333 Some(Value::Object(proto)) => Ok(proto),
15334 _ => Ok(default_proto),
15335 }
15336 }
15337
15338 /// `CreateDataPropertyOrThrow(O, key, value)`.
15339 ///
15340 /// A *definition*, not an assignment. The difference is visible the moment the target
15341 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
15342 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
15343 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
15344 /// refused (`configurable: false`).
15345 ///
15346 /// The fast path exists because this is called once per element by `map`, `filter`,
15347 /// `slice` and friends: a plain array with no custom element descriptors and a writable
15348 /// `length` can store straight into its element vector.
15349 pub fn create_data_property_or_throw(
15350 &mut self,
15351 object: &Gc<JsObject>,
15352 index: usize,
15353 value: Value,
15354 ) -> JsResult<()> {
15355 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
15356 // an array (that is what `Array.isArray` must say), so the element fast path would
15357 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
15358 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
15359 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
15360 // records the exact trap sequence.
15361 if object.proxy_state().is_none()
15362 && object.is_array()
15363 && object.elements_writable()
15364 && !object.has_element_descriptors()
15365 && object.is_extensible()
15366 && object.array_set(self.heap, index, value.clone())
15367 {
15368 return Ok(());
15369 }
15370 let key = PropertyKey::from(index.to_string());
15371 let property = Property {
15372 value: Some(value),
15373 writable: true,
15374 enumerable: true,
15375 configurable: true,
15376 ..Property::default()
15377 };
15378 // `CreateDataProperty` always asks for the default attributes, so it can only ever
15379 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
15380 // the rest. Checking here rather than inside `object_define_own_property` is
15381 // deliberate: that function receives a fully-populated `Property` and cannot tell
15382 // an omitted attribute from an explicit `false`, so the generic check it would need
15383 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
15384 // writable property (that cost eight `Object/defineProperty` tests).
15385 if object.proxy_state().is_none()
15386 && let Some(existing) = self.object_get_own_property(object, &key)?
15387 && !existing.configurable
15388 {
15389 return Err(self.type_error("cannot create the property"));
15390 }
15391 if self.object_define_own_property(object, &key, property)? {
15392 return Ok(());
15393 }
15394 Err(self.type_error("cannot create the property"))
15395 }
15396
15397 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
15398 ///
15399 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
15400 /// its callers have; this is the same operation for the named properties a built-in
15401 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
15402 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
15403 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
15404 pub fn create_named_data_property_or_throw(
15405 &mut self,
15406 object: &Gc<JsObject>,
15407 key: &str,
15408 value: Value,
15409 ) -> JsResult<()> {
15410 let key = PropertyKey::from(key);
15411 let property = Property {
15412 value: Some(value),
15413 writable: true,
15414 enumerable: true,
15415 configurable: true,
15416 ..Property::default()
15417 };
15418 if object.proxy_state().is_none()
15419 && let Some(existing) = self.object_get_own_property(object, &key)?
15420 && !existing.configurable
15421 {
15422 return Err(self.type_error("cannot create the property"));
15423 }
15424 if self.object_define_own_property(object, &key, property)? {
15425 return Ok(());
15426 }
15427 Err(self.type_error("cannot create the property"))
15428 }
15429
15430 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
15431 ///
15432 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
15433 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
15434 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
15435 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
15436 /// run user code and both can throw.
15437 pub fn species_constructor(
15438 &mut self,
15439 object: &Gc<JsObject>,
15440 default: Value,
15441 ) -> JsResult<Value> {
15442 let Some(constructor) = self.get_property(object, "constructor")? else {
15443 return Ok(default);
15444 };
15445 let constructor = match constructor {
15446 Value::Undefined => return Ok(default),
15447 Value::Object(constructor) => constructor,
15448 _ => return Err(self.type_error("constructor is not an object")),
15449 };
15450 let key = self.realm.well_known_key(WellKnown::Species);
15451 let species = self.get_property_key(&constructor, &key)?;
15452 match species {
15453 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
15454 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
15455 Some(_) => Err(self.type_error("species is not a constructor")),
15456 }
15457 }
15458
15459 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
15460 ///
15461 /// The result is an array of `length` holes whose prototype comes from
15462 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
15463 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
15464 /// is why the `IsArray` check is the first step and not an optimisation.
15465 pub fn array_species_create(
15466 &mut self,
15467 original: &Value,
15468 length: usize,
15469 ) -> JsResult<Gc<JsObject>> {
15470 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
15471 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
15472 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
15473 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
15474 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
15475 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
15476 // realm** — the species may be a user function that ignores the length entirely, and
15477 // then `2**53 - 1` is not its problem
15478 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
15479 // a short proxy and expects the copy loop to run).
15480 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
15481 if length > ARRAY_CREATE_LIMIT {
15482 return Err(interp.range_error("invalid array length"));
15483 }
15484 Ok(interp.new_array_of_length(length))
15485 };
15486 let Some(object) = original.as_object().cloned() else {
15487 return default(self);
15488 };
15489 if !object.is_array() {
15490 return default(self);
15491 }
15492 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
15493 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
15494 let Some(constructor) = self.get_property(&object, "constructor")? else {
15495 return default(self);
15496 };
15497 let species = match constructor {
15498 Value::Undefined => return Ok(self.new_array_of_length(length)),
15499 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
15500 return default(self);
15501 }
15502 Value::Object(constructor) => {
15503 let key = self.realm.well_known_key(WellKnown::Species);
15504 match self.get_property_key(&constructor, &key)? {
15505 None | Some(Value::Undefined) | Some(Value::Null) => {
15506 return default(self);
15507 }
15508 Some(species) => species,
15509 }
15510 }
15511 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
15512 // is a `TypeError`, not "the default". Treating it as the default made
15513 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
15514 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
15515 // `concat/create-ctor-non-object` are the same rule three times.
15516 _ => return Err(self.type_error("constructor is not an object")),
15517 };
15518 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
15519 // that is merely callable is the `create-species-non-ctor` case.
15520 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
15521 return Err(self.type_error("species is not a constructor"));
15522 }
15523 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
15524 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
15525 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
15526 let created = self.construct(
15527 species.clone(),
15528 species,
15529 vec![crate::object::length_value(length)],
15530 )?;
15531 let Some(created) = created.as_object().cloned() else {
15532 return Err(self.type_error("species constructor did not answer an object"));
15533 };
15534 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
15535 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
15536 // object, and `create-species-with-non-writable-property` asserts exactly that.
15537 // The length is set for the array case; the generic case is the caller's
15538 // `Set(A, "length", …)`.
15539 if created.is_array() {
15540 created.array_set_length(self.heap, length);
15541 }
15542 Ok(created)
15543 }
15544
15545 /// Whether `object` is this realm's `%Array%`.
15546 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
15547 self.realm
15548 .array_constructor
15549 .as_ref()
15550 .is_some_and(|array| array.ptr_eq(object))
15551 }
15552
15553 /// A fresh `length`-hole array with the intrinsic prototype.
15554 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
15555 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
15556 array.array_set_length(self.heap, length);
15557 array
15558 }
15559
15560 /// Whether this call is a construction, i.e. `new.target` is defined.
15561 ///
15562 /// A native constructor receives `this = undefined` (it builds its own instance), so it
15563 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
15564 /// The native function currently executing, if any.
15565 pub fn current_native(&self) -> Option<Gc<JsObject>> {
15566 self.current_native.clone()
15567 }
15568
15569 /// Whether this call is a construction, i.e. `new.target` is defined.
15570 pub fn is_constructing(&self) -> bool {
15571 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
15572 // `call_value` before a native runs, so by the time a constructor body asks, the
15573 // answer is only in the active slot.
15574 matches!(self.active_new_target, Value::Object(_))
15575 }
15576
15577 /// The `TypeError` a constructor too primitive to have a wrapper raises.
15578 ///
15579 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
15580 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
15581 /// happens inside the native function, which is why the trace carries an
15582 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
15583 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
15584 /// constructor`, and an unnamed one reports the leading space of `" is not a
15585 /// constructor"` because the reference formats the empty name as it is.
15586 ///
15587 /// It is also the answer for a `new.target` that cannot be named at all — not a
15588 /// function, or a throwing `name` getter — where the reference falls back to the bare
15589 /// `not a constructor`.
15590 pub fn not_a_constructor_error(&mut self) -> Signal {
15591 let target = self.active_new_target.clone();
15592 self.not_a_constructor_error_for(target)
15593 }
15594
15595 /// The same `TypeError` for an explicit target, for the callers that check
15596 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
15597 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
15598 let target = match target {
15599 Value::Object(target) if target.is_callable() => target,
15600 _ => return self.type_error("not a constructor"),
15601 };
15602 let name = match self.get_property(&target, "name") {
15603 Ok(Some(value)) => value.to_js_string(),
15604 _ => return self.type_error("not a constructor"),
15605 };
15606 self.type_error(format!("{name} is not a constructor"))
15607 }
15608
15609 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
15610 ///
15611 /// True whenever `new.target` is not the callee itself, or when it has no usable
15612 /// `prototype` — the cases where reading the property is observable at all.
15613 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
15614 match &self.active_new_target {
15615 Value::Object(target) => !target.ptr_eq(callee),
15616 Value::Undefined => false,
15617 _ => true,
15618 }
15619 }
15620
15621 /// The symbol key for one of the engine's own hidden slots.
15622 ///
15623 /// Cached on the realm, so every object of a kind shares one key and a slot can be
15624 /// read back by name.
15625 /// Whether any object on `object`'s **prototype chain** owns an array index.
15626 ///
15627 /// The one question the array methods' dense fast paths have to ask before touching the
15628 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
15629 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
15630 /// vector an unreliable answer. Walking the chain once per call is cheap because a
15631 /// prototype almost never holds an index.
15632 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
15633 let mut current = object.proto();
15634 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
15635 for _ in 0..10_000 {
15636 let Some(proto) = current else {
15637 return false;
15638 };
15639 if proto.has_indexed_own_property() {
15640 return true;
15641 }
15642 current = proto.proto();
15643 }
15644 false
15645 }
15646
15647 /// The hidden symbol a named internal slot is keyed by, created on first use.
15648 ///
15649 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
15650 /// either keeping a table of its own.
15651 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
15652 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
15653 return PropertyKey::Symbol(symbol.clone());
15654 }
15655 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
15656 self.realm
15657 .internal_slots
15658 .borrow_mut()
15659 .insert(name, Value::Symbol(symbol.clone()));
15660 PropertyKey::Symbol(symbol)
15661 }
15662
15663 /// Read a hidden slot, or `None` when the object has none of that name.
15664 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
15665 let slots = self.realm.internal_slots.borrow();
15666 let Value::Symbol(symbol) = slots.get(name)? else {
15667 return None;
15668 };
15669 object
15670 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
15671 .and_then(|property| property.value)
15672 }
15673
15674 /// Define a hidden slot.
15675 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
15676 let key = self.internal_slot(name);
15677 object.define_key(&key, Property::with_attributes(value, false, false));
15678 }
15679
15680 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
15681 ///
15682 /// The method is looked up on the value (through its prototype), called with no
15683 /// arguments, and its result becomes the iterator. A generator gets here through
15684 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
15685 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
15686 ///
15687 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
15688 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
15689 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
15690 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
15691 /// does, and a user-defined iterable works without a special case.
15692 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
15693 /// `Symbol.iterator`.
15694 ///
15695 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
15696 /// iterable is legal there, and each value it produces is simply already settled by
15697 /// the time the `await` around it runs.
15698 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15699 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
15700 let method = self.read_field_key(value, &async_key)?;
15701 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
15702 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
15703 // is *present but not callable* is a TypeError — it does not mean "try the other
15704 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
15705 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
15706 // guard is there to catch.
15707 let absent = matches!(method, Value::Undefined | Value::Null);
15708 if !absent {
15709 let Value::Object(object) = &method else {
15710 return Err(Signal::Throw(
15711 self.make_error("TypeError", "value is not iterable"),
15712 ));
15713 };
15714 if !object.is_callable() {
15715 return Err(Signal::Throw(
15716 self.make_error("TypeError", "value is not iterable"),
15717 ));
15718 }
15719 }
15720 if absent {
15721 // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
15722 // generator's `yield*` both reach here, and the wrapper is what puts
15723 // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
15724 // caller — a poisoned `constructor` on that value rejects instead of being
15725 // yielded, and a rejection closes the synchronous iterator first.
15726 let sync = self.get_iterator(value)?;
15727 return self.async_from_sync_iterator(sync);
15728 }
15729 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15730 if !matches!(iterator, Value::Object(_)) {
15731 return Err(Signal::Throw(
15732 self.make_error("TypeError", "iterator is not an object"),
15733 ));
15734 }
15735 let next = self.read_field(&iterator, "next")?;
15736 Ok(Iterator {
15737 object: iterator,
15738 next,
15739 })
15740 }
15741
15742 /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
15743 ///
15744 /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
15745 /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
15746 /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
15747 fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
15748 let Some(factory) = self.realm.async_from_sync.clone() else {
15749 // No wrapper installed (a realm whose heap refused to hold it): fall back to the
15750 // raw synchronous iterator rather than refusing to iterate at all.
15751 return Ok(sync);
15752 };
15753 let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
15754 let next = self.read_field(&wrapper, "next")?;
15755 Ok(Iterator {
15756 object: wrapper,
15757 next,
15758 })
15759 }
15760
15761 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
15762 /// read — `@@iterator` is **not** consulted.
15763 ///
15764 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
15765 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
15766 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
15767 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
15768 /// refused it with "[object Object] is not iterable".
15769 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
15770 if !matches!(value, Value::Object(_)) {
15771 return Err(self.type_error("iterator is not an object"));
15772 }
15773 let next = self.read_field(&value, "next")?;
15774 Ok(Iterator {
15775 object: value,
15776 next,
15777 })
15778 }
15779
15780 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15781 let key = self.realm.well_known_key(WellKnown::Iterator);
15782 let method = self.read_field_key(value, &key)?;
15783 let Value::Object(function) = &method else {
15784 return Err(Signal::Throw(self.make_error(
15785 "TypeError",
15786 &format!("{} is not iterable", value.to_js_string()),
15787 )));
15788 };
15789 if !function.is_callable() {
15790 return Err(Signal::Throw(self.make_error(
15791 "TypeError",
15792 &format!("{} is not iterable", value.to_js_string()),
15793 )));
15794 }
15795 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15796 // The spec requires an object here; a primitive iterator has no `next` to call
15797 // and would fail one step later with a confusing message.
15798 if !matches!(iterator, Value::Object(_)) {
15799 return Err(Signal::Throw(
15800 self.make_error("TypeError", "iterator is not an object"),
15801 ));
15802 }
15803 let next = self.read_field(&iterator, "next")?;
15804 Ok(Iterator {
15805 object: iterator,
15806 next,
15807 })
15808 }
15809
15810 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15811 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15812 /// exception from `return` propagates normally instead of being swallowed. That is the
15813 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15814 /// because confusing them is exactly the bug both exist to avoid.
15815 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15816 let method = self.read_field(&iterator.object, "return")?;
15817 if matches!(method, Value::Undefined | Value::Null) {
15818 return Ok(());
15819 }
15820 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15821 return Err(self.type_error("iterator return is not a function"));
15822 }
15823 self.call_value(method, iterator.object.clone(), Vec::new())?;
15824 Ok(())
15825 }
15826
15827 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15828 /// cannot replace it.
15829 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15830 let method = self.read_field(&iterator.object, "return")?;
15831 if matches!(method, Value::Undefined | Value::Null) {
15832 return Ok(());
15833 }
15834 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15835 return Err(self.type_error("iterator return is not a function"));
15836 }
15837 self.call_value(method, iterator.object.clone(), Vec::new())?;
15838 Ok(())
15839 }
15840
15841 /// One step of an internal iterator: the value and whether it is exhausted.
15842 /// Replace the iterator slot of an iteration record with `undefined`.
15843 ///
15844 /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15845 /// `undefined` record is what every close path already treats as "nothing to close", so
15846 /// one store both records "this iterator must not be closed" and keeps
15847 /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15848 fn clear_iterator_slot(&mut self, slot: usize) {
15849 let frame = self.frame_mut();
15850 let depth = frame.stack.len();
15851 if depth > slot {
15852 frame.stack[depth - 1 - slot] = Value::Undefined;
15853 }
15854 }
15855
15856 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
15857 // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
15858 // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
15859 // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
15860 // before the first step, so an iterator with no `next` still gets its `return`
15861 // called by `it.return()` instead of failing up front
15862 // (`array-rest-iter-rtrn-close-err`).
15863 if let Value::Object(object) = &iterator.next
15864 && object.is_callable()
15865 {
15866 let result =
15867 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
15868 let Some(result) = result.as_object().cloned() else {
15869 return Err(self.type_error("iterator result is not an object"));
15870 };
15871 let done = self
15872 .get_property(&result, "done")?
15873 .is_some_and(|value| value.to_boolean());
15874 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
15875 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
15876 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
15877 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
15878 // made an unrelated `value` getter observable after the loop was over.
15879 if done {
15880 return Ok((Value::Undefined, true));
15881 }
15882 let value = self
15883 .get_property(&result, "value")?
15884 .unwrap_or(Value::Undefined);
15885 return Ok((value, false));
15886 }
15887 // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
15888 // tested at the call. Treating a non-callable `next` as "exhausted" instead made
15889 // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
15890 // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
15891 Err(Signal::Throw(self.make_error(
15892 "TypeError",
15893 "iterator's next method is not callable",
15894 )))
15895 }
15896
15897 /// `[...iterable]`: append everything the iterator yields, and answer the next
15898 /// index.
15899 ///
15900 /// This goes through the same iterator machinery `for-of` uses rather than copying
15901 /// an array's elements, because a spread source is any iterable: a string spreads
15902 /// into its characters and an array iterator spreads into its results. Handling
15903 /// only arrays made `[..."ab"]` come out empty with no error at all.
15904 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
15905 let Some(target) = array.as_object().cloned() else {
15906 return Ok(0);
15907 };
15908 let start = target.array_length().unwrap_or(0);
15909 let mut added = 0;
15910 let iterator = self.get_iterator(iterable)?;
15911 loop {
15912 let (value, done) = self.iterator_step(&iterator)?;
15913 if done {
15914 break;
15915 }
15916 target.array_set(self.heap, start + added, value);
15917 added += 1;
15918 }
15919 Ok((start + added) as i32)
15920 }
15921
15922 /// How an uncaught exception is reported.
15923 ///
15924 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
15925 /// with `ToString` — `js_std_dump_error` is three lines that end in
15926 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
15927 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
15928 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
15929 ///
15930 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
15931 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
15932 /// `toString`"; it does call it, but only for objects of a class it does not know how
15933 /// to walk, and never for errors, arrays or plain objects.
15934 ///
15935 /// A printer that fails must not take the reporter down with it, so that case falls
15936 /// back to the `ToString` rendering.
15937 pub fn describe_exception(&mut self, value: &Value) -> String {
15938 match crate::print::sprint(self, value) {
15939 Ok(text) => text,
15940 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
15941 }
15942 }
15943
15944 /// The file name of whatever is running, innermost frame first.
15945 ///
15946 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
15947 /// innermost frame's file name, without distinguishing a module body from a plain
15948 /// script. `import()` uses it as the base for a relative specifier, which is why
15949 /// `import('./x.js')` inside a script resolves next to the script and not next to the
15950 /// process's working directory.
15951 pub fn script_or_module_name(&self) -> Option<String> {
15952 self.script_or_module_name_at(0)
15953 }
15954
15955 /// [`Interp::script_or_module_name`] `level` frames further out.
15956 ///
15957 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
15958 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
15959 /// frame without a file name is skipped rather than counted, because a native call
15960 /// pushes no frame of its own and so cannot be a level.
15961 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
15962 self.frames
15963 .iter()
15964 .rev()
15965 .filter_map(|frame| frame.code.code.filename.clone())
15966 .nth(level)
15967 }
15968
15969 /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15970 ///
15971 /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15972 /// because that is what a stack trace should print, but §19.2.1.1's
15973 /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15974 /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15975 /// produced the bare specifier `x.js`, which the loader then looked for in the working
15976 /// directory instead of beside the file that called `eval`.
15977 pub fn script_or_module_file_name(&self) -> Option<String> {
15978 self.frames.iter().rev().find_map(|frame| {
15979 let name = frame.code.code.filename.as_deref()?;
15980 (!name.starts_with('<')).then(|| name.to_string())
15981 })
15982 }
15983
15984 /// The current call stack, formatted the way `qjs` prints `error.stack`.
15985 ///
15986 /// One ` at name (file:line:col)` line per active frame, innermost first. The
15987 /// position is the one recorded for the instruction each frame is stopped on, which
15988 /// is why the compiler builds a pc-to-position table per function: without it a
15989 /// trace could only name the function, not the line inside it.
15990 ///
15991 /// A frame whose code has no positions prints just `(file)`, matching the
15992 /// reference's output for stripped bytecode.
15993 pub fn stack_trace(&self) -> String {
15994 self.stack_trace_skipping(0)
15995 }
15996
15997 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15998 fn stack_trace_skipping(&self, skip: usize) -> String {
15999 // One ordered list, innermost first, so `skip` counts the same thing whether the
16000 // frames it leaves out are native or bytecode. Indices rather than references: a
16001 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
16002 let depth = self.frames.len();
16003 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
16004 // A native entered while `at` bytecode frames were live was called *from* the
16005 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
16006 // entered at the current depth are therefore innermost of all.
16007 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
16008 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
16009 if *at == wanted {
16010 order.push((true, index));
16011 }
16012 }
16013 };
16014 push_natives(&mut order, depth);
16015 for index in (0..depth).rev() {
16016 order.push((false, index));
16017 push_natives(&mut order, index);
16018 }
16019 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
16020 // barrier. Natives entered at exactly the barrier depth are the eval entry point
16021 // itself (`evalScript (native)`), and the reference leaves those out too.
16022 if let Some(barrier) = self.trace_barriers.last().copied() {
16023 order.retain(|(is_native, index)| match is_native {
16024 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
16025 false => *index >= barrier,
16026 });
16027 }
16028
16029 let mut out = String::new();
16030 for (is_native, index) in order.into_iter().skip(skip) {
16031 match is_native {
16032 true => {
16033 out.push_str(" at ");
16034 let (native, _) = &self.native_frames[index];
16035 let name = native
16036 .own_property("name")
16037 .and_then(|property| property.value)
16038 .map(|value| value.to_js_string())
16039 .unwrap_or_default();
16040 out.push_str(&name);
16041 out.push_str(" (native)\n");
16042 }
16043 false => {
16044 let frame = &self.frames[index];
16045 let code = &frame.code.code;
16046 let file = code.filename.as_deref().unwrap_or("<input>");
16047 // The name comes from the function *object*, not from the compiled code:
16048 // an anonymous function expression is named by the property it is stored
16049 // in (`{valueOf: function(){}}`), which only the object knows.
16050 let bound_name = match &frame.callee {
16051 Value::Object(object) => {
16052 object
16053 .own_property("name")
16054 .and_then(|property| match property.value {
16055 Some(Value::String(text)) if !text.wtf8().is_empty() => {
16056 Some(text.to_string_lossy().into_owned())
16057 }
16058 _ => None,
16059 })
16060 }
16061 _ => None,
16062 };
16063 // No callee object means the body was entered by the host, so the
16064 // name has to come from the compiled code. Two cases differ:
16065 //
16066 // * an *unnamed* function of any kind — the reference reads the
16067 // `name` property, finds it empty, and prints `<anonymous>`;
16068 // * a *module* body, which has no `name` property at all: the
16069 // reference builds that function object with `js_closure2` and
16070 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
16071 // so a trace reaching it also prints `<anonymous>` — while a
16072 // *script* body prints `<eval>`, its `name`.
16073 let unnamed = code.name.is_empty() || code.module.is_some();
16074 out.push_str(" at ");
16075 match bound_name.as_deref() {
16076 Some(name) => out.push_str(name),
16077 None if unnamed => out.push_str("<anonymous>"),
16078 None => out.push_str(&code.name),
16079 }
16080 match code.position_at(frame.at as u32) {
16081 Some((line, column)) => {
16082 out.push_str(&format!(" ({file}:{line}:{column})\n"));
16083 }
16084 None => out.push_str(&format!(" ({file})\n")),
16085 }
16086 }
16087 }
16088 }
16089 out
16090 }
16091
16092 /// Give an anonymous function the name of the property it is stored in.
16093 ///
16094 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
16095 /// enumerable and not configurable, and a function that already has a real name
16096 /// keeps it.
16097 ///
16098 /// "Already named" means a *non-empty* name: every function object is created with
16099 /// a `name` of `""` so the property exists on all of them, and treating that empty
16100 /// string as a name left every anonymous function nameless — which is how a stack
16101 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
16102 /// `SetFunctionName`, for a name that came from source text.
16103 fn set_function_name(&mut self, function: &Value, name: &str) {
16104 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
16105 }
16106
16107 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
16108 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
16109 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
16110 let Value::Object(object) = function else {
16111 return;
16112 };
16113 // `SetFunctionName` applies to *functions* and classes only, and only when they are
16114 // anonymous. Without the callability guard, `{value: someObject}` renamed
16115 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
16116 // on the right-hand side of a property. That is how a `zipKeyed` result object
16117 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
16118 // has no `NamedEvaluation` at all.
16119 if !object.is_callable() {
16120 return;
16121 }
16122 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
16123 && !existing.wtf8().is_empty()
16124 {
16125 return;
16126 }
16127 let text = self.string_wtf8(name.clone());
16128 object.define("name", Property::name_or_length(text));
16129 }
16130
16131 // -- global declarations -----------------------------------------------
16132
16133 /// Declare a global binding, creating its reference cell.
16134 /// Declare a `var` or function global, whose home is the global object.
16135 ///
16136 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
16137 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
16138 /// such as `print`, or a redeclaration — is left alone.
16139 pub fn declare_var_global(&mut self, name: &str) {
16140 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
16141 // global object is exactly the leak `typeof my_var === "undefined"` after
16142 // `eval("var my_var=2")` rules out.
16143 if let Some(scope) = self.eval_scope.last_mut() {
16144 scope.entry(name.to_string()).or_insert(Value::Undefined);
16145 return;
16146 }
16147 // A sloppy direct eval declares into its *caller's* variable environment. Doing
16148 // this on the global object instead made `eval("var c = 1")` inside a parameter
16149 // list overwrite a global `c`, and made two calls to the same function share one
16150 // binding.
16151 if let Some(cell) = self.declare_eval_local(name) {
16152 cell.set(Value::Undefined);
16153 return;
16154 }
16155 // The caller's frame already binds the name, so the declaration is satisfied by
16156 // that binding and there is nothing new to create. Without this the fall-through
16157 // below declared a *global* as well, so `var q; eval("var q = 5")` left a
16158 // `globalThis.q` behind (`eval-code/direct/var-env-var-init-local-exstng`).
16159 if self.eval_caller.flatten().is_some_and(|caller| {
16160 self.eval_bindings
16161 .iter()
16162 .any(|binding| binding.name == name && binding.frame == caller)
16163 }) {
16164 return;
16165 }
16166 let global = self.realm.global.clone();
16167 if global.own_property(name).is_some() {
16168 return;
16169 }
16170 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
16171 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
16172 // whole point of that trick and what lets `Object.defineProperty` reshape it
16173 // afterwards. `eval_scope` is `Some` while an eval is running.
16174 let from_eval = self.eval_depth > 0 || !self.eval_scope.is_empty();
16175 global.define(
16176 name,
16177 Property {
16178 value: Some(Value::Undefined),
16179 writable: true,
16180 enumerable: true,
16181 configurable: from_eval,
16182 ..Property::default()
16183 },
16184 );
16185 }
16186
16187 /// Declare a *lexical* global binding, which starts in its dead zone.
16188 ///
16189 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
16190 /// global object and is created when its initialiser runs.
16191 pub fn declare_global(&mut self, name: &str, is_const: bool) {
16192 if is_const {
16193 self.realm.lexical_consts.insert(name.to_string());
16194 }
16195 if !self.realm.globals.contains_key(name) {
16196 // `Uninitialized` rather than `Undefined`: the binding exists but is not
16197 // readable until its initialiser runs, and that is what `let x` before
16198 // `x = 1` has to observe.
16199 let cell = self.new_cell(Value::Uninitialized);
16200 self.realm.globals.insert(name.to_string(), cell);
16201 self.realm.declared.push(name.to_string());
16202 }
16203 }
16204}
16205
16206/// The bytecode and environment of a function object, if it is a bytecode function.
16207///
16208/// Extracted before a call so no borrow of the object is held across it.
16209fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
16210 function.with(|data| match &data.kind {
16211 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
16212 _ => None,
16213 })
16214}
16215
16216/// A native call target, extracted before the call so no borrow is held.
16217enum NativeCall {
16218 Native(NativeFn),
16219 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
16220 /// not hold that object's `RefCell` borrow.
16221 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
16222 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
16223 Bound {
16224 target: Value,
16225 this: Value,
16226 leading: Vec<Value>,
16227 },
16228 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
16229 Revoker(crate::object::ProxyRef),
16230 /// A promise's `resolve`.
16231 PromiseResolve(Gc<JsObject>),
16232 /// A promise's `reject`.
16233 PromiseReject(Gc<JsObject>),
16234 /// The executor `NewPromiseCapability(C)` hands a user constructor.
16235 CapabilityExecutor {
16236 state: Gc<JsObject>,
16237 },
16238 /// One leg of a `then` that settles through a user capability.
16239 ThenShim {
16240 handler: Option<Value>,
16241 resolve: Value,
16242 reject: Value,
16243 fulfilled: bool,
16244 },
16245 /// One continuation of an `await`.
16246 AwaitResume {
16247 coroutine: Gc<JsObject>,
16248 promise: Gc<JsObject>,
16249 kind: ResumeKind,
16250 },
16251 /// One element of a `Promise` combinator settling.
16252 CombinatorSettle {
16253 state: Gc<JsObject>,
16254 index: usize,
16255 fulfilled: bool,
16256 },
16257 /// One of `Promise.prototype.finally`'s two shims.
16258 FinallyShim {
16259 callback: Option<Value>,
16260 fulfilled: bool,
16261 constructor: Value,
16262 },
16263 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
16264 ReturnValue(Value),
16265 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
16266 ThrowValue(Value),
16267 /// Settle a promise with a fixed outcome.
16268 SettlePromise {
16269 promise: Gc<JsObject>,
16270 value: Value,
16271 rejected: bool,
16272 },
16273 /// Continue an async generator after its `await` settled.
16274 GeneratorResume {
16275 generator: Gc<JsObject>,
16276 promise: Gc<JsObject>,
16277 kind: ResumeKind,
16278 },
16279 /// Read a module namespace's binding out of its cell.
16280 ModuleBinding(Gc<Cell>),
16281 /// Finish a completed async generator's `return(v)` once `v` has settled.
16282 CompletedReturn {
16283 generator: Gc<JsObject>,
16284 promise: Gc<JsObject>,
16285 rejected: bool,
16286 },
16287 /// Answer a pending async-generator method with `{value, done}`.
16288 YieldResult {
16289 generator: Gc<JsObject>,
16290 promise: Gc<JsObject>,
16291 done: bool,
16292 },
16293 /// One step of `AsyncDisposableStack.disposeAsync`.
16294 DisposeStep {
16295 remaining: Gc<JsObject>,
16296 promise: Gc<JsObject>,
16297 error: Value,
16298 rejected: bool,
16299 awaited: bool,
16300 needs_await: bool,
16301 },
16302}
16303
16304/// What a store does when the object refuses the write.
16305#[derive(Clone, Copy, PartialEq, Eq)]
16306pub enum DeleteFailure {
16307 /// Raise a `TypeError`, which is what strict mode and every built-in does.
16308 Throw,
16309 /// Ignore the write, which is what a sloppy-mode assignment does.
16310 Ignore,
16311}
16312
16313/// Whether `object` is a `Date` instance, by the class tag it carries.
16314///
16315/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
16316/// builtins module depending on the interpreter's conversion order.
16317fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
16318 interp
16319 .internal_get(object, "_class")
16320 .is_some_and(|value| value.to_js_string() == "Date")
16321}
16322
16323/// Which type `ToPrimitive` prefers when it converts an object.
16324#[derive(Clone, Copy, PartialEq, Eq)]
16325pub enum Hint {
16326 /// The default hint, which behaves like [`Hint::Number`].
16327 Default,
16328 /// `Number(obj)` and the arithmetic operators.
16329 Number,
16330 /// `String(obj)` and `ToPropertyKey`.
16331 String,
16332}
16333
16334/// Which table a binding slot indexes, for the messages that name it.
16335#[derive(Clone, Copy)]
16336enum VarSlot {
16337 Loc,
16338 Closure,
16339}
16340
16341/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
16342fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
16343 Ok(this)
16344}
16345
16346/// An internal iterator: the sequence plus a cursor.
16347pub(crate) struct Iterator {
16348 pub(crate) object: Value,
16349 pub(crate) next: Value,
16350}
16351
16352/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
16353/// and plain `a` for a method.
16354///
16355/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
16356/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
16357/// reads `at get a (file:1:2)`.
16358/// The same prefixing, for a name that may hold an unpaired surrogate.
16359fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
16360 let prefix = match flags & 3 {
16361 1 => "get ",
16362 2 => "set ",
16363 _ => return key.clone(),
16364 };
16365 let mut units: Vec<u16> = prefix.encode_utf16().collect();
16366 units.extend_from_slice(&key.to_units());
16367 crate::value::Wtf8::from_units(&units)
16368}
16369
16370/// `SetFunctionName`'s name for a symbol property key: `[description]`, or `""`.
16371///
16372/// §7.3.24 step 1. A symbol without a description names the function the empty string, not
16373/// `Symbol()` — the two are different and test262 checks both.
16374fn symbol_key_name(key: &PropertyKey) -> crate::value::Wtf8 {
16375 let PropertyKey::Symbol(symbol) = key else {
16376 return crate::value::Wtf8::default();
16377 };
16378 match symbol.description() {
16379 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
16380 None => crate::value::Wtf8::default(),
16381 }
16382}
16383
16384/// Define a method or accessor property, per the `define_method` flag byte.
16385///
16386/// The low two bits pick value/getter/setter and bit 2 marks the property
16387/// enumerable.
16388///
16389/// A getter and a setter arrive as two separate `define_method` instructions, and the
16390/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
16391/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
16392/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
16393/// `JS_DefineProperty`, which leaves the other half alone.
16394fn define_function_property(
16395 object: &Gc<JsObject>,
16396 key: &PropertyKey,
16397 function: Value,
16398 flags: u32,
16399) -> bool {
16400 let enumerable = flags & 4 != 0;
16401 let kind = flags & 3;
16402 let existing = object.own_property_key(key);
16403 let property = match kind {
16404 1 => Property {
16405 getter: Some(function),
16406 // The setter half, if this literal already defined one.
16407 setter: existing
16408 .filter(Property::is_accessor)
16409 .and_then(|p| p.setter),
16410 enumerable,
16411 configurable: true,
16412 ..Property::default()
16413 },
16414 2 => Property {
16415 getter: existing
16416 .filter(Property::is_accessor)
16417 .and_then(|p| p.getter),
16418 setter: Some(function),
16419 enumerable,
16420 configurable: true,
16421 ..Property::default()
16422 },
16423 _ => Property {
16424 value: Some(function),
16425 writable: true,
16426 enumerable,
16427 configurable: true,
16428 ..Property::default()
16429 },
16430 };
16431 object.create_data_property_key(key, property)
16432}
16433
16434// ---------------------------------------------------------------------------
16435// Operand decoding
16436// ---------------------------------------------------------------------------
16437
16438/// How `print` renders a value: the reference's `JS_PrintValue`.
16439///
16440/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
16441/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
16442/// The format is reproduced closely because the test suite compares output text:
16443///
16444/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
16445/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
16446/// * a cycle prints `[circular N]` with `N` the stack index of the object;
16447/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
16448/// end print as `<N empty item(s)>`;
16449/// * a string is quoted inside a container but raw at the top level, which is why
16450/// `print("x")` and `print(["x"])` differ.
16451pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
16452 // A string argument is printed raw: `js_print` converts it with `ToString`
16453 // instead of dumping it, and the quoting only appears inside a container.
16454 if let Value::String(text) = value {
16455 return text.to_string_lossy().into_owned();
16456 }
16457 let mut printer = Printer {
16458 interp,
16459 out: String::new(),
16460 stack: Vec::new(),
16461 };
16462 printer.value(value, 0);
16463 printer.out
16464}
16465
16466/// The internal class name an object carries, when it has one.
16467fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
16468 interp
16469 .internal_get(object, "_class")
16470 .map(|value| value.to_js_string())
16471}
16472
16473/// A string property, looked up the way `GetProperty` does: own first, then the
16474/// prototype chain. Needed because the print formatter holds the interpreter
16475/// immutably and so cannot run getters.
16476fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
16477 let mut current = Some(object.clone());
16478 // Bounded, because a prototype cycle would otherwise loop forever.
16479 for _ in 0..100 {
16480 let node = current?;
16481 if let Some(property) = node.own_property(name)
16482 && let Some(value) = property.value
16483 {
16484 return Some(value.to_js_string());
16485 }
16486 current = node.with(|data| data.proto.clone());
16487 }
16488 None
16489}
16490
16491/// The `JS_PrintValue` state: output, and the objects currently being printed.
16492struct Printer<'a, 'rt> {
16493 /// Kept for the class-name lookups that typed arrays and `Date` will need.
16494 #[allow(dead_code)]
16495 interp: &'a Interp<'rt>,
16496 out: String,
16497 stack: Vec<Gc<JsObject>>,
16498}
16499
16500impl Printer<'_, '_> {
16501 /// Depth past which a container is summarised by its class name.
16502 const MAX_DEPTH: usize = 2;
16503
16504 fn value(&mut self, value: &Value, level: usize) {
16505 match value {
16506 Value::Undefined
16507 | Value::Uninitialized
16508 | Value::Hole
16509 | Value::CatchOffset(_)
16510 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
16511 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
16512 // The printer writes a bigint the way the language spells one, so a dump is
16513 // unambiguous about which kind of number it is showing.
16514 Value::BigInt(big) => {
16515 self.out.push_str(&big.to_decimal_string());
16516 self.out.push('n');
16517 }
16518 Value::Null => self.out.push_str("null"),
16519 Value::Bool(true) => self.out.push_str("true"),
16520 Value::Bool(false) => self.out.push_str("false"),
16521 Value::Int(number) => self.out.push_str(&number.to_string()),
16522 Value::Float(number) => {
16523 self.out
16524 .push_str(&crate::value::number_to_string_for_print(*number));
16525 }
16526 Value::String(text) => self.print_string(&text.to_string_lossy()),
16527 Value::Object(object) => self.object(object, level),
16528 }
16529 }
16530
16531 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
16532 // A cycle is reported rather than followed; the index is where the object
16533 // already sits in the print stack, which is what the reference shows.
16534 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
16535 self.out.push_str(&format!("[circular {index}]"));
16536 return;
16537 }
16538 if object.is_callable() {
16539 let name = object
16540 .own_property("name")
16541 .and_then(|property| property.value)
16542 .map(|value| value.to_js_string())
16543 .unwrap_or_default();
16544 if name.is_empty() {
16545 self.out.push_str("[Function (anonymous)]");
16546 } else {
16547 self.out.push_str(&format!("[Function {name}]"));
16548 }
16549 return;
16550 }
16551 if level >= Self::MAX_DEPTH {
16552 let class = if object.is_array() { "Array" } else { "Object" };
16553 self.out.push_str(&format!("[{class}]"));
16554 return;
16555 }
16556 // A `RegExp` prints as its own literal, `js_print_regexp`'s `/%s/%s`. Without this
16557 // it fell through to the plain-object form and `print(/x/)` answered `{ }` — no
16558 // properties, so nothing to show, and the value's identity lost.
16559 if let Some(data) = object.regexp() {
16560 let source = crate::builtins::regexp::escaped_source(&data.source);
16561 self.out.push('/');
16562 self.out.push_str(&source.to_string_lossy());
16563 self.out.push('/');
16564 self.out.push_str(&data.flags);
16565 return;
16566 }
16567 // `Date` and `Error` print as themselves rather than as bags of properties:
16568 // the ISO string, and `Name: message` followed by the trace.
16569 if let Some(class) = class_of(self.interp, object) {
16570 if class == "Date" {
16571 self.date(object);
16572 return;
16573 }
16574 if class == "Error" {
16575 self.error(object);
16576 return;
16577 }
16578 }
16579 self.stack.push(object.clone());
16580 if object.is_array() {
16581 self.array(object, level);
16582 } else {
16583 self.plain_object(object, level);
16584 }
16585 self.stack.pop();
16586 }
16587
16588 /// A Date prints as its ISO string; an invalid one falls through to the plain
16589 /// object form, the way the reference falls back when `toISOString` throws.
16590 fn date(&mut self, object: &Gc<JsObject>) {
16591 let value = self
16592 .interp
16593 .internal_get(object, "_date_value")
16594 .map(|value| value.to_number());
16595 match value.and_then(crate::builtins::date::iso_string) {
16596 Some(text) => self.out.push_str(&text),
16597 None => self.plain_object(object, 0),
16598 }
16599 }
16600
16601 /// `Name: message`, then the trace with its trailing newline removed.
16602 fn error(&mut self, object: &Gc<JsObject>) {
16603 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
16604 self.out.push_str(&name);
16605 if let Some(message) = inherited(object, "message")
16606 && !message.is_empty()
16607 {
16608 self.out.push_str(": ");
16609 self.out.push_str(&message);
16610 }
16611 if let Some(stack) = inherited(object, "stack") {
16612 self.out.push('\n');
16613 self.out.push_str(stack.trim_end_matches('\n'));
16614 }
16615 }
16616
16617 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
16618 let elements = object.array_elements().unwrap_or_default();
16619 self.out.push_str("[ ");
16620 // An interior hole means the array is "sparse": the reference prints those
16621 // as `index: value` pairs and says nothing about the holes themselves, while
16622 // a hole run at the end becomes a single `<N empty items>` note.
16623 let last_present = elements
16624 .iter()
16625 .rposition(|value| !matches!(value, Value::Hole));
16626 let has_interior_hole = match last_present {
16627 Some(last) => elements[..last]
16628 .iter()
16629 .any(|value| matches!(value, Value::Hole)),
16630 None => false,
16631 };
16632 let mut first = true;
16633 if has_interior_hole {
16634 let mut index = 0;
16635 while index < elements.len() {
16636 let value = &elements[index];
16637 if matches!(value, Value::Hole) {
16638 index += 1;
16639 continue;
16640 }
16641 if !first {
16642 self.out.push_str(", ");
16643 }
16644 first = false;
16645 self.out.push_str(&format!("{index}: "));
16646 self.value(value, level + 1);
16647 index += 1;
16648 }
16649 } else {
16650 for (index, value) in elements.iter().enumerate() {
16651 if matches!(value, Value::Hole) {
16652 continue;
16653 }
16654 if !first {
16655 self.out.push_str(", ");
16656 }
16657 first = false;
16658 let _ = index;
16659 self.value(value, level + 1);
16660 }
16661 if let Some(last) = last_present {
16662 let trailing = elements.len() - last - 1;
16663 if trailing > 0 {
16664 if !first {
16665 self.out.push_str(", ");
16666 }
16667 self.out.push_str(&format!(
16668 "<{trailing} empty item{}>",
16669 if trailing > 1 { "s" } else { "" }
16670 ));
16671 }
16672 } else if !elements.is_empty() {
16673 let count = elements.len();
16674 self.out.push_str(&format!(
16675 "<{count} empty item{}>",
16676 if count > 1 { "s" } else { "" }
16677 ));
16678 }
16679 }
16680 self.out.push_str(" ]");
16681 }
16682
16683 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
16684 self.out.push_str("{ ");
16685 let mut first = true;
16686 for key in object.own_keys() {
16687 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
16688 continue;
16689 };
16690 if !property.enumerable {
16691 continue;
16692 }
16693 if !first {
16694 self.out.push_str(", ");
16695 }
16696 first = false;
16697 self.out
16698 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
16699 &key.to_string_lossy(),
16700 )));
16701 self.out.push_str(": ");
16702 // An accessor has no value to dump; the reference names the half that
16703 // exists instead of calling it.
16704 if property.is_accessor() {
16705 let text = match (property.getter.is_some(), property.setter.is_some()) {
16706 (true, true) => "[Getter/Setter]",
16707 (false, true) => "[Setter]",
16708 _ => "[Getter]",
16709 };
16710 self.out.push_str(text);
16711 } else {
16712 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
16713 }
16714 }
16715 self.out.push_str(" }");
16716 }
16717
16718 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
16719 fn print_string(&mut self, text: &str) {
16720 self.out.push('"');
16721 for character in text.chars() {
16722 match character {
16723 '"' => self.out.push_str("\\\""),
16724 '\\' => self.out.push_str("\\\\"),
16725 '\n' => self.out.push_str("\\n"),
16726 '\r' => self.out.push_str("\\r"),
16727 '\t' => self.out.push_str("\\t"),
16728 c if (c as u32) < 0x20 => {
16729 self.out.push_str(&format!("\\u{:04x}", c as u32));
16730 }
16731 c => self.out.push(c),
16732 }
16733 }
16734 self.out.push('"');
16735 }
16736}
16737
16738/// How `print` renders a value.
16739///
16740/// `ToString`, except that negative zero keeps its sign — the reference's host
16741/// printer does that while `String(-0)` is `"0"`.
16742pub fn display(value: &Value) -> String {
16743 match value {
16744 Value::Float(number) => crate::value::number_to_string_for_print(*number),
16745 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
16746 "undefined".to_string()
16747 }
16748 other => other.to_js_string(),
16749 }
16750}
16751
16752// ---------------------------------------------------------------------------
16753// Numeric operators
16754// ---------------------------------------------------------------------------
16755
16756/// `a + b` keeping the `Int` representation when it fits.
16757fn add_numbers(left: Value, right: Value) -> Value {
16758 match (&left, &right) {
16759 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
16760 Some(sum) => Value::Int(sum),
16761 None => Value::Float(*a as f64 + *b as f64),
16762 },
16763 _ => Value::Float(left.to_number() + right.to_number()),
16764 }
16765}
16766
16767/// The arithmetic operators other than `+`, which needs string concatenation.
16768fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16769 use Opcode::*;
16770 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
16771 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
16772 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
16773 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
16774 return Ok(match op {
16775 And => Value::Int(x & y),
16776 Or => Value::Int(x | y),
16777 Xor => Value::Int(x ^ y),
16778 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
16779 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
16780 Shr => match (*x as u32) >> ((*y as u32) & 31) {
16781 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
16782 shifted => Value::Float(shifted as f64),
16783 },
16784 Sub => match x.checked_sub(*y) {
16785 Some(value) => Value::Int(value),
16786 None => Value::Float(*x as f64 - *y as f64),
16787 },
16788 _ => return arithmetic_slow(op, left, right),
16789 });
16790 }
16791 arithmetic_slow(op, left, right)
16792}
16793
16794/// [`arithmetic`] for everything the integer fast path above does not take.
16795fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16796 use Opcode::*;
16797 let (a, b) = (left.to_number(), right.to_number());
16798 Ok(match op {
16799 Sub => match (&left, &right) {
16800 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
16801 Some(value) => Value::Int(value),
16802 None => Value::Float(a - b),
16803 },
16804 _ => Value::Float(a - b),
16805 },
16806 Mul => Value::Float(a * b),
16807 Div => Value::Float(a / b),
16808 Mod => Value::Float(js_mod(a, b)),
16809 Pow => Value::Float(a.powf(b)),
16810 And => Value::Int(left.to_int32() & right.to_int32()),
16811 Or => Value::Int(left.to_int32() | right.to_int32()),
16812 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
16813 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
16814 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
16815 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
16816 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
16817 // fits the small-integer representation stays an `Int`; the rest become a
16818 // float, which is how the reference keeps `n >>> 0` non-negative.
16819 Shr => {
16820 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
16821 match i32::try_from(shifted) {
16822 Ok(value) => Value::Int(value),
16823 Err(_) => Value::Float(shifted as f64),
16824 }
16825 }
16826 _ => Value::Float(a),
16827 })
16828}
16829
16830/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16831///
16832/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16833/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16834/// slow path where the rules live.
16835fn is_number(value: &Value) -> bool {
16836 matches!(value, Value::Int(_) | Value::Float(_))
16837}
16838
16839/// The `Value::Bool` a comparison operator answers for `ordering`.
16840///
16841/// `None` is the unordered case — a `NaN` on either side — and every operator answers
16842/// false for it, including `<=` and `>=`.
16843fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
16844 use Opcode::*;
16845 let answer = match (op, ordering) {
16846 (_, None) => false,
16847 (Lt, Some(ordering)) => ordering.is_lt(),
16848 (Lte, Some(ordering)) => ordering.is_le(),
16849 (Gt, Some(ordering)) => ordering.is_gt(),
16850 (Gte, Some(ordering)) => ordering.is_ge(),
16851 _ => false,
16852 };
16853 Value::Bool(answer)
16854}
16855
16856/// `%`, which follows the sign of the dividend rather than Rust's.
16857fn js_mod(left: f64, right: f64) -> f64 {
16858 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
16859 return f64::NAN;
16860 }
16861 if right.is_infinite() {
16862 return left;
16863 }
16864 let remainder = left % right;
16865 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
16866 // the spec makes the sign match the dividend.
16867 if remainder == 0.0 {
16868 0.0f64.copysign(left)
16869 } else {
16870 remainder
16871 }
16872}
16873
16874fn negate(value: Value) -> Value {
16875 match value {
16876 Value::Int(0) => Value::Float(-0.0),
16877 Value::Int(i) => Value::Int(-i),
16878 other => Value::Float(-other.to_number()),
16879 }
16880}
16881
16882fn increment(value: Value) -> Value {
16883 match value {
16884 Value::Int(i) => match i.checked_add(1) {
16885 Some(next) => Value::Int(next),
16886 None => Value::Float(i as f64 + 1.0),
16887 },
16888 other => Value::Float(other.to_number() + 1.0),
16889 }
16890}
16891
16892fn decrement(value: Value) -> Value {
16893 match value {
16894 Value::Int(i) => match i.checked_sub(1) {
16895 Some(next) => Value::Int(next),
16896 None => Value::Float(i as f64 - 1.0),
16897 },
16898 other => Value::Float(other.to_number() - 1.0),
16899 }
16900}
16901
16902/// Compare a `BigInt` with an `f64` on their mathematical values.
16903///
16904/// Neither side is rounded to the other's precision: the number is split into its integer
16905/// part (compared as an exact bigint) and its fraction, which is what decides the answer
16906/// when the integer parts are equal. An infinite value is larger than every bigint.
16907fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
16908 use std::cmp::Ordering;
16909 if number.is_nan() {
16910 return None;
16911 }
16912 if number.is_infinite() {
16913 return Some(if number > 0.0 {
16914 Ordering::Less
16915 } else {
16916 Ordering::Greater
16917 });
16918 }
16919 // The comparison is **exact**, because rounding it is observable: an f64 is
16920 // `m * 2^e` with `m` a 53-bit integer, so scaling the bigint by the same power of two
16921 // turns this into an integer comparison at any width. Converting the *bigint* to f64
16922 // instead — which is what this used to do once the number was wider than `i128` —
16923 // rounds it to the nearest double, and `0xfffffffffffff7ff…n < Number.MAX_VALUE` is
16924 // decided by a difference of one bit at 2^971, which rounding erases
16925 // (`less-than/bigint-and-number-extremes`).
16926 // Both branches answer `big.cmp(number)`; which side gets scaled depends on the sign of
16927 // the exponent, because scaling the smaller one keeps the shift bounded by the f64's own
16928 // range (at most 1074 bits) instead of by the bigint's width.
16929 let (mantissa, exponent) = decompose_f64(number);
16930 let product = crate::bigint::BigInt::from_i64(mantissa);
16931 Some(if exponent >= 0 {
16932 // `number = mantissa * 2^exponent`, and that product is the exact f64 value.
16933 big.cmp(&product.shl(exponent as u64))
16934 } else {
16935 // `number = mantissa / 2^-exponent`; scale the *bigint* up instead so both sides stay
16936 // integers.
16937 big.shl((-exponent) as u64).cmp(&product)
16938 })
16939}
16940
16941/// `value` as `(mantissa, exponent)` with `value == mantissa * 2^exponent` exactly.
16942///
16943/// `mantissa` carries the sign and is the f64's significand with its implicit bit made
16944/// explicit, so `|mantissa| <= 2^53` and the `i64` conversion is exact. `value` must be
16945/// finite.
16946fn decompose_f64(value: f64) -> (i64, i32) {
16947 let bits = value.abs().to_bits();
16948 let raw_exponent = ((bits >> 52) & 0x7ff) as i32;
16949 let fraction = bits & ((1u64 << 52) - 1);
16950 // A subnormal has no implicit bit and an exponent of `1 - 1023`; a normal one carries a
16951 // leading 1 at bit 52, and the `-1075` folds in the bias and the 52 fraction bits.
16952 let (significand, exponent) = if raw_exponent == 0 {
16953 (fraction, -1074)
16954 } else {
16955 (fraction | (1u64 << 52), raw_exponent - 1075)
16956 };
16957 let significand = significand as i64;
16958 let mantissa = if value < 0.0 {
16959 -significand
16960 } else {
16961 significand
16962 };
16963 (mantissa, exponent)
16964}
16965
16966/// The UTF-16 code unit ordering of two strings, which is what `<` compares.
16967///
16968/// `JsString` caches its code units on first access, so the first `code_unit_at` builds the
16969/// cache and the rest are O(1) — no allocation here, and no decoding in the loop.
16970fn compare_code_units(
16971 a: &crate::value::JsString,
16972 b: &crate::value::JsString,
16973) -> std::cmp::Ordering {
16974 let (left, right) = (a.utf16_len(), b.utf16_len());
16975 for index in 0..left.min(right) {
16976 let (x, y) = (
16977 a.code_unit_at(index).unwrap_or(0),
16978 b.code_unit_at(index).unwrap_or(0),
16979 );
16980 if x != y {
16981 return x.cmp(&y);
16982 }
16983 }
16984 // A proper prefix sorts first, which is what the length comparison gives.
16985 left.cmp(&right)
16986}
16987
16988/// `StringToBigInt(argument)` (§7.1.14): the string read as an **integer** literal.
16989///
16990/// `undefined` — `None` here — for anything that is only a *number* literal: `"0."`,
16991/// `".0"`, `"0e0"` and `"Infinity"` all fail, which is why `1n > "0."` is `false` rather
16992/// than `true` (`greater-than/bigint-and-incomparable-string`). Leading zeros are outside
16993/// the grammar too (`"007"`), and so is whitespace between the sign and the digits.
16994///
16995/// The empty string *is* `0n`: §7.1.14 turns a whitespace-only literal into `0`.
16996fn string_to_bigint(text: &str) -> Option<crate::bigint::BigInt> {
16997 let trimmed = text.trim();
16998 let body = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
16999 let signed = body.len() != trimmed.len();
17000 // A radix prefix admits no sign, and the digits must follow immediately.
17001 let (radix, digits) = if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
17002 (16, rest)
17003 } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
17004 (8, rest)
17005 } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
17006 (2, rest)
17007 } else {
17008 (10, body)
17009 };
17010 if signed && radix != 10 && signed {
17011 // `StrNonDecimalIntegerLiteral` has no sign.
17012 return None;
17013 }
17014 if radix == 10 && digits.len() > 1 && digits.starts_with('0') {
17015 // `StrUnsignedDecimalLiteral : 0 | NonZeroDigit DecimalDigits?`.
17016 return None;
17017 }
17018 crate::bigint::BigInt::from_string(trimmed)
17019}
17020
17021/// `CanonicalNumericIndexString(argument)` (§7.1.21).
17022///
17023/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
17024/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
17025/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
17026/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
17027/// rather than treating it as `0`.
17028fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
17029 let PropertyKey::String(text) = key else {
17030 // A symbol is never an index.
17031 return None;
17032 };
17033 let text = text.to_string_lossy();
17034 if text == "-0" {
17035 return Some(-0.0);
17036 }
17037 let number: f64 = text.parse().ok()?;
17038 // The round-trip test *is* the definition: only the canonical spelling qualifies.
17039 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
17040 // `"0.10"` does not.
17041 let rendered = Value::Float(number).to_js_string();
17042 (rendered == text).then_some(number)
17043}
17044
17045/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
17046///
17047/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
17048/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
17049/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
17050/// numeric and invalid, which is why they stop the prototype chain instead of falling
17051/// through it.
17052///
17053/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
17054/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
17055/// `in`, `delete` and `defineProperty` separately to make sure it does not.
17056fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
17057 numeric.is_finite()
17058 && numeric.fract() == 0.0
17059 && !(numeric == 0.0 && numeric.is_sign_negative())
17060 && numeric >= 0.0
17061 && object
17062 .typed_array_length()
17063 .is_some_and(|length| (numeric as usize) < length)
17064}
17065
17066/// `ArrayCreate`'s length bound, `2**32 - 1`.
17067///
17068/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
17069/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
17070/// through — can enforce it without depending on a builtin module.
17071const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;