quickjs/interp.rs
1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25 Callable, ClassDef, ClassId, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars,
26 NativeFn, ObjectKind, Opaque, Property, PropertyKey, array_index, has_own, lookup_key,
27 lookup_key_above, same_proto,
28};
29use crate::value::{Cell, Value, number_to_string};
30
31/// Why execution stopped.
32#[derive(Debug, Clone)]
33pub enum Signal {
34 /// A JavaScript exception carrying the thrown value.
35 Throw(Value),
36 /// The runtime ran out of memory.
37 OutOfMemory,
38}
39
40/// What an execution step produced.
41pub type JsResult<T> = std::result::Result<T, Signal>;
42
43/// The result of one instruction.
44enum Step {
45 /// Keep executing the current frame.
46 Continue,
47 /// The current frame returned this value.
48 Return(Value),
49 /// The frame parked at a suspension point, with the yielded value on its stack.
50 ///
51 /// Only a generator or an async function can produce this, and only its own frame —
52 /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
53 /// detached and handed to the generator object, which is what lets it resume later
54 /// with its locals and operand stack intact.
55 Suspend(SuspendKind),
56}
57
58/// Why a frame parked, which decides how the resumption is delivered.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum SuspendKind {
61 /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
62 /// without passing a value, because there is no `yield` expression to receive one.
63 Initial,
64 /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
65 Yield,
66 /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
67 /// `{value, done}` object from the inner iterator and is handed straight back.
68 YieldStar,
69 /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
70 /// what was yielded is the plain value and still has to be awaited and wrapped —
71 /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
72 /// made it pass a bare value through as if it were an iterator result, so
73 /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
74 AsyncYieldStar,
75 /// `await expr`: the value is a promise the async machinery has to settle first.
76 Await,
77}
78
79/// Everything one JavaScript realm owns.
80///
81/// A realm is the set of objects a script can reach without naming them: the global
82/// object, the prototype chain roots, and the global binding cells.
83pub struct Realm {
84 /// The global object.
85 pub global: Gc<JsObject>,
86 /// `Object.prototype`.
87 pub object_proto: Gc<JsObject>,
88 /// `Function.prototype`, which is itself callable.
89 pub function_proto: Gc<JsObject>,
90 /// `Array.prototype`.
91 pub array_proto: Gc<JsObject>,
92 /// Reference cells for globals declared by the script.
93 ///
94 /// A declared global is read with `get_var` (by name) but written with
95 /// `put_var_ref` (through the cell), so the cell is what makes a function
96 /// declaration and its uses agree on one binding.
97 pub globals: BTreeMap<String, Gc<Cell>>,
98 /// Names of the globals that came from a *declaration*, which are
99 /// non-configurable properties of the global object.
100 pub declared: Vec<String>,
101 /// Names among the lexical globals that are `const`.
102 ///
103 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
104 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
105 /// path does not carry, so a store through it would look like a plain `let`. The
106 /// realm records it once, at declaration, and answers for every reader.
107 pub lexical_consts: BTreeSet<String>,
108 /// The error constructors by class name, so a runtime error can throw a real
109 /// `TypeError` instance rather than a look-alike object.
110 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
111 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
112 pub string_proto: Option<Gc<JsObject>>,
113 /// `Number.prototype`.
114 pub number_proto: Option<Gc<JsObject>>,
115 /// `Boolean.prototype`.
116 pub boolean_proto: Option<Gc<JsObject>>,
117 /// `BigInt.prototype`.
118 pub bigint_proto: Option<Gc<JsObject>>,
119 /// `Error.prototype`, the prototype of every error instance.
120 pub error_proto: Gc<JsObject>,
121 /// `Date.prototype`, so the constructor can build an instance in the
122 /// function-call form (`Date()` returns a string) without going through `new`.
123 pub date_proto: Gc<JsObject>,
124 /// `%GeneratorPrototype%`, the prototype of every generator object.
125 pub generator_proto: Gc<JsObject>,
126 /// `Promise.prototype`, the prototype of every promise.
127 pub promise_proto: Option<Gc<JsObject>>,
128 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
129 pub async_generator_proto: Option<Gc<JsObject>>,
130 /// `Symbol.prototype`.
131 pub symbol_proto: Option<Gc<JsObject>>,
132 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
133 /// `_date_value`.
134 ///
135 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
136 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
137 /// language does not have and `new Error()` listed `_class` beside `message` and
138 /// `stack` — and a caller that copies every own property (which
139 /// `Object.create(null, props)` effectively does) tried to write an internal name and
140 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
141 /// and `JSON.stringify`, while remaining an ordinary traced property.
142 ///
143 /// `RefCell` because interning is memoisation rather than observable state: filling the
144 /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
145 /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
146 /// built while reporting a failure must not require an exclusive borrow.
147 pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
148
149 /// The `Symbol.for` registry: `key -> symbol`.
150 ///
151 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
152 /// symbol every time within one script while a fresh realm starts empty.
153 pub symbol_registry: BTreeMap<String, Value>,
154 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
155 pub regexp_proto: Option<Gc<JsObject>>,
156 /// The `RegExp` constructor.
157 pub regexp_ctor: Option<Gc<JsObject>>,
158 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
159 ///
160 /// The prototype rather than the constructor on purpose: a script that replaces
161 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
162 /// error wrapping, which the `using` test suite checks explicitly.
163 pub suppressed_error_proto: Option<Gc<JsObject>>,
164 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
165 pub disposable_stack_proto: Option<Gc<JsObject>>,
166 /// `Map.prototype`.
167 pub map_proto: Option<Gc<JsObject>>,
168 /// `Set.prototype`.
169 pub set_proto: Option<Gc<JsObject>>,
170 /// Every live `FinalizationRegistry`, held weakly.
171 ///
172 /// The cleanup callback has to run from a *safe point* — a place where script is not
173 /// already executing and no engine borrow is held — and the collector cannot enumerate
174 /// heap objects by type. Registering each registry here gives the drain a list to walk.
175 ///
176 /// The handles are weak on purpose: a registry the script dropped must be collectable,
177 /// and it must not be resurrected merely because the drain knew about it. Entries whose
178 /// target has expired are swept out as the drain walks, so the vector does not grow
179 /// without bound in a program that creates many short-lived registries.
180 pub finalization_registries: Vec<WeakGc<JsObject>>,
181 /// `ArrayBuffer.prototype`.
182 pub array_buffer_proto: Option<Gc<JsObject>>,
183 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
184 pub typed_array_proto: Option<Gc<JsObject>>,
185 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
186 ///
187 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
188 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
189 /// `"Object"` and `r instanceof Int32Array` is false.
190 pub typed_array_protos: Vec<Gc<JsObject>>,
191 /// `DataView.prototype`.
192 pub data_view_proto: Option<Gc<JsObject>>,
193 /// The `AsyncDisposableStack` prototype.
194 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
195 /// `Iterator.prototype`.
196 pub iterator_proto: Option<Gc<JsObject>>,
197 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
198 ///
199 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
200 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
201 /// `[object Iterator Helper]`).
202 pub iterator_helper_proto: Option<Gc<JsObject>>,
203 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
204 /// that was not already an `Iterator`.
205 ///
206 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
207 /// untouched and does *not* override `@@toStringTag`, so
208 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
209 pub iterator_wrap_proto: Option<Gc<JsObject>>,
210 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
211 pub generator_function_proto: Option<Gc<JsObject>>,
212 /// `%AsyncFunction.prototype%`.
213 pub async_function_proto: Option<Gc<JsObject>>,
214 /// `%AsyncGeneratorFunction.prototype%`.
215 pub async_generator_function_proto: Option<Gc<JsObject>>,
216 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
217 ///
218 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
219 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
220 /// prototype per iterator made every array iterator's prototype distinct.
221 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
222 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
223 ///
224 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
225 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
226 /// both faster and impossible to break from a script.
227 well_known_symbols: WellKnownSymbols,
228 /// The classes the host registered, and the prototype each one hands its instances.
229 pub host_classes: HostClasses,
230}
231
232/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
233///
234/// One per realm, because a class id is only meaningful within the runtime that handed it
235/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
236/// a host class cannot collide.
237pub struct HostClasses {
238 /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
239 /// `JS_GetOpaque(val, 0)` has to match nothing.
240 next_id: u32,
241 /// What each registered class does.
242 defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
243 /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
244 ///
245 /// A strong reference, so the prototype a host installed outlives every script
246 /// reference to it — which is what `JS_SetClassProto` promises.
247 protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
248}
249
250impl HostClasses {
251 fn new() -> HostClasses {
252 HostClasses {
253 next_id: 1,
254 defs: std::collections::BTreeMap::new(),
255 protos: std::collections::BTreeMap::new(),
256 }
257 }
258
259 /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
260 pub fn register(&mut self, def: ClassDef) -> ClassId {
261 let id = ClassId::from_raw(self.next_id);
262 self.next_id += 1;
263 self.defs.insert(id, std::rc::Rc::new(def));
264 id
265 }
266
267 /// Register `def` under an id the caller already has (`JS_NewClass`).
268 ///
269 /// The C API splits "get an id" from "register a class" because a module may be
270 /// initialised lazily; registering twice under one id replaces the definition, and an
271 /// object created under the old one keeps the old behaviour, since it carries its own
272 /// reference.
273 pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
274 if !id.is_valid() {
275 return false;
276 }
277 // Keep the counter past any id handed out explicitly, so a later `register` cannot
278 // reuse one.
279 self.next_id = self.next_id.max(id.get() + 1);
280 self.defs.insert(id, std::rc::Rc::new(def));
281 true
282 }
283
284 /// What `id` was registered with.
285 pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
286 self.defs.get(&id).cloned()
287 }
288
289 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
290 pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
291 self.protos.insert(id, proto);
292 }
293
294 /// The prototype installed for `id`, if the host installed one.
295 pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
296 self.protos.get(&id).cloned()
297 }
298
299 /// How many classes the host registered.
300 pub fn len(&self) -> usize {
301 self.defs.len()
302 }
303
304 /// Whether no class has been registered.
305 pub fn is_empty(&self) -> bool {
306 self.defs.is_empty()
307 }
308}
309
310impl Default for HostClasses {
311 fn default() -> HostClasses {
312 HostClasses::new()
313 }
314}
315
316/// One binding of the frame that called `eval`, so the eval'd code can read and
317/// write it by name.
318struct EvalBinding {
319 /// The name it was declared with.
320 name: String,
321 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
322 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
323 /// a function that declares `a` must find that `a`.
324 frame: usize,
325 /// Which table of that frame it lives in.
326 slot: EvalSlot,
327 /// The slot index within that table.
328 index: usize,
329}
330
331/// Which table of a frame an [`EvalBinding`] indexes.
332#[derive(Clone, Copy)]
333enum EvalSlot {
334 Arg,
335 Local,
336}
337
338/// One activation record.
339struct Frame {
340 /// The bytecode being run.
341 code: Gc<CompiledCode>,
342 /// The cells this closure captured.
343 env: Gc<ClosureEnv>,
344 /// The `this` binding.
345 this: Value,
346 /// Argument slots, sized to the declared parameter count.
347 args: Vec<Value>,
348 /// How many values the caller actually passed, which is what `arguments.length`
349 /// reports and what `...rest` slices from.
350 passed_count: usize,
351 /// The passed values, **only when they do not fit in [`Self::args`]**.
352 ///
353 /// `args` is sized to the declared parameters, so a call that passes no more than
354 /// that already holds every passed value in its first `passed_count` slots — copying
355 /// them here as well was two writes and a buffer per call, on the hottest path in
356 /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
357 /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
358 /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
359 /// its own copy.
360 ///
361 /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
362 /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
363 /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
364 /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
365 /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
366 /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
367 #[allow(clippy::box_collection)]
368 passed_overflow: Option<Box<Vec<Value>>>,
369 /// Local slots.
370 locals: Vec<Value>,
371 /// Reference cells for this frame's own captured bindings.
372 cells: Vec<Gc<Cell>>,
373 /// The operand stack.
374 stack: Vec<Value>,
375 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
376 local_vars: Option<Gc<LocalVars>>,
377
378 /// Index of the next instruction, not a byte offset.
379 ///
380 /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
381 /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
382 /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
383 /// `Frame`, and `frames.push` copies the whole struct on every call.
384 pc: usize,
385 /// Byte offset of the instruction being executed, which is what a stack trace
386 /// reports. `pc` has already moved past it by the time an instruction runs.
387 ///
388 /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
389 at: usize,
390 /// The callee, so a native builtin can tell which constructor it is.
391 callee: Value,
392 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
393 new_target: Value,
394 /// What this frame costs against [`Interp::stack_limit`], in bytes.
395 ///
396 /// Cached rather than recomputed because it is charged on every call and a call is the
397 /// hottest thing in the interpreter.
398 cost: usize,
399 /// [`Interp::stack_used`] before this frame was pushed.
400 ///
401 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
402 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
403 /// leave the counter wrong. There are eight places that drop frames; one subtraction
404 /// forgotten in any of them would leak budget until the depth limit moved.
405 stack_base: usize,
406 /// Whether this frame's body ended in a `tail_call`.
407 ///
408 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
409 /// with its own frame just like `call` does and only skips storing the result
410 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
411 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
412 /// pushed as usual, and this marker makes its return value the *caller's* return
413 /// value without running the instructions after the call.
414 tail: bool,
415}
416
417impl Frame {
418 /// Read a local slot, taking the frame as `self`.
419 ///
420 /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
421 /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
422 /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
423 /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
424 /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
425 #[inline]
426 fn read_loc(&self, slot: usize) -> Value {
427 let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
428 if cell == -1 {
429 return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
430 }
431 match self.cells.get(cell as usize) {
432 Some(cell) => cell.get(),
433 None => Value::Undefined,
434 }
435 }
436
437 /// [`Self::read_loc`] for an argument slot.
438 #[inline]
439 fn read_arg(&self, slot: usize) -> Value {
440 let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
441 if cell == -1 {
442 return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
443 }
444 match self.cells.get(cell as usize) {
445 Some(cell) => cell.get(),
446 None => Value::Undefined,
447 }
448 }
449
450 /// The values the caller actually passed, which is what `arguments` exposes.
451 ///
452 /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
453 fn passed(&self) -> &[Value] {
454 match &self.passed_overflow {
455 Some(values) => values,
456 None => &self.args[..self.passed_count],
457 }
458 }
459
460 /// The decoded instructions of the function this frame runs.
461 ///
462 /// A method rather than `frame.code.insns` at the call site so that the borrow is
463 /// obviously of the frame — the dispatch loop holds one across a `get`.
464 fn insns(&self) -> &[crate::insn::Insn] {
465 &self.code.insns
466 }
467}
468
469impl js_gc::Trace for Frame {
470 fn trace(&self, tracer: &mut js_gc::Tracer) {
471 self.code.trace(tracer);
472 self.env.trace(tracer);
473 self.this.trace(tracer);
474 for value in &self.args {
475 value.trace(tracer);
476 }
477 for value in self.passed() {
478 value.trace(tracer);
479 }
480 for value in &self.locals {
481 value.trace(tracer);
482 }
483 for cell in &self.cells {
484 cell.trace(tracer);
485 }
486 if let Some(local_vars) = &self.local_vars {
487 tracer.visit(local_vars);
488 }
489 for value in &self.stack {
490 value.trace(tracer);
491 }
492 self.callee.trace(tracer);
493 self.new_target.trace(tracer);
494 }
495}
496
497/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
498/// emitted `if_false` treats as "keep going".
499/// How many finished frames' value buffers are kept for reuse.
500const RECYCLE_SLOTS: usize = 8;
501
502/// The largest buffer worth keeping. See [`Interp::free_values`].
503const RECYCLE_MAX_CAPACITY: usize = 4096;
504
505const RESUME_NEXT: i32 = 0;
506/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
507/// generator fall into its `return_async`.
508const RESUME_RETURN: i32 = 1;
509/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
510/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
511/// must forward the exception into the inner iterator rather than finish.
512const RESUME_THROW: i32 = 2;
513
514/// One microtask.
515///
516/// The queue holds *data* rather than closures because its contents are GC values: a
517/// closure would be invisible to the collector, and a pending reaction is exactly the
518/// kind of thing that must keep its handlers and its promise alive.
519pub enum Job {
520 /// A `then` reaction about to run.
521 Reaction {
522 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
523 handler: Option<Value>,
524 /// The value or reason to call it with.
525 argument: Value,
526 /// Whether the source promise rejected, which decides the pass-through kind.
527 rejected: bool,
528 /// The promise the answer settles.
529 promise: Gc<JsObject>,
530 },
531 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
532 Thenable {
533 /// The `then` that was found on the value.
534 then: Value,
535 /// The thenable itself, which becomes `then`'s `this`.
536 value: Value,
537 /// The promise being resolved.
538 promise: Gc<JsObject>,
539 },
540 /// A pending `import(specifier)`.
541 Import {
542 /// The specifier, already converted to a string.
543 specifier: String,
544 /// The module that asked, which the specifier resolves against.
545 referrer: String,
546 /// The promise `import()` handed back.
547 promise: Gc<JsObject>,
548 },
549 /// An async generator resuming after the value it awaited settled.
550 GeneratorResume {
551 /// The async generator to continue.
552 generator: Gc<JsObject>,
553 /// The promise the pending method returned.
554 promise: Gc<JsObject>,
555 /// Whether this delivers the value or raises the reason.
556 kind: ResumeKind,
557 /// The settled value, or the rejection reason.
558 value: Value,
559 },
560 /// An async function resuming after the value it awaited settled.
561 Resume {
562 /// The body, parked in a coroutine.
563 coroutine: Gc<JsObject>,
564 /// The promise the async function handed its caller.
565 promise: Gc<JsObject>,
566 /// Whether this resumption delivers a value or raises one.
567 kind: ResumeKind,
568 /// The settled value, or the rejection reason.
569 value: Value,
570 },
571}
572
573/// One macro-task: work the event loop owes the script but has not run yet.
574///
575/// The microtask queue ([`Job`]) is different: those run before the host regains control.
576/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
577/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
578/// logic: the engine decides *what* is due, the host decides *how to wait*.
579///
580/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
581/// reference counting even though nothing else references it — the same rule the `HostFn`
582/// documentation states from the other side (a host closure must not hold a `Gc`, so the
583/// `Gc` lives here instead).
584pub enum Task {
585 /// A `setTimeout` that is due at `due_at`.
586 ///
587 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
588 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
589 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
590 /// would give this engine a timer the reference cannot produce, with nothing to
591 /// compare it against.
592 Timer {
593 /// The id `setTimeout` returned, for `clearTimeout`.
594 id: i32,
595 /// What to call when it fires.
596 callback: Value,
597 /// When it becomes runnable, as a monotonic instant.
598 due_at: std::time::Instant,
599 },
600}
601
602/// A descriptor the host has to poll, and which directions have a handler.
603///
604/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
605/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
606/// blocks on it, and the host reports back through [`Interp::fire_fd`].
607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
608pub struct FdInterest {
609 /// The descriptor to watch.
610 pub fd: i32,
611 /// Whether `os.setReadHandler` registered a callback.
612 pub read: bool,
613 /// Whether `os.setWriteHandler` registered a callback.
614 pub write: bool,
615}
616
617/// The callbacks registered for one descriptor, per direction.
618#[derive(Default)]
619pub(crate) struct FdHandlers {
620 /// `os.setReadHandler`'s callback.
621 pub read: Option<Value>,
622 /// `os.setWriteHandler`'s callback.
623 pub write: Option<Value>,
624}
625
626/// The file name `eval` reports, which the reference does not inherit from the caller.
627///
628/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
629/// reference and the names show up in stack traces.
630/// The description of the private symbol a class brand is made from.
631///
632/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
633/// place no script can reach, since no expression can name a private symbol.
634const BRAND_DESCRIPTION: &str = "brand";
635
636/// One validated property lookup.
637///
638/// Covers both own-property hits and prototype hits. The second kind was deliberately left
639/// uncached at first ("a prototype hit depends on more than the object and the name"), and
640/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
641/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
642/// names on every iteration (measured: 100 ns per call over an empty loop).
643pub struct FieldCache {
644 /// The name, so two different properties of one object do not collide.
645 key: PropertyKey,
646 /// Where the value was found, relative to the chain below.
647 index: usize,
648 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
649 level: u8,
650 /// The receiver and every prototype down to (and including) the level that answered,
651 /// each with the length of its property table at the time.
652 ///
653 /// That length is the whole guard, and it is sufficient for the ways the answer can
654 /// change without a lookup: adding or deleting any property moves it, and a
655 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
656 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
657 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
658 /// the one that was cached.
659 ///
660 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
661 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
662 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
663}
664
665/// How many links of a prototype chain a [`FieldCache`] remembers.
666///
667/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
668/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
669/// at three.
670const MAX_CACHED_CHAIN: usize = 3;
671
672/// A remembered global-variable lookup.
673///
674/// A `var` global is an ordinary property of the global object, so reading one walks the
675/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
676/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
677/// fixed by the bytecode, and the slot in the object's table only changes if the global
678/// object is mutated, which the index-and-name check below catches.
679pub struct GlobalCache {
680 /// The global object the lookup was resolved on, weakly.
681 object: js_gc::WeakGc<JsObject>,
682 /// Index of the data property in the global object's table.
683 index: usize,
684}
685
686/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
687const GLOBAL_CACHE_SLOTS: usize = 1024;
688
689/// How many property lookups are remembered.
690///
691/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
692/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
693/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
694/// lookup itself. Making it bigger stops helping: the working set of a real program's
695/// property sites is bounded by its code size.
696const FIELD_CACHE_SLOTS: usize = 4096;
697
698/// How much the heap may grow past the last `out of memory` before saying it again.
699///
700/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
701/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
702/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
703/// because it looks like it works. The reference gets this for free: it fails inside
704/// `js_malloc`, and its printing path happens not to allocate.
705///
706/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
707/// allocating is stopped within a rounding error of the limit) and far above what a
708/// handler needs.
709const OOM_HYSTERESIS: usize = 64 * 1024;
710
711/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
712pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
713
714/// How many instructions run between polls of [`Interp::interrupt`].
715///
716/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
717/// order of magnitude on both implementations — which is what lets a C driver compare its
718/// output byte for byte (see `scripts/m15-capi.sh --embed`).
719pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
720
721/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
722///
723/// Chosen so that the byte budget is what actually decides for every ordinary
724/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
725/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
726/// millions of frames.
727pub const MAX_FRAMES: usize = 200_000;
728
729const EVAL_FILE: &str = "<input>";
730
731/// The file name `std.evalScript` reports.
732const EVAL_SCRIPT_FILE: &str = "<evalScript>";
733
734/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
735///
736/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
737/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
738fn clamp_delay(delay_ms: f64) -> std::time::Duration {
739 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
740 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
741 // non-positive delay mean "due now".
742 if delay_ms.is_nan() || delay_ms <= 0.0 {
743 return std::time::Duration::ZERO;
744 }
745 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
746}
747
748impl js_gc::Trace for Task {
749 fn trace(&self, tracer: &mut js_gc::Tracer) {
750 let Task::Timer { callback, .. } = self;
751 callback.trace(tracer);
752 }
753}
754
755/// What one turn of the event loop did, so the caller cannot spin by accident.
756///
757/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
758/// core until the timer is due. Naming the three cases makes the wait explicit.
759#[derive(Debug, Clone, Copy, PartialEq, Eq)]
760pub enum Turn {
761 /// Something ran. Call again immediately — there may be more ready work.
762 Ran,
763 /// Nothing is runnable, but descriptors are registered: the host must poll
764 /// [`Interp::pending_fds`] for at most this long, then report readiness with
765 /// [`Interp::fire_fd`].
766 ///
767 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
768 /// the failure this project treats as worst — a handler that silently never fires —
769 /// so the two cannot be confused by accident.
770 Poll(std::time::Duration),
771 /// Nothing is runnable yet, but something is pending. Block at most this long, then
772 /// call again.
773 Wait(std::time::Duration),
774 /// Nothing is pending at all: the loop is done.
775 Done,
776}
777
778impl js_gc::Trace for Job {
779 fn trace(&self, tracer: &mut js_gc::Tracer) {
780 match self {
781 Job::Reaction {
782 handler,
783 argument,
784 promise,
785 ..
786 } => {
787 if let Some(handler) = handler {
788 handler.trace(tracer);
789 }
790 argument.trace(tracer);
791 tracer.visit(promise);
792 }
793 Job::Thenable {
794 then,
795 value,
796 promise,
797 } => {
798 then.trace(tracer);
799 value.trace(tracer);
800 tracer.visit(promise);
801 }
802 Job::Resume {
803 coroutine,
804 promise,
805 value,
806 ..
807 } => {
808 tracer.visit(coroutine);
809 tracer.visit(promise);
810 value.trace(tracer);
811 }
812 Job::Import { promise, .. } => tracer.visit(promise),
813 Job::GeneratorResume {
814 generator,
815 promise,
816 value,
817 ..
818 } => {
819 tracer.visit(generator);
820 tracer.visit(promise);
821 value.trace(tracer);
822 }
823 }
824 }
825}
826
827/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
828#[derive(Debug, Clone, Copy, PartialEq, Eq)]
829pub enum ResumeKind {
830 /// The generator was just created and is being run to its first suspension.
831 Start,
832 /// `next(v)`.
833 Next,
834 /// `return(v)`.
835 Return,
836 /// `throw(e)`.
837 Throw,
838}
839
840/// A generator object's saved execution.
841///
842/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
843/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
844/// separately allocated buffers.
845pub struct GeneratorState {
846 /// The detached frame, or `None` once the generator has finished or while it runs.
847 frame: Option<Frame>,
848 /// How far it got.
849 phase: GeneratorPhase,
850 /// Whether the last suspension was an `await` rather than a `yield`.
851 ///
852 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
853 /// value and a magic number, because the emitted code branches on which method
854 /// resumed it, while an `await` simply continues with its value. Getting this wrong
855 /// leaves an extra value on the operand stack that the next instruction then
856 /// consumes — a wrong answer rather than a crash.
857 parked_on_await: bool,
858 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
859 ///
860 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
861 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
862 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
863 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
864 /// delegating. Tracking it as part of the phase, the way the reference splits
865 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
866 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
867 /// exception and never reached `xs.throw`.
868 parked_on_yield_star: bool,
869 /// Pending `next`/`return`/`throw` calls, oldest first.
870 ///
871 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
872 /// called back to back must answer in that order, with the second call's value
873 /// arriving at the *second* `yield`. Running each call straight into the body — which
874 /// is what this engine did before — delivered the last queued value to whichever
875 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
876 /// `a === b ===` the final argument.
877 ///
878 /// The front entry is the one being served; it stays there (with `async_busy` set)
879 /// until its promise settles, because an `await` inside the body is a suspension of
880 /// the *driver*, not the end of the request.
881 requests: std::collections::VecDeque<AsyncRequest>,
882 /// Whether the front request is in flight.
883 async_busy: bool,
884}
885
886/// How one async-generator request ended.
887enum AsyncOutcome {
888 /// The method answered this `{value, done}`.
889 Value(Value),
890 /// The body threw.
891 Error(Value),
892}
893
894/// One queued `next`/`return`/`throw` on an async generator: the reference's
895/// `JSAsyncGeneratorRequest`.
896pub struct AsyncRequest {
897 /// Which method was called.
898 kind: ResumeKind,
899 /// Its argument.
900 value: Value,
901 /// The promise the method answered.
902 promise: Gc<JsObject>,
903}
904
905/// Which of §27.5.3.3's states a generator is in.
906#[derive(Debug, Clone, Copy, PartialEq, Eq)]
907enum GeneratorPhase {
908 /// Created, `initial_yield` reached, body not entered.
909 SuspendedStart,
910 /// Parked at a `yield`.
911 SuspendedYield,
912 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
913 Executing,
914 /// Finished; the frame is gone.
915 Completed,
916}
917
918impl js_gc::Trace for GeneratorState {
919 fn trace(&self, tracer: &mut js_gc::Tracer) {
920 if let Some(frame) = &self.frame {
921 frame.trace(tracer);
922 }
923 for request in &self.requests {
924 request.value.trace(tracer);
925 tracer.visit(&request.promise);
926 }
927 }
928}
929
930/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
931/// them in.
932///
933/// Each is a field rather than a map entry because the runtime reads them on hot paths
934/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
935/// failure — reaching a default here means the builtin did not install, and every
936/// accessor panics rather than silently answering `undefined`.
937///
938/// [`builtins::symbol`]: crate::builtins::symbol
939#[derive(Default)]
940pub struct WellKnownSymbols {
941 /// The symbol values, positionally. Empty until `Symbol` installs.
942 symbols: Vec<Value>,
943}
944
945/// Which well-known symbol a caller wants.
946///
947/// A typed accessor beats passing a name around: a typo is a compile error rather than
948/// an `undefined` key that quietly matches nothing.
949#[derive(Debug, Clone, Copy, PartialEq, Eq)]
950pub enum WellKnown {
951 /// `Symbol.toPrimitive`.
952 ToPrimitive,
953 /// `Symbol.iterator`.
954 Iterator,
955 /// `Symbol.match`.
956 Match,
957 /// `Symbol.matchAll`.
958 MatchAll,
959 /// `Symbol.replace`.
960 Replace,
961 /// `Symbol.search`.
962 Search,
963 /// `Symbol.split`.
964 Split,
965 /// `Symbol.toStringTag`.
966 ToStringTag,
967 /// `Symbol.isConcatSpreadable`.
968 IsConcatSpreadable,
969 /// `Symbol.hasInstance`.
970 HasInstance,
971 /// `Symbol.species`.
972 Species,
973 /// `Symbol.unscopables`.
974 Unscopables,
975 /// `Symbol.asyncIterator`.
976 AsyncIterator,
977 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
978 Disposable,
979 /// `Symbol.asyncDispose` — the awaited form.
980 AsyncDisposable,
981}
982
983impl WellKnown {
984 /// The index `Symbol`'s installer creates this symbol at.
985 fn index(self) -> usize {
986 match self {
987 WellKnown::ToPrimitive => 0,
988 WellKnown::Iterator => 1,
989 WellKnown::Match => 2,
990 WellKnown::MatchAll => 3,
991 WellKnown::Replace => 4,
992 WellKnown::Search => 5,
993 WellKnown::Split => 6,
994 WellKnown::ToStringTag => 7,
995 WellKnown::IsConcatSpreadable => 8,
996 WellKnown::HasInstance => 9,
997 WellKnown::Species => 10,
998 WellKnown::Unscopables => 11,
999 WellKnown::AsyncIterator => 12,
1000 WellKnown::Disposable => 13,
1001 WellKnown::AsyncDisposable => 14,
1002 }
1003 }
1004}
1005
1006impl Realm {
1007 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1008 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1009 self.well_known_symbols.symbols = symbols;
1010 }
1011
1012 /// A well-known symbol.
1013 pub fn well_known(&self, which: WellKnown) -> Value {
1014 self.well_known_symbols
1015 .symbols
1016 .get(which.index())
1017 .cloned()
1018 .unwrap_or(Value::Undefined)
1019 }
1020
1021 /// The well-known symbol as a property key.
1022 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1023 match self.well_known(which) {
1024 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1025 // Unreachable once `Symbol` has installed; an empty string key matches
1026 // nothing, which degrades to "the object has no such method".
1027 _ => PropertyKey::from(String::new()),
1028 }
1029 }
1030}
1031
1032/// The interpreter: a realm plus a frame stack.
1033pub struct Interp<'a> {
1034 /// The heap everything is allocated on.
1035 pub heap: &'a Heap,
1036 /// The realm.
1037 pub realm: Realm,
1038 /// Active frames, outermost first.
1039 frames: Vec<Frame>,
1040 /// Value buffers from frames that have finished, reused by the next call.
1041 ///
1042 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1043 /// the locals and the operand stack — and free all four on return. `call:recursion`
1044 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1045 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1046 ///
1047 /// Bounded in both directions: a few buffers per kind, and none larger than
1048 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1049 /// and keeping its buffer would pin that memory for the rest of the run.
1050 free_values: Vec<Vec<Value>>,
1051 /// A strict-mode `eval`'s own variable scope, while its script runs.
1052 ///
1053 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1054 /// become a global. Name lookups still fall through to the realm, which is why
1055 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1056 eval_scope: Option<BTreeMap<String, Value>>,
1057 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1058 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1059 eval_depth: usize,
1060 /// The calling frame's own bindings, which the running `eval` can read and write.
1061 ///
1062 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1063 /// come from the frame, and a write is applied back to the frame (or to the cell
1064 /// the frame captured) when the eval finishes. That is what makes
1065 /// `f("a = 3")` visible to the caller as `a === 3`.
1066 eval_bindings: Vec<EvalBinding>,
1067 /// The calling frame's `arguments`, while an `eval` runs.
1068 ///
1069 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1070 /// own yet still has to see the caller's `arguments`.
1071 eval_arguments: Option<Value>,
1072 /// The `with` objects live at the moment the running `eval` started, innermost first.
1073 ///
1074 /// `None` outside an eval, which is what keeps a finished block's object from
1075 /// shadowing ordinary bytecode reads.
1076 eval_with: Option<Vec<Gc<JsObject>>>,
1077 /// The bindings the running direct `eval` makes visible, as name → cell.
1078 ///
1079 /// Set for the duration of an eval and then restored, but every closure created
1080 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1081 /// `eval("f = () => i")` work after the eval has returned.
1082 active_eval_scope: Option<Gc<EvalScope>>,
1083 /// The frame that called the direct `eval` currently running, if any.
1084 ///
1085 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1086 /// on the global object, which is what keeps
1087 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1088 /// gives each call its own `x`.
1089 eval_caller: Option<Option<usize>>,
1090 /// The caller's `new.target`, while an `eval` runs.
1091 ///
1092 /// The eval'd code is a script with no constructor of its own, so it inherits the
1093 /// one the enclosing function was called with.
1094 eval_new_target: Option<Value>,
1095 /// `new.target` for the frame about to be pushed.
1096 ///
1097 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1098 /// value reaches the frame without threading a parameter through every call site.
1099 pending_new_target: Option<Value>,
1100 /// Names of the native functions currently executing, outermost first.
1101 ///
1102 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1103 /// trace still names it with `(native)` instead of a position, so the names are
1104 /// tracked separately and stitched into [`Interp::stack_trace`].
1105 ///
1106 /// The third field is how many bytecode frames were live when the native was entered,
1107 /// which is what places it *among* them rather than before all of them. Native
1108 /// functions used to be emitted up front on the grounds that they never re-enter
1109 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1110 /// The natives currently running, innermost last: the function object and the
1111 /// depth it was entered at.
1112 ///
1113 /// The *name* is deliberately not stored. It used to be, read with
1114 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1115 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1116 /// benchmark. A stack trace is built rarely; it can read the name then.
1117 native_frames: Vec<(Gc<JsObject>, usize)>,
1118 /// The native function currently executing, for the ones that have to know *which*
1119 /// function they are — a typed-array constructor reads its element type off itself.
1120 ///
1121 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1122 /// reports whatever the enclosing bytecode frame was called with.
1123 current_native: Option<Gc<JsObject>>,
1124 /// Text written by `print` and friends, in order.
1125 ///
1126 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1127 /// once at the end, which is also when upstream's line buffering becomes
1128 /// visible for the cases compared here.
1129 pub output: String,
1130 /// Where `print` also writes, as it goes. `output` keeps the full log for
1131 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1132 ///
1133 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1134 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1135 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1136 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1137 /// would show a script's output all at once when it finished.
1138 pub output_sink: Option<Box<dyn std::io::Write>>,
1139 /// Where recent property reads found their value.
1140 ///
1141 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1142 /// table remembering *which object* and *which entry of its property table* answered a
1143 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1144 /// can move; the property can become an accessor), which is what makes a stale entry a
1145 /// miss rather than a wrong answer.
1146 ///
1147 /// The object is held weakly: a cache that held it strongly would keep up to
1148 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1149 /// program cannot see and cannot work around.
1150 pub field_cache: Vec<Option<FieldCache>>,
1151 /// Global lookups, by binding slot. See [`GlobalCache`].
1152 global_cache: Vec<Option<GlobalCache>>,
1153 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1154 /// under its limit. See [`Interp::check_memory`].
1155 pub oom_reported_at: usize,
1156 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1157 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1158 ///
1159 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1160 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1161 /// host that wants to stop a runaway script must not have to wait for it to return.
1162 ///
1163 /// Two things this cannot do, both of them differences a host can observe:
1164 ///
1165 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1166 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1167 /// needs a signal that the `catch` machinery does not see, which is a change to
1168 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1169 /// a host that stops the script itself.
1170 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1171 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1172 /// both, so the difference is when the counter hits zero, not whether it will.
1173 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1174 /// Instructions until the next [`Interp::interrupt`] poll.
1175 pub interrupt_counter: u32,
1176 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1177 ///
1178 /// A separate field from [`Interp::uncatchable`] because the two live for different
1179 /// spans. This one is the host's standing request; it survives the start of an
1180 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1181 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1182 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1183 /// cleared it before the script it was set for had a chance to throw.
1184 pub uncatchable_next: bool,
1185 /// Whether the exception now unwinding may be caught by a `catch`.
1186 ///
1187 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1188 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1189 /// a host stopping a runaway loop is not fought by the loop.
1190 ///
1191 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1192 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1193 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1194 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1195 pub uncatchable: bool,
1196 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1197 ///
1198 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1199 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1200 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1201 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1202 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1203 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1204 ///
1205 /// The numbers come out close for the same reason a C frame and a heap frame of this
1206 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1207 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1208 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1209 /// `crates/quickjs-cli/tests/limits.rs`.
1210 pub stack_limit: usize,
1211 /// The most frames that may be live at once, whatever the byte budget says.
1212 ///
1213 /// A second bound for a reason the reference does not have: our frames cost less than
1214 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1215 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1216 /// `--stack-size 1G` from being a memory bomb.
1217 pub max_frames: usize,
1218 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1219 ///
1220 /// Script execution does not return until this has drained, which is what makes
1221 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1222 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1223 /// not a `for`.
1224 pub(crate) jobs: std::collections::VecDeque<Job>,
1225 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1226 ///
1227 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1228 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1229 pub(crate) tasks: Vec<Task>,
1230 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1231 /// barrier'd evaluation started.
1232 ///
1233 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1234 /// lets a REPL report an error from the line it just evaluated without also reporting
1235 /// its own readline loop.
1236 trace_barriers: Vec<usize>,
1237 /// `os.signal` handlers, keyed by signal number.
1238 ///
1239 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1240 /// a handler cannot be freed while it is still registered.
1241 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1242 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1243 ///
1244 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1245 /// that is only reachable from a host closure could be freed while still registered.
1246 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1247 /// The next timer id.
1248 ///
1249 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1250 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1251 next_timer_id: i32,
1252 /// Errors thrown by timer callbacks, already rendered.
1253 ///
1254 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1255 /// that throws has no promise behind it. Both are reported by the host at the end of
1256 /// the loop, but only one is fixed up by a later `.catch`.
1257 timer_errors: Vec<String>,
1258 /// The module registry, keyed by canonical name.
1259 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1260 /// How the host turns a specifier into bytes.
1261 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1262 /// The module the host was asked to run, for `import.meta.main`.
1263 pub main_module_name: Option<String>,
1264 /// Module bodies currently running, innermost last.
1265 ///
1266 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1267 /// this is the only place that knows which module that is.
1268 pub module_stack: Vec<String>,
1269 /// Rejections that no handler has claimed, with the promise they belong to.
1270 ///
1271 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1272 /// reason alone cannot say whether somebody eventually listened.
1273 unhandled: Vec<(Gc<JsObject>, Value)>,
1274}
1275
1276impl<'a> Interp<'a> {
1277 /// Build an interpreter over `heap`, with a fresh realm.
1278 pub fn new(heap: &'a Heap) -> Interp<'a> {
1279 let object_proto = JsObject::ordinary(heap, None);
1280 let function_proto = JsObject::function(
1281 heap,
1282 Some(object_proto.clone()),
1283 Callable::Native {
1284 func: |_, _, _| Ok(Value::Undefined),
1285 own_instance: false,
1286 },
1287 );
1288 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1289 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1290 let mut interp = Interp {
1291 heap,
1292 realm: Realm {
1293 global,
1294 object_proto,
1295 function_proto,
1296 array_proto,
1297 globals: BTreeMap::new(),
1298 declared: Vec::new(),
1299 lexical_consts: BTreeSet::new(),
1300 errors: BTreeMap::new(),
1301 string_proto: None,
1302 number_proto: None,
1303 boolean_proto: None,
1304 bigint_proto: None,
1305 error_proto: JsObject::ordinary(heap, None),
1306 date_proto: JsObject::ordinary(heap, None),
1307 generator_proto: JsObject::ordinary(heap, None),
1308 promise_proto: None,
1309 async_generator_proto: None,
1310 symbol_proto: None,
1311 symbol_registry: BTreeMap::new(),
1312 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1313 regexp_proto: None,
1314 regexp_ctor: None,
1315 suppressed_error_proto: None,
1316 disposable_stack_proto: None,
1317 map_proto: None,
1318 set_proto: None,
1319 finalization_registries: Vec::new(),
1320 array_buffer_proto: None,
1321 typed_array_proto: None,
1322 typed_array_protos: Vec::new(),
1323 data_view_proto: None,
1324 async_disposable_stack_proto: None,
1325 iterator_proto: None,
1326 iterator_helper_proto: None,
1327 iterator_wrap_proto: None,
1328 generator_function_proto: None,
1329 async_function_proto: None,
1330 async_generator_function_proto: None,
1331 iterator_protos: std::collections::BTreeMap::new(),
1332 well_known_symbols: WellKnownSymbols::default(),
1333 host_classes: HostClasses::new(),
1334 },
1335 frames: Vec::new(),
1336 free_values: Vec::new(),
1337 global_cache: {
1338 let mut cache = Vec::new();
1339 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1340 cache
1341 },
1342 eval_scope: None,
1343 eval_depth: 0,
1344 eval_bindings: Vec::new(),
1345 eval_arguments: None,
1346 eval_with: None,
1347 active_eval_scope: None,
1348 eval_caller: None,
1349 pending_new_target: None,
1350 eval_new_target: None,
1351 native_frames: Vec::new(),
1352 current_native: None,
1353 output: String::new(),
1354 output_sink: None,
1355 field_cache: {
1356 let mut cache = Vec::new();
1357 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1358 cache
1359 },
1360 oom_reported_at: 0,
1361 interrupt: None,
1362 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1363 uncatchable_next: false,
1364 uncatchable: false,
1365 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1366 // absent.
1367 stack_limit: DEFAULT_STACK_SIZE,
1368 max_frames: MAX_FRAMES,
1369 jobs: std::collections::VecDeque::new(),
1370 tasks: Vec::new(),
1371 trace_barriers: Vec::new(),
1372 signal_handlers: std::collections::BTreeMap::new(),
1373 fd_handlers: std::collections::BTreeMap::new(),
1374 next_timer_id: 1,
1375 timer_errors: Vec::new(),
1376 modules: std::collections::BTreeMap::new(),
1377 module_loader: None,
1378 main_module_name: None,
1379 module_stack: Vec::new(),
1380 unhandled: Vec::new(),
1381 };
1382 crate::builtins::install(&mut interp);
1383 interp
1384 }
1385
1386 // -- allocation helpers -------------------------------------------------
1387
1388 /// A new string value.
1389 /// A `BigInt` value from a computed big integer.
1390 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1391 Value::BigInt(Gc::new(self.heap, value))
1392 }
1393
1394 /// A string value from bytes that are already WTF-8, which is how a string with an
1395 /// unpaired surrogate reaches a `Value`.
1396 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1397 Value::string_wtf8(self.heap, text)
1398 }
1399
1400 /// A new string value, from text that is valid UTF-8.
1401 pub fn string(&self, text: impl Into<String>) -> Value {
1402 Value::string(self.heap, text)
1403 }
1404
1405 /// A new ordinary object with the given prototype.
1406 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1407 JsObject::ordinary(self.heap, proto)
1408 }
1409
1410 // -- host classes -------------------------------------------------------
1411
1412 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1413 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1414 self.realm.host_classes.register(def)
1415 }
1416
1417 /// Register `def` under an id the host already holds (`JS_NewClass`).
1418 ///
1419 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1420 /// `JS_NewClass`.
1421 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1422 self.realm.host_classes.define(id, def)
1423 }
1424
1425 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1426 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1427 self.realm.host_classes.set_proto(id, proto);
1428 }
1429
1430 /// The prototype installed for `id`, if any.
1431 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1432 self.realm.host_classes.proto(id)
1433 }
1434
1435 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1436 ///
1437 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1438 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1439 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1440 /// host installed none.
1441 ///
1442 /// Answers `None` for an id that was never registered: the C API would return an
1443 /// exception, and silently making an ordinary object instead would move the failure to
1444 /// the first `JS_GetOpaque` that no longer matches.
1445 pub fn new_host_object(
1446 &mut self,
1447 proto: Option<Gc<JsObject>>,
1448 class_id: ClassId,
1449 ) -> Option<Gc<JsObject>> {
1450 let class = self.realm.host_classes.def(class_id)?;
1451 let proto = proto
1452 .or_else(|| self.realm.host_classes.proto(class_id))
1453 .or_else(|| Some(self.realm.object_proto.clone()));
1454 Some(JsObject::host_object(self.heap, proto, class_id, class))
1455 }
1456
1457 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1458 ///
1459 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1460 /// object, it is an object of another class, or the class never got a payload. A host
1461 /// that has to tell them apart uses [`JsObject::host_class_id`].
1462 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1463 let object = value.as_object()?;
1464 if object.host_class_id()? != class_id {
1465 return None;
1466 }
1467 object.host_opaque()
1468 }
1469
1470 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1471 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1472 match value.as_object() {
1473 Some(object) => object.set_host_opaque(opaque),
1474 None => false,
1475 }
1476 }
1477
1478 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1479 ///
1480 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1481 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1482 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1483 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1484 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1485 /// said `[object Object]` instead of `[object Array Iterator]`.
1486 ///
1487 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1488 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1489 /// its own.
1490 pub fn new_iterator_prototype(
1491 &mut self,
1492 tag: &str,
1493 next: crate::object::NativeFn,
1494 ) -> Gc<JsObject> {
1495 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1496 return existing.clone();
1497 }
1498 let parent = self.realm.iterator_proto.clone();
1499 let proto = self.new_object(parent);
1500 let next = self.new_native("next", 0, next);
1501 proto.define(
1502 "next",
1503 Property::with_attributes(Value::Object(next), true, false),
1504 );
1505 let key = self.realm.well_known_key(WellKnown::Iterator);
1506 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1507 proto.define_key(
1508 &key,
1509 Property::with_attributes(Value::Object(identity), true, false),
1510 );
1511 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1512 let tag_value = self.string(tag);
1513 proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
1514 self.realm
1515 .iterator_protos
1516 .insert(tag.to_string(), proto.clone());
1517 proto
1518 }
1519
1520 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1521 ///
1522 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1523 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1524 /// produced. That is why the two branches are not merged.
1525 pub fn object_own_property_keys(
1526 &mut self,
1527 object: &Gc<JsObject>,
1528 ) -> JsResult<Vec<PropertyKey>> {
1529 if let Some(keys) = self.proxy_own_keys(object)? {
1530 return Ok(keys);
1531 }
1532 // Integer-like keys ascending, then the string keys in insertion order, then the
1533 // symbols — the order every schema that walks an object expects.
1534 let entries = object.property_entries();
1535 let mut numeric: Vec<u32> = Vec::new();
1536 let mut strings: Vec<PropertyKey> = Vec::new();
1537 let mut symbols: Vec<PropertyKey> = Vec::new();
1538 for (key, _) in entries {
1539 match &key {
1540 // A class-private name is never reported by any enumeration: that is the
1541 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1542 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1543 // symbol skip, `Object.assign`) therefore cannot see it.
1544 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1545 PropertyKey::Symbol(_) => symbols.push(key),
1546 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1547 Some(index) => {
1548 if !numeric.contains(&index) {
1549 numeric.push(index);
1550 }
1551 }
1552 None => strings.push(key),
1553 },
1554 }
1555 }
1556 numeric.sort_unstable();
1557 let mut keys: Vec<PropertyKey> = numeric
1558 .into_iter()
1559 .map(|index| PropertyKey::from(index.to_string()))
1560 .collect();
1561 keys.extend(strings);
1562 keys.extend(symbols);
1563 Ok(keys)
1564 }
1565
1566 /// The state behind a promise object, or `None` when `object` is not one.
1567 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1568 object.with(|data| match &data.kind {
1569 ObjectKind::Promise(state) => Some(state.clone()),
1570 _ => None,
1571 })
1572 }
1573
1574 /// A new pending promise.
1575 pub fn new_promise(&mut self) -> Gc<JsObject> {
1576 let proto = self.realm.promise_proto.clone();
1577 let promise = JsObject::ordinary(self.heap, proto);
1578 promise.with_mut(|data| {
1579 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1580 crate::object::PromiseState::default(),
1581 )));
1582 });
1583 promise
1584 }
1585
1586 /// Fulfil `promise`, unless it has already settled.
1587 ///
1588 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1589 /// after `reject`, changes nothing.
1590 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1591 let Some(state) = self.promise_state(promise) else {
1592 return;
1593 };
1594 let reactions = {
1595 let mut state = state.borrow_mut();
1596 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1597 return;
1598 }
1599 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1600 std::mem::take(&mut state.reactions)
1601 };
1602 self.queue_reactions(reactions, value, false);
1603 }
1604
1605 /// Reject `promise`, unless it has already settled.
1606 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1607 let Some(state) = self.promise_state(promise) else {
1608 return;
1609 };
1610 let reactions = {
1611 let mut state = state.borrow_mut();
1612 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1613 return;
1614 }
1615 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1616 std::mem::take(&mut state.reactions)
1617 };
1618 // Remember it only when nothing is listening *now*; a `then` registered later
1619 // prunes the entry in `perform_then`.
1620 if reactions.is_empty() {
1621 self.unhandled.push((promise.clone(), reason.clone()));
1622 }
1623 self.queue_reactions(reactions, reason, true);
1624 }
1625
1626 /// Queue one job per reaction.
1627 ///
1628 /// This is what makes `then` asynchronous even on an already-settled promise:
1629 /// `p.then(f); g()` calls `g` first.
1630 fn queue_reactions(
1631 &mut self,
1632 reactions: Vec<crate::object::PromiseReaction>,
1633 argument: Value,
1634 rejected: bool,
1635 ) {
1636 for reaction in reactions {
1637 let handler = if rejected {
1638 reaction.on_rejected.clone()
1639 } else {
1640 reaction.on_fulfilled.clone()
1641 };
1642 self.jobs.push_back(Job::Reaction {
1643 handler,
1644 argument: argument.clone(),
1645 rejected,
1646 promise: reaction.promise,
1647 });
1648 }
1649 }
1650
1651 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1652 /// resolve/reject pair.
1653 ///
1654 /// The pair are callable objects rather than Rust closures, because the script gets
1655 /// them and may stash them for later.
1656 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1657 let promise = self.new_promise();
1658 let resolve = JsObject::function(
1659 self.heap,
1660 Some(self.realm.function_proto.clone()),
1661 Callable::PromiseResolve(promise.clone()),
1662 );
1663 let reject = JsObject::function(
1664 self.heap,
1665 Some(self.realm.function_proto.clone()),
1666 Callable::PromiseReject(promise.clone()),
1667 );
1668 (promise, Value::Object(resolve), Value::Object(reject))
1669 }
1670
1671 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1672 /// promise, as `{ value: completion }`.
1673 ///
1674 /// The three cases are the reference's, and they differ on purpose:
1675 ///
1676 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1677 /// exception before any promise exists;
1678 /// * a **runtime** error rejects the returned promise;
1679 /// * success resolves it with `{ value }`, where the value is the script's completion
1680 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1681 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1682 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1683 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1684 ///
1685 /// # What this does not do
1686 ///
1687 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1688 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1689 /// the parser and the suspension machinery to accept a suspended top-level script, and
1690 /// is not implemented — such source is a syntax error here. Everything else about the
1691 /// flag is reproduced.
1692 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1693 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1694 // too, and the reference truncates that one at the same place as a runtime failure.
1695 if barrier {
1696 let depth = self.frames.len();
1697 self.trace_barriers.push(depth);
1698 }
1699 // Compiled before the promise exists, so a parse failure propagates as a throw
1700 // instead of being folded into a rejection.
1701 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1702 Ok(compiled) => compiled,
1703 Err(error) => {
1704 if barrier {
1705 self.trace_barriers.pop();
1706 }
1707 return Err(error);
1708 }
1709 };
1710 // An async body answers its own promise, and that promise is what the reference
1711 // hands back — the same object, not a wrapper around it. Its resolution value is
1712 // the `{value}` object the compiled epilogue built.
1713 if compiled.kind.is_async() {
1714 let strict = compiled.strict;
1715 let promise = self.run_eval_script(compiled, strict)?;
1716 if barrier {
1717 self.trace_barriers.pop();
1718 }
1719 return Ok(promise);
1720 }
1721 let (promise, resolve, reject) = self.new_promise_capability();
1722 let strict = compiled.strict;
1723 match self.run_eval_script(compiled, strict) {
1724 Ok(value) => {
1725 // `{ value }` is a plain object, so resolving with it adopts nothing even
1726 // when the completion value is itself a promise.
1727 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1728 self.set_property(&wrapped, "value", value)?;
1729 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1730 }
1731 Err(Signal::Throw(error)) => {
1732 self.call_value(reject, Value::Undefined, vec![error])?;
1733 }
1734 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1735 }
1736 if barrier {
1737 self.trace_barriers.pop();
1738 }
1739 Ok(Value::Object(promise))
1740 }
1741
1742 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1743 ///
1744 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1745 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1746 /// timer table, where the collector already scans it.
1747 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1748 let (promise, resolve, _reject) = self.new_promise_capability();
1749 let resolve = self.new_host_function(
1750 "resolve",
1751 1,
1752 Box::new(
1753 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1754 let value = args.first().cloned().unwrap_or(Value::Undefined);
1755 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1756 },
1757 ),
1758 );
1759 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1760 // timer table is part of what the collector walks.
1761 self.schedule_timer(Value::Object(resolve), delay_ms);
1762 Ok(Value::Object(promise))
1763 }
1764
1765 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1766 /// new promise resolved with it.
1767 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1768 if let Value::Object(object) = &value
1769 && self.promise_state(object).is_some()
1770 {
1771 return Ok(value);
1772 }
1773 let promise = self.new_promise();
1774 self.resolve_promise_with(&promise, value)?;
1775 Ok(Value::Object(promise))
1776 }
1777
1778 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1779 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1780 // Resolving a promise with itself is a `TypeError`. The check exists because the
1781 // alternative is a chain of self-reactions that never settles.
1782 if let Value::Object(object) = &value
1783 && object.ptr_eq(promise)
1784 {
1785 // The spec rejects *and* throws, so both the promise and the caller see it.
1786 let thrown = self.type_error("cannot resolve a promise with itself");
1787 let Signal::Throw(error) = thrown.clone() else {
1788 unreachable!("type_error always throws")
1789 };
1790 self.reject_promise(promise, error);
1791 return Err(thrown);
1792 }
1793 let then = match &value {
1794 Value::Object(object) => self.get_property(object, "then")?,
1795 _ => None,
1796 };
1797 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1798 if !callable_then {
1799 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1800 self.fulfill_promise(promise, value);
1801 return Ok(());
1802 }
1803 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1804 // inside `resolve`, so a script cannot make a promise settle synchronously.
1805 self.jobs.push_back(Job::Thenable {
1806 then: then.expect("checked callable"),
1807 value,
1808 promise: promise.clone(),
1809 });
1810 Ok(())
1811 }
1812
1813 /// `Promise.prototype.then`: register a reaction and answer the derived promise.
1814 pub fn perform_then(
1815 &mut self,
1816 promise: &Gc<JsObject>,
1817 on_fulfilled: Option<Value>,
1818 on_rejected: Option<Value>,
1819 ) -> JsResult<Value> {
1820 let Some(state) = self.promise_state(promise) else {
1821 return Err(self.type_error("not a promise"));
1822 };
1823 // Whether a rejection handler is being attached decides whether a recorded
1824 // rejection stops being unhandled, so it is read before the values are moved.
1825 let has_rejection_handler = on_rejected.is_some();
1826 let derived = self.new_promise();
1827 let reaction = crate::object::PromiseReaction {
1828 on_fulfilled,
1829 on_rejected,
1830 promise: derived.clone(),
1831 };
1832 let settled = {
1833 let mut state = state.borrow_mut();
1834 // A rejection somebody reacts to is no longer unhandled.
1835 state.handled = true;
1836 match &state.status {
1837 crate::object::PromiseStatus::Pending => {
1838 state.reactions.push(reaction.clone());
1839 None
1840 }
1841 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1842 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1843 }
1844 };
1845 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1846 // later, means somebody is listening after all.
1847 if has_rejection_handler {
1848 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1849 }
1850 if let Some((argument, rejected)) = settled {
1851 let handler = if rejected {
1852 reaction.on_rejected
1853 } else {
1854 reaction.on_fulfilled
1855 };
1856 self.jobs.push_back(Job::Reaction {
1857 handler,
1858 argument,
1859 rejected,
1860 promise: reaction.promise,
1861 });
1862 }
1863 Ok(Value::Object(derived))
1864 }
1865
1866 /// The rejections nobody listened to, formatted the way the reference reports them.
1867 ///
1868 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
1869 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
1870 /// unhandled at the point the queue drains, because a `then` may still be attached
1871 /// before the host acts on it.
1872 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
1873 let entries = std::mem::take(&mut self.unhandled);
1874 // Somebody may have attached a handler after the rejection was recorded, so the
1875 // promise is the authority rather than the list.
1876 let still_unhandled: Vec<Value> = entries
1877 .into_iter()
1878 .filter_map(|(promise, reason)| {
1879 let handled = self
1880 .promise_state(&promise)
1881 .map(|state| state.borrow().handled)
1882 .unwrap_or(true);
1883 (!handled).then_some(reason)
1884 })
1885 .collect();
1886 still_unhandled
1887 .into_iter()
1888 .map(|reason| {
1889 let text = self.describe_exception(&reason);
1890 let stack = match &reason {
1891 Value::Object(object) => self
1892 .get_property(object, "stack")
1893 .ok()
1894 .flatten()
1895 .map(|value| value.to_js_string())
1896 // `stack` carries a trailing newline of its own, which would leave
1897 // a blank line between two reported rejections.
1898 .map(|text| text.trim_end().to_string())
1899 .unwrap_or_default(),
1900 _ => String::new(),
1901 };
1902 if stack.is_empty() {
1903 format!("Possibly unhandled promise rejection: {text}")
1904 } else {
1905 format!("Possibly unhandled promise rejection: {text}\n{stack}")
1906 }
1907 })
1908 .collect()
1909 }
1910
1911 /// Run the microtask queue to exhaustion.
1912 ///
1913 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
1914 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
1915 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
1916 ///
1917 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
1918 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
1919 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
1920 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
1921 crate::builtins::json::parse_text(self, text, true)
1922 }
1923
1924 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
1925 ///
1926 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
1927 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
1928 /// immediately, and `setTimeout(f, -1)` is ordinary code.
1929 ///
1930 /// The callback is called with **no arguments**. The reference stores only the function
1931 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
1932 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
1933 /// extra arguments arrive as `undefined`.
1934 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
1935 let id = self.next_timer_id;
1936 // Wrap rather than grow: the id reaches the script as an `Int32`.
1937 self.next_timer_id = if self.next_timer_id == i32::MAX {
1938 1
1939 } else {
1940 self.next_timer_id + 1
1941 };
1942 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
1943 self.tasks.push(Task::Timer {
1944 id,
1945 callback,
1946 due_at,
1947 });
1948 id
1949 }
1950
1951 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
1952 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
1953 pub fn cancel_timer(&mut self, id: i32) -> bool {
1954 let before = self.tasks.len();
1955 self.tasks.retain(|task| match task {
1956 Task::Timer { id: task_id, .. } => *task_id != id,
1957 });
1958 self.tasks.len() != before
1959 }
1960
1961 /// How long until the earliest pending timer, or `None` when none is pending.
1962 pub fn next_timeout(&self) -> Option<std::time::Duration> {
1963 let now = std::time::Instant::now();
1964 self.tasks
1965 .iter()
1966 .map(|task| match task {
1967 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
1968 })
1969 .min()
1970 }
1971
1972 /// Run one turn of the event loop.
1973 ///
1974 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
1975 /// run at most one due timer, then drain again. The blocking belongs to the caller
1976 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
1977 /// is how it asks.
1978 ///
1979 /// One timer per turn rather than all of them: a timer callback may schedule another
1980 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
1981 /// starve the microtask queue.
1982 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
1983 self.drain_jobs()?;
1984 let now = std::time::Instant::now();
1985 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
1986 // followed by `setTimeout(g, 1)` must run `g` first.
1987 let due = self
1988 .tasks
1989 .iter()
1990 .enumerate()
1991 .filter(|(_, task)| match task {
1992 Task::Timer { due_at, .. } => *due_at <= now,
1993 })
1994 .min_by_key(|(_, task)| match task {
1995 Task::Timer { due_at, .. } => *due_at,
1996 })
1997 .map(|(index, _)| index);
1998 let Some(index) = due else {
1999 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2000 // descriptor is registered but no timer is closer, so a script that never
2001 // touches the descriptor still gets control back. Without a cap a handler on a
2002 // descriptor that is never ready would block for as long as the host allows.
2003 let timeout = self
2004 .next_timeout()
2005 .unwrap_or(std::time::Duration::from_secs(10))
2006 .min(std::time::Duration::from_secs(10));
2007 if !self.fd_handlers.is_empty() {
2008 // Blocking on a timer while descriptors are registered would starve them,
2009 // and blocking on the descriptors while a timer is due would delay it; the
2010 // host polls with the earlier of the two deadlines, which this timeout is.
2011 return Ok(Turn::Poll(timeout));
2012 }
2013 return Ok(match self.next_timeout() {
2014 Some(wait) => Turn::Wait(wait),
2015 None => Turn::Done,
2016 });
2017 };
2018 let Task::Timer { callback, .. } = self.tasks.remove(index);
2019 let this = Value::Undefined;
2020 // A throwing timer callback must not stop the loop: the reference reports it and
2021 // keeps going, because the alternative is that one bad timer silently stops every
2022 // later one.
2023 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2024 match self.call_value(callback, this, Vec::new()) {
2025 Ok(_) => {}
2026 Err(Signal::Throw(value)) => {
2027 let text = self.describe_exception(&value);
2028 self.timer_errors.push(text);
2029 }
2030 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2031 }
2032 self.drain_jobs()?;
2033 Ok(Turn::Ran)
2034 }
2035
2036 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2037 ///
2038 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2039 /// left is removed — the reference does the same, so a script can rely on
2040 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2041 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2042 let entry = self.fd_handlers.entry(fd).or_default();
2043 if readable {
2044 entry.read = callback;
2045 } else {
2046 entry.write = callback;
2047 }
2048 if entry.read.is_none() && entry.write.is_none() {
2049 self.fd_handlers.remove(&fd);
2050 }
2051 }
2052
2053 /// Register or clear an `os.signal` handler.
2054 ///
2055 /// `None` removes it; the host separately restores the default disposition or sets
2056 /// ignore, because which of those happened is the script's choice (`null` versus
2057 /// `undefined`) and not something this table can express.
2058 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2059 match handler {
2060 Some(handler) => {
2061 self.signal_handlers.insert(signal, handler);
2062 }
2063 None => {
2064 self.signal_handlers.remove(&signal);
2065 }
2066 }
2067 }
2068
2069 /// Run the handler for `signal`, reporting whether one ran.
2070 ///
2071 /// A throwing handler is reported and the loop continues, like a timer's.
2072 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2073 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2074 return Ok(false);
2075 };
2076 match self.call_value(handler, Value::Undefined, Vec::new()) {
2077 Ok(_) => {}
2078 Err(Signal::Throw(value)) => {
2079 let text = self.describe_exception(&value);
2080 self.timer_errors.push(text);
2081 }
2082 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2083 }
2084 self.drain_jobs()?;
2085 Ok(true)
2086 }
2087
2088 /// The descriptors the host has to poll, and in which direction.
2089 ///
2090 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2091 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2092 /// `os_poll` asks for.
2093 pub fn pending_fds(&self) -> Vec<FdInterest> {
2094 self.fd_handlers
2095 .iter()
2096 .map(|(fd, entry)| FdInterest {
2097 fd: *fd,
2098 read: entry.read.is_some(),
2099 write: entry.write.is_some(),
2100 })
2101 .collect()
2102 }
2103
2104 /// Call the handler registered for `fd`, reporting whether one ran.
2105 ///
2106 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2107 /// poll iteration and then restarts the loop, because the handler may have changed the
2108 /// registration list underneath it; doing the same here keeps a handler that
2109 /// unregisters itself from being called with stale state.
2110 ///
2111 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2112 /// every later one, exactly as with timers.
2113 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2114 let Some(entry) = self.fd_handlers.get(&fd) else {
2115 return Ok(false);
2116 };
2117 let callback = if readable {
2118 entry.read.clone()
2119 } else if writable {
2120 entry.write.clone()
2121 } else {
2122 None
2123 };
2124 let Some(callback) = callback else {
2125 return Ok(false);
2126 };
2127 self.drain_jobs()?;
2128 match self.call_value(callback, Value::Undefined, Vec::new()) {
2129 Ok(_) => {}
2130 Err(Signal::Throw(value)) => {
2131 let text = self.describe_exception(&value);
2132 self.timer_errors.push(text);
2133 }
2134 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2135 }
2136 self.drain_jobs()?;
2137 Ok(true)
2138 }
2139
2140 /// Take the errors timer callbacks threw, leaving the list empty.
2141 pub fn take_timer_errors(&mut self) -> Vec<String> {
2142 std::mem::take(&mut self.timer_errors)
2143 }
2144
2145 /// Whether anything is still pending: a microtask or a timer.
2146 pub fn has_pending_work(&self) -> bool {
2147 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2148 }
2149
2150 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2151 pub fn has_pending_timers_or_jobs(&self) -> bool {
2152 !self.jobs.is_empty() || !self.tasks.is_empty()
2153 }
2154
2155 /// Run every queued microtask, including ones queued while draining.
2156 pub fn drain_jobs(&mut self) -> JsResult<()> {
2157 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2158 // would spin forever, so the drain is bounded the way the call stack is.
2159 let mut budget = 1_000_000usize;
2160 while let Some(job) = self.jobs.pop_front() {
2161 if budget == 0 {
2162 return Err(Signal::Throw(
2163 self.make_error("InternalError", "promise job queue did not drain"),
2164 ));
2165 }
2166 budget -= 1;
2167 self.run_job(job)?;
2168 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2169 // engine may run script that the script itself did not ask for. Doing it here
2170 // rather than from a drop hook is what keeps the callback out of arbitrary
2171 // engine bookkeeping — see `builtins::weak`'s header.
2172 crate::builtins::weak::drain_finalizers(self)?;
2173 }
2174 // A script that queued no jobs may still have dropped targets, so the checkpoint
2175 // runs once more after the queue empties.
2176 crate::builtins::weak::drain_finalizers(self)?;
2177 Ok(())
2178 }
2179
2180 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2181 ///
2182 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2183 /// `None` and is swept out here. This is also where the realm learns that a registry
2184 /// died, which is why it is a mutation rather than a read.
2185 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2186 let handles = std::mem::take(&mut self.realm.finalization_registries);
2187 let mut live = Vec::with_capacity(handles.len());
2188 for handle in handles {
2189 let Some(object) = handle.upgrade() else {
2190 continue;
2191 };
2192 let Some(state) = object.finalization_state() else {
2193 continue;
2194 };
2195 live.push((object.clone(), *state));
2196 self.realm.finalization_registries.push(object.downgrade());
2197 }
2198 live
2199 }
2200
2201 /// Run one microtask.
2202 fn run_job(&mut self, job: Job) -> JsResult<()> {
2203 match job {
2204 Job::Reaction {
2205 handler: None,
2206 argument,
2207 rejected,
2208 promise,
2209 } => {
2210 // No handler: the settlement passes straight through to the derived
2211 // promise, which is why `p.catch(f)` ignores fulfilments.
2212 if rejected {
2213 self.reject_promise(&promise, argument);
2214 } else {
2215 self.fulfill_promise(&promise, argument);
2216 }
2217 Ok(())
2218 }
2219 Job::Reaction {
2220 handler: Some(handler),
2221 argument,
2222 promise,
2223 ..
2224 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2225 Ok(answer) => {
2226 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2227 self.reject_promise(&promise, error);
2228 }
2229 Ok(())
2230 }
2231 Err(Signal::Throw(reason)) => {
2232 self.reject_promise(&promise, reason);
2233 Ok(())
2234 }
2235 Err(other) => Err(other),
2236 },
2237 Job::Thenable {
2238 then,
2239 value,
2240 promise,
2241 } => {
2242 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2243 // the value it produces settles `promise`.
2244 // The thenable's `then` gets this promise's own pair, so whatever it
2245 // produces settles `promise`.
2246 let resolve = JsObject::function(
2247 self.heap,
2248 Some(self.realm.function_proto.clone()),
2249 Callable::PromiseResolve(promise.clone()),
2250 );
2251 let reject = JsObject::function(
2252 self.heap,
2253 Some(self.realm.function_proto.clone()),
2254 Callable::PromiseReject(promise.clone()),
2255 );
2256 match self.call_value(
2257 then,
2258 value,
2259 vec![Value::Object(resolve), Value::Object(reject)],
2260 ) {
2261 Ok(_) => Ok(()),
2262 Err(Signal::Throw(reason)) => {
2263 self.reject_promise(&promise, reason);
2264 Ok(())
2265 }
2266 Err(other) => Err(other),
2267 }
2268 }
2269 Job::Resume {
2270 coroutine,
2271 promise,
2272 kind,
2273 value,
2274 } => self.drive_async(&coroutine, &promise, kind, value),
2275 Job::GeneratorResume {
2276 generator,
2277 promise,
2278 kind,
2279 value,
2280 } => self.step_async_generator(&generator, &promise, kind, value),
2281 Job::Import {
2282 specifier,
2283 referrer,
2284 promise,
2285 } => {
2286 self.run_dynamic_import(&specifier, &referrer, &promise);
2287 Ok(())
2288 }
2289 }
2290 }
2291
2292 /// One element of a `Promise` combinator settled.
2293 ///
2294 /// The shared state object holds the results array, the number still outstanding, and
2295 /// the combinator's own resolve/reject pair. `all` fills by index so the answer keeps
2296 /// the input order; `race` settles on the first element and ignores the rest, which a
2297 /// one-shot settle gives for free.
2298 fn settle_combinator(
2299 &mut self,
2300 state: &Gc<JsObject>,
2301 index: usize,
2302 fulfilled: bool,
2303 value: Value,
2304 ) -> JsResult<()> {
2305 let kind = state
2306 .own_property("kind")
2307 .and_then(|property| property.value)
2308 .map(|value| value.to_int32())
2309 .unwrap_or(0);
2310 let outcome = state
2311 .own_property("outcome")
2312 .and_then(|property| property.value);
2313 let Some(Value::Object(outcome)) = outcome else {
2314 return Ok(());
2315 };
2316 if kind == 3 {
2317 // `race`: the first settlement wins; the rest are ignored by the one-shot rule.
2318 if fulfilled {
2319 self.resolve_promise_with(&outcome, value)?;
2320 } else {
2321 self.reject_promise(&outcome, value);
2322 }
2323 return Ok(());
2324 }
2325 let results = state
2326 .own_property("results")
2327 .and_then(|property| property.value)
2328 .and_then(|value| value.as_object().cloned());
2329 let remaining = state
2330 .own_property("remaining")
2331 .and_then(|property| property.value)
2332 .map(|value| value.to_int32())
2333 .unwrap_or(0);
2334 match kind {
2335 0 => {
2336 // `all`: the first rejection wins outright.
2337 if !fulfilled {
2338 self.reject_promise(&outcome, value);
2339 return Ok(());
2340 }
2341 let Some(results) = &results else {
2342 return Ok(());
2343 };
2344 results.array_set(self.heap, index, value);
2345 }
2346 1 => {
2347 // `allSettled`: never rejects; each slot records what happened.
2348 let Some(results) = &results else {
2349 return Ok(());
2350 };
2351 let record = self.new_object(Some(self.realm.object_proto.clone()));
2352 if fulfilled {
2353 record.define_data("status", self.string("fulfilled"));
2354 record.define_data("value", value);
2355 } else {
2356 record.define_data("status", self.string("rejected"));
2357 record.define_data("reason", value);
2358 }
2359 results.array_set(self.heap, index, Value::Object(record));
2360 }
2361 // `any`: the first fulfilment wins; a full sweep of rejections does not settle
2362 // here — it is handled by the count below.
2363 2 if fulfilled => {
2364 self.resolve_promise_with(&outcome, value)?;
2365 return Ok(());
2366 }
2367 _ => {}
2368 }
2369 let left = remaining - 1;
2370 state.define_data("remaining", Value::Int(left));
2371 if left != 0 {
2372 return Ok(());
2373 }
2374 match kind {
2375 0 | 1 => {
2376 let Some(results) = results else {
2377 return Ok(());
2378 };
2379 self.resolve_promise_with(&outcome, Value::Object(results))?;
2380 }
2381 2 => {
2382 let error = self.make_error("AggregateError", "all promises were rejected");
2383 self.reject_promise(&outcome, error);
2384 }
2385 _ => {}
2386 }
2387 Ok(())
2388 }
2389
2390 /// Build an async function's result: a promise whose body runs as a coroutine.
2391 pub fn new_async_function(
2392 &mut self,
2393 function: Value,
2394 this: Value,
2395 args: Vec<Value>,
2396 ) -> JsResult<Value> {
2397 let promise = self.new_promise();
2398 let coroutine = self.new_coroutine(function, this, args)?;
2399 if let Err(Signal::Throw(reason)) =
2400 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2401 {
2402 self.reject_promise(&promise, reason);
2403 }
2404 Ok(Value::Object(promise))
2405 }
2406
2407 /// The coroutine an async body runs in.
2408 ///
2409 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2410 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2411 /// than growing a second state machine. The difference is only in the ending — a
2412 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2413 /// Run `code` as an async function body, answering the promise it settles.
2414 ///
2415 /// Used for a module with top-level `await`: its body is an async function whose
2416 /// caller is the host, so there is no function object to pass through
2417 /// [`Interp::new_async_function`].
2418 pub fn run_async_body(
2419 &mut self,
2420 code: Gc<CompiledCode>,
2421 env: Gc<ClosureEnv>,
2422 this: Value,
2423 ) -> JsResult<Value> {
2424 let promise = self.new_promise();
2425 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2426 if let Err(Signal::Throw(reason)) =
2427 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2428 {
2429 self.reject_promise(&promise, reason);
2430 }
2431 Ok(Value::Object(promise))
2432 }
2433
2434 fn new_coroutine(
2435 &mut self,
2436 function: Value,
2437 this: Value,
2438 args: Vec<Value>,
2439 ) -> JsResult<Gc<JsObject>> {
2440 let Some(object) = function.as_object().cloned() else {
2441 return Err(self.type_error("not a function"));
2442 };
2443 let Some((code, env)) = bytecode_of(&object) else {
2444 return Err(self.type_error("not a function"));
2445 };
2446 self.new_coroutine_from(code, env, this, args)
2447 }
2448
2449 /// Build a coroutine over an already-resolved body.
2450 fn new_coroutine_from(
2451 &mut self,
2452 code: Gc<CompiledCode>,
2453 env: Gc<ClosureEnv>,
2454 this: Value,
2455 args: Vec<Value>,
2456 ) -> JsResult<Gc<JsObject>> {
2457 let function = Value::Undefined;
2458 self.push_frame(code, env, this, args, function)?;
2459 let frame = self.frames.pop().expect("push_frame just pushed it");
2460 let state = GeneratorState {
2461 frame: Some(frame),
2462 phase: GeneratorPhase::SuspendedStart,
2463 parked_on_await: false,
2464 parked_on_yield_star: false,
2465 requests: std::collections::VecDeque::new(),
2466 async_busy: false,
2467 };
2468 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2469 coroutine.with_mut(|data| {
2470 data.kind = ObjectKind::Generator(Box::new(state));
2471 });
2472 Ok(coroutine)
2473 }
2474
2475 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2476 /// `await` and `value` is what it awaited.
2477 fn resume_coroutine(
2478 &mut self,
2479 coroutine: &Gc<JsObject>,
2480 kind: ResumeKind,
2481 value: Value,
2482 ) -> JsResult<(Value, bool)> {
2483 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2484 ObjectKind::Generator(state) => Some(std::mem::replace(
2485 state.as_mut(),
2486 GeneratorState {
2487 frame: None,
2488 phase: GeneratorPhase::Executing,
2489 parked_on_await: false,
2490 parked_on_yield_star: false,
2491 requests: std::collections::VecDeque::new(),
2492 async_busy: false,
2493 },
2494 )),
2495 _ => None,
2496 }) else {
2497 return Err(self.type_error("not a coroutine"));
2498 };
2499 let result = self.step_generator(&mut state, kind, value);
2500 coroutine.with_mut(|data| {
2501 data.kind = ObjectKind::Generator(Box::new(state));
2502 });
2503 let (value, done, _ready, _reason) = result?;
2504 Ok((value, done))
2505 }
2506
2507 /// Advance an async body and settle its promise with the outcome.
2508 fn drive_async(
2509 &mut self,
2510 coroutine: &Gc<JsObject>,
2511 promise: &Gc<JsObject>,
2512 kind: ResumeKind,
2513 value: Value,
2514 ) -> JsResult<()> {
2515 match self.resume_coroutine(coroutine, kind, value) {
2516 Ok((value, true)) => {
2517 // `Ok` with `done` means the body finished *normally*, even when it was
2518 // resumed by a `throw` — `try { await p } catch {}` completes by
2519 // returning. Only the `Err` arm below is a rejection.
2520 //
2521 // Resolving rather than fulfilling matters: `return promise` in an async
2522 // body adopts the inner promise, so `async function f(){ return
2523 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2524 // promise.
2525 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2526 self.reject_promise(promise, reason);
2527 }
2528 Ok(())
2529 }
2530 Ok((value, false)) => {
2531 // Parked on `await`: follow what it awaited and resume with the outcome.
2532 let awaited = match self.promise_resolve_value(value) {
2533 Ok(awaited) => awaited,
2534 Err(Signal::Throw(error)) => {
2535 self.reject_promise(promise, error);
2536 return Ok(());
2537 }
2538 Err(other) => return Err(other),
2539 };
2540 self.hook_await(awaited, coroutine, promise)
2541 }
2542 Err(Signal::Throw(reason)) => {
2543 self.reject_promise(promise, reason);
2544 Ok(())
2545 }
2546 Err(other) => Err(other),
2547 }
2548 }
2549
2550 /// Arrange for `coroutine` to resume when `awaited` settles.
2551 fn hook_await(
2552 &mut self,
2553 awaited: Value,
2554 coroutine: &Gc<JsObject>,
2555 promise: &Gc<JsObject>,
2556 ) -> JsResult<()> {
2557 let resumed = JsObject::function(
2558 self.heap,
2559 Some(self.realm.function_proto.clone()),
2560 Callable::AwaitResume {
2561 coroutine: coroutine.clone(),
2562 promise: promise.clone(),
2563 kind: ResumeKind::Next,
2564 },
2565 );
2566 let raised = JsObject::function(
2567 self.heap,
2568 Some(self.realm.function_proto.clone()),
2569 Callable::AwaitResume {
2570 coroutine: coroutine.clone(),
2571 promise: promise.clone(),
2572 kind: ResumeKind::Throw,
2573 },
2574 );
2575 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2576 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2577 let Value::Object(awaited) = &awaited else {
2578 self.jobs.push_back(Job::Resume {
2579 coroutine: coroutine.clone(),
2580 promise: promise.clone(),
2581 kind: ResumeKind::Next,
2582 value: awaited,
2583 });
2584 return Ok(());
2585 };
2586 self.perform_then(
2587 awaited,
2588 Some(Value::Object(resumed)),
2589 Some(Value::Object(raised)),
2590 )?;
2591 Ok(())
2592 }
2593
2594 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2595 /// things an engine keeps outside it — array elements and an array's `length`.
2596 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2597 if let Some(property) = object.own_property_key(key) {
2598 return Some(property);
2599 }
2600 // An array's elements live in their own vector rather than the property table, so
2601 // a descriptor for one has to be synthesized — with the attributes an element has.
2602 if let Some(index) = key.as_str().and_then(array_index)
2603 && let Some(value) = object.array_get(index as usize)
2604 && !matches!(value, Value::Hole)
2605 {
2606 return Some(Property::data(value));
2607 }
2608 // `length` is an own property of an array that is not in its property table
2609 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2610 // and non-enumerable.
2611 if key.as_str() == Some("length")
2612 && let Some(length) = object.array_length()
2613 {
2614 return Some(Property {
2615 value: Some(crate::object::length_value(length)),
2616 writable: object.length_writable(),
2617 enumerable: false,
2618 configurable: false,
2619 getter: None,
2620 setter: None,
2621 });
2622 }
2623 None
2624 }
2625
2626 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2627 pub fn object_get_own_property(
2628 &mut self,
2629 object: &Gc<JsObject>,
2630 key: &PropertyKey,
2631 ) -> JsResult<Option<Property>> {
2632 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2633 return Ok(answer);
2634 }
2635 if let Some(exotic) = object.exotic()
2636 && let Some(answer) = exotic.get_own_property(self, object, key)?
2637 {
2638 return Ok(answer);
2639 }
2640 Ok(Self::ordinary_own_property(object, key))
2641 }
2642
2643 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2644 pub fn object_define_own_property(
2645 &mut self,
2646 object: &Gc<JsObject>,
2647 key: &PropertyKey,
2648 property: Property,
2649 ) -> JsResult<bool> {
2650 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2651 return Ok(accepted);
2652 }
2653 // A host class that intercepts definitions owns the attributes of the properties it
2654 // defines: `_class`-style storage on the native side is the usual reason.
2655 if let Some(exotic) = object.exotic()
2656 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
2657 {
2658 return Ok(accepted);
2659 }
2660 // An array index is stored in the element vector, which can hold a plain value and
2661 // nothing else. An accessor — or a data property with non-default attributes —
2662 // therefore has to live in the property table, and the element slot is blanked so
2663 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2664 // {get})` stored the accessor where no read ever looked, and the array kept
2665 // answering its old value.
2666 // An array's `length` is not stored in the property table, so defining it has to
2667 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2668 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2669 // {value: 1})` reported success and changed nothing.
2670 if key.as_str() == Some("length") && object.is_array() {
2671 // `{writable: false}` on `length` does not change the length, but it does make
2672 // it read-only — after which neither a later `{writable: true}` nor a store
2673 // past the end may succeed.
2674 if property.value.is_none() {
2675 if !object.length_writable() && property.writable {
2676 return Ok(false);
2677 }
2678 object.set_length_writable(property.writable);
2679 return Ok(true);
2680 }
2681 if !object.length_writable() {
2682 return Ok(false);
2683 }
2684 }
2685 if key.as_str() == Some("length")
2686 && object.is_array()
2687 && let Some(value) = property.value.clone()
2688 {
2689 let requested = value.to_number();
2690 let valid = requested.is_finite()
2691 && requested >= 0.0
2692 && requested.fract() == 0.0
2693 && requested <= u32::MAX as f64;
2694 if !valid {
2695 return Err(self.range_error("invalid array length"));
2696 }
2697 // Truncating deletes the elements above the new length, and a non-configurable
2698 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2699 // makes `a.length = 2` fail rather than quietly drop it.
2700 let current = object.array_length().unwrap_or(0);
2701 let requested = requested as usize;
2702 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2703 return Ok(false);
2704 }
2705 object.array_set_length(self.heap, requested);
2706 return Ok(true);
2707 }
2708 let plain = property.writable
2709 && property.enumerable
2710 && property.configurable
2711 && !property.is_accessor();
2712 if let Some(index) = key.as_str().and_then(array_index)
2713 && object.is_array()
2714 {
2715 // Growing the array needs a writable `length`: after
2716 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2717 // be added.
2718 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2719 return Ok(false);
2720 }
2721 if plain && property.value.is_some() {
2722 // An ordinary element: the vector is where a read looks first, so it has
2723 // to be the vector that changes — unless the index is too far out to be
2724 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2725 // one property, because past its own limit it stores the index as an
2726 // ordinary key. Falling through to `define_key` below is the same choice,
2727 // and the alternative was worse: the store used to be *dropped* and the
2728 // length left at 0, which is a silent wrong answer.
2729 let value = property.value.clone().unwrap_or(Value::Undefined);
2730 object.delete_key(key);
2731 if object.array_set(self.heap, index as usize, value) {
2732 return Ok(true);
2733 }
2734 // Past the dense limit the element lives in the table like any property.
2735 object.note_element_descriptor();
2736 object.define_key(key, property);
2737 // A sparse store past the dense limit still extends `length`, which is what
2738 // `a[a.length] = v` relies on — but only extends: shortening would delete
2739 // the sparse properties above the index, including this one.
2740 if index as usize + 1 > object.array_length().unwrap_or(0) {
2741 object.array_set_length(self.heap, index as usize + 1);
2742 }
2743 return Ok(true);
2744 }
2745 // A non-plain element — an accessor, or an attribute that is not the default —
2746 // lives in the table while the slot becomes a hole. Recording it keeps every
2747 // later `a[i] = v` off the dense path, where the write would have shadowed the
2748 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
2749 // replace the accessor with a plain data property.
2750 object.note_element_descriptor();
2751 object.define_key(key, property);
2752 // The slot stays, so `length` does not shrink; a hole is not an element, so
2753 // the table entry is now what a read finds.
2754 object.array_set(self.heap, index as usize, Value::Hole);
2755 return Ok(true);
2756 }
2757 object.define_key(key, property);
2758 Ok(true)
2759 }
2760
2761 /// Build a proxy object over `target`, with its traps read from `handler`.
2762 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2763 JsObject::proxy(self.heap, target, handler)
2764 }
2765
2766 /// The `revoke` function for a proxy's slots.
2767 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2768 JsObject::function(
2769 self.heap,
2770 Some(self.realm.function_proto.clone()),
2771 Callable::Revoker(slots),
2772 )
2773 }
2774
2775 /// A new array.
2776 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2777 let array = JsObject::array(
2778 self.heap,
2779 Some(self.realm.array_proto.clone()),
2780 elements.len(),
2781 );
2782 for (index, element) in elements.into_iter().enumerate() {
2783 array.array_set(self.heap, index, element);
2784 }
2785 array
2786 }
2787
2788 /// A new native function object.
2789 ///
2790 /// The observable `name` and `length` are installed as properties here, which is
2791 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2792 /// so `f.name = "x"` behaves like the writable property it is.
2793 /// A native constructor that builds its own instance after validating its arguments.
2794 ///
2795 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2796 /// check runs before `new.target.prototype` is read.
2797 pub fn new_native_ctor(
2798 &self,
2799 name: impl Into<String>,
2800 length: u32,
2801 func: NativeFn,
2802 ) -> Gc<JsObject> {
2803 let function = JsObject::function(
2804 self.heap,
2805 Some(self.realm.function_proto.clone()),
2806 Callable::Native {
2807 func,
2808 own_instance: true,
2809 },
2810 );
2811 function.set_constructible(true);
2812 function.define(
2813 "length",
2814 Property::name_or_length(Value::Int(length as i32)),
2815 );
2816 function.define("name", Property::name_or_length(self.string(name)));
2817 function
2818 }
2819
2820 /// A native constructor that lets `new` build the instance first.
2821 ///
2822 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
2823 /// validation that must precede reading `new.target.prototype`, so the object can be
2824 /// created before the implementation runs. Distinct from [`Interp::new_native`],
2825 /// which makes a *method* and therefore not a constructor at all.
2826 pub fn new_native_constructor(
2827 &self,
2828 name: impl Into<String>,
2829 length: u32,
2830 func: NativeFn,
2831 ) -> Gc<JsObject> {
2832 let function = self.new_native(name, length, func);
2833 function.set_constructible(true);
2834 function
2835 }
2836
2837 /// A new host function object: a native closure that carries its own state.
2838 ///
2839 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
2840 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
2841 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
2842 /// this safe: the closure must not capture a `Gc`.
2843 pub fn new_host_function(
2844 &self,
2845 name: impl Into<String>,
2846 length: u32,
2847 func: crate::object::HostFn,
2848 ) -> Gc<JsObject> {
2849 self.new_host_inner(name.into(), length, func, false)
2850 }
2851
2852 /// A host constructor: `new` hands it `this = undefined`, so it validates its
2853 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
2854 pub fn new_host_ctor(
2855 &self,
2856 name: impl Into<String>,
2857 length: u32,
2858 func: crate::object::HostFn,
2859 ) -> Gc<JsObject> {
2860 let function = self.new_host_inner(name.into(), length, func, true);
2861 function.set_constructible(true);
2862 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
2863 // installs its own methods on it, so it starts as a plain object.
2864 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
2865 function.define(
2866 "prototype",
2867 Property {
2868 value: Some(Value::Object(proto)),
2869 writable: true,
2870 enumerable: false,
2871 configurable: false,
2872 ..Property::default()
2873 },
2874 );
2875 function
2876 }
2877
2878 fn new_host_inner(
2879 &self,
2880 name: String,
2881 length: u32,
2882 func: crate::object::HostFn,
2883 own_instance: bool,
2884 ) -> Gc<JsObject> {
2885 let function = JsObject::function(
2886 self.heap,
2887 Some(self.realm.function_proto.clone()),
2888 Callable::Host {
2889 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
2890 own_instance,
2891 },
2892 );
2893 function.define(
2894 "length",
2895 Property::name_or_length(Value::Int(length as i32)),
2896 );
2897 function.define("name", Property::name_or_length(self.string(name)));
2898 function
2899 }
2900
2901 /// A new native function object.
2902 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
2903 let function = JsObject::function(
2904 self.heap,
2905 Some(self.realm.function_proto.clone()),
2906 Callable::Native {
2907 func,
2908 own_instance: false,
2909 },
2910 );
2911 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
2912 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
2913 // `length,name` and this listed `name,length`. A bytecode function already gets it
2914 // the right way round; only native ones were built backwards.
2915 function.define(
2916 "length",
2917 Property::name_or_length(Value::Int(length as i32)),
2918 );
2919 function.define("name", Property::name_or_length(self.string(name)));
2920 function
2921 }
2922
2923 /// A new bound function.
2924 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
2925 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
2926 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
2927 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
2928 let constructible = target
2929 .as_object()
2930 .is_some_and(|target| target.is_constructor());
2931 let bound = JsObject::function(
2932 self.heap,
2933 Some(self.realm.function_proto.clone()),
2934 Callable::Bound { target, this, args },
2935 );
2936 bound.set_constructible(constructible);
2937 bound
2938 }
2939
2940 /// A new reference cell.
2941 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
2942 Gc::new(self.heap, Cell::new(value))
2943 }
2944
2945 // -- running ------------------------------------------------------------
2946
2947 /// Evaluate `code` as a script body and return its completion value.
2948 /// Compile and run `source` for the engine's own use, returning its completion value.
2949 ///
2950 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
2951 /// needs to be a real async function, and the engine already runs those as coroutines,
2952 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
2953 ///
2954 /// Differences from [`Self::eval_in_global`], both deliberate:
2955 ///
2956 /// * It does **not** drain the microtask queue. Install runs while the realm is still
2957 /// being built, and the source is an IIFE that only constructs a closure, so there
2958 /// is nothing to drain — and draining here would run script-queued jobs in the
2959 /// middle of `install`.
2960 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
2961 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
2962 /// and it should not look like the user wrote something wrong.
2963 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
2964 let program = match js_parse::parse_script(source) {
2965 Ok(program) => program,
2966 Err(error) => {
2967 let message = format!("builtin source does not parse: {error}");
2968 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2969 }
2970 };
2971 let mut code = match js_compile::compile_script(&program) {
2972 Ok(code) => code,
2973 Err(error) => {
2974 let message = format!("builtin source does not compile: {}", error.message);
2975 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2976 }
2977 };
2978 // The frame has to name something, and `<builtin>` is what a stack trace through
2979 // this code should say.
2980 code.set_filename("<builtin>");
2981 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2982 let closure_vars = compiled.code.closure_vars.clone();
2983 let env = self.global_env(&closure_vars);
2984 let this = Value::Object(self.realm.global.clone());
2985 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
2986 }
2987
2988 /// Run an already-parsed script and drain the microtasks it queued.
2989 ///
2990 /// The drain is what lets an `async` function's body advance past its first `await`
2991 /// before the host sees the result: nothing else pumps the job queue.
2992 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
2993 let this = Value::Object(self.realm.global.clone());
2994 self.run_script_with_this(code, this)
2995 }
2996
2997 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
2998 ///
2999 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3000 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3001 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3002 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3003 /// state the next script evaluation tripped over.
3004 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3005 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3006 let closure_vars = compiled.code.closure_vars.clone();
3007 let env = self.global_env(&closure_vars);
3008 let callee = Value::Undefined;
3009 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3010 // The script is done, so the microtasks it queued run before the host sees the
3011 // result. Without this an `async` function's body would never advance past its
3012 // first `await`, because nothing else drains the queue.
3013 self.drain_jobs()?;
3014 Ok(result)
3015 }
3016
3017 /// Compile and run `source` in global scope, returning its completion value.
3018 ///
3019 /// This is what `eval` and `new Function` use. Running it as a script means it
3020 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3021 /// for a `Function` body; a *direct* eval that reads a local variable would need
3022 /// the compiler to hand its variable environment over, which is not implemented.
3023 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3024 self.eval_in_global_named(source, EVAL_FILE, false)
3025 }
3026
3027 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3028 ///
3029 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3030 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3031 /// through the code, so they cannot share one constant.
3032 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3033 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3034 }
3035
3036 /// Evaluate `source` as a global script, reported under `file`.
3037 ///
3038 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3039 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3040 /// from inside a C callback, where the interpreter is the running one rather than a
3041 /// context's own.
3042 pub fn eval_in_global_named(
3043 &mut self,
3044 source: &str,
3045 file: &str,
3046 barrier: bool,
3047 ) -> JsResult<Value> {
3048 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3049 // eval-created global binding — configurable, unlike a script's own `var`.
3050 self.eval_depth += 1;
3051 if barrier {
3052 let depth = self.frames.len();
3053 self.trace_barriers.push(depth);
3054 }
3055 let result = self.eval_in_global_inner(source, file);
3056 if barrier {
3057 self.trace_barriers.pop();
3058 }
3059 self.eval_depth -= 1;
3060 result
3061 }
3062
3063 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3064 let compiled = self.compile_global_script(source, file, false)?;
3065 let strict = compiled.strict;
3066 self.run_eval_script(compiled, strict)
3067 }
3068
3069 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3070 ///
3071 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3072 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3073 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3074 /// direct eval's is.
3075 pub fn eval_script_with_this(
3076 &mut self,
3077 source: &str,
3078 file: &str,
3079 this: Value,
3080 ) -> JsResult<Value> {
3081 let program = match js_parse::parse_script(source) {
3082 Ok(program) => program,
3083 Err(error) => {
3084 return Err(Signal::Throw(self.syntax_error_at(
3085 file,
3086 error.span.start.line,
3087 error.span.start.column,
3088 &error.message,
3089 )));
3090 }
3091 };
3092 let mut compiled = match js_compile::compile_script(&program) {
3093 Ok(compiled) => compiled,
3094 Err(error) => {
3095 return Err(Signal::Throw(self.syntax_error_at(
3096 file,
3097 error.span.start.line,
3098 error.span.start.column,
3099 &error.message,
3100 )));
3101 }
3102 };
3103 compiled.set_filename(file);
3104 self.run_script_with_this(compiled, this)
3105 }
3106
3107 /// Parse and compile `source` as a global script, without running it.
3108 ///
3109 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3110 /// before a promise exists to reject — while still evaluating in the same eval context
3111 /// (direct-eval strictness, `new.target`, `super`).
3112 fn compile_global_script(
3113 &mut self,
3114 source: &str,
3115 file: &str,
3116 async_body: bool,
3117 ) -> JsResult<CompiledFunction> {
3118 // A *direct* eval inherits the strictness of the code that called it, which is
3119 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3120 // implicit global. The caller's frame is the innermost one here, because a
3121 // native function does not push a frame of its own.
3122 let strict = self.current_strict();
3123 // `eval` runs in the caller's function context, so `new.target` is legal here
3124 // even though the source is a bare script — and so is `super.x` when the caller
3125 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3126 // caller's, which is what `special_object 4` already does.
3127 let context = js_parse::EvalContext {
3128 in_method: self.enclosing_home_object().is_some(),
3129 // `super()` belongs to a derived constructor, and an eval'd body is not a
3130 // constructor at all: the caller frame's `this` is already built.
3131 in_derived_constructor: false,
3132 };
3133 // A *global* eval is not a function body: `new.target` and `super` are out of
3134 // reach there. Its `{async: true}` form differs in the other direction — the body
3135 // may `await` — so the two flags are independent and the reference sets both from
3136 // the eval type rather than from the caller.
3137 let parsed = if async_body {
3138 js_parse::parse_suspensible_global_eval(source, strict)
3139 } else {
3140 js_parse::parse_eval_script_in(source, strict, context)
3141 };
3142 let program = match parsed {
3143 Ok(program) => program,
3144 Err(error) => {
3145 // The message is bare: the position lives in `fileName`,
3146 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3147 // the reference puts it. An `invalid source: L:C: ` prefix made
3148 // `e.message` differ from the reference while the stack already agreed.
3149 return Err(Signal::Throw(self.syntax_error_at(
3150 file,
3151 error.span.start.line,
3152 error.span.start.column,
3153 &error.message,
3154 )));
3155 }
3156 };
3157 let mut compiled = match if async_body {
3158 js_compile::compile_script_suspensible(&program)
3159 } else {
3160 js_compile::compile_script(&program)
3161 } {
3162 Ok(compiled) => compiled,
3163 // A construct the compiler does not handle yet is reported the same way a
3164 // parse error is: it happens before anything runs, so the trace is the
3165 // position in the source followed by the caller.
3166 Err(error) => {
3167 return Err(Signal::Throw(self.syntax_error_at(
3168 file,
3169 error.span.start.line,
3170 error.span.start.column,
3171 &error.message,
3172 )));
3173 }
3174 };
3175 compiled.set_filename(file);
3176 Ok(compiled)
3177 }
3178
3179 /// Run an `eval`'d script in the caller's scope.
3180 ///
3181 /// Three things have to come from the calling frame, because the eval'd code is a
3182 /// script and would otherwise see only the global object:
3183 ///
3184 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3185 /// * `arguments`, exposed as a binding of the eval's own scope, so
3186 /// `f("arguments.length", 1)` sees the caller's arguments;
3187 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3188 /// `eval("var v = 1")` into the global object.
3189 ///
3190 /// Locals of the calling function are *not* reachable: that needs the compiler to
3191 /// hand its variable environment over, which this milestone does not do.
3192 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3193 // `this` and `arguments` come from the innermost frame only — those are not
3194 // lexical — while the name bindings come from the whole chain of frames, part
3195 // of it being ordinary scope resolution.
3196 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3197 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3198 // read from its closure.
3199 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3200 // variable environment is the innermost frame of all: an arrow's own body is where
3201 // `var`s declared by an `eval` inside it belong.
3202 let caller_index = self
3203 .frames
3204 .iter()
3205 .rposition(|frame| !frame.code.code.is_arrow)
3206 .or_else(|| self.frames.len().checked_sub(1));
3207 let env_index = self.frames.len().checked_sub(1);
3208 let caller = caller_index.and_then(|index| self.frames.get(index));
3209 let (this, passed) = match caller {
3210 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3211 // No frame at all: the eval is running at the top level, so there is
3212 // nothing to inherit and the global receiver is right.
3213 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3214 };
3215 // Innermost frame first, so the first binding found for a name is the one that
3216 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3217 let mut bindings: Vec<EvalBinding> = Vec::new();
3218 // The calling function's own bindings, resolved by the compiler at the call
3219 // site. That table is the only reliable answer when a name is declared twice in
3220 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3221 // body means, and guessing by declaration order picks the wrong one as soon as
3222 // two loops in a row use the same name.
3223 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3224 // every direct call — a bare `eval(...)` callee — so finding one at the current
3225 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3226 // callee to a value first and leave no site behind.
3227 let mut direct = false;
3228 let mut resolved_here = false;
3229 if let Some(frame) = self.frames.last() {
3230 let (line, column) = frame
3231 .code
3232 .code
3233 .position_at(frame.at as u32)
3234 .unwrap_or_default();
3235 // The nearest site at or before the current position, not an exact match:
3236 // the recorded position of the `call` instruction is the callee's, which
3237 // sits a few columns inside the call expression the compiler recorded. A
3238 // site is unique per call, so "the closest one behind us" identifies it.
3239 if let Some(site) = frame
3240 .code
3241 .code
3242 .eval_sites
3243 .iter()
3244 .filter(|site| (site.line, site.column) <= (line, column))
3245 .max_by_key(|site| (site.line, site.column))
3246 {
3247 direct = true;
3248 resolved_here = true;
3249 for binding in &site.bindings {
3250 // An enclosing function's frame sits `owner` levels below the one
3251 // running the call.
3252 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3253 else {
3254 continue;
3255 };
3256 bindings.push(EvalBinding {
3257 name: binding.name.clone(),
3258 frame,
3259 slot: if binding.is_arg {
3260 EvalSlot::Arg
3261 } else {
3262 EvalSlot::Local
3263 },
3264 index: binding.index as usize,
3265 });
3266 }
3267 }
3268 }
3269 for frame_index in (0..self.frames.len()).rev() {
3270 // Skip the innermost frame's flat scan when the compiler already answered
3271 // for it; an enclosing frame still needs one, because the eval resolves
3272 // those names dynamically.
3273 if resolved_here && frame_index == self.frames.len() - 1 {
3274 continue;
3275 }
3276 let frame = &self.frames[frame_index];
3277 for (index, arg) in frame.code.code.args.iter().enumerate() {
3278 bindings.push(EvalBinding {
3279 name: arg.name.clone(),
3280 frame: frame_index,
3281 slot: EvalSlot::Arg,
3282 index,
3283 });
3284 }
3285 for (index, local) in frame.code.code.vars.iter().enumerate() {
3286 bindings.push(EvalBinding {
3287 name: local.name.clone(),
3288 frame: frame_index,
3289 slot: EvalSlot::Local,
3290 index,
3291 });
3292 }
3293 }
3294 let mut seen = BTreeSet::new();
3295 bindings.retain(|binding| seen.insert(binding.name.clone()));
3296
3297 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3298 // elements is all the spec's ordinary uses need.
3299 //
3300 // Known divergence: this is bound for a *global* eval too, where there is no
3301 // caller and the reference throws `'arguments' is not defined`. Deciding properly
3302 // needs "does the calling frame have an `arguments` of its own", which is not
3303 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3304 // script or eval body does not, and `eval(b)` passes the callee as a value so even
3305 // the call-site detection does not answer it. Modelled as a binding in the caller's
3306 // variable environment, this would fall out; that is a larger change than the one
3307 // this comment is attached to.
3308 let arguments = Value::Object(self.new_array(passed));
3309
3310 // Only a *strict* eval gets a variable environment of its own. A sloppy one
3311 // declares its `var`s in the caller's — which for a top-level eval is the global
3312 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3313 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3314 // vanish into a scope nobody reads back from.
3315 let previous_scope = if code_strict {
3316 self.eval_scope.replace(BTreeMap::new())
3317 } else {
3318 None
3319 };
3320 let previous_arguments = self.eval_arguments.replace(arguments);
3321 let previous_with = self.eval_with.replace(self.with_objects());
3322 let inherited_new_target = self
3323 .frames
3324 .iter()
3325 .rev()
3326 .find(|frame| !frame.code.code.is_arrow)
3327 .map(|frame| frame.new_target.clone());
3328 let previous_new_target = self
3329 .eval_new_target
3330 .replace(inherited_new_target.unwrap_or(Value::Undefined));
3331 let eval_cells = self.eval_cells_for(&bindings);
3332 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3333 // A sloppy direct eval declares its `var`s in the caller's variable environment;
3334 // `declare_eval_local` needs to know which frame that is.
3335 // An indirect eval gets the global environment, so nothing of the caller's is
3336 // recorded as the place its `var`s belong.
3337 let previous_caller = self
3338 .eval_caller
3339 .replace(if direct { env_index } else { None });
3340 // The cell-based view of the same bindings, which is what a closure created
3341 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3342 // whose compiler did not put a binding in a cell simply does not appear here —
3343 // reads and writes still work through `eval_bindings`, they just cannot outlive
3344 // the eval.
3345 let previous_eval_scope = self
3346 .active_eval_scope
3347 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3348 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3349 let closure_vars = compiled.code.closure_vars.clone();
3350 let env = self.global_env(&closure_vars);
3351 let callee = Value::Undefined;
3352 // An async body does not run here: it becomes a coroutine and answers a promise,
3353 // which is what makes `await` legal in it. `this` still has to be the caller's
3354 // (for a global eval, the global object), because `this` is not part of `await`.
3355 let result = if compiled.code.kind.is_async() {
3356 self.run_async_body(compiled, env, this)
3357 } else {
3358 self.execute(compiled, env, this, Vec::new(), callee)
3359 };
3360 self.eval_scope = previous_scope;
3361 self.eval_arguments = previous_arguments;
3362 self.eval_with = previous_with;
3363 self.eval_new_target = previous_new_target;
3364 self.eval_bindings = previous_bindings;
3365 self.eval_caller = previous_caller;
3366 self.active_eval_scope = previous_eval_scope;
3367 result
3368 }
3369
3370 /// The cell-backed subset of `bindings`, in the same priority order.
3371 ///
3372 /// Both lookup routes have to agree — the eval's own reads go through
3373 /// [`Interp::eval_binding_value`] and the closures it builds go through
3374 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3375 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3376 /// is not in a cell simply does not appear: reads and writes still work, they just
3377 /// cannot be handed to a closure that outlives the eval.
3378 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3379 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3380 for binding in bindings {
3381 let Some(frame) = self.frames.get(binding.frame) else {
3382 continue;
3383 };
3384 let cell = match binding.slot {
3385 EvalSlot::Arg => frame
3386 .code
3387 .arg_cell
3388 .get(binding.index)
3389 .copied()
3390 .unwrap_or(-1),
3391 EvalSlot::Local => frame
3392 .code
3393 .loc_cell
3394 .get(binding.index)
3395 .copied()
3396 .unwrap_or(-1),
3397 };
3398 if cell < 0 {
3399 continue;
3400 }
3401 if let Some(cell) = frame.cells.get(cell as usize) {
3402 names.push((binding.name.clone(), cell.clone()));
3403 }
3404 }
3405 names
3406 }
3407
3408 /// A `SyntaxError` that reports where in the source it happened.
3409 ///
3410 /// Compile-time failures never run, so they have no frame of their own; the
3411 /// reference still puts the position first in the trace, with no function name and
3412 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3413 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3414 /// reference borrows), which is how a script reads the position without parsing
3415 /// the trace.
3416 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3417 ///
3418 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3419 /// `columnNumber`, which is how the reference prints one. A positionless error
3420 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3421 /// the reference raises it from `js_resolve_module`, where there is no position.
3422 pub(crate) fn syntax_error_plain(
3423 &mut self,
3424 error: &js_parse::SyntaxError,
3425 file: &str,
3426 ) -> Value {
3427 if error.positionless {
3428 return self.make_error("SyntaxError", &error.message);
3429 }
3430 self.syntax_error_at(
3431 file,
3432 error.span.start.line,
3433 error.span.start.column,
3434 &error.message,
3435 )
3436 }
3437
3438 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3439 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
3440 let value = self.make_error("SyntaxError", message);
3441 if let Value::Object(object) = &value {
3442 let text = self.string(blamed);
3443 object.define("stack", Property::with_attributes(text, true, true));
3444 let name = self.string(file);
3445 object.define("fileName", Property::with_attributes(name, true, true));
3446 object.define(
3447 "lineNumber",
3448 Property::with_attributes(Value::Int(line as i32), true, true),
3449 );
3450 object.define(
3451 "columnNumber",
3452 Property::with_attributes(Value::Int(column as i32), true, true),
3453 );
3454 }
3455 value
3456 }
3457
3458 /// Run a compiled script whose completion value is a function, returning it.
3459 ///
3460 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3461 /// get the closure out, which keeps the constant-pool plumbing in one place.
3462 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3463 self.run_script(code)
3464 }
3465
3466 /// The environment of a script or of any function compiled at global scope:
3467 /// every entry is a global binding, so each one resolves to the realm's cell.
3468 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3469 let mut cells = Vec::with_capacity(closure_vars.len());
3470 for closure_var in closure_vars {
3471 let cell = match closure_var.closure_type {
3472 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3473 if closure_var.is_lexical =>
3474 {
3475 // A lexical declaration: the cell is created here holding the
3476 // dead-zone marker, which is what makes the binding exist and
3477 // unreadable before its initialiser runs.
3478 self.declare_global(&closure_var.name, closure_var.is_const);
3479 self.realm.globals[&closure_var.name].clone()
3480 }
3481 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3482 // A `var` or function declaration becomes a property of the global
3483 // object, and it exists from here on — which is why
3484 // `print(v); var v = 1` prints `undefined` instead of raising.
3485 // Declaring it at instantiation time (rather than at the
3486 // initialiser) is also what makes it non-configurable: the store
3487 // then lands on an existing property instead of creating one.
3488 self.declare_var_global(&closure_var.name);
3489 // The cell is a placeholder that nothing indexes; it cannot be
3490 // omitted because the slot has to hold something.
3491 self.new_cell(Value::Undefined)
3492 }
3493 _ => {
3494 // An undeclared global is read by name; the cell is a
3495 // placeholder that nothing indexes.
3496 self.new_cell(Value::Undefined)
3497 }
3498 };
3499 cells.push(cell);
3500 }
3501 Gc::new(
3502 self.heap,
3503 ClosureEnv {
3504 cells,
3505 eval_scope: None,
3506 local_vars: None,
3507 local_phase: 1,
3508 },
3509 )
3510 }
3511
3512 /// Push a frame and run until it returns.
3513 pub(crate) fn execute(
3514 &mut self,
3515 code: Gc<CompiledCode>,
3516 env: Gc<ClosureEnv>,
3517 this: Value,
3518 args: Vec<Value>,
3519 callee: Value,
3520 ) -> JsResult<Value> {
3521 let depth = self.frames.len();
3522 if depth == 0 {
3523 // A throw that reached the host ends the *active* mode: the next one is catchable
3524 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3525 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3526 // for the throw that evaluation will raise.
3527 self.uncatchable = false;
3528 }
3529 self.push_frame(code, env, this, args, callee)?;
3530 loop {
3531 // The fast loop first: it runs whole runs of records with `pc` in a register.
3532 //
3533 // `step`'s `pc` lives in the frame, so every instruction writes it back and
3534 // reads it again — a store, a load and two bounds checks that a loop body does
3535 // not need, because nothing outside the loop can run in between. This is the
3536 // classic split: advance a register, and only spill it when leaving.
3537 //
3538 // `Some(value)` means the function ended by running off the end of its
3539 // instruction array, which is a normal return.
3540 let step = match self.run_fast() {
3541 Ok(Some(value)) => Ok(Step::Return(value)),
3542 Ok(None) => self.step(),
3543 Err(signal) => Err(signal),
3544 };
3545 match step {
3546 Ok(Step::Continue) => {}
3547 Ok(Step::Return(value)) => {
3548 self.pop_frame();
3549 // A frame that ended in a `tail_call` hands its value straight to
3550 // its caller: nothing after the call can run, so every frame above
3551 // the callee unwinds with the same value. See [`Frame::tail`] —
3552 // the reference does not reuse frames either, so recursion depth
3553 // and the stack-overflow limit behave the same way.
3554 while self.frames.len() > depth && self.frame().tail {
3555 self.pop_frame();
3556 }
3557 if self.frames.len() == depth {
3558 return Ok(value);
3559 }
3560 // The caller resumes with the value on its stack.
3561 self.frames
3562 .last_mut()
3563 .expect("a caller is live")
3564 .stack
3565 .push(value);
3566 }
3567 Err(Signal::Throw(value)) => {
3568 // The host's standing request becomes the active mode for this unwind,
3569 // and is consumed here so it does not leak into the next throw.
3570 if self.uncatchable_next {
3571 self.uncatchable_next = false;
3572 self.uncatchable = true;
3573 }
3574 // An uncatchable throw walks past every `catch` on the way out. The
3575 // frames are still popped, because the values they hold have to be
3576 // dropped — only the search for a handler is skipped.
3577 if self.uncatchable {
3578 while self.frames.len() > depth {
3579 self.frames.pop();
3580 }
3581 return Err(Signal::Throw(value));
3582 }
3583 // A handler lives on the stack of the frame that is throwing —
3584 // `catch` pushed it there — so this frame gets the first chance
3585 // to catch before it is popped.
3586 let value = value;
3587 loop {
3588 if self.frames.len() <= depth {
3589 return Err(Signal::Throw(value));
3590 }
3591 if self.catch_here(value.clone()).is_some() {
3592 break;
3593 }
3594 self.frames.pop();
3595 }
3596 }
3597 // A `yield` in a frame that `execute` is running directly means a
3598 // generator body was entered as an ordinary call, which only happens if
3599 // the generator check in `call_or_push` was bypassed.
3600 Ok(Step::Suspend(_)) => {
3601 return Err(Signal::Throw(self.make_error(
3602 "InternalError",
3603 "a generator body ran as an ordinary call",
3604 )));
3605 }
3606 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3607 }
3608 }
3609 }
3610
3611 /// Install a handler for `value` if this frame has one, resuming at it.
3612 ///
3613 /// The scan is the reference's: walk the frame's stack downwards looking for the
3614 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3615 /// `0` is an enumerator marker rather than a handler — it exists so that a
3616 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3617 /// here and the unwinding continues.
3618 fn catch_here(&mut self, value: Value) -> Option<()> {
3619 let frame = self.frames.last_mut()?;
3620 while let Some(top) = frame.stack.pop() {
3621 if let Value::CatchOffset(offset) = top {
3622 if offset == 0 {
3623 continue;
3624 }
3625 frame.stack.push(value);
3626 frame.pc = offset as usize;
3627 return Some(());
3628 }
3629 }
3630 None
3631 }
3632
3633 fn push_frame(
3634 &mut self,
3635 code: Gc<CompiledCode>,
3636 env: Gc<ClosureEnv>,
3637 this: Value,
3638 mut args: Vec<Value>,
3639 callee: Value,
3640 ) -> JsResult<()> {
3641 // Two bounds, and the byte budget is the one that decides in practice. The
3642 // reference's message is `stack overflow` on an `InternalError`, not V8's
3643 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3644 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3645 let frame_cost = Self::frame_cost(&code);
3646 let stack_base = self.stack_used();
3647 if self.frames.len() >= self.max_frames
3648 || stack_base.saturating_add(frame_cost) > self.stack_limit
3649 {
3650 return Err(Signal::Throw(
3651 self.make_error("InternalError", "stack overflow"),
3652 ));
3653 }
3654 let arg_count = code.code.args.len();
3655 // How many were actually passed, which `arguments.length` reports and
3656 // `assert(x)` depends on: a call with one argument must not look like a call
3657 // with one argument and an explicit `undefined`.
3658 let passed = args.len();
3659 // Missing arguments are `undefined` in their slots; extra ones are dropped
3660 // from the slots but still reachable through `arguments`.
3661 //
3662 // A call that passes no more than the declared parameters needs **no** copy:
3663 // after the resize below, `args[..passed]` *is* the passed values. Only the
3664 // extra ones — which `truncate` is about to drop — have to be kept, and they are
3665 // the rare case. This used to copy every call: one `Value` clone per argument
3666 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
3667 let passed_overflow = (passed > arg_count).then(|| {
3668 let mut values = self.take_values(passed, Value::Undefined);
3669 values[..passed].clone_from_slice(&args[..passed]);
3670 values
3671 });
3672 // Only when the counts differ, which for the overwhelmingly common call — as many
3673 // arguments as parameters — is never. `resize` followed by `truncate` on equal
3674 // lengths is two length compares and nothing else, but this is the hottest few
3675 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
3676 if passed != arg_count {
3677 args.resize(arg_count, Value::Undefined);
3678 args.truncate(arg_count);
3679 }
3680 let cell_count = code.code.var_ref_count as usize;
3681 let mut cells = Vec::with_capacity(cell_count);
3682 for _ in 0..cell_count {
3683 cells.push(self.new_cell(Value::Undefined));
3684 }
3685 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
3686 // A captured argument lives in its cell, not in the argument slot, so the
3687 // incoming value has to be moved there before the body runs.
3688 for (slot, cell) in code.arg_cell.iter().enumerate() {
3689 if *cell >= 0
3690 && let Some(value) = args.get(slot).cloned()
3691 {
3692 cells[*cell as usize].set(value);
3693 }
3694 }
3695 // Sloppy mode substitutes the global object for a missing receiver and boxes a
3696 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3697 // reports `object`. Strict mode passes the value through untouched.
3698 let this = if code.code.strict {
3699 this
3700 } else if this.is_nullish() {
3701 Value::Object(self.realm.global.clone())
3702 } else if matches!(this, Value::Object(_)) {
3703 this
3704 } else {
3705 match crate::builtins::this_object(self, &this) {
3706 Ok(boxed) => Value::Object(boxed),
3707 Err(_) => this,
3708 }
3709 };
3710 let stack_depth = code.code.stack_size as usize + 1;
3711 // Taken before the `push` borrows `self.frames`, because the operand stack comes
3712 // out of the same recycle pool the locals did.
3713 let stack = self.take_values(stack_depth, Value::Undefined);
3714 self.frames.push(Frame {
3715 code,
3716 env,
3717 this,
3718 args,
3719 passed_count: passed,
3720 passed_overflow: passed_overflow.map(Box::new),
3721 locals,
3722 cells,
3723 local_vars: None,
3724 // Exactly the depth the compiler computed, so the operand stack never
3725 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
3726 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
3727 // the buffer between calls, so "exactly" costs nothing after the first one.
3728 stack,
3729 pc: 0,
3730 at: 0,
3731 callee,
3732 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3733 cost: frame_cost,
3734 stack_base,
3735 tail: false,
3736 });
3737 Ok(())
3738 }
3739
3740 /// A value buffer of `len` slots, from the recycle pool when there is one.
3741 ///
3742 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
3743 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
3744 // A frame with no locals asks for nothing, and that is most frames: taking a
3745 // buffer out of the pool, clearing it and resizing it to zero is four operations
3746 // and a pool pop for an empty `Vec`, which is free to construct.
3747 if len == 0 {
3748 return Vec::new();
3749 }
3750 let mut buffer = self.free_values.pop().unwrap_or_default();
3751 buffer.clear();
3752 buffer.resize(len, fill);
3753 buffer
3754 }
3755
3756 /// Return a finished frame's value buffers for the next call to reuse.
3757 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
3758 for mut buffer in [
3759 std::mem::take(&mut frame.locals),
3760 frame
3761 .passed_overflow
3762 .take()
3763 .map(|buffer| *buffer)
3764 .unwrap_or_default(),
3765 std::mem::take(&mut frame.stack),
3766 ] {
3767 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
3768 // GC root: it kept every value the frame held reachable, which is invisible
3769 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
3770 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
3771 // exactly that within one run — the target `{}` of a finished IIFE was still
3772 // in its operand stack, in the pool.
3773 buffer.clear();
3774 // A buffer with no capacity is what `Vec::new` is; putting it back would just
3775 // fill the pool with nothing to offer.
3776 if free_values.len() < RECYCLE_SLOTS
3777 && buffer.capacity() > 0
3778 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
3779 {
3780 free_values.push(buffer);
3781 }
3782 }
3783 }
3784
3785 /// Pop a finished frame and keep its buffers.
3786 ///
3787 /// Every place that drops a frame goes through here: a recycled buffer is also where
3788 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
3789 /// nothing but the reuse.
3790 fn pop_frame(&mut self) -> Option<()> {
3791 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
3792 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
3793 let last = self.frames.len().checked_sub(1)?;
3794 Self::recycle(&mut self.free_values, &mut self.frames[last]);
3795 self.frames.truncate(last);
3796 Some(())
3797 }
3798
3799 /// Poll the host's interrupt handler, if one is installed.
3800 ///
3801 /// The counter is what keeps this off the hot path when nobody asked: the early return is
3802 /// one `Option` test, and with no handler installed the whole function is that test —
3803 /// `check_memory` next door already costs more, so this cannot be what shows up in a
3804 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
3805 #[inline]
3806 fn check_interrupt(&mut self) -> JsResult<()> {
3807 if self.interrupt.is_none() {
3808 return Ok(());
3809 }
3810 if self.interrupt_counter > 0 {
3811 self.interrupt_counter -= 1;
3812 return Ok(());
3813 }
3814 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
3815 // The closure is taken out for the duration so that a handler which re-enters the
3816 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
3817 let mut handler = self.interrupt.take().expect("checked above");
3818 let abort = handler();
3819 self.interrupt = Some(handler);
3820 if abort {
3821 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
3822 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
3823 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
3824 // documentation says.
3825 self.uncatchable = true;
3826 return Err(Signal::Throw(
3827 self.make_error("InternalError", "interrupted"),
3828 ));
3829 }
3830 Ok(())
3831 }
3832
3833 /// A memory checkpoint: does the heap still fit under its limit?
3834 ///
3835 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
3836 /// a `Cell` read and a predictable branch, and the point of asking that often is that
3837 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
3838 /// only at calls would let it run until the machine died, which is the exact failure
3839 /// `--memory-limit` exists to prevent.
3840 ///
3841 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
3842 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
3843 /// script that catches it, drops the reference and carries on is legitimate: measured
3844 /// on `qjs --memory-limit 1M`, the engine recovers.
3845 fn check_memory(&mut self) -> JsResult<()> {
3846 // One `Cell` read and a predictable branch when no limit is set, and an integer
3847 // compare when one is. Containers report their own growth as it happens
3848 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
3849 // walking it here was the first version and it was O(live) per 256 instructions,
3850 // which turned a 100k-element push loop into a five-minute one.
3851 let Some(limit) = self.heap.memory_limit() else {
3852 return Ok(());
3853 };
3854 let used = self.heap.used_bytes();
3855 if used <= limit {
3856 // Back under the limit — a collection or a dropped reference did it. The next
3857 // time it goes over is a new failure, not a repeat of this one.
3858 self.oom_reported_at = 0;
3859 return Ok(());
3860 }
3861 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
3862 // block runs normally after `out of memory` — it allocates nothing, so nothing
3863 // fails. A check that re-fired on every instruction made the handler itself throw,
3864 // which is a dead end: the error became unobservable from script.
3865 //
3866 // Comparing against the total at the last report gives the same behaviour: the
3867 // handler runs while the total is unchanged, and the very next allocation over the
3868 // limit fails.
3869 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
3870 {
3871 return Ok(());
3872 }
3873 self.oom_reported_at = used;
3874 Err(Signal::Throw(
3875 self.make_error("InternalError", "out of memory"),
3876 ))
3877 }
3878
3879 /// Fail before allocating `payload` bytes, if they would not fit.
3880 ///
3881 /// For the allocations whose size comes from script data — `new Array(n)`,
3882 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
3883 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
3884 /// answering NULL for the one big request.
3885 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
3886 if self.heap.fits(payload) {
3887 return Ok(());
3888 }
3889 Err(Signal::Throw(
3890 self.make_error("InternalError", "out of memory"),
3891 ))
3892 }
3893
3894 /// Bytes of frame state the live call chain accounts for.
3895 pub fn stack_used(&self) -> usize {
3896 match self.frames.last() {
3897 Some(frame) => frame.stack_base + frame.cost,
3898 None => 0,
3899 }
3900 }
3901
3902 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
3903 ///
3904 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
3905 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
3906 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
3907 /// instead. That is the whole difference between the two models: it rations C stack, we
3908 /// ration frame state, and both quantities are dominated by the value slots — which is
3909 /// why the two depths come out comparable rather than merely proportional.
3910 fn frame_cost(code: &CompiledCode) -> usize {
3911 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
3912 std::mem::size_of::<Frame>()
3913 + std::mem::size_of::<Value>() * slots
3914 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
3915 }
3916
3917 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
3918 ///
3919 /// Only names the eval created are here: a name the frame already declared statically
3920 /// is written through to its own slot instead, so this cannot shadow a real local.
3921 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
3922 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
3923 let (local_vars, phase) = self.visible_local_vars()?;
3924 if !local_vars.contains(name) {
3925 return None;
3926 }
3927 local_vars.get(name, phase)
3928 }
3929
3930 /// The variables a direct `eval` declared, as the code currently running sees them.
3931 ///
3932 /// Inside an eval that is the *caller's* set — the eval's own variable environment
3933 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
3934 /// else it is the current frame's, falling back to the frame the closure was created
3935 /// in.
3936 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
3937 ///
3938 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
3939 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
3940 /// refcount operations (the clone out of the frame, the drop at the end of the match)
3941 /// just to be asked `is_none`.
3942 fn has_visible_local_vars(&self) -> bool {
3943 let index = match self.eval_caller.flatten() {
3944 Some(caller) => caller,
3945 None => match self.frames.len().checked_sub(1) {
3946 Some(top) => top,
3947 None => return false,
3948 },
3949 };
3950 match self.frames.get(index) {
3951 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
3952 None => false,
3953 }
3954 }
3955
3956 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
3957 // While an `eval` runs, its own frame is on top but its variable environment is
3958 // the *caller's* — so the caller is what the lookup has to start from.
3959 let (index, phase) = match self.eval_caller.flatten() {
3960 Some(caller) => (
3961 caller,
3962 if self.in_parameter_list_at(caller) {
3963 0
3964 } else {
3965 1
3966 },
3967 ),
3968 None => (
3969 self.frames.len().checked_sub(1)?,
3970 if self.in_parameter_list() { 0 } else { 1 },
3971 ),
3972 };
3973 let frame = self.frames.get(index)?;
3974 // The frame's own variables, or — for an arrow, which has no variable environment
3975 // of its own — the one it was created in, which `ClosureEnv` carries.
3976 if let Some(local_vars) = frame.local_vars.clone() {
3977 return Some((local_vars, phase));
3978 }
3979 frame
3980 .env
3981 .local_vars
3982 .clone()
3983 .map(|local_vars| (local_vars, frame.env.local_phase))
3984 }
3985
3986 /// Whether the innermost frame is still evaluating its parameter list.
3987 ///
3988 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
3989 /// and a closure created there may only see that much of [`LocalVars`].
3990 fn in_parameter_list(&self) -> bool {
3991 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
3992 }
3993
3994 /// [`Interp::in_parameter_list`] for a specific frame.
3995 fn in_parameter_list_at(&self, frame: usize) -> bool {
3996 let Some(frame) = self.frames.get(frame) else {
3997 return false;
3998 };
3999 let code = &frame.code.code;
4000 if !code.has_parameter_expressions {
4001 return false;
4002 }
4003 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4004 // function as its body and let a direct `eval` act accordingly.
4005 if code.body_start == (0, 0) {
4006 return false;
4007 }
4008 match code.position_at(frame.at as u32) {
4009 Some(position) => position < code.body_start,
4010 None => false,
4011 }
4012 }
4013
4014 fn frame(&self) -> &Frame {
4015 self.frames.last().expect("a frame is live")
4016 }
4017
4018 fn frame_mut(&mut self) -> &mut Frame {
4019 self.frames.last_mut().expect("a frame is live")
4020 }
4021
4022 // -- slot access --------------------------------------------------------
4023
4024 /// Move a local's value out, leaving `undefined` in the slot.
4025 ///
4026 /// `None` for a captured slot: its value lives in a cell shared with every closure
4027 /// that closed over it, so it can never be exclusively ours and must not be taken.
4028 ///
4029 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4030 /// for every read and fatal for this one — a clone is exactly the second handle that
4031 /// rules out growing the string in place.
4032 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4033 let frame = self.frames.last_mut()?;
4034 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4035 return None;
4036 }
4037 frame
4038 .locals
4039 .get_mut(slot)
4040 .map(|value| std::mem::replace(value, Value::Undefined))
4041 }
4042
4043 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4044 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4045 ///
4046 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4047 /// it** — the value is put back before the general path runs — so a `valueOf` that
4048 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4049 /// error as it would have without the fusion. This is why the in-place attempt is a
4050 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4051 /// a wrong answer with a good excuse.
4052 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4053 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4054 // is put back on every path that does not append. An earlier version wrote the two
4055 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4056 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4057 // through with its value already taken and dropped: the general path below then
4058 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4059 // A wrong answer, from an optimisation, with every test green.
4060 if matches!(right, Value::String(_))
4061 && let Some(taken) = self.take_loc(slot)
4062 {
4063 if let Value::String(mut left) = taken {
4064 let appended = match left.get_mut() {
4065 Some(string) => string.append_in_place(
4066 // The pattern is the one `matches!` just checked.
4067 match &right {
4068 Value::String(text) => text,
4069 _ => unreachable!("guarded above"),
4070 },
4071 ),
4072 None => None,
4073 };
4074 self.put_loc(slot, Value::String(left));
4075 if let Some(added) = appended {
4076 // The buffer grew where it stood, so the heap's running total has to
4077 // be told: `measure_used` would report the new length, and the two must
4078 // agree or the subtraction at free time leaves the counter wrong.
4079 self.heap.adjust_payload(added as isize);
4080 return Ok(());
4081 }
4082 } else {
4083 self.put_loc(slot, taken);
4084 }
4085 }
4086 // The two-number case, without an operand stack round trip. Everything below
4087 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4088 // store it — five operations and two `Value` clones for what is one integer add.
4089 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4090 // for string append and never got the numeric half, so `t += i` — a counting loop
4091 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4092 let left = self.get_loc(slot);
4093 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4094 self.put_loc(
4095 slot,
4096 match a.checked_add(*b) {
4097 Some(sum) => Value::Int(sum),
4098 None => Value::Float(*a as f64 + *b as f64),
4099 },
4100 );
4101 return Ok(());
4102 }
4103 self.push(left);
4104 self.push(right);
4105 self.binary_add()?;
4106 let value = self.pop();
4107 self.put_loc(slot, value);
4108 Ok(())
4109 }
4110
4111 fn get_arg(&self, slot: usize) -> Value {
4112 self.frame().read_arg(slot)
4113 }
4114
4115 fn put_arg(&mut self, slot: usize, value: Value) {
4116 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4117 if cell == -1 {
4118 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4119 *slot = value;
4120 }
4121 } else {
4122 self.frame().cells[cell as usize].set(value);
4123 }
4124 }
4125
4126 fn get_loc(&self, slot: usize) -> Value {
4127 // The cell mapping is `-1` for every slot that was not captured — which is all of
4128 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4129 // so the common case is one array read and a clone: 20% of every loop iteration
4130 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4131 // sample of `dispatch:arith`).
4132 self.frame().read_loc(slot)
4133 }
4134
4135 fn put_loc(&mut self, slot: usize, value: Value) {
4136 // One borrow instead of three, and the cell check on the frame we already hold.
4137 let frame = self.frames.last_mut().expect("a frame is live");
4138 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4139 if cell < 0 {
4140 if let Some(slot) = frame.locals.get_mut(slot) {
4141 *slot = value;
4142 }
4143 } else if let Some(cell) = frame.cells.get(cell as usize) {
4144 cell.set(value);
4145 }
4146 }
4147
4148 // -- globals ------------------------------------------------------------
4149
4150 /// The name a global-slot operand refers to.
4151 fn global_name(&self, slot: usize) -> String {
4152 self.frame()
4153 .code
4154 .code
4155 .closure_vars
4156 .get(slot)
4157 .map(|c| c.name.clone())
4158 .unwrap_or_default()
4159 }
4160
4161 /// The facts about a global binding that decide where it lives.
4162 ///
4163 /// A script's globals split in two, and the split is observable: `var` and
4164 /// function declarations become properties of the global object (`globalThis.v`
4165 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4166 /// declarations live in the global *lexical* environment and are invisible there
4167 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4168 /// `is_lexical` flag means the answer is already in the bytecode.
4169 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4170 let name = self.global_name(slot);
4171 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4172 // while forwarding a reference through a nested function is built with the
4173 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4174 // closure. Presence in the realm's lexical table is the same fact, recorded
4175 // once, and every slot sees it.
4176 let lexical = self.realm.globals.contains_key(&name);
4177 let is_const = self.realm.lexical_consts.contains(&name);
4178 (name, lexical, is_const)
4179 }
4180
4181 /// The value of `name` in the innermost active `with` object, if any.
4182 ///
4183 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4184 /// innermost frame first and innermost block first within one. Walking frames rather
4185 /// than keeping a separate stack is what makes a closure called from inside a `with`
4186 /// see it, and what keeps the object alive only as long as the block is.
4187 /// The innermost active `with` object that has `name`, if any.
4188 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4189 let objects = self.eval_with.clone().unwrap_or_default();
4190 for object in objects {
4191 let key = self.string(name.to_string());
4192 if self
4193 .has_property(&key, &Value::Object(object.clone()))
4194 .ok()?
4195 {
4196 return Some(object);
4197 }
4198 }
4199 None
4200 }
4201
4202 /// Every active `with` object, innermost first.
4203 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4204 let mut objects = Vec::new();
4205 for frame in self.frames.iter().rev() {
4206 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4207 if var.kind != js_compile::VarKind::With {
4208 continue;
4209 }
4210 // A captured binding lives in its cell and not in the slot list, so the
4211 // cell is consulted first — a closure created inside the block is exactly
4212 // what makes the object captured. Before the store runs the slot still
4213 // holds `undefined`, and a `with` object is always boxed, so a non-object
4214 // entry is simply not in scope yet.
4215 let value = frame
4216 .code
4217 .loc_cell
4218 .get(index)
4219 .copied()
4220 .filter(|cell| *cell >= 0)
4221 .and_then(|cell| frame.cells.get(cell as usize))
4222 .map(|cell| cell.get())
4223 .or_else(|| frame.locals.get(index).cloned());
4224 if let Some(Value::Object(object)) = value {
4225 objects.push(object);
4226 }
4227 }
4228 }
4229 objects
4230 }
4231
4232 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4233 for object in self.eval_with.clone().unwrap_or_default() {
4234 let key = self.string(name.to_string());
4235 if self.has_property(&key, &Value::Object(object.clone()))? {
4236 return Ok(Some(self.read_field(&Value::Object(object), name)?));
4237 }
4238 }
4239 Ok(None)
4240 }
4241
4242 /// Whether every scope between here and the global object is an ordinary one.
4243 ///
4244 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4245 /// bytecode resolved; when any is live the general path has to run in full order. When
4246 /// none is — every ordinary program — a global read is a property read and nothing
4247 /// else, and that is worth caching.
4248 fn scopes_are_plain(&self) -> bool {
4249 self.eval_caller.is_none()
4250 && self.eval_with.is_none()
4251 && self.eval_arguments.is_none()
4252 && self.eval_bindings.is_empty()
4253 && self.eval_scope.is_none()
4254 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4255 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4256 // its `ClosureEnv`, so the test has to be the same one the general path makes.
4257 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4258 // upstream corpus caught and no unit test did.
4259 && !self.has_visible_local_vars()
4260 && self.frame().env.eval_scope.is_none()
4261 }
4262
4263 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4264 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4265 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4266 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4267 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4268 // borrow outlive the `&mut self` the lookup needs.
4269 //
4270 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4271 // forwarded through a nested function has its flags cleared, so the flag cannot
4272 // be believed.
4273 let code = self.frame().code.clone();
4274 let name = code
4275 .code
4276 .closure_vars
4277 .get(slot)
4278 .map(|c| c.name.as_str())
4279 .unwrap_or_default();
4280 let lexical = self.realm.globals.contains_key(name);
4281 // The common case, first: an ordinary global `var`, with a cache in front of the
4282 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4283 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4284 // cache hit and return without touching any of it.
4285 if !lexical && self.scopes_are_plain() {
4286 return self.get_plain_global(name, slot);
4287 }
4288 if name == "arguments"
4289 && let Some(arguments) = &self.eval_arguments
4290 {
4291 return Ok(arguments.clone());
4292 }
4293 // A `with` block around the *call site* is part of the scope an `eval` sees, so
4294 // the objects live when the eval started are consulted before anything else. The
4295 // snapshot is taken at entry rather than scanning the frames on every read: a
4296 // block that has already finished still leaves its object in the slot, and a
4297 // bytecode read outside the block must not see it.
4298 if let Some(value) = self.with_lookup(name)? {
4299 return Ok(value);
4300 }
4301 // A variable a direct `eval` declared shadows everything the compiler resolved,
4302 // including an enclosing function's binding: the eval put it in the caller's own
4303 // variable environment, which is nearer than any captured scope.
4304 if let Some((local_vars, phase)) = self.visible_local_vars()
4305 && let Some(cell) = local_vars.get(name, phase)
4306 {
4307 return Ok(cell.get());
4308 }
4309 // The frame that called `eval` is the innermost scope the eval'd code sees, so
4310 // its local `a` wins over a global `a`.
4311 if let Some(value) = self.eval_binding_value(name) {
4312 return Ok(value);
4313 }
4314 // A closure created by an `eval` resolves its free names against the bindings
4315 // that eval saw, even after the eval (and its frames) are gone.
4316 if let Some(cell) = self
4317 .frame()
4318 .env
4319 .eval_scope
4320 .as_ref()
4321 .and_then(|scope| scope.get(name))
4322 {
4323 let value = cell.get();
4324 if matches!(value, Value::Uninitialized) {
4325 return Err(self.throw_reference(name));
4326 }
4327 return Ok(value);
4328 }
4329 // A binding declared by the strict `eval` currently running shadows anything
4330 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4331 if let Some(scope) = &self.eval_scope
4332 && let Some(value) = scope.get(name)
4333 {
4334 return Ok(value.clone());
4335 }
4336 if lexical {
4337 // A lexical global is a binding in a side table, so the dead zone is
4338 // visible and it is nowhere on the global object.
4339 if let Some(cell) = self.realm.globals.get(name) {
4340 let value = cell.get();
4341 if matches!(value, Value::Uninitialized) {
4342 return Err(self.throw_reference(name));
4343 }
4344 return Ok(value);
4345 }
4346 return Err(self.throw_reference(name));
4347 }
4348 // A `var` global is an ordinary property, so the prototype chain and the
4349 // global object's own builtins are all reachable through it.
4350 match self.get_property(&self.realm.global.clone(), name)? {
4351 Some(value) => Ok(value),
4352 None => Err(self.throw_reference(name)),
4353 }
4354 }
4355
4356 /// Read a plain global `var`: a cached own data property, or the full lookup.
4357 ///
4358 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4359 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4360 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4361 let object = self.realm.global.clone();
4362 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4363 if let Some(cached) = &self.global_cache[site]
4364 && object.upgrades_to(&cached.object)
4365 && let Some(value) = object.data_property_at(cached.index, name)
4366 {
4367 return Ok(value);
4368 }
4369 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4370 // chain exactly as before, then remember the answer if it is worth remembering.
4371 let Some(value) = self.get_property(&object, name)? else {
4372 return Err(self.throw_reference(name));
4373 };
4374 if let Some(index) = object.own_data_index(name) {
4375 self.global_cache[site] = Some(GlobalCache {
4376 object: object.downgrade(),
4377 index,
4378 });
4379 }
4380 Ok(value)
4381 }
4382
4383 /// Store to a global binding.
4384 ///
4385 /// Returns a signal when the store is refused: a `const` global may only be
4386 /// written by its initialiser, and a non-configurable `var` global may not be
4387 /// deleted but is always writable.
4388 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4389 let (name, lexical, is_const) = self.global_binding(slot);
4390
4391 // An assignment inside a `with` writes through to the object that supplies the
4392 // name, which for an `eval` means consulting the same chain `get_global` does.
4393 if let Some(owner) = self.with_owner(&name) {
4394 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4395 return Ok(());
4396 }
4397 // A variable the running eval *declared* takes the write before any caller
4398 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4399 // environment even when an enclosing function has a `var c` of its own.
4400 if self.eval_caller.flatten().is_some()
4401 && let Some((local_vars, phase)) = self.visible_local_vars()
4402 && local_vars.contains(&name)
4403 && let Some(cell) = local_vars.get(&name, phase)
4404 {
4405 cell.set(value);
4406 return Ok(());
4407 }
4408 // A binding of the frame that called `eval` takes the write, which is what
4409 // makes `f("a = 3")` change the caller's `a`.
4410 if self.set_eval_binding(&name, &value)? {
4411 return Ok(());
4412 }
4413 // A closure that outlived its `eval` writes through to the same cell it reads.
4414 if let Some(cell) = self
4415 .frame()
4416 .env
4417 .eval_scope
4418 .as_ref()
4419 .and_then(|scope| scope.get(&name))
4420 .cloned()
4421 {
4422 cell.set(value);
4423 return Ok(());
4424 }
4425 // Inside a strict `eval`, a name it declared itself is stored there. An
4426 // *assignment* to a name nobody declared is not a declaration, so it falls
4427 // through: strict mode raises `ReferenceError` for it, which is what
4428 // `eval("1 + (@not_def = 1)")` has to do.
4429 if let Some(scope) = self.eval_scope.as_mut()
4430 && scope.contains_key(&name)
4431 {
4432 scope.insert(name, value);
4433 return Ok(());
4434 }
4435 if lexical {
4436 if let Some(cell) = self.realm.globals.get(&name).cloned() {
4437 if is_const && !matches!(cell.get(), Value::Uninitialized) {
4438 return Err(self.read_only_global(&name));
4439 }
4440 cell.set(value);
4441 return Ok(());
4442 }
4443 // Writing an undeclared lexical global is a `ReferenceError` in strict
4444 // mode and a silent global creation otherwise; creating the cell here
4445 // keeps both paths from losing the value.
4446 let cell = self.new_cell(value);
4447 self.realm.globals.insert(name, cell);
4448 return Ok(());
4449 }
4450 // A variable a direct `eval` declared in this call shadows the global object, even
4451 // when the global already has a property of that name — `var c = "global"` at the
4452 // top level must not capture `eval("var c = 1")` inside a function.
4453 if let Some((local_vars, phase)) = self.visible_local_vars()
4454 && local_vars.contains(&name)
4455 && let Some(cell) = local_vars.get(&name, phase)
4456 {
4457 cell.set(value);
4458 return Ok(());
4459 }
4460 let global = self.realm.global.clone();
4461 match global.own_property(&name) {
4462 // A `var` global is writable, so the store goes straight through — but
4463 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4464 // store (a non-writable or accessor-without-setter global) is a silent
4465 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4466 // split every other assignment has.
4467 Some(_) => {
4468 let on_failure = if self.current_strict() {
4469 DeleteFailure::Throw
4470 } else {
4471 DeleteFailure::Ignore
4472 };
4473 self.set_property_with(&global, &name, value, on_failure)
4474 }
4475 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4476 // declaration creates a *configurable* property, which is what makes it
4477 // deletable and is the one way a global differs from a declared `var`.
4478 // In strict mode the same store is a `ReferenceError` instead: that is the
4479 // whole point of strict mode, and creating the global silently meant
4480 // `"use strict"; x = 1` looked like it worked.
4481 None => {
4482 if self.current_strict() {
4483 return Err(self.throw_reference(&name));
4484 }
4485 // A direct eval declares here rather than on the global object: its
4486 // `var`s belong to the caller's variable environment. `declare_eval_local`
4487 // also covers a plain assignment to a variable an earlier eval made.
4488 if let Some(cell) = self.declare_eval_local(&name) {
4489 cell.set(value);
4490 return Ok(());
4491 }
4492 global.define_data(&name, value);
4493 Ok(())
4494 }
4495 }
4496 }
4497
4498 /// The value of a binding of the frame that called `eval`, if there is one.
4499 fn eval_binding_value(&self, name: &str) -> Option<Value> {
4500 let binding = self
4501 .eval_bindings
4502 .iter()
4503 .find(|binding| binding.name == name)?;
4504 let owner = self.frames.get(binding.frame)?;
4505 let (slot, index) = (binding.slot, binding.index);
4506 Some(match slot {
4507 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4508 cell if cell >= 0 => owner
4509 .cells
4510 .get(cell as usize)
4511 .map(|cell| cell.get())
4512 .unwrap_or(Value::Undefined),
4513 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4514 },
4515 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4516 cell if cell >= 0 => owner
4517 .cells
4518 .get(cell as usize)
4519 .map(|cell| cell.get())
4520 .unwrap_or(Value::Undefined),
4521 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4522 },
4523 })
4524 }
4525
4526 /// Write to a binding of the frame that called `eval`.
4527 ///
4528 /// `Ok(false)` means no binding matched and the caller should keep looking. A
4529 /// matched binding can still refuse the store, which is why this is fallible: a
4530 /// `const` is read-only everywhere, and a named function expression's own name is
4531 /// read-only in strict mode.
4532 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4533 let Some(binding) = self
4534 .eval_bindings
4535 .iter()
4536 .find(|binding| binding.name == name)
4537 else {
4538 return Ok(false);
4539 };
4540 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4541 let strict = self.current_strict();
4542 let Some(owner) = self.frames.get_mut(frame) else {
4543 return Ok(false);
4544 };
4545 match slot {
4546 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4547 cell if cell >= 0 => {
4548 if let Some(cell) = owner.cells.get(cell as usize) {
4549 cell.set(value.clone());
4550 }
4551 }
4552 _ => {
4553 if let Some(slot) = owner.args.get_mut(index) {
4554 *slot = value.clone();
4555 }
4556 }
4557 },
4558 EvalSlot::Local => {
4559 let declared = owner.code.code.vars.get(index);
4560 // A `const` is read-only even through `eval`. The realm records this for
4561 // globals (see `lexical_consts`), but a local's `const`-ness is only in
4562 // the bytecode, so this is where it has to be enforced.
4563 if declared.is_some_and(|var| var.is_const) {
4564 return Err(self.read_only_local(name));
4565 }
4566 // The name of a named function expression is read-only too, but only
4567 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4568 // such a name is ignored, the same as a direct store would be.
4569 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4570 return if strict {
4571 Err(self.read_only_local(name))
4572 } else {
4573 Ok(true)
4574 };
4575 }
4576 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4577 cell if cell >= 0 => {
4578 if let Some(cell) = owner.cells.get(cell as usize) {
4579 cell.set(value.clone());
4580 }
4581 }
4582 _ => {
4583 if let Some(slot) = owner.locals.get_mut(index) {
4584 *slot = value.clone();
4585 }
4586 }
4587 }
4588 }
4589 }
4590 Ok(true)
4591 }
4592
4593 /// The `TypeError` an assignment to a read-only binding raises.
4594 fn read_only_local(&self, name: &str) -> Signal {
4595 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4596 }
4597
4598 /// Declare `name` as a variable of the frame that called the running `eval`.
4599 ///
4600 /// `None` when there is no direct eval in progress, or it was called from the top
4601 /// level — then the caller's variable environment *is* the global one and the
4602 /// existing path is right.
4603 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4604 let caller = self.eval_caller.flatten()?;
4605 // The bottom frame is the top-level script, whose variable environment *is* the
4606 // global one — so `eval("var x = 1")` at the top level still creates a global.
4607 if caller == 0 {
4608 return None;
4609 }
4610 // A name the eval's *own* variable environment already binds is not a new
4611 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4612 // `arguments`, and creating a second binding would leave the first — the one
4613 // closures read — untouched. A binding of an *outer* frame does not count: a
4614 // declaration shadows it rather than writing through.
4615 if self
4616 .eval_bindings
4617 .iter()
4618 .any(|binding| binding.name == name && binding.frame == caller)
4619 {
4620 return None;
4621 }
4622 let phase = if self.in_parameter_list_at(caller) {
4623 0
4624 } else {
4625 1
4626 };
4627 self.frame_local_vars(caller)?;
4628 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4629 if let Some(cell) = local_vars.get(name, 1) {
4630 return Some(cell);
4631 }
4632 let cell = self.new_cell(Value::Undefined);
4633 Some(local_vars.declare(name, phase, cell))
4634 }
4635
4636 /// Make sure `frame` has a `LocalVars`, creating it on demand.
4637 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4638 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4639 return Some(local_vars.clone());
4640 }
4641 let local_vars = Gc::new(self.heap, LocalVars::new());
4642 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4643 Some(local_vars)
4644 }
4645
4646 /// Whether the realm already has a binding for `name`, lexically or as an *own*
4647 /// property of the global object. Used to decide whether a store inside an
4648 /// `eval` writes through to the realm or declares a binding of its own.
4649 ///
4650 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4651 /// write to `Object.prototype.toString`, and must not shadow it either.
4652 fn global_knows(&mut self, name: &str) -> bool {
4653 if self.realm.globals.contains_key(name) {
4654 return true;
4655 }
4656 self.realm.global.own_property(name).is_some()
4657 }
4658
4659 /// Whether the code currently running is strict.
4660 ///
4661 /// Read off the frame's function, which is where the parser's answer ended up; a
4662 /// native function never runs strict-only checks, and there is no frame at all
4663 /// before the first script.
4664 pub fn current_strict(&self) -> bool {
4665 self.frames
4666 .last()
4667 .is_some_and(|frame| frame.code.code.strict)
4668 }
4669
4670 /// Initialise a declared global, which is what ends its dead zone.
4671 ///
4672 /// A `var` global becomes a property of the global object: writable, so a later
4673 /// assignment goes through, and non-configurable, so `delete` refuses.
4674 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4675 let (name, lexical, _) = self.global_binding(slot);
4676 // A `var` declared by the strict `eval` currently running belongs to the
4677 // eval's scope, not to the global object: `eval("var v = 1")` must not make
4678 // `typeof v` answer `"number"` afterwards. A name the realm already has is
4679 // initialised in place, which is what a re-declaration inside eval does.
4680 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4681 self.eval_scope
4682 .as_mut()
4683 .expect("checked above")
4684 .insert(name, value);
4685 return Ok(());
4686 }
4687 if let Some(scope) = self.eval_scope.as_mut()
4688 && scope.contains_key(&name)
4689 {
4690 scope.insert(name, value);
4691 return Ok(());
4692 }
4693 if lexical {
4694 // The cell exists (created at declaration time) holding the dead-zone
4695 // marker; storing the value is what makes the binding readable.
4696 if let Some(cell) = self.realm.globals.get(&name).cloned() {
4697 cell.set(value);
4698 return Ok(());
4699 }
4700 let cell = self.new_cell(value);
4701 self.realm.globals.insert(name, cell);
4702 return Ok(());
4703 }
4704 let global = self.realm.global.clone();
4705 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
4706 // to answer `false` and leave the binding in place. `with_attributes` ties
4707 // `configurable` to `writable`, so the property is built field by field.
4708 global.define(
4709 &name,
4710 Property {
4711 value: Some(value),
4712 writable: true,
4713 enumerable: true,
4714 configurable: false,
4715 ..Property::default()
4716 },
4717 );
4718 Ok(())
4719 }
4720
4721 /// The `TypeError` a store to a `const` global raises.
4722 fn read_only_global(&self, name: &str) -> Signal {
4723 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4724 }
4725
4726 // -- properties ---------------------------------------------------------
4727
4728 /// Read `object[key]`, following the prototype chain.
4729 ///
4730 /// An inherited accessor runs with the *receiver* as `this`, which is why the
4731 /// lookup returns the owner rather than just the value.
4732 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
4733 self.get_property_key(object, &PropertyKey::from(key))
4734 }
4735
4736 /// [`Interp::get_property`] with a key that may be a symbol.
4737 pub fn get_property_key(
4738 &mut self,
4739 object: &Gc<JsObject>,
4740 key: &PropertyKey,
4741 ) -> JsResult<Option<Value>> {
4742 self.get_property_key_for(object, None, key)
4743 }
4744
4745 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
4746 ///
4747 /// The receiver matters when the property is found on a *prototype*: a getter has to
4748 /// see the object the read started from. For a primitive that is the primitive
4749 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
4750 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
4751 /// the owner.
4752 pub fn get_property_key_for(
4753 &mut self,
4754 object: &Gc<JsObject>,
4755 receiver: Option<&Value>,
4756 key: &PropertyKey,
4757 ) -> JsResult<Option<Value>> {
4758 // A proxy answers for itself, before any of the shortcuts below: `new
4759 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
4760 // have.
4761 if object.proxy_state().is_some() {
4762 let receiver = receiver
4763 .cloned()
4764 .unwrap_or_else(|| Value::Object(object.clone()));
4765 return self.proxy_get(object, &receiver, key);
4766 }
4767 // A host class's `get_property` trap replaces the whole read, prototype walk
4768 // included — that is what makes a native accessor free rather than a JavaScript
4769 // getter call.
4770 if let Some(exotic) = object.exotic() {
4771 let receiver_value = receiver
4772 .cloned()
4773 .unwrap_or_else(|| Value::Object(object.clone()));
4774 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
4775 return Ok(Some(value));
4776 }
4777 // With no `get_property` trap, a `get_own_property` trap still answers for the
4778 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
4779 // and the hook lives exactly there. A key the trap reports as absent is still
4780 // looked for on the prototype, which is why the search resumes *above*.
4781 if let Some(property) = exotic.get_own_property(self, object, key)? {
4782 return match property {
4783 Some(property) => self.read_property(property, object, receiver),
4784 None => match lookup_key_above(object, key) {
4785 Some((_, property)) => self.read_property(property, object, receiver),
4786 None => Ok(None),
4787 },
4788 };
4789 }
4790 }
4791 // The element-vector and `length` shortcuts are string-only: an array index
4792 // has no symbol spelling.
4793 if let Some(text) = key.as_str() {
4794 if let Some(value) = self.own_element(object, text) {
4795 return Ok(Some(value));
4796 }
4797 // `length` is not stored as a property: an array's length is its element
4798 // count, and keeping one copy of it is what makes `push`/`pop` and
4799 // `a.length = n` agree.
4800 if let Some(length) = object.array_length()
4801 && text == "length"
4802 {
4803 // Not `Value::Int(length as i32)`: see [`length_value`].
4804 return Ok(Some(crate::object::length_value(length)));
4805 }
4806 }
4807 match lookup_key(object, key) {
4808 Some((_, property)) => self.read_property(property, object, receiver),
4809 None => Ok(None),
4810 }
4811 }
4812
4813 /// The value a property read answers.
4814 ///
4815 /// One place rather than three, because an accessor has to run with the *receiver* as
4816 /// `this` whether the descriptor came from the property table, an exotic
4817 /// `get_own_property` trap, or a prototype above one.
4818 fn read_property(
4819 &mut self,
4820 property: Property,
4821 object: &Gc<JsObject>,
4822 receiver: Option<&Value>,
4823 ) -> JsResult<Option<Value>> {
4824 if property.is_accessor() {
4825 match &property.getter {
4826 Some(getter) if !matches!(getter, Value::Undefined) => {
4827 let receiver = receiver
4828 .cloned()
4829 .unwrap_or_else(|| Value::Object(object.clone()));
4830 self.call_value(getter.clone(), receiver, Vec::new())
4831 .map(Some)
4832 }
4833 // An accessor with no getter reads as `undefined`.
4834 _ => Ok(Some(Value::Undefined)),
4835 }
4836 } else {
4837 Ok(property.value)
4838 }
4839 }
4840
4841 /// `super.key` — start the search at `proto`, but report to `receiver`.
4842 ///
4843 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
4844 /// found on the prototype of a class has to see the *instance* as `this`, and a
4845 /// plain property read off `proto` would lose that.
4846 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
4847 let start = self.require_object(proto)?;
4848 let key = self.propkey(key)?;
4849 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
4850 if matches!(proto, Value::Null) {
4851 return Ok(Value::Undefined);
4852 }
4853 match lookup_key(&start, &key) {
4854 Some((_, property)) if property.is_accessor() => match &property.getter {
4855 Some(getter) if !matches!(getter, Value::Undefined) => {
4856 self.call_value(getter.clone(), receiver.clone(), Vec::new())
4857 }
4858 _ => Ok(Value::Undefined),
4859 },
4860 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
4861 None => Ok(Value::Undefined),
4862 }
4863 }
4864
4865 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
4866 ///
4867 /// A setter found on the prototype runs with `receiver` as `this`; a data property
4868 /// is shadowed by a new own property on the receiver, the same rule an ordinary
4869 /// assignment follows.
4870 fn super_write(
4871 &mut self,
4872 receiver: &Value,
4873 proto: &Value,
4874 key: &Value,
4875 value: Value,
4876 ) -> JsResult<()> {
4877 let target = self.require_object(receiver)?;
4878 let key = self.propkey(key)?;
4879 if !matches!(proto, Value::Null)
4880 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
4881 {
4882 if property.is_accessor() {
4883 if let Some(setter) = &property.setter
4884 && !matches!(setter, Value::Undefined)
4885 {
4886 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
4887 }
4888 return Ok(());
4889 }
4890 // A data property on the prototype is writable or not; reading `owner` at
4891 // all is only for the attribute check.
4892 if !property.writable {
4893 return Err(self.type_error(format!("'{key}' is read-only")));
4894 }
4895 let _ = owner;
4896 }
4897 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
4898 }
4899
4900 /// The object a `super` operation needs, or the `TypeError` the spec raises.
4901 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
4902 match value.as_object() {
4903 Some(object) => Ok(object.clone()),
4904 None => Err(Signal::Throw(
4905 self.make_error("TypeError", "value is not an object"),
4906 )),
4907 }
4908 }
4909
4910 /// Build the class object `define_class` produces.
4911 ///
4912 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
4913 /// whose prototype property is a fresh object inheriting from the parent's
4914 /// prototype, and whose own prototype is the parent constructor — which is what makes
4915 /// a static method inherited too.
4916 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
4917 let ctor = self.pop();
4918 let parent = self.pop();
4919 let Value::Object(function) = &ctor else {
4920 return Err(Signal::Throw(
4921 self.make_error("TypeError", "class constructor must be a function"),
4922 ));
4923 };
4924 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
4925 // but gives the instances no prototype at all.
4926 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
4927 match &parent {
4928 Value::Null => (Some(self.realm.function_proto.clone()), None),
4929 Value::Object(parent_class) => {
4930 if !parent_class.is_callable() {
4931 return Err(Signal::Throw(
4932 self.make_error("TypeError", "parent class must be constructor"),
4933 ));
4934 }
4935 let proto = self.get_property(parent_class, "prototype")?;
4936 match proto {
4937 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
4938 Some(Value::Null) => (Some(parent_class.clone()), None),
4939 _ => {
4940 return Err(Signal::Throw(self.make_error(
4941 "TypeError",
4942 "parent prototype must be an object or null",
4943 )));
4944 }
4945 }
4946 }
4947 _ => {
4948 return Err(Signal::Throw(
4949 self.make_error("TypeError", "parent class must be constructor"),
4950 ));
4951 }
4952 }
4953 } else {
4954 (
4955 Some(self.realm.function_proto.clone()),
4956 Some(self.realm.object_proto.clone()),
4957 )
4958 };
4959 let proto = self.new_object(parent_proto);
4960 function.set_proto(parent_ctor);
4961 // A class is not callable without `new`, and its `prototype` is not writable —
4962 // both follow from being a class and are what `class A {}; A()` throws on.
4963 function.set_class_constructor(true);
4964 function.set_home_object(None);
4965 self.set_function_name(&ctor, name);
4966 self.define_class_properties(function, &ctor, &proto)?;
4967 Ok((ctor, proto))
4968 }
4969
4970 /// Give the constructor its `prototype` and `length`, and the prototype its
4971 /// `constructor` back-pointer.
4972 fn define_class_properties(
4973 &mut self,
4974 function: &Gc<JsObject>,
4975 ctor: &Value,
4976 proto: &Gc<JsObject>,
4977 ) -> JsResult<()> {
4978 proto.define(
4979 "constructor",
4980 Property::with_attributes(ctor.clone(), true, false),
4981 );
4982 function.define(
4983 "prototype",
4984 Property::prototype_of(Value::Object(proto.clone()), false),
4985 );
4986 if let Some((code, _)) = bytecode_of(function) {
4987 let length = code.code.defined_args;
4988 function.define(
4989 "length",
4990 Property::name_or_length(Value::Int(length as i32)),
4991 );
4992 }
4993 Ok(())
4994 }
4995
4996 /// The own array element `key` names, if this object has one.
4997 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
4998 let index = array_index(key)?;
4999 // A typed array's elements live in its buffer, not in a property list: reading one
5000 // goes through the view's element type so a bounds check and a detached buffer are
5001 // both handled there.
5002 if object.typed_array_parts().is_some() {
5003 return object.typed_array_element(index as usize);
5004 }
5005 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5006 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5007 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5008 // `[1,,3][1]`.
5009 match object.array_get(index as usize) {
5010 Some(Value::Hole) | None => None,
5011 other => other,
5012 }
5013 }
5014
5015 /// Store `object[key] = value`, honouring setters and inherited properties.
5016 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5017 self.set_property_with(object, key, value, DeleteFailure::Throw)
5018 }
5019
5020 /// Store a property, choosing what to do when the object refuses.
5021 ///
5022 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5023 /// mode, which is the one place assignment differs by mode. Native code (the array
5024 /// methods, `JSON`) always asks for the throw.
5025 pub fn set_property_with(
5026 &mut self,
5027 object: &Gc<JsObject>,
5028 key: &str,
5029 value: Value,
5030 on_failure: DeleteFailure,
5031 ) -> JsResult<()> {
5032 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5033 }
5034
5035 /// [`Interp::set_property_with`] with a key that may be a symbol.
5036 pub fn set_property_with_key(
5037 &mut self,
5038 object: &Gc<JsObject>,
5039 key: &PropertyKey,
5040 value: Value,
5041 on_failure: DeleteFailure,
5042 ) -> JsResult<()> {
5043 // A proxy's `set` trap decides, and its `false` means the same thing an
5044 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5045 if object.proxy_state().is_some() {
5046 let receiver = Value::Object(object.clone());
5047 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5048 return match (accepted, on_failure) {
5049 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5050 (false, DeleteFailure::Throw) => {
5051 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5052 }
5053 };
5054 }
5055 }
5056 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5057 // refusal and means exactly what a proxy's `false` means.
5058 if let Some(exotic) = object.exotic() {
5059 let receiver = Value::Object(object.clone());
5060 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5061 return match (accepted, on_failure) {
5062 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5063 (false, DeleteFailure::Throw) => {
5064 Err(self.type_error(format!("property '{key}' is read-only")))
5065 }
5066 };
5067 }
5068 }
5069 // The element and `length` shortcuts only exist for string keys: an array
5070 // index has no symbol spelling, and a symbol named `length` is an ordinary
5071 // property.
5072 let text = key.as_str();
5073 // A typed array's elements are a window onto its buffer: the store has to go
5074 // through the view's element type so the value is wrapped (or clamped) and so an
5075 // out-of-range or detached write is a silent no-op, as the spec says.
5076 if let Some(text) = text
5077 && let Some(index) = array_index(text)
5078 && let Some(element) = object.typed_array_element_type()
5079 {
5080 // §10.4.5.5: an out-of-bounds index answers `true` *before* `V` is converted,
5081 // so a `valueOf` with a side effect must not run. Checking the length first is
5082 // what keeps `valueOfCalled` at 0 in `key-is-out-of-bounds-receiver-is-…`.
5083 let length = object.typed_array_length().unwrap_or(0);
5084 if index as usize >= length {
5085 return Ok(());
5086 }
5087 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5088 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5089 // in `Interp`, because it is script-observable and the storage borrow inside
5090 // `typed_array_set` must not be held across it.
5091 let stored = self.element_value(element, value)?;
5092 if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5093 return Err(self.type_error(reason));
5094 }
5095 return Ok(());
5096 }
5097 if let Some(text) = text
5098 && let Some(index) = array_index(text)
5099 && object.is_array()
5100 {
5101 // An accessor defined on an index lives in the property table while the
5102 // element slot is a hole, so the store has to go through the property first.
5103 // Writing the vector directly skipped the setter entirely.
5104 if let Some(existing) = object.own_property_key(key) {
5105 if existing.is_accessor() {
5106 return match existing.setter.clone() {
5107 Some(setter) if !matches!(setter, Value::Undefined) => {
5108 let receiver = Value::Object(object.clone());
5109 self.call_value(setter, receiver, vec![value]).map(|_| ())
5110 }
5111 _ => match on_failure {
5112 DeleteFailure::Throw => Err(self.type_error(format!(
5113 "cannot set property '{text}', it has only a getter"
5114 ))),
5115 DeleteFailure::Ignore => Ok(()),
5116 },
5117 };
5118 }
5119 if !existing.writable {
5120 return match on_failure {
5121 DeleteFailure::Throw => {
5122 Err(self.type_error(format!("'{text}' is read-only")))
5123 }
5124 DeleteFailure::Ignore => Ok(()),
5125 };
5126 }
5127 }
5128 {
5129 // Growing the array needs a writable `length`.
5130 if (index as usize) >= object.array_length().unwrap_or(0)
5131 && !object.length_writable()
5132 {
5133 return match on_failure {
5134 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5135 DeleteFailure::Ignore => Ok(()),
5136 };
5137 }
5138 // Adding an index past the end makes the array longer, which a
5139 // non-extensible array refuses.
5140 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5141 return match on_failure {
5142 DeleteFailure::Throw => Err(self.type_error(format!(
5143 "cannot add property '{key}', object is not extensible"
5144 ))),
5145 DeleteFailure::Ignore => Ok(()),
5146 };
5147 }
5148 if object.element_is_locked(index) {
5149 return match on_failure {
5150 DeleteFailure::Throw => {
5151 Err(self.type_error(format!("'{key}' is read-only")))
5152 }
5153 DeleteFailure::Ignore => Ok(()),
5154 };
5155 }
5156 // The element vector is only half of `[[Set]]` for an index: the
5157 // prototype chain is consulted first, and a setter there answers instead
5158 // of the element store. This branch used to write the element directly, so
5159 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5160 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5161 // the reference calls the setter and the array keeps no own index.
5162 if let Some((owner, property)) = lookup_key(object, key)
5163 && !owner.ptr_eq(object)
5164 {
5165 match &property {
5166 property if property.is_accessor() => {
5167 match &property.setter {
5168 Some(setter) if !matches!(setter, Value::Undefined) => {
5169 let receiver = Value::Object(object.clone());
5170 self.call_value(setter.clone(), receiver, vec![value])?;
5171 }
5172 _ => {
5173 return match on_failure {
5174 DeleteFailure::Throw => Err(self.type_error(format!(
5175 "cannot set property '{text}', it has only a getter"
5176 ))),
5177 DeleteFailure::Ignore => Ok(()),
5178 };
5179 }
5180 }
5181 return Ok(());
5182 }
5183 property if !property.writable => {
5184 return match on_failure {
5185 DeleteFailure::Throw => {
5186 Err(self.type_error(format!("'{text}' is read-only")))
5187 }
5188 DeleteFailure::Ignore => Ok(()),
5189 };
5190 }
5191 _ => {}
5192 }
5193 }
5194 if object.array_set(self.heap, index as usize, value.clone()) {
5195 return Ok(());
5196 }
5197 // Past the dense limit the slot is too far out to be worth one `Value`
5198 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5199 // constant time by keeping the index as an ordinary property. The store
5200 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5201 // to a legal program.
5202 object.define_key(key, Property::with_attributes(value, true, true));
5203 // Extend, never shorten: the index may be *inside* the current length (a
5204 // huge `length` with a sparse store), and shortening would delete the
5205 // sparse properties above it — including the one just stored.
5206 if index as usize + 1 > object.array_length().unwrap_or(0) {
5207 object.array_set_length(self.heap, index as usize + 1);
5208 }
5209 return Ok(());
5210 }
5211 }
5212 if text == Some("length") && object.is_array() {
5213 if !object.length_writable() {
5214 return match on_failure {
5215 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5216 DeleteFailure::Ignore => Ok(()),
5217 };
5218 }
5219 let length = value.to_number();
5220 if length.is_finite() && length >= 0.0 {
5221 let length = length as usize;
5222 // `a.length = n` with `n` below a non-configurable element cannot
5223 // drop that element, so the whole assignment fails. The spec makes
5224 // this a `TypeError` rather than a silent no-op, in any mode.
5225 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5226 // Sloppy mode stops the truncation at the blocking element
5227 // instead of failing; strict mode raises.
5228 // Both modes stop at the blocking element; they differ in
5229 // whether that is reported. The reference truncates *then*
5230 // throws, so the array is left in the shortened state.
5231 object.array_truncate(self.heap, blocked + 1);
5232 return match on_failure {
5233 DeleteFailure::Throw => {
5234 Err(self.type_error(format!("cannot delete property '{blocked}'")))
5235 }
5236 DeleteFailure::Ignore => Ok(()),
5237 };
5238 }
5239 object.array_set_length(self.heap, length);
5240 return Ok(());
5241 }
5242 }
5243 if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5244 {
5245 return match on_failure {
5246 DeleteFailure::Throw => Err(self.type_error(format!(
5247 "cannot add property {}, object is not extensible",
5248 key
5249 ))),
5250 DeleteFailure::Ignore => Ok(()),
5251 };
5252 }
5253 if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5254 if property.is_accessor() {
5255 match &property.setter {
5256 Some(setter) if !matches!(setter, Value::Undefined) => {
5257 let receiver = Value::Object(object.clone());
5258 self.call_value(setter.clone(), receiver, vec![value])?;
5259 }
5260 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5261 // Sloppy code swallows that refusal, strict code raises — the same
5262 // rule the read-only *data* property below follows, and skipping it
5263 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5264 // return silently. The reference answers `TypeError: 'x' is
5265 // read-only`.
5266 _ => {
5267 return match on_failure {
5268 DeleteFailure::Throw => {
5269 Err(self.type_error(format!("'{key}' is read-only")))
5270 }
5271 DeleteFailure::Ignore => Ok(()),
5272 };
5273 }
5274 }
5275 return Ok(());
5276 }
5277 // A non-writable data property refuses the write, own **or inherited**: an
5278 // own one stops here because nothing may change it, and an inherited one
5279 // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5280 //
5281 // The `ptr_eq` this used to carry meant an inherited read-only property fell
5282 // through to `define_data_key` and *did* create the shadow — `var o =
5283 // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5284 // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5285 // and `false`.
5286 if !property.writable {
5287 return match on_failure {
5288 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5289 DeleteFailure::Ignore => Ok(()),
5290 };
5291 }
5292 // An existing writable own property keeps its attributes: only the value
5293 // moves. Redefining instead would reset them, which is how a
5294 // non-configurable global `var` used to become deletable.
5295 if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5296 return Ok(());
5297 }
5298 }
5299 // No own data property: create one, shadowing whatever the prototype holds.
5300 object.define_data_key(key, value);
5301 Ok(())
5302 }
5303
5304 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5305 ///
5306 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5307 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5308 /// a virtual accessor gets its setter run without implementing `set_property` at all.
5309 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5310 /// the prototype, so the walk resumes above the object.
5311 fn lookup_for_write(
5312 &mut self,
5313 object: &Gc<JsObject>,
5314 key: &PropertyKey,
5315 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5316 let Some(exotic) = object.exotic() else {
5317 return Ok(lookup_key(object, key));
5318 };
5319 Ok(match exotic.get_own_property(self, object, key)? {
5320 Some(Some(property)) => Some((object.clone(), property)),
5321 Some(None) => lookup_key_above(object, key),
5322 None => lookup_key(object, key),
5323 })
5324 }
5325
5326 /// Delete `object[key]`.
5327 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5328 self.delete_property_key(object, &PropertyKey::from(key))
5329 }
5330
5331 /// [`Interp::delete_property`] with a key that may be a symbol.
5332 pub fn delete_property_key(
5333 &mut self,
5334 object: &Gc<JsObject>,
5335 key: &PropertyKey,
5336 ) -> JsResult<bool> {
5337 // A proxy decides for itself, and may even throw; the invariant checks live in
5338 // `proxy_delete`.
5339 if let Some(answer) = self.proxy_delete(object, key)? {
5340 return Ok(answer);
5341 }
5342 // A host class's `delete_property` trap decides; `false` is a refusal, which the
5343 // caller reports as a failed delete.
5344 if let Some(exotic) = object.exotic()
5345 && let Some(answer) = exotic.delete_property(self, object, key)?
5346 {
5347 return Ok(answer);
5348 }
5349 if let Some(index) = key.as_str().and_then(array_index)
5350 && let Some(length) = object.array_length()
5351 && (index as usize) < length
5352 {
5353 // An accessor defined on an index lives in the property table rather than the
5354 // element vector, so both have to be cleared: `delete` after
5355 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5356 object.delete_key(key);
5357 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5358 // index stops answering `in`.
5359 if object.element_is_undeletable(index) {
5360 return Ok(false);
5361 }
5362 object.array_set(self.heap, index as usize, Value::Hole);
5363 return Ok(true);
5364 }
5365 Ok(object.delete_key(key))
5366 }
5367
5368 // -- proxy traps --------------------------------------------------------
5369 //
5370 // A proxy's internal methods all look the same: ask the handler for the trap, call it
5371 // with the target and the operation's own arguments, then check the answer against
5372 // the target. The checks are not decoration — they are what stops a proxy from
5373 // reporting a `non-configurable` property as missing, which would let a frozen object
5374 // be rewritten by standing in front of it.
5375
5376 /// The target and handler of `object`, or `None` when it is not a proxy.
5377 ///
5378 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5379 /// one has to fail: the slots the traps would have been read from are gone.
5380 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5381 let Some(state) = object.proxy_state() else {
5382 return Ok(None);
5383 };
5384 let state = state.borrow();
5385 match (&state.target, &state.handler) {
5386 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5387 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5388 }
5389 }
5390
5391 /// Call `handler[name]`, or answer `None` when the trap is absent.
5392 ///
5393 /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5394 /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5395 /// back to the target.
5396 fn proxy_trap(
5397 &mut self,
5398 handler: &Value,
5399 name: &str,
5400 args: Vec<Value>,
5401 ) -> JsResult<Option<Value>> {
5402 let Value::Object(table) = handler else {
5403 return Err(self.type_error("proxy handler is not an object"));
5404 };
5405 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5406 match trap {
5407 Value::Undefined => Ok(None),
5408 Value::Object(function) if function.is_callable() => {
5409 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5410 Ok(Some(answer))
5411 }
5412 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5413 }
5414 }
5415
5416 /// Whether `object`'s own property `key` is one the target refuses to lose.
5417 ///
5418 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5419 /// its value behind the target's back. This goes through
5420 /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5421 /// elements and its `length` — both fixed, both outside the table — are covered.
5422 fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5423 Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5424 }
5425
5426 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5427 fn proxy_get(
5428 &mut self,
5429 object: &Gc<JsObject>,
5430 receiver: &Value,
5431 key: &PropertyKey,
5432 ) -> JsResult<Option<Value>> {
5433 let Some((target, handler)) = self.proxy_parts(object)? else {
5434 return Ok(None);
5435 };
5436 let key_value = self.key_value(key);
5437 let Some(result) = self.proxy_trap(
5438 &handler,
5439 "get",
5440 vec![Value::Object(target.clone()), key_value, receiver.clone()],
5441 )?
5442 else {
5443 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5444 // inherited getter still sees the proxy.
5445 return Ok(Some(
5446 self.get_property_key_for(&target, Some(receiver), key)?
5447 .unwrap_or(Value::Undefined),
5448 ));
5449 };
5450 if let Some(fixed) = Self::is_fixed_property(&target, key) {
5451 if fixed.is_accessor() {
5452 // A fixed accessor with no getter must read as `undefined`.
5453 let has_getter = fixed
5454 .getter
5455 .as_ref()
5456 .is_some_and(|getter| !matches!(getter, Value::Undefined));
5457 if !has_getter && !matches!(result, Value::Undefined) {
5458 return Err(self.type_error(format!(
5459 "proxy 'get' must report undefined for the non-configurable property '{key}'"
5460 )));
5461 }
5462 } else if !fixed.writable {
5463 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5464 if !fixed_value.same_value(&result) {
5465 return Err(self.type_error(format!(
5466 "proxy 'get' disagrees with the non-configurable property '{key}'"
5467 )));
5468 }
5469 }
5470 }
5471 Ok(Some(result))
5472 }
5473
5474 /// `[[Set]]` on a proxy.
5475 ///
5476 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5477 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5478 /// read-only store has.
5479 fn proxy_set(
5480 &mut self,
5481 object: &Gc<JsObject>,
5482 key: &PropertyKey,
5483 value: Value,
5484 receiver: &Value,
5485 ) -> JsResult<Option<bool>> {
5486 let Some((target, handler)) = self.proxy_parts(object)? else {
5487 return Ok(None);
5488 };
5489 let key_value = self.key_value(key);
5490 let Some(result) = self.proxy_trap(
5491 &handler,
5492 "set",
5493 vec![
5494 Value::Object(target.clone()),
5495 key_value,
5496 value.clone(),
5497 receiver.clone(),
5498 ],
5499 )?
5500 else {
5501 // No trap: store on the target, which is where an ordinary proxy write lands.
5502 self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5503 return Ok(Some(true));
5504 };
5505 if !result.to_boolean() {
5506 return Ok(Some(false));
5507 }
5508 if let Some(fixed) = Self::is_fixed_property(&target, key) {
5509 if fixed.is_accessor() {
5510 let has_setter = fixed
5511 .setter
5512 .as_ref()
5513 .is_some_and(|setter| !matches!(setter, Value::Undefined));
5514 if !has_setter {
5515 return Err(self.type_error(format!(
5516 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5517 )));
5518 }
5519 } else if !fixed.writable {
5520 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5521 if !fixed_value.same_value(&value) {
5522 return Err(self.type_error(format!(
5523 "proxy 'set' changed the non-configurable property '{key}'"
5524 )));
5525 }
5526 }
5527 }
5528 // A new property cannot appear on a target that refuses new properties.
5529 if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5530 return Err(self.type_error(format!(
5531 "proxy 'set' added '{key}' to a non-extensible target"
5532 )));
5533 }
5534 Ok(Some(true))
5535 }
5536
5537 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5538 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5539 let Some((target, handler)) = self.proxy_parts(object)? else {
5540 return Ok(None);
5541 };
5542 let key_value = self.key_value(key);
5543 let Some(result) = self.proxy_trap(
5544 &handler,
5545 "has",
5546 vec![Value::Object(target.clone()), key_value],
5547 )?
5548 else {
5549 return Ok(Some(self.has_own_or_inherited(&target, key)?));
5550 };
5551 if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5552 return Err(self.type_error(format!(
5553 "proxy 'has' denied the non-configurable property '{key}'"
5554 )));
5555 }
5556 // A non-extensible target cannot grow, so every own property it *has* is fixed.
5557 if !result.to_boolean()
5558 && !target.is_extensible()
5559 && Self::ordinary_own_property(&target, key).is_some()
5560 {
5561 return Err(self.type_error(format!(
5562 "proxy 'has' denied the own property '{key}' of a non-extensible target"
5563 )));
5564 }
5565 Ok(Some(result.to_boolean()))
5566 }
5567
5568 /// `[[Delete]]` on a proxy.
5569 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5570 let Some((target, handler)) = self.proxy_parts(object)? else {
5571 return Ok(None);
5572 };
5573 let key_value = self.key_value(key);
5574 let Some(result) = self.proxy_trap(
5575 &handler,
5576 "deleteProperty",
5577 vec![Value::Object(target.clone()), key_value],
5578 )?
5579 else {
5580 return Ok(Some(self.delete_property_key(&target, key)?));
5581 };
5582 if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5583 return Err(self.type_error(format!(
5584 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5585 )));
5586 }
5587 if result.to_boolean()
5588 && !target.is_extensible()
5589 && Self::ordinary_own_property(&target, key).is_some()
5590 {
5591 return Err(self.type_error(format!(
5592 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5593 )));
5594 }
5595 Ok(Some(result.to_boolean()))
5596 }
5597
5598 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5599 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5600 let Some((target, handler)) = self.proxy_parts(object)? else {
5601 return Ok(None);
5602 };
5603 let Some(result) =
5604 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5605 else {
5606 // No trap: the target's own keys, already in the order an object reports.
5607 return Ok(Some(self.object_own_property_keys(&target)?));
5608 };
5609 // `CreateListFromArrayLike` with the string-or-symbol restriction.
5610 let list = self.list_from_array_like(&result, true)?;
5611 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5612 for value in list {
5613 let key = self.propkey(&value)?;
5614 if keys.contains(&key) {
5615 return Err(self.type_error(format!(
5616 "proxy 'ownKeys' returned the duplicate key '{key}'"
5617 )));
5618 }
5619 keys.push(key);
5620 }
5621 for (key, property) in target.property_entries() {
5622 if !property.configurable && !keys.contains(&key) {
5623 return Err(self.type_error(format!(
5624 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5625 )));
5626 }
5627 if !target.is_extensible() && !keys.contains(&key) {
5628 return Err(self.type_error(format!(
5629 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5630 )));
5631 }
5632 }
5633 if !target.is_extensible() {
5634 let own = target.property_entries().len();
5635 if keys.len() != own {
5636 return Err(
5637 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5638 );
5639 }
5640 }
5641 Ok(Some(keys))
5642 }
5643
5644 /// `[[GetOwnProperty]]` on a proxy.
5645 fn proxy_get_own_property(
5646 &mut self,
5647 object: &Gc<JsObject>,
5648 key: &PropertyKey,
5649 ) -> JsResult<Option<Option<Property>>> {
5650 let Some((target, handler)) = self.proxy_parts(object)? else {
5651 return Ok(None);
5652 };
5653 let key_value = self.key_value(key);
5654 let Some(result) = self.proxy_trap(
5655 &handler,
5656 "getOwnPropertyDescriptor",
5657 vec![Value::Object(target.clone()), key_value],
5658 )?
5659 else {
5660 // No trap: the target's own descriptor is the answer. This has to go through
5661 // the same synthesis an ordinary object gets, because a proxy's own property
5662 // table is empty by design — reading it directly reported `undefined` for
5663 // every key, including an array's indices and `length`.
5664 return Ok(Some(Self::ordinary_own_property(&target, key)));
5665 };
5666 let answer = if matches!(result, Value::Undefined) {
5667 None
5668 } else {
5669 Some(self.property_from_descriptor(&result)?)
5670 };
5671 let fixed = Self::is_fixed_property(&target, key);
5672 match (&answer, &fixed) {
5673 // A non-configurable property cannot be reported as absent.
5674 (None, Some(_)) => {
5675 return Err(self.type_error(format!(
5676 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
5677 )));
5678 }
5679 (Some(descriptor), Some(fixed)) => {
5680 if descriptor.configurable {
5681 return Err(self.type_error(format!(
5682 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
5683 )));
5684 }
5685 if fixed.is_accessor() != descriptor.is_accessor() {
5686 return Err(self.type_error(format!(
5687 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
5688 )));
5689 }
5690 if !fixed.is_accessor() && !fixed.writable {
5691 let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
5692 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
5693 if !fixed_value.same_value(&reported) {
5694 return Err(self.type_error(format!(
5695 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
5696 )));
5697 }
5698 }
5699 }
5700 _ => {}
5701 }
5702 Ok(Some(answer))
5703 }
5704
5705 /// `[[DefineOwnProperty]]` on a proxy.
5706 fn proxy_define_property(
5707 &mut self,
5708 object: &Gc<JsObject>,
5709 key: &PropertyKey,
5710 property: Property,
5711 ) -> JsResult<Option<bool>> {
5712 let Some((target, handler)) = self.proxy_parts(object)? else {
5713 return Ok(None);
5714 };
5715 let key_value = self.key_value(key);
5716 let descriptor = self.descriptor_from_property(&property);
5717 let Some(result) = self.proxy_trap(
5718 &handler,
5719 "defineProperty",
5720 vec![Value::Object(target.clone()), key_value, descriptor],
5721 )?
5722 else {
5723 return Ok(None);
5724 };
5725 if !result.to_boolean() {
5726 return Ok(Some(false));
5727 }
5728 let fixed = Self::is_fixed_property(&target, key);
5729 let creating = Self::ordinary_own_property(&target, key).is_none();
5730 if creating && !target.is_extensible() {
5731 return Err(self.type_error(format!(
5732 "proxy 'defineProperty' added '{key}' to a non-extensible target"
5733 )));
5734 }
5735 if let Some(fixed) = fixed {
5736 if property.configurable {
5737 return Err(self.type_error(format!(
5738 "proxy 'defineProperty' made the non-configurable '{key}' configurable"
5739 )));
5740 }
5741 if !fixed.writable && property.writable && !fixed.is_accessor() {
5742 return Err(self.type_error(format!(
5743 "proxy 'defineProperty' made the read-only '{key}' writable"
5744 )));
5745 }
5746 }
5747 Ok(Some(true))
5748 }
5749
5750 /// `[[GetPrototypeOf]]` on a proxy.
5751 fn proxy_get_prototype_of(
5752 &mut self,
5753 object: &Gc<JsObject>,
5754 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
5755 let Some((target, handler)) = self.proxy_parts(object)? else {
5756 return Ok(None);
5757 };
5758 let Some(result) = self.proxy_trap(
5759 &handler,
5760 "getPrototypeOf",
5761 vec![Value::Object(target.clone())],
5762 )?
5763 else {
5764 return Ok(Some(target.proto()));
5765 };
5766 let proto = match &result {
5767 Value::Null => None,
5768 Value::Object(proto) => Some(proto.clone()),
5769 _ => {
5770 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
5771 }
5772 };
5773 if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
5774 return Err(self.type_error(
5775 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
5776 ));
5777 }
5778 Ok(Some(proto))
5779 }
5780
5781 /// `[[SetPrototypeOf]]` on a proxy.
5782 fn proxy_set_prototype_of(
5783 &mut self,
5784 object: &Gc<JsObject>,
5785 proto: Option<Gc<JsObject>>,
5786 ) -> JsResult<Option<bool>> {
5787 let Some((target, handler)) = self.proxy_parts(object)? else {
5788 return Ok(None);
5789 };
5790 let proto_value = match &proto {
5791 Some(proto) => Value::Object(proto.clone()),
5792 None => Value::Null,
5793 };
5794 let Some(result) = self.proxy_trap(
5795 &handler,
5796 "setPrototypeOf",
5797 vec![Value::Object(target.clone()), proto_value],
5798 )?
5799 else {
5800 target.set_proto(proto);
5801 return Ok(Some(true));
5802 };
5803 if result.to_boolean()
5804 && !target.is_extensible()
5805 && !same_proto(proto.as_ref(), target.proto().as_ref())
5806 {
5807 return Err(self.type_error(
5808 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
5809 ));
5810 }
5811 Ok(Some(result.to_boolean()))
5812 }
5813
5814 /// `[[IsExtensible]]` on a proxy.
5815 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
5816 let Some((target, handler)) = self.proxy_parts(object)? else {
5817 return Ok(None);
5818 };
5819 let Some(result) = self.proxy_trap(
5820 &handler,
5821 "isExtensible",
5822 vec![Value::Object(target.clone())],
5823 )?
5824 else {
5825 return Ok(Some(target.is_extensible()));
5826 };
5827 // The answer is not the proxy's to invent: it must agree with the target, or a
5828 // script could learn `false` while the target keeps accepting new properties.
5829 if result.to_boolean() != target.is_extensible() {
5830 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
5831 }
5832 Ok(Some(result.to_boolean()))
5833 }
5834
5835 /// `[[PreventExtensions]]` on a proxy.
5836 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
5837 let Some((target, handler)) = self.proxy_parts(object)? else {
5838 return Ok(None);
5839 };
5840 let Some(result) = self.proxy_trap(
5841 &handler,
5842 "preventExtensions",
5843 vec![Value::Object(target.clone())],
5844 )?
5845 else {
5846 target.set_extensible(false);
5847 return Ok(Some(true));
5848 };
5849 if result.to_boolean() && target.is_extensible() {
5850 return Err(self.type_error(
5851 "proxy 'preventExtensions' reported success but the target is still extensible",
5852 ));
5853 }
5854 Ok(Some(result.to_boolean()))
5855 }
5856
5857 /// `[[Call]]` on a proxy, through the `apply` trap.
5858 fn proxy_apply(
5859 &mut self,
5860 object: &Gc<JsObject>,
5861 this: Value,
5862 args: Vec<Value>,
5863 ) -> JsResult<Option<Value>> {
5864 let Some((target, handler)) = self.proxy_parts(object)? else {
5865 return Ok(None);
5866 };
5867 // The trap gets the arguments as one array, which is the shape the spec passes
5868 // and the shape `apply` traps are written against (`args[0]` is the first one).
5869 let arguments = self.new_array(args.clone());
5870 let this_for_trap = this.clone();
5871 let Some(result) = self.proxy_trap(
5872 &handler,
5873 "apply",
5874 vec![
5875 Value::Object(target.clone()),
5876 this_for_trap,
5877 Value::Object(arguments),
5878 ],
5879 )?
5880 else {
5881 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
5882 };
5883 Ok(Some(result))
5884 }
5885
5886 /// `[[Construct]]` on a proxy, through the `construct` trap.
5887 fn proxy_construct(
5888 &mut self,
5889 object: &Gc<JsObject>,
5890 args: Vec<Value>,
5891 new_target: &Value,
5892 ) -> JsResult<Option<Value>> {
5893 let Some((target, handler)) = self.proxy_parts(object)? else {
5894 return Ok(None);
5895 };
5896 if !target.is_callable() {
5897 return Err(self.type_error("proxy target is not a constructor"));
5898 }
5899 let arguments = self.new_array(args.clone());
5900 let Some(result) = self.proxy_trap(
5901 &handler,
5902 "construct",
5903 vec![
5904 Value::Object(target.clone()),
5905 Value::Object(arguments),
5906 new_target.clone(),
5907 ],
5908 )?
5909 else {
5910 return Ok(Some(self.construct(
5911 Value::Object(target),
5912 new_target.clone(),
5913 args,
5914 )?));
5915 };
5916 if !matches!(result, Value::Object(_)) {
5917 return Err(self.type_error("proxy 'construct' must return an object"));
5918 }
5919 Ok(Some(result))
5920 }
5921
5922 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
5923 pub(crate) fn has_own_or_inherited(
5924 &mut self,
5925 object: &Gc<JsObject>,
5926 key: &PropertyKey,
5927 ) -> JsResult<bool> {
5928 // The object itself first: it may be a proxy, and then the answer is its trap's.
5929 if let Some(answer) = self.proxy_has(object, key)? {
5930 return Ok(answer);
5931 }
5932 // A host class answers `in` for its own keys, which may live nowhere in a property
5933 // table — `"x" in point` is true because the class says so, not because a property
5934 // exists.
5935 if let Some(exotic) = object.exotic()
5936 && let Some(answer) = exotic.has_property(self, object, key)?
5937 {
5938 return Ok(answer);
5939 }
5940 // `has_own` rather than `own_property_key`: an array's elements and its derived
5941 // `length` are invisible to the property table, and `Array.prototype` is an array.
5942 // A host class's `get_own_property` counts too, because the reference's
5943 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
5944 // lives — a class with only `get_own_property` answers `in` through it.
5945 if self.exotic_has_own(object, key)? {
5946 return Ok(true);
5947 }
5948 // A hole is *not* the end of the search: the chain may still have the key, which
5949 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
5950 for ancestor in object.chain() {
5951 // A proxy further up the chain answers for itself.
5952 if let Some(answer) = self.proxy_has(&ancestor, key)? {
5953 return Ok(answer);
5954 }
5955 // Same for a host class: a prototype may be one, and `in` reaches it.
5956 if let Some(exotic) = ancestor.exotic()
5957 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
5958 {
5959 return Ok(answer);
5960 }
5961 if self.exotic_has_own(&ancestor, key)? {
5962 return Ok(true);
5963 }
5964 }
5965 Ok(false)
5966 }
5967
5968 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
5969 /// trap included.
5970 ///
5971 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
5972 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
5973 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
5974 if let Some(exotic) = object.exotic()
5975 && let Some(answer) = exotic.get_own_property(self, object, key)?
5976 {
5977 return Ok(answer.is_some());
5978 }
5979 Ok(has_own(object, key))
5980 }
5981
5982 /// `CreateListFromArrayLike`, optionally restricted to property keys.
5983 ///
5984 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
5985 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
5986 /// `TypeError` instead of a property named `"1.5"`.
5987 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
5988 let object = self.object_from(value)?;
5989 let length = self
5990 .get_property(&object, "length")?
5991 .map(|value| value.to_number())
5992 .unwrap_or(0.0);
5993 if !length.is_finite() || length < 0.0 {
5994 return Err(self.type_error("invalid array-like length"));
5995 }
5996 let length = length as usize;
5997 let mut items = Vec::with_capacity(length.min(1024));
5998 for index in 0..length {
5999 let item = self
6000 .get_property(&object, &index.to_string())?
6001 .unwrap_or(Value::Undefined);
6002 if keys_only && matches!(&item, Value::Symbol(_)) {
6003 items.push(item);
6004 continue;
6005 }
6006 if keys_only && !matches!(&item, Value::String(_)) {
6007 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6008 }
6009 items.push(item);
6010 }
6011 Ok(items)
6012 }
6013
6014 /// A `Property` from the descriptor object a trap returned.
6015 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6016 let object = self.object_from(value)?;
6017 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6018 interp.get_property(&object, name)
6019 };
6020 let getter = field(self, "get")?;
6021 let setter = field(self, "set")?;
6022 let accessor = getter.is_some() || setter.is_some();
6023 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6024 Ok(interp
6025 .get_property(&object, name)?
6026 .is_some_and(|value| value.to_boolean()))
6027 };
6028 let enumerable = boolean(self, "enumerable")?;
6029 let configurable = boolean(self, "configurable")?;
6030 if accessor {
6031 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6032 return Err(
6033 self.type_error("a descriptor cannot be both a data property and an accessor")
6034 );
6035 }
6036 Ok(Property {
6037 getter: getter.or(Some(Value::Undefined)),
6038 setter: setter.or(Some(Value::Undefined)),
6039 enumerable,
6040 configurable,
6041 writable: false,
6042 value: None,
6043 })
6044 } else {
6045 Ok(Property {
6046 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6047 writable: boolean(self, "writable")?,
6048 enumerable,
6049 configurable,
6050 getter: None,
6051 setter: None,
6052 })
6053 }
6054 }
6055
6056 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6057 fn descriptor_from_property(&mut self, property: &Property) -> Value {
6058 let object = self.new_object(None);
6059 if property.is_accessor() {
6060 let getter = property.getter.clone().unwrap_or(Value::Undefined);
6061 let setter = property.setter.clone().unwrap_or(Value::Undefined);
6062 object.define_data("get", getter);
6063 object.define_data("set", setter);
6064 } else {
6065 let value = property.value.clone().unwrap_or(Value::Undefined);
6066 object.define_data("value", value);
6067 object.define_data("writable", Value::Bool(property.writable));
6068 }
6069 object.define_data("enumerable", Value::Bool(property.enumerable));
6070 object.define_data("configurable", Value::Bool(property.configurable));
6071 Value::Object(object)
6072 }
6073
6074 // -- calling ------------------------------------------------------------
6075
6076 /// Call `callee` with `this` and `args`.
6077 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6078 let Value::Object(function) = &callee else {
6079 // `typeof x === "function"` is not enough to make `x()` legal: only a
6080 // callable object is. `null` and `undefined` need no special wording
6081 // here — their `ToString` already reads the way the reference's does.
6082 let what = format!("{} is not a function", callee.to_js_string());
6083 return Err(Signal::Throw(self.make_error("TypeError", &what)));
6084 };
6085 // A proxy of a function is called through its `apply` trap. It has no
6086 // `ObjectKind::Function` of its own, so this has to come before the dispatch
6087 // below, and a proxy of a non-function has nothing to forward to.
6088 if function.proxy_state().is_some() {
6089 return match self.proxy_apply(function, this, args)? {
6090 Some(result) => Ok(result),
6091 None => Err(Signal::Throw(
6092 self.make_error("TypeError", "proxy target is not callable"),
6093 )),
6094 };
6095 }
6096 let callable = function.with(|data| match &data.kind {
6097 ObjectKind::Function(callable) => match callable {
6098 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6099 // The `Rc` is cloned out so the borrow of this object's data is released
6100 // before the closure runs: the closure may touch the same object.
6101 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6102 Callable::Bound {
6103 target,
6104 this,
6105 args: leading,
6106 } => Some(NativeCall::Bound {
6107 target: target.clone(),
6108 this: this.clone(),
6109 leading: leading.clone(),
6110 }),
6111 Callable::Bytecode { code, env } => {
6112 Some(NativeCall::Bytecode(code.clone(), env.clone()))
6113 }
6114 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6115 Callable::PromiseResolve(promise) => {
6116 Some(NativeCall::PromiseResolve(promise.clone()))
6117 }
6118 Callable::PromiseReject(promise) => {
6119 Some(NativeCall::PromiseReject(promise.clone()))
6120 }
6121 Callable::AwaitResume {
6122 coroutine,
6123 promise,
6124 kind,
6125 } => Some(NativeCall::AwaitResume {
6126 coroutine: coroutine.clone(),
6127 promise: promise.clone(),
6128 kind: *kind,
6129 }),
6130 Callable::CombinatorSettle {
6131 state,
6132 index,
6133 fulfilled,
6134 } => Some(NativeCall::CombinatorSettle {
6135 state: state.clone(),
6136 index: *index,
6137 fulfilled: *fulfilled,
6138 }),
6139 Callable::FinallyShim {
6140 callback,
6141 fulfilled,
6142 } => Some(NativeCall::FinallyShim {
6143 callback: callback.clone(),
6144 fulfilled: *fulfilled,
6145 }),
6146 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6147 Callable::CompletedReturn {
6148 generator,
6149 promise,
6150 rejected,
6151 } => Some(NativeCall::CompletedReturn {
6152 generator: generator.clone(),
6153 promise: promise.clone(),
6154 rejected: *rejected,
6155 }),
6156 Callable::YieldResult {
6157 generator,
6158 promise,
6159 done,
6160 } => Some(NativeCall::YieldResult {
6161 generator: generator.clone(),
6162 promise: promise.clone(),
6163 done: *done,
6164 }),
6165 Callable::DisposeStep {
6166 remaining,
6167 promise,
6168 error,
6169 rejected,
6170 } => Some(NativeCall::DisposeStep {
6171 remaining: remaining.clone(),
6172 promise: promise.clone(),
6173 error: error.clone(),
6174 rejected: *rejected,
6175 }),
6176 Callable::GeneratorResume {
6177 generator,
6178 promise,
6179 kind,
6180 } => Some(NativeCall::GeneratorResume {
6181 generator: generator.clone(),
6182 promise: promise.clone(),
6183 kind: *kind,
6184 }),
6185 Callable::SettlePromise {
6186 promise,
6187 value,
6188 rejected,
6189 } => Some(NativeCall::SettlePromise {
6190 promise: promise.clone(),
6191 value: value.clone(),
6192 rejected: *rejected,
6193 }),
6194 },
6195 _ => None,
6196 });
6197 match callable {
6198 Some(NativeCall::Host(func)) => {
6199 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6200 // function by name rather than stopping at the caller.
6201 let frame_less = function
6202 .own_property("_frame_less")
6203 .and_then(|property| property.value)
6204 .is_some_and(|value| value.to_boolean());
6205 let outer = if frame_less {
6206 None
6207 } else {
6208 self.native_frames
6209 .push((function.clone(), self.frames.len()));
6210 Some(self.current_native.replace(function.clone()))
6211 };
6212 let result = {
6213 let mut body = func.borrow_mut();
6214 body(self, this, &args)
6215 };
6216 if !frame_less {
6217 self.native_frames.pop();
6218 self.current_native = outer.flatten();
6219 }
6220 result
6221 }
6222 Some(NativeCall::Native(func)) => {
6223 // A function marked `_frame_less` is one the reference implements
6224 // without a call frame — `eval` is the only one so far.
6225 let frame_less = function
6226 .own_property("_frame_less")
6227 .and_then(|property| property.value)
6228 .is_some_and(|value| value.to_boolean());
6229 let outer = if frame_less {
6230 None
6231 } else {
6232 self.native_frames
6233 .push((function.clone(), self.frames.len()));
6234 Some(self.current_native.replace(function.clone()))
6235 };
6236 let result = func(self, this, &args);
6237 if !frame_less {
6238 self.native_frames.pop();
6239 self.current_native = outer.flatten();
6240 }
6241 result
6242 }
6243 Some(NativeCall::Revoker(slots)) => {
6244 // Idempotent: revoking twice answers `undefined` again rather than
6245 // complaining, which is what the spec says and what a `finally` block
6246 // relies on.
6247 let mut state = slots.borrow_mut();
6248 state.target = None;
6249 state.handler = None;
6250 Ok(Value::Undefined)
6251 }
6252 Some(NativeCall::PromiseResolve(promise)) => {
6253 // One-shot: a second call is silently ignored, which
6254 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6255 let value = args.first().cloned().unwrap_or(Value::Undefined);
6256 self.resolve_promise_with(&promise, value)?;
6257 Ok(Value::Undefined)
6258 }
6259 Some(NativeCall::PromiseReject(promise)) => {
6260 let reason = args.first().cloned().unwrap_or(Value::Undefined);
6261 self.reject_promise(&promise, reason);
6262 Ok(Value::Undefined)
6263 }
6264 Some(NativeCall::CombinatorSettle {
6265 state,
6266 index,
6267 fulfilled,
6268 }) => {
6269 let value = args.first().cloned().unwrap_or(Value::Undefined);
6270 self.settle_combinator(&state, index, fulfilled, value)?;
6271 Ok(Value::Undefined)
6272 }
6273 Some(NativeCall::AwaitResume {
6274 coroutine,
6275 promise,
6276 kind,
6277 }) => {
6278 // Resume *inline*, in the reaction that delivered the value. Deferring it
6279 // by another job inserts a tick between every `await` and its
6280 // continuation, which reorders `await` against unrelated `then` chains —
6281 // `f().then(g)` then runs before `f`'s own next statement.
6282 self.drive_async(
6283 &coroutine,
6284 &promise,
6285 kind,
6286 args.first().cloned().unwrap_or(Value::Undefined),
6287 )
6288 .map(|()| Value::Undefined)
6289 }
6290 Some(NativeCall::FinallyShim {
6291 callback,
6292 fulfilled,
6293 }) => {
6294 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6295 // that settles with the *original* outcome once the callback's result has
6296 // settled. The callback's own value is discarded — that is the whole
6297 // difference between `finally` and `then`.
6298 let original = args.first().cloned().unwrap_or(Value::Undefined);
6299 let result = match &callback {
6300 Some(callback) => {
6301 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6302 }
6303 None => Value::Undefined,
6304 };
6305 let resolved = self.promise_resolve_value(result)?;
6306 let Value::Object(resolved) = resolved else {
6307 return Ok(original);
6308 };
6309 // The wait is a chained promise rather than a bare return, so a callback
6310 // that returns a slow promise really does delay the continuation.
6311 let waiting = self.new_promise();
6312 let pass = JsObject::function(
6313 self.heap,
6314 Some(self.realm.function_proto.clone()),
6315 Callable::SettlePromise {
6316 promise: waiting.clone(),
6317 value: original,
6318 rejected: !fulfilled,
6319 },
6320 );
6321 let pass = Value::Object(pass);
6322 // Whichever way the callback's promise settles, the original outcome wins.
6323 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6324 Ok(Value::Object(waiting))
6325 }
6326 Some(NativeCall::DisposeStep {
6327 remaining,
6328 promise,
6329 error,
6330 rejected,
6331 }) => {
6332 let error = if rejected {
6333 let reason = args.first().cloned().unwrap_or(Value::Undefined);
6334 self.merge_dispose_error(reason, error)
6335 } else {
6336 error
6337 };
6338 self.dispose_step(&remaining, &promise, error)?;
6339 Ok(Value::Undefined)
6340 }
6341 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6342 Some(NativeCall::CompletedReturn {
6343 generator,
6344 promise,
6345 rejected,
6346 }) => {
6347 let value = args.first().cloned().unwrap_or(Value::Undefined);
6348 let outcome = if rejected {
6349 AsyncOutcome::Error(value)
6350 } else {
6351 AsyncOutcome::Value(self.iterator_result(value, true)?)
6352 };
6353 self.settle_async_request(&generator, &promise, outcome)?;
6354 Ok(Value::Undefined)
6355 }
6356 Some(NativeCall::YieldResult {
6357 generator,
6358 promise,
6359 done,
6360 }) => {
6361 let value = args.first().cloned().unwrap_or(Value::Undefined);
6362 let result = self.iterator_result(value, done)?;
6363 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6364 Ok(Value::Undefined)
6365 }
6366 Some(NativeCall::GeneratorResume {
6367 generator,
6368 promise,
6369 kind,
6370 }) => {
6371 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6372 // tick and reorders the generator against other chains.
6373 self.step_async_generator(
6374 &generator,
6375 &promise,
6376 kind,
6377 args.first().cloned().unwrap_or(Value::Undefined),
6378 )
6379 .map(|()| Value::Undefined)
6380 }
6381 Some(NativeCall::SettlePromise {
6382 promise,
6383 value,
6384 rejected,
6385 }) => {
6386 if rejected {
6387 self.reject_promise(&promise, value);
6388 } else {
6389 self.fulfill_promise(&promise, value);
6390 }
6391 Ok(Value::Undefined)
6392 }
6393 Some(NativeCall::Bound {
6394 target,
6395 this: bound_this,
6396 leading,
6397 }) => {
6398 let mut all = leading;
6399 all.extend(args);
6400 self.call_value(target, bound_this, all)
6401 }
6402 Some(NativeCall::Bytecode(code, env)) => {
6403 if code.code.kind.is_generator() {
6404 return self.new_generator(callee, this, args);
6405 }
6406 if code.code.kind.is_async() {
6407 // Same coroutine machinery as a generator; the difference is only in
6408 // what the completion does — see `new_async_function`.
6409 return self.new_async_function(callee, this, args);
6410 }
6411 self.execute(code, env, this, args, callee)
6412 }
6413 None => Err(Signal::Throw(
6414 self.make_error("TypeError", "not a function"),
6415 )),
6416 }
6417 }
6418
6419 /// Give a freshly built function its own `prototype` object.
6420 ///
6421 /// Every function that can be used with `new` carries one, and its
6422 /// `constructor` points back at the function — a reference cycle, which is
6423 /// exactly what the collector's cycle pass exists to reclaim.
6424 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6425 let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6426 let constructor = Value::Object(function.clone());
6427 prototype.define(
6428 "constructor",
6429 Property::with_attributes(constructor, true, false),
6430 );
6431 let value = Value::Object(prototype);
6432 function.define("prototype", Property::prototype_of(value, true));
6433 }
6434
6435 /// The object `special_object` builds.
6436 ///
6437 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6438 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6439 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6440 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6441 /// write through `arguments` does not reach the parameter.
6442 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6443 match magic {
6444 0 | 1 => {
6445 let args = self.frame().passed().to_vec();
6446 let proto = self.realm.object_proto.clone();
6447 let object = self.new_object(Some(proto));
6448 // The marker `Object.prototype.toString` needs: an arguments object is an
6449 // ordinary object apart from reporting `[object Arguments]`, and that has
6450 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6451 // show up ahead of them in a key listing anyway — it is non-enumerable.
6452 self.internal_set(&object, "_class", self.string("Arguments"));
6453 // `length` is writable and configurable but neither enumerable nor a
6454 // plain data property: `Object.keys(arguments)` lists the indices only,
6455 // which is how `{...arguments}` copies them without the length.
6456 object.define(
6457 "length",
6458 Property::with_attributes(Value::Int(args.len() as i32), true, false),
6459 );
6460 for (index, value) in args.into_iter().enumerate() {
6461 object.define_data(&index.to_string(), value);
6462 }
6463 // An arguments object is iterable: `[...arguments]` and
6464 // `for (const a of arguments)` both work, through the *array* iterator
6465 // because the object is array-like. Without this the whole spread form
6466 // reported "not iterable".
6467 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
6468 let values = self
6469 .realm
6470 .array_proto
6471 .own_property("values")
6472 .and_then(|property| property.value);
6473 if let Some(values) = values {
6474 object.define_key(
6475 &iterator_key,
6476 Property::with_attributes(values, true, false),
6477 );
6478 }
6479 Ok(Value::Object(object))
6480 }
6481 // `this.active_func`: the constructor `super()` resolves against.
6482 //
6483 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
6484 // own, so it inherits this from the function it was written in along with `this`
6485 // — and that is a lexical relationship, not a stack one: an arrow that escaped
6486 // the constructor and is called back later (`iter.return = () => super()`) has
6487 // the constructor nowhere on the stack. The compiler therefore reads it out of
6488 // a closure variable of the enclosing function, exactly as the reference does
6489 // with its `this_active_func` local.
6490 2 => Ok(self
6491 .current_callee()
6492 .map_or(Value::Undefined, Value::Object)),
6493 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
6494 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
6495 // its own either, so the lookup walks out to the nearest non-arrow frame for
6496 // the same reason as `this.active_func` above — without that, `super()` inside
6497 // an arrow passed `undefined` as the new target and the parent constructor was
6498 // then rejected for being invoked without `new`.
6499 3 => Ok(self
6500 .eval_new_target
6501 .clone()
6502 .unwrap_or_else(|| self.frame().new_target.clone())),
6503 // `[[HomeObject]]` of the function being run: what `super` is relative to.
6504 // An arrow has none of its own, so the lookup walks out to the enclosing
6505 // method — which is why `super` works inside an arrow inside a method.
6506 4 => Ok(self
6507 .frames
6508 .iter()
6509 .rev()
6510 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6511 .map_or(Value::Undefined, Value::Object)),
6512 // `import.meta`: the innermost module body's meta object. Outside a module
6513 // the compiler never emits this, so an empty fallback is unreachable rather
6514 // than permissive.
6515 6 => {
6516 let name = self.module_stack.last().cloned();
6517 let meta = name
6518 .and_then(|name| self.modules.get(&name).cloned())
6519 .and_then(|module| module.with(|r| r.import_meta.clone()));
6520 Ok(meta.map_or(Value::Undefined, Value::Object))
6521 }
6522 other => Err(Signal::Throw(self.make_error(
6523 "InternalError",
6524 &format!("special_object {other} is not implemented yet"),
6525 ))),
6526 }
6527 }
6528
6529 /// `[[HomeObject]]` of the innermost function that has one, if any.
6530 ///
6531 /// An arrow has none, so the search walks out to the enclosing method — the same
6532 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
6533 /// inside a method.
6534 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
6535 self.frames
6536 .iter()
6537 .rev()
6538 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6539 }
6540
6541 /// The dispose method a `using` declaration should snapshot, or an error.
6542 ///
6543 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
6544 /// is what makes a resource that only knows the synchronous protocol usable in both
6545 /// forms.
6546 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
6547 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
6548 if value.is_nullish() {
6549 return Ok(Value::Undefined);
6550 }
6551 let Some(object) = value.as_object() else {
6552 return Err(self.type_error("not an object"));
6553 };
6554 let mut method = if await_form {
6555 let found = self.get_property_key(
6556 object,
6557 &self.realm.well_known_key(WellKnown::AsyncDisposable),
6558 )?;
6559 match found {
6560 Some(found) if !found.is_nullish() => Some(found),
6561 _ => self
6562 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
6563 }
6564 } else {
6565 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
6566 };
6567 let Some(found) = method.take() else {
6568 return Err(self.type_error("value is not disposable"));
6569 };
6570 if found.is_nullish() {
6571 return Err(self.type_error("value is not disposable"));
6572 }
6573 let callable = found.as_object().is_some_and(|object| object.is_callable());
6574 if !callable {
6575 return Err(self.type_error("dispose method is not a function"));
6576 }
6577 Ok(found)
6578 }
6579
6580 /// Call one resource's disposer, folding a failure into `error_state`.
6581 ///
6582 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
6583 /// because a captured `using` binding lives in its reference cell and the local slot is
6584 /// stale — a closure over the resource is legal and must not change what is disposed.
6585 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
6586 let value = self.get_loc(slot);
6587 let method = self.get_loc(slot + 1);
6588 // A resource that was never initialised — its declaration threw — or that is
6589 // `null`/`undefined` has nothing to dispose.
6590 if value.is_nullish() || matches!(value, Value::Uninitialized) {
6591 return Ok(error_state);
6592 }
6593 if matches!(method, Value::Undefined | Value::Uninitialized) {
6594 return Ok(error_state);
6595 }
6596 match self.call_value(method, value, Vec::new()) {
6597 Ok(_) => Ok(error_state),
6598 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
6599 Err(other) => Err(other),
6600 }
6601 }
6602
6603 /// Combine a disposal failure with whatever was already going wrong.
6604 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
6605 if matches!(error_state, Value::Uninitialized) {
6606 return new_error;
6607 }
6608 self.new_suppressed_error(new_error, error_state)
6609 }
6610
6611 /// A `SuppressedError` instance built straight from its prototype.
6612 ///
6613 /// Not through the constructor: a script that rewrites
6614 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
6615 /// error wrapping.
6616 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
6617 let proto = self
6618 .realm
6619 .suppressed_error_proto
6620 .clone()
6621 .unwrap_or_else(|| self.realm.error_proto.clone());
6622 let object = self.new_object(Some(proto));
6623 object.define("error", Property::with_attributes(error, true, true));
6624 object.define(
6625 "suppressed",
6626 Property::with_attributes(suppressed, true, true),
6627 );
6628 object.define(
6629 "message",
6630 Property::with_attributes(self.string("SuppressedError"), true, true),
6631 );
6632 self.internal_set(&object, "_class", self.string("Error"));
6633 self.add_stack(&object);
6634 Value::Object(object)
6635 }
6636
6637 /// Call `callee`, or push its frame and let the main loop run it.
6638 ///
6639 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
6640 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
6641 /// continues, so `function f(){ return f() }` costs heap and stops at
6642 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
6643 /// is entered directly, and natives do not re-enter JavaScript in this
6644 /// milestone.
6645 ///
6646 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
6647 /// because the returning frame will.
6648 /// The elements of an array-like value, as a call argument list.
6649 ///
6650 /// `apply` accepts any array-like, not only a real array: the reference reads
6651 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
6652 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
6653 let Some(object) = value.as_object().cloned() else {
6654 if value.is_nullish() {
6655 // `f.apply(this, null)` passes no arguments at all.
6656 return Ok(Vec::new());
6657 }
6658 return Err(self.type_error("createListFromArrayLike called on non-object"));
6659 };
6660 let length = match self.get_property(&object, "length")? {
6661 Some(length) => length.to_number(),
6662 None => 0.0,
6663 };
6664 if !length.is_finite() || length <= 0.0 {
6665 return Ok(Vec::new());
6666 }
6667 let length = (length as usize).min(1_000_000);
6668 let mut args = Vec::with_capacity(length);
6669 for index in 0..length {
6670 let element = self.get_property(&object, &index.to_string())?;
6671 args.push(element.unwrap_or(Value::Undefined));
6672 }
6673 Ok(args)
6674 }
6675
6676 /// Turn a call to a generator function into a generator object.
6677 ///
6678 /// The frame is built exactly as an ordinary call would build it, then detached and
6679 /// stored in the generator before any body instruction runs — which is what makes
6680 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
6681 /// is `initial_yield`, the first instruction of every suspending body.
6682 pub fn new_generator(
6683 &mut self,
6684 function: Value,
6685 this: Value,
6686 args: Vec<Value>,
6687 ) -> JsResult<Value> {
6688 let Some(object) = function.as_object().cloned() else {
6689 return Err(self.type_error("not a generator function"));
6690 };
6691 let Some((code, env)) = bytecode_of(&object) else {
6692 return Err(self.type_error("not a generator function"));
6693 };
6694 let is_async = code.code.kind.is_async();
6695 self.push_frame(code, env, this, args, function)?;
6696 let frame = self.frames.pop().expect("push_frame just pushed it");
6697 // A fresh generator is *suspended at start*: the body has not run, so a
6698 // `return`/`throw` on it finishes without executing anything.
6699 let mut state = GeneratorState {
6700 frame: Some(frame),
6701 phase: GeneratorPhase::SuspendedStart,
6702 parked_on_await: false,
6703 parked_on_yield_star: false,
6704 requests: std::collections::VecDeque::new(),
6705 async_busy: false,
6706 };
6707 // Run to the first suspension. For a generator that is `initial_yield`, so no
6708 // body code runs; for a malformed body it would be the first `yield`.
6709 // An `async function*` answers an async generator: same coroutine, but its
6710 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
6711 let proto = if is_async {
6712 self.realm
6713 .async_generator_proto
6714 .clone()
6715 .unwrap_or_else(|| self.realm.generator_proto.clone())
6716 } else {
6717 self.realm.generator_proto.clone()
6718 };
6719 let generator = self.new_object(Some(proto));
6720 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
6721 Ok(_) => {}
6722 Err(error) => return Err(error),
6723 }
6724 generator.with_mut(|data| {
6725 data.kind = ObjectKind::Generator(Box::new(state));
6726 });
6727 Ok(Value::Object(generator))
6728 }
6729
6730 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
6731 ///
6732 /// Returns the `{value, done}` object itself rather than the pair, because a
6733 /// `yield*` suspension already has one — the inner iterator's own result — and the
6734 /// protocol says to hand that straight through rather than nest it.
6735 /// Advance a generator and report *why* it parked.
6736 ///
6737 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
6738 /// "hand this value to the caller" — but an async generator does: an `await` has to
6739 /// settle before it can answer, while a `yield` is the answer.
6740 fn resume_generator_detailed(
6741 &mut self,
6742 generator: &Gc<JsObject>,
6743 kind: ResumeKind,
6744 value: Value,
6745 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
6746 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
6747 ObjectKind::Generator(state) => Some(std::mem::replace(
6748 state.as_mut(),
6749 GeneratorState {
6750 frame: None,
6751 phase: GeneratorPhase::Executing,
6752 parked_on_await: false,
6753 parked_on_yield_star: false,
6754 requests: std::collections::VecDeque::new(),
6755 async_busy: false,
6756 },
6757 )),
6758 _ => None,
6759 }) else {
6760 return Err(self.type_error("not a generator"));
6761 };
6762 let result = self.step_generator(&mut state, kind, value);
6763 generator.with_mut(|data| {
6764 data.kind = ObjectKind::Generator(Box::new(state));
6765 });
6766 result
6767 }
6768
6769 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
6770 ///
6771 /// Returns the `{value, done}` object itself rather than the pair, because a
6772 /// `yield*` suspension already has one — the inner iterator's own result — and the
6773 /// protocol says to hand that straight through rather than nest it.
6774 pub fn resume_generator(
6775 &mut self,
6776 generator: &Gc<JsObject>,
6777 kind: ResumeKind,
6778 value: Value,
6779 ) -> JsResult<Value> {
6780 let (value, done, ready, _reason) =
6781 self.resume_generator_detailed(generator, kind, value)?;
6782 if ready {
6783 return Ok(value);
6784 }
6785 self.iterator_result(value, done)
6786 }
6787
6788 /// `next`/`return`/`throw` on an async generator, which answer a promise.
6789 ///
6790 /// The body is the same coroutine a sync generator runs; what changes is that an
6791 /// `await` inside it has to settle before the method can answer, so the step is
6792 /// driven off the job queue rather than returning inline.
6793 pub fn resume_async_generator(
6794 &mut self,
6795 generator: &Gc<JsObject>,
6796 kind: ResumeKind,
6797 value: Value,
6798 ) -> JsResult<Value> {
6799 let promise = self.new_promise();
6800 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
6801 // that order, and the second value must reach the *second* `yield`.
6802 let idle = generator.with_mut(|data| match &mut data.kind {
6803 ObjectKind::Generator(state) => {
6804 state.requests.push_back(AsyncRequest {
6805 kind,
6806 value,
6807 promise: promise.clone(),
6808 });
6809 !state.async_busy
6810 }
6811 _ => false,
6812 });
6813 if idle {
6814 self.next_async_request(generator)?;
6815 }
6816 Ok(Value::Object(promise))
6817 }
6818
6819 /// Serve the front queued request, if the generator is free to run one.
6820 ///
6821 /// A finished generator answers from the queue without running anything:
6822 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
6823 /// first, and `throw(e)` rejects.
6824 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
6825 enum Front {
6826 Idle,
6827 Run(ResumeKind, Value, Gc<JsObject>),
6828 Finished(ResumeKind, Value, Gc<JsObject>),
6829 }
6830 let front = generator.with_mut(|data| match &mut data.kind {
6831 ObjectKind::Generator(state) => {
6832 let Some(request) = state.requests.front() else {
6833 return Front::Idle;
6834 };
6835 // Busy means a request is still in flight — awaiting inside the body, not
6836 // finished. Serving another now would interleave two requests.
6837 if state.async_busy && state.phase != GeneratorPhase::Completed {
6838 return Front::Idle;
6839 }
6840 let kind = request.kind;
6841 let value = request.value.clone();
6842 let promise = request.promise.clone();
6843 state.async_busy = true;
6844 if state.phase == GeneratorPhase::Completed {
6845 Front::Finished(kind, value, promise)
6846 } else {
6847 Front::Run(kind, value, promise)
6848 }
6849 }
6850 _ => Front::Idle,
6851 });
6852 match front {
6853 Front::Idle => Ok(()),
6854 Front::Run(kind, value, promise) => {
6855 self.step_async_generator(generator, &promise, kind, value)
6856 }
6857 Front::Finished(kind, value, promise) => match kind {
6858 ResumeKind::Throw => {
6859 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
6860 }
6861 ResumeKind::Next | ResumeKind::Start => {
6862 let result = self.iterator_result(Value::Undefined, true)?;
6863 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
6864 }
6865 ResumeKind::Return => {
6866 // `js_async_generator_completed_return`: the value is awaited before it
6867 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
6868 // finished generator answers `1`, not a promise.
6869 let resolved = match self.promise_resolve_value(value) {
6870 Ok(resolved) => resolved,
6871 Err(Signal::Throw(reason)) => {
6872 return self.settle_async_request(
6873 generator,
6874 &promise,
6875 AsyncOutcome::Error(reason),
6876 );
6877 }
6878 Err(other) => return Err(other),
6879 };
6880 let done = JsObject::function(
6881 self.heap,
6882 Some(self.realm.function_proto.clone()),
6883 Callable::CompletedReturn {
6884 generator: generator.clone(),
6885 promise: promise.clone(),
6886 rejected: false,
6887 },
6888 );
6889 let failed = JsObject::function(
6890 self.heap,
6891 Some(self.realm.function_proto.clone()),
6892 Callable::CompletedReturn {
6893 generator: generator.clone(),
6894 promise: promise.clone(),
6895 rejected: true,
6896 },
6897 );
6898 let Value::Object(resolved) = resolved else {
6899 return self.settle_async_request(
6900 generator,
6901 &promise,
6902 AsyncOutcome::Error(Value::Undefined),
6903 );
6904 };
6905 self.perform_then(
6906 &resolved,
6907 Some(Value::Object(done)),
6908 Some(Value::Object(failed)),
6909 )?;
6910 Ok(())
6911 }
6912 },
6913 }
6914 }
6915
6916 /// Settle the front request and start the next one.
6917 ///
6918 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
6919 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
6920 /// generator would strand every later request.
6921 fn settle_async_request(
6922 &mut self,
6923 generator: &Gc<JsObject>,
6924 promise: &Gc<JsObject>,
6925 outcome: AsyncOutcome,
6926 ) -> JsResult<()> {
6927 let settled = generator.with_mut(|data| match &mut data.kind {
6928 ObjectKind::Generator(state) => {
6929 let front = state.requests.front();
6930 debug_assert!(
6931 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
6932 "a request settled outside its turn"
6933 );
6934 state.requests.pop_front();
6935 state.async_busy = false;
6936 true
6937 }
6938 _ => false,
6939 });
6940 if settled {
6941 match outcome {
6942 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
6943 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
6944 }
6945 }
6946 self.next_async_request(generator)
6947 }
6948
6949 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
6950 ///
6951 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
6952 /// disposer runs **synchronously** — the reference starts it before returning, which
6953 /// a test can observe by logging after the call — and the rest follow once their
6954 /// predecessor settles.
6955 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
6956 let promise = self.new_promise();
6957 let mut pairs = Vec::with_capacity(resources.len());
6958 for (value, method) in resources {
6959 let pair = self.new_array(vec![value, method]);
6960 pairs.push(Value::Object(pair));
6961 }
6962 let remaining = self.new_array(pairs);
6963 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
6964 Ok(Value::Object(promise))
6965 }
6966
6967 /// One link of the `disposeAsync` chain.
6968 ///
6969 /// Loops while the disposers finish synchronously, and parks on the first thenable it
6970 /// meets — pushing itself back in as the continuation, with the accumulated error
6971 /// carried along so a later failure can still be folded into the `SuppressedError`.
6972 fn dispose_step(
6973 &mut self,
6974 remaining: &Gc<JsObject>,
6975 promise: &Gc<JsObject>,
6976 mut error: Value,
6977 ) -> JsResult<()> {
6978 loop {
6979 let length = remaining.array_length().unwrap_or(0);
6980 if length == 0 {
6981 if matches!(error, Value::Uninitialized) {
6982 self.fulfill_promise(promise, Value::Undefined);
6983 } else {
6984 self.reject_promise(promise, error);
6985 }
6986 return Ok(());
6987 }
6988 let Some(Value::Object(pair)) = remaining
6989 .array_get(length - 1)
6990 .filter(|v| !matches!(v, Value::Hole))
6991 else {
6992 remaining.array_truncate(self.heap, length - 1);
6993 continue;
6994 };
6995 remaining.array_truncate(self.heap, length - 1);
6996 let value = pair.array_get(0).unwrap_or(Value::Undefined);
6997 let Some(Value::Object(method)) = pair.array_get(1) else {
6998 continue;
6999 };
7000 if !method.is_callable() {
7001 continue;
7002 }
7003 match self.call_value(Value::Object(method), value, Vec::new()) {
7004 Ok(result) => {
7005 if !self.is_thenable(&result)? {
7006 // Finished synchronously; the next disposer is the next iteration.
7007 continue;
7008 }
7009 let awaited = match self.promise_resolve_value(result) {
7010 Ok(awaited) => awaited,
7011 Err(Signal::Throw(reason)) => {
7012 self.reject_promise(promise, reason);
7013 return Ok(());
7014 }
7015 Err(other) => return Err(other),
7016 };
7017 let Value::Object(awaited) = awaited else {
7018 continue;
7019 };
7020 let ok = JsObject::function(
7021 self.heap,
7022 Some(self.realm.function_proto.clone()),
7023 Callable::DisposeStep {
7024 remaining: remaining.clone(),
7025 promise: promise.clone(),
7026 error: error.clone(),
7027 rejected: false,
7028 },
7029 );
7030 let failed = JsObject::function(
7031 self.heap,
7032 Some(self.realm.function_proto.clone()),
7033 Callable::DisposeStep {
7034 remaining: remaining.clone(),
7035 promise: promise.clone(),
7036 error,
7037 rejected: true,
7038 },
7039 );
7040 self.perform_then(
7041 &awaited,
7042 Some(Value::Object(ok)),
7043 Some(Value::Object(failed)),
7044 )?;
7045 return Ok(());
7046 }
7047 Err(Signal::Throw(thrown)) => {
7048 error = self.merge_dispose_error(thrown, error);
7049 }
7050 Err(other) => return Err(other),
7051 }
7052 }
7053 }
7054
7055 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7056 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7057 let Value::Object(object) = value else {
7058 return Ok(false);
7059 };
7060 Ok(matches!(
7061 self.get_property(object, "then")?,
7062 Some(Value::Object(then)) if then.is_callable()
7063 ))
7064 }
7065
7066 /// One step of an async generator, settling `promise` with an `{value, done}` result.
7067 fn step_async_generator(
7068 &mut self,
7069 generator: &Gc<JsObject>,
7070 promise: &Gc<JsObject>,
7071 kind: ResumeKind,
7072 value: Value,
7073 ) -> JsResult<()> {
7074 let stepped = self.resume_generator_detailed(generator, kind, value);
7075 let (value, done, ready, reason) = match stepped {
7076 Ok(stepped) => stepped,
7077 Err(Signal::Throw(reason)) => {
7078 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7079 }
7080 Err(other) => return Err(other),
7081 };
7082 // Only an `await` has to wait before the method can answer.
7083 if !done && reason == Some(SuspendKind::Await) {
7084 let awaited = match self.promise_resolve_value(value) {
7085 Ok(awaited) => awaited,
7086 Err(Signal::Throw(reason)) => {
7087 return self.settle_async_request(
7088 generator,
7089 promise,
7090 AsyncOutcome::Error(reason),
7091 );
7092 }
7093 Err(other) => return Err(other),
7094 };
7095 let Value::Object(awaited) = awaited else {
7096 return Ok(());
7097 };
7098 let resumed = JsObject::function(
7099 self.heap,
7100 Some(self.realm.function_proto.clone()),
7101 Callable::GeneratorResume {
7102 generator: generator.clone(),
7103 promise: promise.clone(),
7104 kind: ResumeKind::Next,
7105 },
7106 );
7107 let raised = JsObject::function(
7108 self.heap,
7109 Some(self.realm.function_proto.clone()),
7110 Callable::GeneratorResume {
7111 generator: generator.clone(),
7112 promise: promise.clone(),
7113 kind: ResumeKind::Throw,
7114 },
7115 );
7116 self.perform_then(
7117 &awaited,
7118 Some(Value::Object(resumed)),
7119 Some(Value::Object(raised)),
7120 )?;
7121 return Ok(());
7122 }
7123 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7124 // completes it — both arrive as the settled value rather than as the promise
7125 // object. A plain value skips the round trip, which is also what keeps `yield 1`
7126 // from costing an extra tick.
7127 let awaits_value = self.is_thenable(&value)?;
7128 if awaits_value {
7129 let awaited = match self.promise_resolve_value(value) {
7130 Ok(awaited) => awaited,
7131 Err(Signal::Throw(reason)) => {
7132 return self.settle_async_request(
7133 generator,
7134 promise,
7135 AsyncOutcome::Error(reason),
7136 );
7137 }
7138 Err(other) => return Err(other),
7139 };
7140 let Value::Object(awaited) = awaited else {
7141 return Ok(());
7142 };
7143 // A rejected yield throws *at the yield* inside the body, so the rejection
7144 // resumes the generator rather than the method's promise.
7145 let answer = JsObject::function(
7146 self.heap,
7147 Some(self.realm.function_proto.clone()),
7148 Callable::YieldResult {
7149 generator: generator.clone(),
7150 promise: promise.clone(),
7151 done,
7152 },
7153 );
7154 let raise = JsObject::function(
7155 self.heap,
7156 Some(self.realm.function_proto.clone()),
7157 Callable::GeneratorResume {
7158 generator: generator.clone(),
7159 promise: promise.clone(),
7160 kind: ResumeKind::Throw,
7161 },
7162 );
7163 self.perform_then(
7164 &awaited,
7165 Some(Value::Object(answer)),
7166 Some(Value::Object(raise)),
7167 )?;
7168 return Ok(());
7169 }
7170 let result = if ready {
7171 // `yield*` handed back the inner iterator's own result object.
7172 value
7173 } else {
7174 self.iterator_result(value, done)?
7175 };
7176 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7177 }
7178
7179 /// The `{value, done}` object an iterator method answers with.
7180 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7181 let result = self.new_object(Some(self.realm.object_proto.clone()));
7182 result.define_data("value", value);
7183 result.define_data("done", Value::Bool(done));
7184 Ok(Value::Object(result))
7185 }
7186
7187 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7188 fn step_generator(
7189 &mut self,
7190 state: &mut GeneratorState,
7191 kind: ResumeKind,
7192 value: Value,
7193 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7194 match state.phase {
7195 GeneratorPhase::Executing => {
7196 return Err(self.type_error("cannot invoke a running generator"));
7197 }
7198 GeneratorPhase::Completed => {
7199 // A finished generator answers every resumption without running.
7200 return Ok(match kind {
7201 ResumeKind::Throw => return Err(Signal::Throw(value)),
7202 ResumeKind::Return => (value, true, false, None),
7203 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7204 });
7205 }
7206 GeneratorPhase::SuspendedStart => {
7207 if kind != ResumeKind::Next && kind != ResumeKind::Start {
7208 // The body never started, so there is nothing to unwind or return
7209 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7210 state.frame = None;
7211 state.phase = GeneratorPhase::Completed;
7212 return Ok(match kind {
7213 ResumeKind::Throw => return Err(Signal::Throw(value)),
7214 _ => (value, true, false, None),
7215 });
7216 }
7217 }
7218 GeneratorPhase::SuspendedYield => {}
7219 }
7220
7221 let Some(mut frame) = state.frame.take() else {
7222 return Ok((Value::Undefined, true, false, None));
7223 };
7224 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7225 // number that says which method resumed it; the emitted `if_false` branches on
7226 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7227 let mut raised = None;
7228 match kind {
7229 ResumeKind::Next | ResumeKind::Start => {
7230 if state.phase == GeneratorPhase::SuspendedYield {
7231 frame.stack.push(value);
7232 // An `await` resumes with its value alone; only a `yield` gets the
7233 // magic number that says which of `next`/`return` resumed it.
7234 if !state.parked_on_await {
7235 frame.stack.push(Value::Int(RESUME_NEXT));
7236 }
7237 }
7238 }
7239 ResumeKind::Return => {
7240 // A `return` on a not-yet-started generator is handled above, so this is
7241 // always a real resumption.
7242 frame.stack.push(value);
7243 frame.stack.push(Value::Int(RESUME_RETURN));
7244 }
7245 ResumeKind::Throw => {
7246 // At a `yield*` the exception is *data* for the delegation: the compiled
7247 // code resumes with the value and magic `2` and calls the inner iterator's
7248 // `throw`. Everywhere else it is raised at the suspension point, so the
7249 // body's own handler sees it.
7250 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7251 frame.stack.push(value);
7252 frame.stack.push(Value::Int(RESUME_THROW));
7253 } else {
7254 raised = Some(value);
7255 }
7256 }
7257 }
7258 state.phase = GeneratorPhase::Executing;
7259
7260 let depth = self.frames.len();
7261 self.frames.push(frame);
7262 // A `throw` unwinds from where the frame parked, exactly as if the exception had
7263 // happened at the `yield`.
7264 if let Some(exception) = raised {
7265 if self.catch_here(exception.clone()).is_none() {
7266 self.pop_frame();
7267 state.phase = GeneratorPhase::Completed;
7268 return Err(Signal::Throw(exception));
7269 }
7270 }
7271
7272 // Only the generator's *own* frame ends the generator. The body may call ordinary
7273 // functions, and those push frames of their own: a `Step::Return` from one of them
7274 // is a nested call finishing, not the generator completing. Miscounting that is
7275 // silent — the generator reports the callee's value as its own result and marks
7276 // itself done — so the depth comparison is load-bearing, not defensive.
7277 let own_frame = depth + 1;
7278 loop {
7279 match self.step() {
7280 Ok(Step::Continue) => {}
7281 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7282 let mut frame = self.frames.pop().expect("a frame is live");
7283 // `yield` left the value on the stack; `initial_yield` left nothing.
7284 let yielded = if reason == SuspendKind::Initial {
7285 Value::Undefined
7286 } else {
7287 frame.stack.pop().unwrap_or(Value::Undefined)
7288 };
7289 state.frame = Some(frame);
7290 state.parked_on_await = reason == SuspendKind::Await;
7291 state.parked_on_yield_star =
7292 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7293 state.phase = if reason == SuspendKind::Initial {
7294 GeneratorPhase::SuspendedStart
7295 } else {
7296 GeneratorPhase::SuspendedYield
7297 };
7298 // `yield*` hands the inner iterator's own result object straight
7299 // back, so the caller sees one `{value, done}` rather than a nested
7300 // one — which is why the third field says "already a result".
7301 return Ok((
7302 yielded,
7303 false,
7304 reason == SuspendKind::YieldStar,
7305 Some(reason),
7306 ));
7307 }
7308 Ok(Step::Suspend(_)) => {
7309 // A `yield` in a frame other than the generator's would mean a
7310 // generator body entered as an ordinary call, which
7311 // `call_or_push` prevents.
7312 self.unwind_to(depth);
7313 state.phase = GeneratorPhase::Completed;
7314 return Err(Signal::Throw(self.make_error(
7315 "InternalError",
7316 "a generator body ran as an ordinary call",
7317 )));
7318 }
7319 Ok(Step::Return(value)) => {
7320 self.pop_frame();
7321 if self.frames.len() > depth {
7322 // A nested call finished: hand the value back to its caller and
7323 // keep running the generator body.
7324 self.frames
7325 .last_mut()
7326 .expect("a caller is live")
7327 .stack
7328 .push(value);
7329 continue;
7330 }
7331 state.phase = GeneratorPhase::Completed;
7332 // The reference closes the generator's closure variables here; ours
7333 // live in cells the frame owned, which the drop below releases.
7334 return Ok((value, true, false, None));
7335 }
7336 Err(Signal::Throw(exception)) => {
7337 // The frame that threw gets the first chance to catch, exactly as in
7338 // the ordinary call loop; a frame above the generator's is popped and
7339 // the exception carries on down.
7340 let exception = exception;
7341 loop {
7342 if self.frames.len() <= depth {
7343 // The generator's own frame is gone, so nothing here caught it.
7344 state.phase = GeneratorPhase::Completed;
7345 return Err(Signal::Throw(exception));
7346 }
7347 if self.catch_here(exception.clone()).is_some() {
7348 break;
7349 }
7350 self.pop_frame();
7351 }
7352 }
7353 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7354 }
7355 }
7356 }
7357
7358 /// Pop frames until `depth` are left, keeping their buffers.
7359 fn unwind_to(&mut self, depth: usize) {
7360 while self.frames.len() > depth {
7361 self.pop_frame();
7362 }
7363 }
7364 fn call_or_push(
7365 &mut self,
7366 callee: Value,
7367 this: Value,
7368 args: Vec<Value>,
7369 ) -> JsResult<Option<Value>> {
7370 if let Value::Object(function) = &callee
7371 && let Some((code, env)) = bytecode_of(function)
7372 {
7373 // Calling a generator function does not run anything: it captures the
7374 // arguments in a frame and hands back the generator object.
7375 if code.code.kind.is_generator() {
7376 return self.new_generator(callee, this, args).map(Some);
7377 }
7378 // An async function answers a promise and runs its body as a coroutine, so it
7379 // takes the same path as a plain call into it.
7380 if code.code.kind.is_async() {
7381 return self.new_async_function(callee, this, args).map(Some);
7382 }
7383 self.push_frame(code, env, this, args, callee)?;
7384 return Ok(None);
7385 }
7386 self.call_value(callee, this, args).map(Some)
7387 }
7388
7389 /// `new callee(args)`.
7390 ///
7391 /// A constructor differs from a plain call in three ways: it gets a fresh object
7392 /// as `this` whose prototype is the constructor's `prototype` property, its
7393 /// return value is *replaced* by that object unless it returns an object itself,
7394 /// and a native constructor is expected to initialise the object it is given
7395 /// rather than build one.
7396 pub fn construct(
7397 &mut self,
7398 callee: Value,
7399 new_target: Value,
7400 args: Vec<Value>,
7401 ) -> JsResult<Value> {
7402 // `new` on a bound function constructs its *target*, prepending the arguments
7403 // the bind fixed and ignoring the bound `this` — a bound function is a
7404 // constructor only when its target is one, and `new` always makes a fresh
7405 // object of the target's prototype rather than reusing the bound receiver.
7406 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
7407 // ran the body with `this === null` and threw on `this.x = a`.
7408 let mut callee = callee;
7409 let mut new_target = new_target;
7410 let mut args = args;
7411 loop {
7412 let Some(object) = callee.as_object().cloned() else {
7413 return Err(Signal::Throw(
7414 self.make_error("TypeError", "not a constructor"),
7415 ));
7416 };
7417 // A proxy of a function constructs through its `construct` trap, and the
7418 // trap's answer is the result directly — no fresh object is made here.
7419 if object.proxy_state().is_some() {
7420 return match self.proxy_construct(&object, args, &new_target)? {
7421 Some(result) => Ok(result),
7422 None => Err(Signal::Throw(
7423 self.make_error("TypeError", "proxy target is not a constructor"),
7424 )),
7425 };
7426 }
7427 // A generator function has no `[[Construct]]`, and the reference names it in
7428 // the message: `new (function* G(){})()` reports "G is not a constructor".
7429 if object.with(|data| match &data.kind {
7430 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
7431 code.code.kind.is_generator()
7432 }
7433 _ => false,
7434 }) {
7435 let name = object
7436 .own_property("name")
7437 .and_then(|property| property.value)
7438 .map(|value| value.to_js_string())
7439 .unwrap_or_default();
7440 return Err(Signal::Throw(
7441 self.make_error("TypeError", &format!("{name} is not a constructor")),
7442 ));
7443 }
7444 let bound = object.with(|data| match &data.kind {
7445 ObjectKind::Function(Callable::Bound {
7446 target,
7447 args: leading,
7448 ..
7449 }) => Some((target.clone(), leading.clone())),
7450 _ => None,
7451 });
7452 let Some((target, leading)) = bound else {
7453 // Not a bound function, so this object is the callee. §7.2.4
7454 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
7455 // refusals above cover only the built-ins the reference also refuses by
7456 // name. Everything else — a method, an arrow, an async function — has no
7457 // `[[Construct]]` either, and answering "yes" here made
7458 // `new (Array.prototype.map)` build an object instead of throwing.
7459 if !object.is_constructor() {
7460 let name = object
7461 .own_property("name")
7462 .and_then(|property| property.value)
7463 .map(|value| value.to_js_string())
7464 .unwrap_or_default();
7465 return Err(Signal::Throw(
7466 self.make_error("TypeError", &format!("{name} is not a constructor")),
7467 ));
7468 }
7469 break;
7470 };
7471 let mut all = leading;
7472 all.extend(args);
7473 args = all;
7474 // A bound function that is its own `new.target` stands in for its target:
7475 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
7476 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
7477 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
7478 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
7479 _ => false,
7480 };
7481 if same_wrapper {
7482 new_target = target.clone();
7483 }
7484 callee = target;
7485 }
7486 let Value::Object(function) = &callee else {
7487 unreachable!("the loop above only breaks on an object");
7488 };
7489 // The fresh object's prototype comes from `new.target`, not from the callee: a
7490 // derived constructor reaches here through `super()`, and the instance must be a
7491 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
7492 // an object inheriting `D.prototype` rather than `C.prototype`.
7493 let prototype_source = match new_target.as_object() {
7494 Some(target) => target.clone(),
7495 None => function.clone(),
7496 };
7497 // A native constructor builds its own instance, through `new_ctor_instance`, once it
7498 // has validated its arguments. Pre-building one here would read
7499 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
7500 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
7501 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
7502 let is_native = function.native_creates_own_instance();
7503 let this = if is_native {
7504 Value::Undefined
7505 } else {
7506 let prototype = self.get_property(&prototype_source, "prototype")?;
7507 let prototype = match prototype {
7508 Some(Value::Object(proto)) => Some(proto),
7509 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
7510 // object, the answer is the realm's *intrinsic* prototype for this
7511 // constructor, not `%Object.prototype%`.
7512 _ => {
7513 let fallback = self.get_property(function, "prototype")?;
7514 match fallback {
7515 Some(Value::Object(proto)) => Some(proto),
7516 _ => Some(self.realm.object_proto.clone()),
7517 }
7518 }
7519 };
7520 Value::Object(self.new_object(prototype))
7521 };
7522 // `new.target` inside the body is the constructor that was written, so a bound
7523 // function's target sees itself rather than the bound wrapper.
7524 //
7525 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
7526 // `?`, so assigning `None` after the call would be skipped and the failed
7527 // `new.target` would stay visible to every later native call. The symptom was a
7528 // native constructor refusing a plain call — `var s = Symbol(); new
7529 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
7530 // "FinalizationRegistry is not a constructor".
7531 let outer_new_target = self.pending_new_target.replace(new_target);
7532 let result = self.call_value(callee, this.clone(), args);
7533 self.pending_new_target = outer_new_target;
7534 let result = result?;
7535 // A constructor that returns an object overrides `this`; any other return
7536 // value (including `undefined`) is ignored.
7537 Ok(match result {
7538 Value::Object(_) => result,
7539 _ => this,
7540 })
7541 }
7542
7543 /// `new.target` for the call currently being made.
7544 ///
7545 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
7546 /// it as `this`), but a *host* constructor that builds its own instance is handed
7547 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
7548 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
7549 /// it here.
7550 ///
7551 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
7552 /// receives for a plain call.
7553 pub fn current_new_target(&self) -> Value {
7554 self.pending_new_target.clone().unwrap_or(Value::Undefined)
7555 }
7556
7557 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
7558 ///
7559 /// The error classes themselves arrive with the builtins milestone; what
7560 /// matters here is that the thrown value stringifies the way a script printing
7561 /// the caught value expects.
7562 ///
7563 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
7564 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
7565 /// rely on when they print a caught value.
7566 pub fn make_error(&self, name: &str, message: &str) -> Value {
7567 let proto = self
7568 .realm
7569 .errors
7570 .get(name)
7571 .map(|constructor| self.prototype_of(constructor))
7572 .unwrap_or_else(|| self.realm.error_proto.clone());
7573 let error = self.new_object(Some(proto));
7574 // `name` and `message` are own properties of the instance, which is what
7575 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
7576 // `Error`.
7577 error.define(
7578 "name",
7579 Property::with_attributes(self.string(name), true, false),
7580 );
7581 error.define(
7582 "message",
7583 Property::with_attributes(self.string(message), true, false),
7584 );
7585 // The internal class, which is what tells a printer this is an error rather than a
7586 // plain object with `name` and `message` properties. The constructor path sets it
7587 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
7588 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
7589 // literally `"Error"` in both places — the *name* is read from `name`, which is why
7590 // a `RangeError` still prints as `RangeError`.
7591 self.internal_set(&error, "_class", self.string("Error"));
7592 // The trace is captured where the error is *made*, which is where the reference
7593 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
7594 // way out, so a caught engine error already has its stack even if the handler
7595 // never rethrows it.
7596 self.add_stack(&error);
7597 Value::Object(error)
7598 }
7599
7600 /// Give an error object its `stack` property, from the current frame stack.
7601 ///
7602 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
7603 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
7604 /// `stack` a script set, is not rewritten.
7605 pub fn add_stack(&self, object: &Gc<JsObject>) {
7606 self.add_stack_skipping(object, 0);
7607 }
7608
7609 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
7610 ///
7611 /// An `Error` constructor passes 1: the reference builds those traces with
7612 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
7613 /// constructor itself, while a `RangeError` raised inside `toISOString` does
7614 /// report `at toISOString (native)`.
7615 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
7616 if object.has_own("stack") {
7617 return;
7618 }
7619 let trace = self.stack_trace_skipping(skip);
7620 let text = self.string(trace);
7621 object.define("stack", Property::with_attributes(text, true, true));
7622 }
7623
7624 /// The function object currently being called, if any.
7625 ///
7626 /// A native function is a bare `fn` pointer, so it cannot capture which class
7627 /// it belongs to; it reads that from the callee instead. This is also what a
7628 /// stack trace would use.
7629 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
7630 match &self.frames.last()?.callee {
7631 Value::Object(object) => Some(object.clone()),
7632 _ => None,
7633 }
7634 }
7635
7636 /// The `prototype` property of a constructor, falling back to
7637 /// `Object.prototype` for anything that is not shaped like one.
7638 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
7639 constructor
7640 .own_property("prototype")
7641 .and_then(|property| property.value)
7642 .and_then(|value| value.as_object().cloned())
7643 .unwrap_or_else(|| self.realm.object_proto.clone())
7644 }
7645
7646 /// Throw a `TypeError` carrying `message`.
7647 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
7648 Signal::Throw(self.make_error("TypeError", message.as_ref()))
7649 }
7650
7651 /// Throw a `RangeError` carrying `message`.
7652 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
7653 Signal::Throw(self.make_error("RangeError", message.as_ref()))
7654 }
7655
7656 /// The `ReferenceError` a read of an uninitialised binding raises.
7657 /// The name of the binding `slot` refers to, for an error message.
7658 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
7659 match kind {
7660 VarSlot::Loc => self
7661 .frame()
7662 .code
7663 .code
7664 .vars
7665 .get(slot)
7666 .map(|v| v.name.clone()),
7667 VarSlot::Closure => self
7668 .frame()
7669 .code
7670 .code
7671 .closure_vars
7672 .get(slot)
7673 .map(|c| c.name.clone()),
7674 }
7675 .unwrap_or_default()
7676 }
7677
7678 /// Whether `slot` names a `const` binding, which rejects every store after its
7679 /// initialiser.
7680 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
7681 match kind {
7682 VarSlot::Loc => self
7683 .frame()
7684 .code
7685 .code
7686 .vars
7687 .get(slot)
7688 .is_some_and(|v| v.is_const),
7689 VarSlot::Closure => self
7690 .frame()
7691 .code
7692 .code
7693 .closure_vars
7694 .get(slot)
7695 .is_some_and(|c| c.is_const),
7696 }
7697 }
7698
7699 /// The `TypeError` a store to a `const` binding raises.
7700 ///
7701 /// `const` is enforced here rather than at compile time because the binding can be
7702 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
7703 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
7704 /// both halves of what "checked store" means: the dead zone is over, and the
7705 /// binding is writable.
7706 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
7707 let name = self.binding_name(slot, kind);
7708 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
7709 }
7710
7711 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
7712 let name = match kind {
7713 VarSlot::Loc => self
7714 .frame()
7715 .code
7716 .code
7717 .vars
7718 .get(slot)
7719 .map(|v| v.name.clone()),
7720 VarSlot::Closure => self
7721 .frame()
7722 .code
7723 .code
7724 .closure_vars
7725 .get(slot)
7726 .map(|c| c.name.clone()),
7727 }
7728 .unwrap_or_default();
7729 Signal::Throw(self.make_error(
7730 "ReferenceError",
7731 &format!("cannot access '{name}' before initialization"),
7732 ))
7733 }
7734
7735 fn throw_reference(&self, name: &str) -> Signal {
7736 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
7737 }
7738
7739 // -- the instruction loop -----------------------------------------------
7740
7741 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
7742 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
7743 // measured at 16% of a tight arithmetic loop's total time.
7744 #[inline(always)]
7745 fn step(&mut self) -> JsResult<Step> {
7746 // The instruction is already decoded (see [`crate::insn`]), so this is an index
7747 // and a `Copy` read rather than a table lookup plus a width switch. Only the
7748 // borrow lives across the boundary; nothing is cloned.
7749 // **One** borrow of the frame: fetch the record, then advance in the same scope.
7750 // The obvious version borrowed it three times (`last` to read, `last_mut` to
7751 // write, and once more inside the handler), and each is a bounds check plus an
7752 // `Option` unwrap — on the one path every instruction takes.
7753 let Some((insn, next)) = ({
7754 let frame = self
7755 .frames
7756 .last_mut()
7757 .expect("step() is only called with a live frame");
7758 // Past the last instruction is a normal return: the compiler ends a function
7759 // with `return`, and a jump to the end of a block lands here.
7760 let insn = frame.insns().get(frame.pc).copied();
7761 match insn {
7762 None => None,
7763 Some(insn) => {
7764 // A fused record stands for the next few instructions, so the next
7765 // `pc` is its width ahead — the instructions it replaces are never
7766 // dispatched. `at` is the byte offset a stack trace reports; it stays
7767 // an offset because the line table is keyed by bytes.
7768 frame.at = insn.offset as usize;
7769 frame.pc += insn.width();
7770 Some((insn, frame.pc))
7771 }
7772 }
7773 }) else {
7774 return Ok(Step::Return(Value::Undefined));
7775 };
7776 self.check_memory()?;
7777 self.check_interrupt()?;
7778 if insn.fused == crate::insn::Fused::None {
7779 self.execute_instruction(insn.op, insn.a, insn.b, next)
7780 } else {
7781 self.execute_fused(insn)
7782 }
7783 }
7784
7785 /// Run a fused instruction: several bytecode instructions in one dispatch.
7786 ///
7787 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
7788 /// it cannot throw and cannot allocate — and anything else falls back to the real
7789 /// instructions, in their real order, so an exception leaves the operand stack
7790 /// exactly as it would have been.
7791 #[inline]
7792 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
7793 use crate::insn::Fused;
7794 let slot = insn.a as usize;
7795 match insn.fused {
7796 // `x = k`: `push k; put_loc x`.
7797 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
7798 // `x += k`: `get_loc x; push k; add; put_loc x`.
7799 Fused::AddImmLoc => {
7800 let delta = insn.b as i32;
7801 match self.get_loc(slot) {
7802 Value::Int(left) => {
7803 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
7804 // that built two `Value`s, called a function, and matched on them
7805 // again to reach this same `checked_add`. It is the innermost
7806 // operation of every accumulator in every program.
7807 let answer = match left.checked_add(delta) {
7808 Some(sum) => Value::Int(sum),
7809 None => Value::Float(left as f64 + delta as f64),
7810 };
7811 self.put_loc(slot, answer);
7812 }
7813 other => {
7814 self.push(other);
7815 self.push(Value::Int(delta));
7816 self.binary_add()?;
7817 let value = self.pop();
7818 self.put_loc(slot, value);
7819 }
7820 }
7821 }
7822 // `x += "literal"` and `x += y`: the two shapes that can append in place.
7823 Fused::AddAtomLoc => {
7824 let text = self.atom_wtf8(insn.b as usize);
7825 let right = self.string_wtf8(text);
7826 self.add_into_loc(slot, right)?;
7827 }
7828 Fused::AddLocLoc => {
7829 let source = (insn.a & 0xFFFF) as usize;
7830 let target = (insn.a >> 16) as usize;
7831 let right = self.get_loc(source);
7832 self.add_into_loc(target, right)?;
7833 }
7834 Fused::AddArgLoc => {
7835 let source = (insn.a & 0xFFFF) as usize;
7836 let target = (insn.a >> 16) as usize;
7837 let right = self.get_arg(source);
7838 self.add_into_loc(target, right)?;
7839 }
7840 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
7841 Fused::PostIncLoc => match self.get_loc(slot) {
7842 Value::Int(left) => {
7843 let answer = match left.checked_add(1) {
7844 Some(sum) => Value::Int(sum),
7845 None => Value::Float(left as f64 + 1.0),
7846 };
7847 self.put_loc(slot, answer);
7848 }
7849 other => {
7850 self.push(other);
7851 let raw = self.pop();
7852 let (old, updated) = self.advance_numeric(raw, true)?;
7853 self.push(old);
7854 self.push(updated);
7855 let value = self.pop();
7856 self.put_loc(slot, value);
7857 self.pop();
7858 }
7859 },
7860 // `if (!(x < arg)) goto target`: a loop header.
7861 //
7862 // The comparison is computed rather than replayed on the operand stack. That
7863 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
7864 // that throws: the effects happen in the same order, and a handler truncates
7865 // the stack down to its marker, so the intermediate values are unobservable.
7866 Fused::LtLocArgJump => {
7867 let loc = (insn.a >> 16) as usize;
7868 let arg = (insn.a & 0xFFFF) as usize;
7869 let left = self.get_loc(loc);
7870 let right = self.get_arg(arg);
7871 let taken = match (&left, &right) {
7872 (Value::Int(left), Value::Int(right)) => !(left < right),
7873 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
7874 };
7875 if taken {
7876 self.frame_mut().pc = insn.b as usize;
7877 }
7878 }
7879 // `i < k` in a loop header, where `k` is an integer literal.
7880 Fused::LtLocImmJump => {
7881 let left = self.get_loc(insn.a as usize);
7882 let right = Value::Int(insn.imm as i32);
7883 let taken = match &left {
7884 Value::Int(left) => !(*left < insn.imm as i32),
7885 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
7886 };
7887 if taken {
7888 self.frame_mut().pc = insn.b as usize;
7889 }
7890 }
7891 Fused::None => unreachable!("only called for a fused record"),
7892 }
7893 Ok(Step::Continue)
7894 }
7895
7896 /// Run records that cannot call script, cannot throw and cannot change frames.
7897 ///
7898 /// Returns `Some(value)` when the function ran off the end of its instructions (a
7899 /// normal return), and `None` when it stopped in front of an instruction the slow path
7900 /// has to handle — `pc` is written back either way, so `step` resumes at the right
7901 /// place.
7902 ///
7903 /// **The invariant is the whole point.** Every arm here is restricted to work that
7904 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
7905 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
7906 /// that the memory limit has to see. An opcode whose operands turn out to need any of
7907 /// that **stops the loop** instead of trying, so the slow path gets the instruction
7908 /// untouched and with its operands still on the stack. That is why the fallback is a
7909 /// `break` and not a duplicated slow arm: a second implementation of the same
7910 /// semantics is how a wrong answer gets in with no test noticing.
7911 ///
7912 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
7913 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
7914 fn run_fast(&mut self) -> JsResult<Option<Value>> {
7915 use crate::insn::Fused;
7916 // The outer loop exists only so a `Call` can come back through here: once a
7917 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
7918 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
7919 // frame. Re-entering re-reads both from whichever frame is now on top. Every
7920 // other exit from the inner loop returns, so this costs one loop per call.
7921 'outer: loop {
7922 // One reference-count bump per *slow* instruction (a call, an allocation, a
7923 // property access), never one per instruction — that distinction is worth
7924 // two orders of magnitude and was measured as such.
7925 let (code, mut pc) = {
7926 let frame = self.frame();
7927 (frame.code.clone(), frame.pc)
7928 };
7929 let insns = &code.insns;
7930 loop {
7931 let Some(insn) = insns.get(pc).copied() else {
7932 self.frame_mut().pc = pc;
7933 return Ok(Some(Value::Undefined));
7934 };
7935 match insn.fused {
7936 // `x = k`
7937 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
7938 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
7939 // object — stops the loop so `binary_add` can decide.
7940 Fused::AddImmLoc => {
7941 let slot = insn.a as usize;
7942 let delta = insn.b as i32;
7943 let Value::Int(left) = self.get_loc(slot) else {
7944 return Ok(self.stop(pc));
7945 };
7946 let sum = match left.checked_add(delta) {
7947 Some(sum) => Value::Int(sum),
7948 None => Value::Float(left as f64 + delta as f64),
7949 };
7950 self.put_loc(slot, sum);
7951 }
7952 // `x += "literal"` / `x += y`: the operand is a string, so the append
7953 // either allocates one or grows one. Both are the slow path's business;
7954 // the fusion's job is only to make the *slot* the sole owner, which is what
7955 // `execute_fused` needs and what `get_loc` alone destroys.
7956 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
7957 return Ok(self.stop(pc));
7958 }
7959 // `x++` on an integer, old value dropped.
7960 Fused::PostIncLoc => {
7961 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
7962 // value is read in place and overwritten in place, so the reference
7963 // count it held is released by the same assignment that stores the
7964 // new one. `get_loc` plus `put_loc` did two borrows, two table
7965 // lookups and a clone, and this arm is the whole body of a counting
7966 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
7967 let slot = insn.a as usize;
7968 let frame = self.frames.last_mut().expect("a frame is live");
7969 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
7970 let target = if cell < 0 {
7971 frame.locals.get_mut(slot)
7972 } else {
7973 None
7974 };
7975 let Some(target) = target else {
7976 return Ok(self.stop(pc));
7977 };
7978 let Value::Int(left) = *target else {
7979 return Ok(self.stop(pc));
7980 };
7981 *target = match left.checked_add(1) {
7982 Some(sum) => Value::Int(sum),
7983 None => Value::Float(left as f64 + 1.0),
7984 };
7985 }
7986 // A loop header, `if (!(x < arg)) goto target`, with both sides already
7987 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
7988 // bound stayed small integers.
7989 Fused::LtLocArgJump => {
7990 let loc = (insn.a >> 16) as usize;
7991 let arg = (insn.a & 0xFFFF) as usize;
7992 // One borrow for both slots: this arm *is* the whole loop of a
7993 // `for (i = 0; i < n; i++)` with an argument bound, so a second
7994 // `frames.last()` here is paid on every iteration. Measured 7.5% on
7995 // `dispatch:empty-loop`.
7996 let (left, right) = {
7997 let frame = self.frame();
7998 (frame.read_loc(loc), frame.read_arg(arg))
7999 };
8000 // Heavily measured: the bound is very often a `Float` even when the
8001 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8002 // `JSON.parse` or a division is one — so requiring both sides to be
8003 // `Int` sent every iteration of those loops down the slow path. The
8004 // comparison below is the same one `relational` makes for two numbers.
8005 if !is_number(&left) || !is_number(&right) {
8006 return Ok(self.stop(pc));
8007 }
8008 // `if_false` branches on the comparison being false, which is **not**
8009 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8010 // `>=` is also false and would keep it running forever. Clippy wants the
8011 // negation folded; that would be a wrong answer.
8012 let ordered = left.to_number() < right.to_number();
8013 let take_branch = !ordered;
8014 if take_branch {
8015 pc = insn.b as usize;
8016 continue;
8017 }
8018 }
8019 // The same header with a literal bound: `if (!(x < k)) goto target`.
8020 // The bound is an immediate, so only the counter needs a type test.
8021 #[allow(clippy::neg_cmp_op_on_partial_ord)]
8022 Fused::LtLocImmJump => {
8023 let left = self.get_loc(insn.a as usize);
8024 if !is_number(&left) {
8025 return Ok(self.stop(pc));
8026 }
8027 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8028 if take_branch {
8029 pc = insn.b as usize;
8030 continue;
8031 }
8032 }
8033 Fused::None => match insn.op {
8034 // -- branches ---------------------------------------------------
8035 // A jump is an assignment now, because the target is an instruction
8036 // index. No arithmetic, no resolution table.
8037 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8038 let target = insn.a as usize;
8039 // A **back-edge** is a loop, and it is the only place an
8040 // instruction-level checkpoint can stop one: `for(;;){}` compiles
8041 // to a jump to itself and never leaves this loop, so the
8042 // per-instruction checks in `step` never run. That is exactly the
8043 // hole this arm closes — a host's `JS_SetInterruptHandler` did
8044 // nothing to a `for(;;){}` until it did, which is what
8045 // `tests/c/embed.c` is for.
8046 //
8047 // Polling here rather than on every instruction in this loop is
8048 // also the reference's choice (`OP_goto` calls
8049 // `js_poll_interrupts`), and it costs one compare per branch
8050 // instead of one decrement per instruction.
8051 if target <= pc {
8052 self.frame_mut().pc = target;
8053 self.check_memory()?;
8054 self.check_interrupt()?;
8055 }
8056 pc = target;
8057 continue;
8058 }
8059 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8060 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8061 let taken = self.pop().to_boolean();
8062 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8063 if taken == want {
8064 pc = insn.a as usize;
8065 continue;
8066 }
8067 }
8068 // -- slot access -------------------------------------------------
8069 // A load's slot is already an operand (see `insn::implicit_operand`);
8070 // a captured one goes through its cell, which runs no script.
8071 Opcode::GetLoc
8072 | Opcode::GetLoc8
8073 | Opcode::GetLoc0
8074 | Opcode::GetLoc1
8075 | Opcode::GetLoc2
8076 | Opcode::GetLoc3 => {
8077 let value = self.get_loc(insn.a as usize);
8078 self.push(value);
8079 }
8080 Opcode::PutLoc
8081 | Opcode::PutLoc8
8082 | Opcode::PutLoc0
8083 | Opcode::PutLoc1
8084 | Opcode::PutLoc2
8085 | Opcode::PutLoc3 => {
8086 let value = self.pop();
8087 self.put_loc(insn.a as usize, value);
8088 }
8089 Opcode::GetArg
8090 | Opcode::GetArg0
8091 | Opcode::GetArg1
8092 | Opcode::GetArg2
8093 | Opcode::GetArg3 => {
8094 let value = self.get_arg(insn.a as usize);
8095 self.push(value);
8096 }
8097 Opcode::PutArg
8098 | Opcode::PutArg0
8099 | Opcode::PutArg1
8100 | Opcode::PutArg2
8101 | Opcode::PutArg3 => {
8102 let value = self.pop();
8103 self.put_arg(insn.a as usize, value);
8104 }
8105 // `a[i]` with an integer index on a dense array: see `fast_array_get`
8106 // for why a non-hole own element is exactly the slow path's answer.
8107 // The two operands are *peeked*, so a miss leaves the stack as the
8108 // slow path expects to find it.
8109 Opcode::GetArrayEl => {
8110 // One lookup, not two. The guard used `if …is_some()` and the arm
8111 // then called it again to get the value — two `peek`s, two
8112 // `array_get`s and two `Value` clones for one element.
8113 // `fast_array_get` was 13.1% of `array:indexed`, and the same
8114 // double call was the first version of the `get_field` fast path.
8115 let Some(value) = self.fast_array_get() else {
8116 return Ok(self.stop(pc));
8117 };
8118 // `a[i]` consumes both operands and leaves the element in their
8119 // place: one `truncate` and one write, no `pop`/`push` pair.
8120 let frame = self.frame_mut();
8121 frame.stack.truncate(frame.stack.len() - 2);
8122 frame.stack.push(value);
8123 }
8124 // `a[i] = v` on a dense array with an integer index: see
8125 // `fast_array_set` for why the whole store is one step.
8126 Opcode::PutArrayEl if self.fast_array_set() => {}
8127 // `o.x` resolved from the inline cache without leaving the loop.
8128 //
8129 // The cache is keyed by `(receiver identity, atom, site)` and a
8130 // monomorphic read re-validates the same chain every iteration, so
8131 // each one used to cost a `stop(pc)` — a write of `pc` into the
8132 // frame, a return out of this loop, a re-dispatch through `step` and
8133 // a re-entry. `property:monomorphic` spent 18% in
8134 // `read_field_cached` and 21% in `push`, both across that boundary.
8135 //
8136 // The site is `pc + width`, which is exactly the `next` the slow arm
8137 // passes — the two must agree or every fast lookup misses and
8138 // re-records the same entry forever.
8139 //
8140 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8141 // slow arm finds the receiver where it expects it.
8142 // `name` resolved from the global-variable cache inside the loop.
8143 //
8144 // Same shape as `get_field` above and for the same reason: `get_var`
8145 // was not in the fast loop, so reading a global — which `fib` does
8146 // once per recursive call, for its own name — cost a `stop(pc)`, a
8147 // return out of the loop, a `step` re-dispatch and a re-entry, before
8148 // `get_global` even started its `scopes_are_plain` checks.
8149 //
8150 // Everything here is exactly `get_global`'s first branch: not lexical,
8151 // no `eval` scope, cache hit. Anything else leaves the stack untouched
8152 // and lets the slow arm decide.
8153 Opcode::GetVar => {
8154 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8155 return Ok(self.stop(pc));
8156 };
8157 self.push(value);
8158 }
8159 Opcode::GetField | Opcode::GetField2 => {
8160 let Some(value) =
8161 self.fast_field_get(insn.a as usize, pc + insn.width())
8162 else {
8163 return Ok(self.stop(pc));
8164 };
8165 if insn.op == Opcode::GetField2 {
8166 // `get_field2` keeps the receiver for the `call_method` that
8167 // follows.
8168 self.push(value);
8169 } else {
8170 // `get_field` replaces the receiver, so this is one store over
8171 // the top slot rather than a `pop` and a `push`: the length
8172 // never changes, so neither `Vec` arm has a capacity check or a
8173 // drop to run beyond the one the overwrite itself does.
8174 let frame = self.frame_mut();
8175 match frame.stack.last_mut() {
8176 Some(slot) => *slot = value,
8177 None => return Ok(self.stop(pc)),
8178 }
8179 }
8180 }
8181 // -- constants ---------------------------------------------------
8182 Opcode::PushMinus1
8183 | Opcode::Push0
8184 | Opcode::Push1
8185 | Opcode::Push2
8186 | Opcode::Push3
8187 | Opcode::Push4
8188 | Opcode::Push5
8189 | Opcode::Push6
8190 | Opcode::Push7
8191 | Opcode::PushI8
8192 | Opcode::PushI16
8193 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8194 // -- stack shuffling ---------------------------------------------
8195 Opcode::Drop => {
8196 self.pop();
8197 }
8198 // -- arithmetic on two integers ----------------------------------
8199 //
8200 // The operands are *looked at* before they are popped, so a non-integer
8201 // pair leaves the stack exactly as the slow path expects to find it.
8202 Opcode::Add if self.numeric_pair() => {
8203 let right = self.pop();
8204 let left = self.pop();
8205 // Exactly [`add_numbers`], which is what the slow arm reaches.
8206 let answer = match (&left, &right) {
8207 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8208 Some(sum) => Value::Int(sum),
8209 None => Value::Float(*a as f64 + *b as f64),
8210 },
8211 _ => Value::Float(left.to_number() + right.to_number()),
8212 };
8213 self.push(answer);
8214 }
8215 Opcode::Sub
8216 | Opcode::And
8217 | Opcode::Or
8218 | Opcode::Xor
8219 | Opcode::Shl
8220 | Opcode::Sar
8221 | Opcode::Shr
8222 if self.numeric_pair() =>
8223 {
8224 let right = self.pop();
8225 let left = self.pop();
8226 let answer =
8227 arithmetic(insn.op, left, right).expect("numbers cannot throw");
8228 self.push(answer);
8229 }
8230 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8231 if self.numeric_pair() =>
8232 {
8233 let right = self.pop();
8234 let left = self.pop();
8235 let answer = self
8236 .relational(insn.op, left, right)
8237 .expect("numbers cannot throw");
8238 self.push(answer);
8239 }
8240 // -- calls -------------------------------------------------------
8241 //
8242 // A plain call: `callee(arg0, …, argN) -> result`.
8243 //
8244 // This arm exists because of one measurement. `call:recursion` had
8245 // **20.4% of its profile in `execute_instruction`** — the *slow*
8246 // executor — and `fib`'s recursive call is the only thing in that
8247 // function which is not a fast arm. Every call therefore left this
8248 // loop via `stop()`, went through `step()`'s dispatch and
8249 // `execute_instruction`'s match over every opcode, and came back here
8250 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8251 //
8252 // Two things make it safe to do here rather than only in the slow path:
8253 //
8254 // * the caller's `pc` is stored *before* the call, which is what
8255 // `step` does too — so when the callee returns, the caller resumes
8256 // after the call and not at it;
8257 // * `check_memory` runs, because `step` calls it once per instruction
8258 // and a call allocates a frame, its locals and its cells. Skipping
8259 // the checkpoint here would let a `--memory-limit` script overshoot
8260 // by one call per instruction.
8261 Opcode::Call
8262 | Opcode::Call0
8263 | Opcode::Call1
8264 | Opcode::Call2
8265 | Opcode::Call3 => {
8266 let argc = self.argc_operand(insn.op, insn.a);
8267 let next = pc + insn.width();
8268 {
8269 let frame = self
8270 .frames
8271 .last_mut()
8272 .expect("run_fast() is only called with a live frame");
8273 // `at` is what a stack trace reports for this frame, so a throw
8274 // inside the callee has to see the call site and not whatever
8275 // the last `stop()` left there.
8276 frame.at = insn.offset as usize;
8277 frame.pc = next;
8278 }
8279 self.check_memory()?;
8280 self.check_interrupt()?;
8281 let args = self.pop_n(argc);
8282 let callee = self.pop();
8283 // A plain call has no receiver; the callee decides what to do with
8284 // `undefined` (a sloppy function substitutes the global object).
8285 if let Some(result) =
8286 self.call_or_push(callee, Value::Undefined, args)?
8287 {
8288 // Native, host, generator, async, bound — no frame was pushed,
8289 // so this loop is still describing the right function. `pc`
8290 // is advanced by the loop tail like every other arm; only the
8291 // frame's copy had to be written here, and it already was.
8292 self.push(result);
8293 } else {
8294 // A bytecode callee: its frame is on top now, and `insns` and
8295 // `pc` both belong to the caller. Start over on the new frame.
8296 continue 'outer;
8297 }
8298 }
8299 // -- return ------------------------------------------------------
8300 Opcode::Return => {
8301 let value = self.pop();
8302 self.frame_mut().pc = pc + insn.width();
8303 return Ok(Some(value));
8304 }
8305 Opcode::ReturnUndef => {
8306 self.frame_mut().pc = pc + insn.width();
8307 return Ok(Some(Value::Undefined));
8308 }
8309 // Everything else needs the slow path.
8310 _ => return Ok(self.stop(pc)),
8311 },
8312 }
8313 pc += insn.width();
8314 }
8315 }
8316 }
8317
8318 /// Whether the top two operand-stack values are both numbers.
8319 ///
8320 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8321 /// cannot run script, so the arm may not throw and may not change frames.
8322 fn numeric_pair(&self) -> bool {
8323 is_number(&self.peek(0)) && is_number(&self.peek(1))
8324 }
8325
8326 /// `a[i]` for a dense array and an integer index, without the string round trip.
8327 ///
8328 /// The slow path answers this by turning `i` into a string (`propkey` →
8329 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8330 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8331 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8332 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8333 /// without even the cheap `Int` formatting.
8334 ///
8335 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8336 /// unambiguously the one the slow path would give:
8337 ///
8338 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8339 /// `2^32-1` is the length, not an index),
8340 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8341 /// typed array or an ordinary object, all of which have their own rules),
8342 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8343 /// starts walking the prototype chain, and `a[i]` on a hole must find
8344 /// `Array.prototype[i]` if it exists rather than `undefined`.
8345 ///
8346 /// The last condition is the one that makes this safe rather than merely fast: an own
8347 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8348 /// `get_var` answered from the global-variable cache, or `None`.
8349 ///
8350 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8351 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
8352 /// records nothing — the slow arm is about to walk the chain and record it.
8353 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
8354 let frame = self.frame();
8355 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
8356 // "Lexical" is presence in the realm's table, not the closure var's flag: a
8357 // `GlobalRef` forwarded through a nested function has its flags cleared.
8358 if self.realm.globals.contains_key(name) {
8359 return None;
8360 }
8361 if !self.scopes_are_plain() {
8362 return None;
8363 }
8364 let object = &self.realm.global;
8365 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
8366 let cached = self.global_cache[site].as_ref()?;
8367 if !object.upgrades_to(&cached.object) {
8368 return None;
8369 }
8370 object.data_property_at(cached.index, name)
8371 }
8372
8373 /// `o.x` answered entirely from the inline cache, or `None`.
8374 ///
8375 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
8376 /// about to do exactly that and recording it twice would rebuild the chain for every
8377 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
8378 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
8379 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
8380 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
8381 // an object receiver is a reference-count bump that the answer never needs.
8382 let frame = self.frame();
8383 let object = frame.stack.last()?;
8384 let Value::Object(target) = object else {
8385 return None;
8386 };
8387 // A proxy traps the lookup, so no cache entry ever describes it.
8388 if target.proxy_state().is_some() {
8389 return None;
8390 }
8391 let key = frame.code.atom_keys.get(atom)?;
8392 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
8393 if cached.key != *key {
8394 return None;
8395 }
8396 Self::cached_hit(target, cached)
8397 }
8398
8399 fn fast_array_get(&self) -> Option<Value> {
8400 let Value::Int(index) = self.peek(0) else {
8401 return None;
8402 };
8403 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
8404 // set for an `i32`.
8405 if index < 0 {
8406 return None;
8407 }
8408 let Value::Object(object) = self.peek(1) else {
8409 return None;
8410 };
8411 match object.array_get(index as usize) {
8412 Some(value) if !matches!(value, Value::Hole) => Some(value),
8413 _ => None,
8414 }
8415 }
8416
8417 /// `a[i] = v` on a dense array with an integer index, as one store.
8418 ///
8419 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
8420 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
8421 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
8422 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
8423 /// reference at the time it was measured (14.7x).
8424 ///
8425 /// Every condition here is one the slow path would also have to satisfy before
8426 /// storing into the element vector:
8427 ///
8428 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
8429 /// accepts as an index;
8430 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
8431 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
8432 /// one inside a recorded descriptor, reports `false` and the caller stops.
8433 ///
8434 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
8435 /// writes the own element too once `array_set` says it did.
8436 fn fast_array_set(&mut self) -> bool {
8437 // Every test runs *before* anything is popped: a refusal has to leave the stack
8438 // exactly as the slow path expects to find it. Popping first and reporting the
8439 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
8440 // then ran the slow path with nothing to write.
8441 let Value::Int(index) = self.peek(1) else {
8442 return false;
8443 };
8444 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
8445 if index < 0 {
8446 return false;
8447 }
8448 // Only a real array: a typed array's elements live in its buffer, a string-like
8449 // object has no element vector, and `array_set` on either does nothing.
8450 let Value::Object(object) = self.peek(2) else {
8451 return false;
8452 };
8453 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
8454 return false;
8455 }
8456 // A non-extensible array reports `false` here, but the *slow* path has to decide
8457 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
8458 // that with the key and the stack still intact.
8459 if !object.is_extensible() {
8460 return false;
8461 }
8462 // Inside the logical length, so the store cannot change `length`. Combined with
8463 // extensibility above, the only growth left for `array_set` is filling a hole in
8464 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
8465 // shape this fast path exists for. A store past the length would grow the array,
8466 // and whether that is allowed is the slow path's question.
8467 if index as usize >= object.array_length().unwrap_or(0) {
8468 return false;
8469 }
8470 // The bound `array_set` refuses past. Checking it here keeps that arm from having
8471 // to report a failure after the operands are gone.
8472 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
8473 return false;
8474 }
8475 let value = self.pop();
8476 self.pop();
8477 self.pop();
8478 object.array_store(self.heap, index as usize, value)
8479 }
8480
8481 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
8482 fn stop(&mut self, pc: usize) -> Option<Value> {
8483 self.frame_mut().pc = pc;
8484 None
8485 }
8486
8487 fn push(&mut self, value: Value) {
8488 self.frame_mut().stack.push(value);
8489 }
8490
8491 fn pop(&mut self) -> Value {
8492 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
8493 }
8494
8495 fn pop_n(&mut self, count: usize) -> Vec<Value> {
8496 let frame = self.frame_mut();
8497 let start = frame.stack.len().saturating_sub(count);
8498 frame.stack.split_off(start)
8499 }
8500
8501 fn peek(&self, back: usize) -> Value {
8502 let frame = self.frame();
8503 frame
8504 .stack
8505 .get(frame.stack.len().wrapping_sub(1 + back))
8506 .cloned()
8507 .unwrap_or(Value::Undefined)
8508 }
8509
8510 #[allow(clippy::too_many_lines)]
8511 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
8512 use Opcode::*;
8513 match op {
8514 // -- constants and stack shuffling -----------------------------
8515 Nop => {}
8516 PushMinus1 => self.push(Value::Int(-1)),
8517 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
8518 let value = match op {
8519 Push0 => 0,
8520 Push1 => 1,
8521 Push2 => 2,
8522 Push3 => 3,
8523 Push4 => 4,
8524 Push5 => 5,
8525 Push6 => 6,
8526 _ => 7,
8527 };
8528 self.push(Value::Int(value));
8529 }
8530 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
8531 PushBigintI32 => {
8532 // The immediate form of a `BigInt` literal; the reference has the same
8533 // split between this and a constant-pool entry.
8534 let value = crate::bigint::BigInt::from_i64(a as i64);
8535 self.push(self.bigint(value));
8536 }
8537 PushTrue => self.push(Value::Bool(true)),
8538 PushFalse => self.push(Value::Bool(false)),
8539 PushEmptyString => self.push(self.string("")),
8540 Undefined => self.push(Value::Undefined),
8541 Null => self.push(Value::Null),
8542 Object => {
8543 let proto = self.realm.object_proto.clone();
8544 self.push(Value::Object(self.new_object(Some(proto))));
8545 }
8546 PushThis => {
8547 let this = self.frame().this.clone();
8548 self.push(this);
8549 }
8550 PushConst | PushConst8 => {
8551 let value = self.constant(a as usize)?;
8552 self.push(value);
8553 }
8554 PushAtomValue => {
8555 let text = self.atom_wtf8(a as usize);
8556 self.push(self.string_wtf8(text));
8557 }
8558 Dup => {
8559 let value = self.peek(0);
8560 self.push(value);
8561 }
8562 Dup2 => {
8563 // `a b -> a b a b`
8564 let b = self.peek(0);
8565 let a = self.peek(1);
8566 self.push(a);
8567 self.push(b);
8568 }
8569 Dup3 => {
8570 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
8571 // prototype and key while reading the current value through them.
8572 let c = self.peek(0);
8573 let b = self.peek(1);
8574 let a = self.peek(2);
8575 self.push(a);
8576 self.push(b);
8577 self.push(c);
8578 }
8579 Swap => {
8580 // `a b -> b a`
8581 let bottom = self.pop();
8582 let top = self.pop();
8583 self.push(bottom);
8584 self.push(top);
8585 }
8586 Perm3 => {
8587 // `a b c -> b a c`, the reference's reordering for a spread method
8588 // call: `obj func array` becomes the `func this array` that `apply`
8589 // takes.
8590 let c = self.pop();
8591 let b = self.pop();
8592 let a = self.pop();
8593 self.push(b);
8594 self.push(a);
8595 self.push(c);
8596 }
8597 Dup1 => {
8598 let value = self.peek(1);
8599 self.push(value);
8600 }
8601 Drop => {
8602 self.pop();
8603 }
8604 Nip => {
8605 // `a b -> b`
8606 let top = self.pop();
8607 self.pop();
8608 self.push(top);
8609 }
8610 Perm4 => {
8611 // `obj prop a b -> a obj prop b`, the reference's reordering for a
8612 // postfix update of a computed element: it puts the *old* value
8613 // underneath the receiver and key so `put_array_el` can consume them
8614 // and leave the old value as the expression's result.
8615 let d = self.pop();
8616 let c = self.pop();
8617 let b = self.pop();
8618 let a = self.pop();
8619 self.push(c);
8620 self.push(a);
8621 self.push(b);
8622 self.push(d);
8623 }
8624 Insert2 => {
8625 // `obj a -> a obj a`
8626 let value = self.pop();
8627 let object = self.pop();
8628 self.push(value.clone());
8629 self.push(object);
8630 self.push(value);
8631 }
8632 Insert3 => {
8633 // `obj prop a -> a obj prop a`
8634 let value = self.pop();
8635 let key = self.pop();
8636 let object = self.pop();
8637 self.push(value.clone());
8638 self.push(object);
8639 self.push(key);
8640 self.push(value);
8641 }
8642 Insert4 => {
8643 // `this obj prop a -> a this obj prop a`
8644 //
8645 // `put_super_value` consumes all four and yields nothing, so the copy
8646 // underneath is what leaves the assignment an expression value.
8647 let value = self.pop();
8648 let key = self.pop();
8649 let object = self.pop();
8650 let receiver = self.pop();
8651 self.push(value.clone());
8652 self.push(receiver);
8653 self.push(object);
8654 self.push(key);
8655 self.push(value);
8656 }
8657 Swap2 => {
8658 // `a b c d -> c d a b`
8659 let d = self.pop();
8660 let c = self.pop();
8661 let b = self.pop();
8662 let a = self.pop();
8663 self.push(c);
8664 self.push(d);
8665 self.push(a);
8666 self.push(b);
8667 }
8668 Rot3l => {
8669 // `x a b -> a b x`
8670 let b = self.pop();
8671 let a = self.pop();
8672 let x = self.pop();
8673 self.push(a);
8674 self.push(b);
8675 self.push(x);
8676 }
8677 Rot3r => {
8678 // `a b c -> c a b`
8679 let c = self.pop();
8680 let b = self.pop();
8681 let a_value = self.pop();
8682 self.push(c);
8683 self.push(a_value);
8684 self.push(b);
8685 }
8686
8687 Rest => {
8688 // `...rest` in a parameter list: the arguments from index `a` on, as a
8689 // real array. It takes nothing off the stack — the arguments are in the
8690 // frame, not on it.
8691 let frame = self.frame();
8692 let from = a as usize;
8693 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
8694 let array = self.new_array(collected);
8695 self.push(Value::Object(array));
8696 }
8697
8698 // -- slots ------------------------------------------------------
8699 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
8700 let slot = self.slot_operand(op, a);
8701 let value = self.get_loc(slot);
8702 self.push(value);
8703 }
8704 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
8705 let slot = self.slot_operand(op, a);
8706 let value = self.pop();
8707 self.put_loc(slot, value);
8708 }
8709 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
8710 let slot = self.slot_operand(op, a);
8711 let value = self.pop();
8712 self.put_loc(slot, value.clone());
8713 self.push(value);
8714 }
8715 // The `_check` forms are the temporal dead zone: they throw when the
8716 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
8717 // *reads*, so only the two writes may pop — mishandling that quietly
8718 // consumes the value the caller pushed just before.
8719 GetLocCheck => {
8720 let slot = self.slot_operand(op, a);
8721 let value = self.get_loc(slot);
8722 if matches!(value, Value::Uninitialized) {
8723 return Err(self.dead_zone(slot, VarSlot::Loc));
8724 }
8725 self.push(value);
8726 }
8727 PutLocCheck | SetLocCheck => {
8728 let slot = self.slot_operand(op, a);
8729 let value = self.pop();
8730 if matches!(value, Value::Uninitialized) {
8731 return Err(self.dead_zone(slot, VarSlot::Loc));
8732 }
8733 // The initialiser goes through `put_loc`, not this, so any store that
8734 // reaches here is a later assignment — which a `const` refuses.
8735 if self.is_read_only(slot, VarSlot::Loc) {
8736 return Err(self.read_only(slot, VarSlot::Loc));
8737 }
8738 if op == SetLocCheck {
8739 self.put_loc(slot, value.clone());
8740 self.push(value);
8741 } else {
8742 self.put_loc(slot, value);
8743 }
8744 }
8745 PutLocCheckInit => {
8746 // The one store that *initialises* a lexical slot: `this` in a derived
8747 // constructor, which only exists after `super()` has run. A second
8748 // initialisation is the error the reference reports as
8749 // "'this' can be initialized only once".
8750 let slot = self.slot_operand(op, a);
8751 let value = self.pop();
8752 if !matches!(self.get_loc(slot), Value::Uninitialized) {
8753 return Err(Signal::Throw(self.make_error(
8754 "ReferenceError",
8755 "'this' can be initialized only once",
8756 )));
8757 }
8758 self.put_loc(slot, value);
8759 }
8760 CheckCtor => {
8761 // A class constructor may only run under `new`, which is what makes
8762 // `class A {}; A()` a TypeError.
8763 if matches!(self.frame().new_target, Value::Undefined) {
8764 return Err(Signal::Throw(self.make_error(
8765 "TypeError",
8766 "class constructors must be invoked with 'new'",
8767 )));
8768 }
8769 }
8770 InitCtor => {
8771 // The body a derived class gets when it declares no constructor:
8772 // forward every argument to the parent constructor, keeping `new.target`.
8773 if matches!(self.frame().new_target, Value::Undefined) {
8774 return Err(Signal::Throw(self.make_error(
8775 "TypeError",
8776 "class constructors must be invoked with 'new'",
8777 )));
8778 }
8779 let Some(callee) = self.current_callee() else {
8780 return Err(Signal::Throw(
8781 self.make_error("TypeError", "no constructor to inherit from"),
8782 ));
8783 };
8784 let parent = callee.proto().map_or(Value::Null, Value::Object);
8785 let new_target = self.frame().new_target.clone();
8786 let args = self.frame().passed().to_vec();
8787 let result = self.construct(parent, new_target, args)?;
8788 self.push(result);
8789 }
8790 SetLocUninitialized => {
8791 let slot = self.slot_operand(op, a);
8792 self.put_loc(slot, Value::Uninitialized);
8793 }
8794 CloseLoc => {
8795 // "Close" a binding: give it a *fresh* cell holding the current
8796 // value. Closures created before this point keep the old cell and the
8797 // ones created after see the new one, which is what makes every
8798 // iteration of `for (let i ...)` capture its own `i`, and what freezes
8799 // a block-scoped binding when the block ends.
8800 //
8801 // Clearing the slot instead (which this used to do) broke both: a
8802 // closure over a captured block variable read `undefined`, and a loop
8803 // terminated after one iteration.
8804 let slot = self.slot_operand(op, a);
8805 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
8806 if index >= 0 {
8807 let current = self.frame().cells[index as usize].get();
8808 let fresh = self.new_cell(current);
8809 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
8810 *cell = fresh;
8811 }
8812 }
8813 }
8814 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
8815 let slot = self.slot_operand(op, a);
8816 let value = self.get_arg(slot);
8817 self.push(value);
8818 }
8819 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
8820 let slot = self.slot_operand(op, a);
8821 let value = self.pop();
8822 self.put_arg(slot, value);
8823 }
8824 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
8825 let slot = self.slot_operand(op, a);
8826 let value = self.pop();
8827 self.put_arg(slot, value.clone());
8828 self.push(value);
8829 }
8830
8831 // -- closure variables ------------------------------------------
8832 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
8833 let slot = self.slot_operand(op, a);
8834 // A name a direct `eval` created shadows the binding the compiler chose.
8835 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
8836 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
8837 // and only a runtime lookup can know that.
8838 if let Some(cell) = self.eval_created_local(slot) {
8839 self.push(cell.get());
8840 return self.step();
8841 }
8842 let value = self.cell_value(slot)?;
8843 self.push(value);
8844 }
8845 GetVarRefCheck => {
8846 let slot = self.slot_operand(op, a);
8847 let value = self.cell_value(slot)?;
8848 if matches!(value, Value::Uninitialized) {
8849 return Err(self.dead_zone(slot, VarSlot::Closure));
8850 }
8851 self.push(value);
8852 }
8853 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
8854 let slot = self.slot_operand(op, a);
8855 let value = self.pop();
8856 if let Some(cell) = self.eval_created_local(slot) {
8857 cell.set(value);
8858 return self.step();
8859 }
8860 // Same rule as `PutLocCheck`: a checked store to a captured binding
8861 // refuses a `const` once its initialiser has run.
8862 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
8863 return Err(self.read_only(slot, VarSlot::Closure));
8864 }
8865 self.set_cell(slot, value)?;
8866 }
8867 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
8868 let slot = self.slot_operand(op, a);
8869 let value = self.pop();
8870 if let Some(cell) = self.eval_created_local(slot) {
8871 cell.set(value.clone());
8872 self.push(value);
8873 return self.step();
8874 }
8875 self.set_cell(slot, value.clone())?;
8876 self.push(value);
8877 }
8878
8879 // -- globals ----------------------------------------------------
8880 GetVar => {
8881 let value = self.get_global(a as usize)?;
8882 self.push(value);
8883 }
8884 GetVarUndef => {
8885 let value = self
8886 .get_global(a as usize)
8887 .or_else(|_| Ok(Value::Undefined))?;
8888 self.push(value);
8889 }
8890 DeleteVar => {
8891 // `delete name` for a name that is not a declared binding. A lexical
8892 // global lives in the reference table and cannot be deleted; anything
8893 // reachable only as a property of the global object is *implicit* —
8894 // `x = 1` with no declaration — and goes away if it is configurable,
8895 // which is what `delete` on an implicit global answers.
8896 let name = self.atom_text(a as usize);
8897 let global = self.realm.global.clone();
8898 let deleted = if self.realm.globals.contains_key(&name) {
8899 false
8900 } else if global.own_property(&name).is_some() {
8901 self.delete_property(&global, &name)?
8902 } else {
8903 true
8904 };
8905 self.push(Value::Bool(deleted));
8906 }
8907 PutVar => {
8908 let value = self.pop();
8909 self.put_global(a as usize, value)?;
8910 }
8911 PutVarInit => {
8912 let slot = a as usize;
8913 let value = self.pop();
8914 self.init_global(slot, value)?;
8915 }
8916
8917 // -- arithmetic -------------------------------------------------
8918 Add => self.binary_add()?,
8919 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
8920 let raw_right = self.pop();
8921 let raw_left = self.pop();
8922 // BigInt arithmetic is a separate path, and not only for the type of the
8923 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
8924 // rather than a silent conversion.
8925 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
8926 let left = self.primitive_of(raw_left)?;
8927 let right = self.primitive_of(raw_right)?;
8928 let value = self.bigint_arithmetic(op, left, right)?;
8929 self.push(value);
8930 } else {
8931 let right = self.numeric(raw_right)?;
8932 let left = self.numeric(raw_left)?;
8933 self.push(arithmetic(op, left, right)?);
8934 }
8935 }
8936 Neg => {
8937 let raw = self.pop();
8938 match raw {
8939 // A bigint negates exactly, however wide it is.
8940 Value::BigInt(big) => {
8941 let negated = big.negate();
8942 self.push(self.bigint(negated));
8943 }
8944 other => {
8945 let value = self.numeric(other)?;
8946 self.push(negate(value));
8947 }
8948 }
8949 }
8950 Plus => {
8951 let value = self.pop();
8952 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
8953 // unary plus is defined to produce a *number*, which a bigint cannot
8954 // become without loss. It used to fall through to `NaN`.
8955 if matches!(value, Value::BigInt(_)) {
8956 return Err(self.type_error("cannot convert bigint to number"));
8957 }
8958 let numeric = self.numeric_of(value)?;
8959 self.push(numeric);
8960 }
8961 Inc => {
8962 let raw = self.pop();
8963 let (_, updated) = self.advance_numeric(raw, true)?;
8964 self.push(updated);
8965 }
8966 Dec => {
8967 let raw = self.pop();
8968 let (_, updated) = self.advance_numeric(raw, false)?;
8969 self.push(updated);
8970 }
8971 PostInc | PostDec => {
8972 // `x -> x x+1`: the *new* value ends up on top, so the store the
8973 // compiler emits right after (`put_var`) writes the incremented
8974 // one, while the old value stays underneath for the expression's
8975 // own result. Getting this backwards makes `i++` a no-op, which
8976 // turns `while (i < 3)` into an infinite loop.
8977 let raw = self.pop();
8978 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
8979 self.push(old);
8980 self.push(updated);
8981 }
8982 Not => {
8983 let raw = self.pop();
8984 match raw {
8985 // `~x` on a bigint is `-x - 1`, exact at any width.
8986 Value::BigInt(big) => {
8987 let inverted = big.bitnot();
8988 self.push(self.bigint(inverted));
8989 }
8990 other => {
8991 let value = self.numeric(other)?;
8992 self.push(Value::Int(!value.to_int32()));
8993 }
8994 }
8995 }
8996 Lnot => {
8997 let value = self.pop();
8998 self.push(Value::Bool(!value.to_boolean()));
8999 }
9000
9001 // -- comparison -------------------------------------------------
9002 Lt | Lte | Gt | Gte => {
9003 let right = self.pop();
9004 let left = self.pop();
9005 let answer = self.relational(op, left, right)?;
9006 self.push(answer);
9007 }
9008 Eq | Neq => {
9009 let right = self.pop();
9010 let left = self.pop();
9011 let equal = self.abstract_equals(left, right)?;
9012 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9013 }
9014 StrictEq => {
9015 let right = self.pop();
9016 let left = self.pop();
9017 self.push(Value::Bool(left.strict_equals(&right)));
9018 }
9019 StrictNeq => {
9020 let right = self.pop();
9021 let left = self.pop();
9022 self.push(Value::Bool(!left.strict_equals(&right)));
9023 }
9024 IsUndefined => {
9025 // `=== undefined`, which is what a destructuring default tests. It is
9026 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9027 let value = self.pop();
9028 self.push(Value::Bool(matches!(value, Value::Undefined)));
9029 }
9030 IsUndefinedOrNull => {
9031 let value = self.pop();
9032 self.push(Value::Bool(value.is_nullish()));
9033 }
9034 Typeof => {
9035 let value = self.pop();
9036 self.push(self.string(value.type_of()));
9037 }
9038 ToObject => {
9039 // A destructuring *object* pattern starts here, which is why
9040 // `var {} = null` throws. Only `undefined` and `null` are refused; a
9041 // primitive is boxed.
9042 let value = self.pop();
9043 let object = self.object_from(&value)?;
9044 self.push(Value::Object(object));
9045 }
9046 Instanceof => {
9047 let constructor = self.pop();
9048 let object = self.pop();
9049 let answer = self.instance_of(&object, &constructor)?;
9050 self.push(Value::Bool(answer));
9051 }
9052 In => {
9053 let object = self.pop();
9054 let key = self.pop();
9055 let answer = self.has_property(&key, &object)?;
9056 self.push(Value::Bool(answer));
9057 }
9058
9059 // -- control flow -----------------------------------------------
9060 Goto | Goto8 | Goto16 => {
9061 self.frame_mut().pc = a as usize;
9062 }
9063 IfTrue | IfTrue8 => {
9064 let value = self.pop();
9065 if value.to_boolean() {
9066 self.frame_mut().pc = a as usize;
9067 }
9068 }
9069 IfFalse | IfFalse8 => {
9070 let value = self.pop();
9071 if !value.to_boolean() {
9072 self.frame_mut().pc = a as usize;
9073 }
9074 }
9075 Catch => {
9076 // Pushes the handler target onto the value stack; `unwind` finds it.
9077 self.push(Value::CatchOffset(a));
9078 }
9079 Gosub => {
9080 self.push(Value::ReturnAddress(next as u32));
9081 self.frame_mut().pc = a as usize;
9082 }
9083 Ret => {
9084 let value = self.pop();
9085 match value {
9086 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9087 _ => {
9088 return Err(Signal::Throw(
9089 self.make_error("InternalError", "invalid return address"),
9090 ));
9091 }
9092 }
9093 }
9094 NipCatch => {
9095 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9096 // including the marker, keeping the top value.
9097 let top = self.pop();
9098 loop {
9099 match self.pop() {
9100 Value::CatchOffset(_) | Value::Undefined => break,
9101 _ => {}
9102 }
9103 if self.frame().stack.is_empty() {
9104 break;
9105 }
9106 }
9107 self.push(top);
9108 }
9109 Throw => {
9110 let value = self.pop();
9111 return Err(Signal::Throw(value));
9112 }
9113 ThrowError => {
9114 let name = self.atom_text(a as usize);
9115 let (class, message) = match b {
9116 0 => ("TypeError", format!("'{name}' is read-only")),
9117 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9118 2 => ("ReferenceError", format!("'{name}' is not initialized")),
9119 // `delete super.x` is a syntax-level mistake the reference reports
9120 // with this wording, not a property-access failure.
9121 3 => (
9122 "ReferenceError",
9123 "unsupported reference to 'super'".to_string(),
9124 ),
9125 4 => (
9126 "TypeError",
9127 "iterator does not have a throw method".to_string(),
9128 ),
9129 5 => (
9130 "ReferenceError",
9131 "invalid assignment left-hand side".to_string(),
9132 ),
9133 _ => ("TypeError", format!("invalid operation on '{name}'")),
9134 };
9135 return Err(Signal::Throw(self.make_error(class, &message)));
9136 }
9137 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9138 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9139 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9140 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9141 Await => return Ok(Step::Suspend(SuspendKind::Await)),
9142 ReturnAsync => {
9143 // The reference's `return_async` returns `undefined` and lets the resume
9144 // machinery pick the real value off `sp[-1]`, which is how it tells a
9145 // completion from a suspension. Carrying the value explicitly says the
9146 // same thing without the implicit stack slot.
9147 let value = self.pop();
9148 return Ok(Step::Return(value));
9149 }
9150 Return => {
9151 let value = self.pop();
9152 return Ok(Step::Return(value));
9153 }
9154 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9155
9156 // -- calls ------------------------------------------------------
9157 Call | Call0 | Call1 | Call2 | Call3 => {
9158 let argc = self.argc_operand(op, a);
9159 let args = self.pop_n(argc);
9160 let callee = self.pop();
9161 // A plain call has no receiver; the callee decides what to do with
9162 // `undefined` (a sloppy function substitutes the global object).
9163 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9164 self.push(result);
9165 }
9166 }
9167 CallConstructor => {
9168 // `constructor this_obj args… -> object`. The duplicated
9169 // constructor is `new.target`; this milestone does not expose it,
9170 // so the extra copy is simply consumed here.
9171 let argc = a as usize;
9172 let args = self.pop_n(argc);
9173 let new_target = self.pop();
9174 let callee = self.pop();
9175 let result = self.construct(callee, new_target, args)?;
9176 self.push(result);
9177 }
9178 CallMethod => {
9179 let argc = a as usize;
9180 let args = self.pop_n(argc);
9181 let callee = self.pop();
9182 let this = self.pop();
9183 if let Some(result) = self.call_or_push(callee, this, args)? {
9184 self.push(result);
9185 }
9186 }
9187 Apply => {
9188 // `func this array -> result`, the spread-call form: the compiler
9189 // builds one array of arguments, and all that is left here is to
9190 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9191 let array = self.pop();
9192 let this = self.pop();
9193 let callee = self.pop();
9194 let args = self.array_like_to_args(&array)?;
9195 if a & 1 != 0 {
9196 let result = self.construct(callee, this, args)?;
9197 self.push(result);
9198 } else if let Some(result) = self.call_or_push(callee, this, args)? {
9199 self.push(result);
9200 }
9201 }
9202 TailCall | TailCallMethod => {
9203 // `tail_call` is `call` whose result is returned immediately — the
9204 // reference jumps straight to `done` instead of storing the value and
9205 // running on. The callee still gets its own frame, so deep tail
9206 // recursion hits the stack limit exactly like plain recursion does;
9207 // marking this frame lets the return path unwind without needing
9208 // instructions after the call.
9209 let argc = if op == TailCallMethod {
9210 a as usize
9211 } else {
9212 self.argc_operand(op, a)
9213 };
9214 let args = self.pop_n(argc);
9215 let callee = self.pop();
9216 let this = if op == TailCallMethod {
9217 self.pop()
9218 } else {
9219 Value::Undefined
9220 };
9221 if let Value::Object(function) = &callee
9222 && let Some((code, env)) = bytecode_of(function)
9223 {
9224 // A generator or async body is not run here at all: calling it only
9225 // *creates* the generator/coroutine, so it must not inherit this
9226 // frame. Doing so made `function f(){ return g() }` push `g`'s body
9227 // onto `f`'s frame, and the first `yield`/`await` then reported
9228 // "a generator body ran as an ordinary call".
9229 if code.code.kind.is_generator() || code.code.kind.is_async() {
9230 let value = self.call_value(callee, this, args)?;
9231 return Ok(Step::Return(value));
9232 }
9233 self.frame_mut().tail = true;
9234 self.push_frame(code, env, this, args, callee)?;
9235 return Ok(Step::Continue);
9236 }
9237 // A native callee has no frame to reuse, so its value is simply
9238 // returned.
9239 let value = self.call_value(callee, this, args)?;
9240 return Ok(Step::Return(value));
9241 }
9242
9243 // -- objects ----------------------------------------------------
9244 SpecialObject => {
9245 let value = self.special_object(a)?;
9246 self.push(value);
9247 }
9248 PrivateSymbol => {
9249 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9250 // symbol each time it is evaluated, which is why the compiler evaluates it
9251 // once (at class definition) and stores it in a class-scope binding.
9252 let name = self.atom_text(a as usize);
9253 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9254 self.push(Value::Symbol(symbol));
9255 }
9256 GetPrivateField => {
9257 // `obj symbol -> value`. A missing private field is a TypeError, which is what
9258 // makes `#x` inaccessible on any object not built by this class.
9259 let symbol = self.pop();
9260 let object = self.pop();
9261 let value = self.read_private_field(&object, &symbol)?;
9262 self.push(value);
9263 }
9264 PutPrivateField => {
9265 // `obj value symbol ->`, and the store is a plain assignment to a property the
9266 // class already created, so there is no setter to consult.
9267 let symbol = self.pop();
9268 let value = self.pop();
9269 let object = self.pop();
9270 self.write_private_field(&object, &symbol, value)?;
9271 }
9272 DefinePrivateField => {
9273 // `obj symbol value -> obj`: a field initialiser creates the property, and
9274 // redefining one is a TypeError ("already exists").
9275 let value = self.pop();
9276 let symbol = self.pop();
9277 let object = self.pop();
9278 self.define_private_field(&object, &symbol, value)?;
9279 self.push(object);
9280 }
9281 PrivateIn => {
9282 // `obj key -> bool`: `#x in o`. The second operand decides which question is
9283 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9284 // is a field, so this is an own-property test; a *function* is a method or
9285 // accessor, so this is a brand check.
9286 let key = self.pop();
9287 let object = self.pop();
9288 let Some(target) = object.as_object() else {
9289 return Err(Signal::Throw(
9290 self.make_error("TypeError", "invalid 'in' operand"),
9291 ));
9292 };
9293 let present = match &key {
9294 Value::Object(_) => self.check_brand(target, &key)?,
9295 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9296 };
9297 self.push(Value::Bool(present));
9298 }
9299 AddBrand => {
9300 // `obj home ->`: create the class brand on `home` if it has none, then give
9301 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9302 // class definition: only the prototype's copy of the symbol is wanted.
9303 let home = self.pop();
9304 let object = self.pop();
9305 self.add_brand(&object, &home)?;
9306 }
9307 CheckBrand => {
9308 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9309 // Both stay, because the caller needs them — `nip` halves a read into its
9310 // value and `call_method` uses the pair as receiver and callee.
9311 let function = self.peek(0);
9312 let object = self.peek(1);
9313 let Some(target) = object.as_object() else {
9314 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9315 };
9316 if !self.check_brand(target, &function)? {
9317 return Err(Signal::Throw(
9318 self.make_error("TypeError", "invalid brand on object"),
9319 ));
9320 }
9321 }
9322 GetLength => {
9323 // `get_length` is the `.length` read; an array and a string answer
9324 // from their own length, anything else from the property.
9325 let target = self.pop();
9326 let value = match &target {
9327 Value::Object(object) => match object.array_length() {
9328 Some(length) => crate::object::length_value(length),
9329 None => self.read_field(&target, "length")?,
9330 },
9331 Value::String(text) => Value::Int(text.utf16_len() as i32),
9332 _ => self.read_field(&target, "length")?,
9333 };
9334 self.push(value);
9335 }
9336 GetField | GetField2 => {
9337 let object = self.pop();
9338 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9339 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9340 // just below is what lets the borrow outlive the `&mut self` the lookup
9341 // needs — one refcount bump instead of a key clone plus its drop, on the
9342 // hottest property path there is: every `o.x` and every `o.m()` receiver.
9343 let code = self.frame().code.clone();
9344 let key = &code.atom_keys[a as usize];
9345 let value = self.read_field_cached(&object, key, next)?;
9346 if op == GetField2 {
9347 self.push(object);
9348 }
9349 self.push(value);
9350 }
9351 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
9352 let key = self.pop();
9353 let object = self.pop();
9354 let key = self.propkey(&key)?;
9355 let value = self.read_field_key(&object, &key)?;
9356 if matches!(op, GetArrayEl2 | GetArrayEl3) {
9357 self.push(object);
9358 }
9359 if op == GetArrayEl3 {
9360 // The key goes back in its *value* form, which the compiler stores
9361 // into the target of a destructuring assignment.
9362 self.push(match &key {
9363 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9364 PropertyKey::String(text) => self.string_wtf8(text.clone()),
9365 });
9366 }
9367 self.push(value);
9368 }
9369 PutField => {
9370 let value = self.pop();
9371 let object = self.pop();
9372 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
9373 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
9374 // only reads. `this.value = …` is the write half of the hottest loop in
9375 // `property:method-call`, and `own_property_key` was 4.8% of the case.
9376 let code = self.frame().code.clone();
9377 let key = &code.atom_keys[a as usize];
9378 self.write_field_key(&object, key, value)?;
9379 }
9380 PutArrayEl => {
9381 let value = self.pop();
9382 let key = self.pop();
9383 let object = self.pop();
9384 let key = self.propkey(&key)?;
9385 self.write_field_key(&object, &key, value)?;
9386 }
9387 DefineField => {
9388 let value = self.pop();
9389 let object = self.pop();
9390 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
9391 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
9392 // three U+FFFD — a property under a different name from the one
9393 // `o["\uD800"]` reads.
9394 let code = self.frame().code.clone();
9395 let key = code.atom_keys[a as usize].clone();
9396 // No naming here. `{m: function(){}}` is named by the *compiler*, which
9397 // emits `set_name` — and only where `NamedEvaluation` applies, so
9398 // `{m: (0, function(){})}` stays anonymous. Naming every function that
9399 // reaches a property definition got that case wrong, and the compiler is
9400 // the only place that can tell the two apart.
9401 if let Some(target) = object.as_object() {
9402 // Only an *array* stores into the element vector. A numeric key
9403 // on an ordinary object is an ordinary property, which is what
9404 // makes `{1: 'a'}` iterate as a key rather than disappear.
9405 let stored = target.is_array()
9406 && key.as_str().and_then(array_index).is_some_and(|index| {
9407 target.array_set(self.heap, index as usize, value.clone())
9408 });
9409 if !stored {
9410 target.define_data_key(&key, value);
9411 }
9412 }
9413 self.push(object);
9414 }
9415 DefineArrayEl => {
9416 // `obj key value -> obj key`. The *value* form of the key is what goes
9417 // back on the stack — the compiler stores it into the pattern's binding —
9418 // so the symbol is not stringified on the way through.
9419 let value = self.pop();
9420 let key_value = self.pop();
9421 let object = self.peek(0);
9422 let key = self.propkey(&key_value)?;
9423 self.write_field_key(&object, &key, value)?;
9424 self.push(key_value);
9425 }
9426 SetHomeObject => {
9427 // `obj func -> obj func`: records the object a method was defined on so
9428 // `super` inside it resolves against that object's prototype.
9429 let function = self.peek(0);
9430 let home = self.peek(1);
9431 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
9432 function.set_home_object(Some(home.clone()));
9433 }
9434 }
9435 Regexp => {
9436 // `pattern flags -> regexp`. A literal compiles here rather than through the
9437 // constructor, which is both what the reference's dedicated opcode is for
9438 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
9439 let flags = self.pop();
9440 let pattern = self.pop();
9441 let pattern = self.to_js_string(&pattern)?;
9442 let flags = self.to_js_string(&flags)?;
9443 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
9444 self.push(Value::Object(object));
9445 }
9446 UsingDisposeInit => {
9447 // The error state a disposal accumulates into. Uninitialised means "no
9448 // failure yet"; anything else is the exception being propagated.
9449 self.push(Value::Uninitialized);
9450 }
9451 UsingCheck => {
9452 // `value -> value, method`: validate and snapshot the disposer now, so a
9453 // later change to `Symbol.dispose` cannot change what gets called, and so a
9454 // value that is not disposable fails before the body runs.
9455 let value = self.pop();
9456 let method = self.using_method_for(&value, a as u8 == 1)?;
9457 self.push(value);
9458 self.push(method);
9459 }
9460 UsingDispose => {
9461 // `error_state -> error_state'`: dispose the variable at `slot` — its value
9462 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
9463 // the pending error.
9464 let slot = self.slot_operand(op, a);
9465 let error_state = self.pop();
9466 let merged = self.using_dispose_once(slot, error_state)?;
9467 self.push(merged);
9468 }
9469 UsingDisposeMerge => {
9470 let new_error = self.pop();
9471 let error_state = self.pop();
9472 let merged = self.merge_dispose_error(new_error, error_state);
9473 self.push(merged);
9474 }
9475 UsingDisposeEnd => {
9476 // A disposal that failed replaces the block's normal completion, so the
9477 // error state becomes a real throw here rather than at the call site.
9478 let error_state = self.pop();
9479 if !matches!(error_state, Value::Uninitialized) {
9480 return Err(Signal::Throw(error_state));
9481 }
9482 }
9483 UsingDisposeAsync => {
9484 // `await using` needs a promise to await and this runtime has no
9485 // `Promise` builtin, so the disposer is called synchronously and its result
9486 // discarded. That is correct for a disposer that returns nothing and is
9487 // reported as a gap rather than silently skipped.
9488 let slot = self.slot_operand(op, a);
9489 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
9490 self.push(error_state);
9491 }
9492 GetSuper => {
9493 // `obj -> obj's prototype`: the starting point of a `super` lookup.
9494 let object = self.pop();
9495 let proto = match &object {
9496 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
9497 _ => Value::Null,
9498 };
9499 self.push(proto);
9500 }
9501 GetSuperValue => {
9502 // `receiver proto key -> value`, searching from `proto` but reporting to
9503 // `receiver`, which is what `super.g` must do for a getter to see `this`.
9504 //
9505 // Three values in, one out: the receiver is *consumed*, not left under the
9506 // result. Leaving it there was invisible for `super.x` in `return` or
9507 // statement position (the result is what gets popped) and corrupted the
9508 // frame everywhere else — `print(super.x)` left the class where the call
9509 // opcode looks for the receiver and called the class itself.
9510 let key = self.pop();
9511 let proto = self.pop();
9512 let receiver = self.pop();
9513 let value = self.super_read(&receiver, &proto, &key)?;
9514 self.push(value);
9515 }
9516 PutSuperValue => {
9517 // `receiver proto key value ->`: a store that starts at `proto` but
9518 // assigns to `receiver`.
9519 let value = self.pop();
9520 let key = self.pop();
9521 let proto = self.pop();
9522 let receiver = self.pop();
9523 self.super_write(&receiver, &proto, &key, value)?;
9524 }
9525 DefineClass => {
9526 // `parent ctor -> ctor proto`: the constructor becomes the class and a
9527 // fresh prototype object lands on top for the methods to go on.
9528 let name = self.atom_text(a as usize);
9529 let (ctor, proto) = self.define_class(&name, b)?;
9530 self.push(ctor);
9531 self.push(Value::Object(proto));
9532 }
9533 DefineClassComputed => {
9534 // `parent ctor key -> ctor proto key`: the computed name stays put so
9535 // `define_field`-style consumers can still read it.
9536 let key = self.pop();
9537 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9538 let (ctor, proto) = self.define_class(&name, b)?;
9539 self.push(ctor);
9540 self.push(Value::Object(proto));
9541 self.push(key);
9542 }
9543 DefineMethod => {
9544 let function = self.pop();
9545 let object = self.pop();
9546 // The exact key, like `define_field`: a quoted method key may hold an
9547 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
9548 // that `o["\uD800"]` finds.
9549 let code = self.frame().code.clone();
9550 let key = code.atom_keys[a as usize].clone();
9551 // A method's `[[HomeObject]]` is the object it was defined on, which is
9552 // what `super` inside it resolves against.
9553 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9554 function.set_home_object(Some(object.clone()));
9555 }
9556 if let Some(text) = key.as_wtf8() {
9557 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
9558 } else {
9559 self.set_function_name(
9560 &function,
9561 &key_with_accessor_prefix(&key.to_string(), b),
9562 );
9563 }
9564 if let Some(array) = object.as_object() {
9565 define_function_property(array, &key, function, b);
9566 }
9567 self.push(object);
9568 }
9569 DefineMethodComputed => {
9570 let function = self.pop();
9571 let key = self.pop();
9572 let object = self.pop();
9573 let key = self.propkey(&key)?;
9574 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
9575 // the name: `super` inside a computed method resolves through it. Without
9576 // this, `class B extends A { [k]() { return super.m() } }` read the
9577 // home object as null and threw.
9578 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9579 function.set_home_object(Some(object.clone()));
9580 }
9581 match key.as_wtf8() {
9582 Some(text) => {
9583 let name = accessor_prefixed(text, a);
9584 self.set_function_name_wtf8(&function, &name);
9585 }
9586 None => self.set_function_name(
9587 &function,
9588 &key_with_accessor_prefix(&key.to_string(), a),
9589 ),
9590 }
9591 if let Some(array) = object.as_object() {
9592 define_function_property(array, &key, function, a);
9593 }
9594 self.push(object);
9595 }
9596 SetProto => {
9597 let proto = self.pop();
9598 let object = self.pop();
9599 if let Some(target) = object.as_object() {
9600 target.set_proto(proto.as_object().cloned());
9601 }
9602 self.push(object);
9603 }
9604 CopyDataProperties => {
9605 let exclusion = self.pop();
9606 let source = self.pop();
9607 let target = self.peek(0);
9608 self.copy_properties(&target, &source, &exclusion)?;
9609 self.push(source);
9610 self.push(exclusion);
9611 }
9612 ToPropkey => {
9613 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
9614 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
9615 // ordinary `"Symbol(b)"` property.
9616 let value = self.pop();
9617 let key = match self.propkey(&value)? {
9618 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
9619 PropertyKey::String(text) => self.string_wtf8(text),
9620 };
9621 self.push(key);
9622 }
9623 SetName => {
9624 let function = self.peek(0);
9625 let name = self.atom_wtf8(a as usize);
9626 self.set_function_name_wtf8(&function, &name);
9627 }
9628 SetNameComputed => {
9629 let key = self.peek(1);
9630 let function = self.peek(0);
9631 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9632 self.set_function_name(&function, &name);
9633 }
9634
9635 // -- arrays -----------------------------------------------------
9636 ArrayFrom => {
9637 let count = a as usize;
9638 let elements = self.pop_n(count);
9639 let array = self.new_array(elements);
9640 self.push(Value::Object(array));
9641 }
9642 Append => {
9643 // `array index iterable -> array new_index`
9644 let iterable = self.pop();
9645 self.pop();
9646 let array = self.peek(0);
9647 let added = self.append_enumerate(&array, &iterable)?;
9648 self.push(Value::Int(added));
9649 }
9650
9651 // -- iteration --------------------------------------------------
9652 ForInStart => {
9653 let value = self.pop();
9654 let record = self.for_in_record(&value)?;
9655 self.push(Value::Object(record));
9656 }
9657 ForInNext => {
9658 // `record -> record key done`. The flag is *done*, not "found":
9659 // the compiler tests it with `if_false` to jump back into the body,
9660 // so reporting `true` while keys remain would end the loop at once.
9661 let record = self.peek(0);
9662 match self.for_in_advance(&record)? {
9663 Some(key) => {
9664 let text = self.string(key);
9665 self.push(text);
9666 self.push(Value::Bool(false));
9667 }
9668 None => {
9669 self.push(Value::Undefined);
9670 self.push(Value::Bool(true));
9671 }
9672 }
9673 }
9674 ForOfStart => {
9675 let value = self.pop();
9676 let iterator = self.get_iterator(&value)?;
9677 self.push(iterator.object);
9678 self.push(iterator.next);
9679 self.push(Value::CatchOffset(0));
9680 }
9681 ForOfNext => {
9682 // `iter next catch_offset -> iter next catch_offset value done`.
9683 //
9684 // The operand is how many values sit *above* the iterator triple: a
9685 // destructuring rest element keeps its target array and running index
9686 // there while draining the iterator, so the triple is not at the top.
9687 let extra = a as usize;
9688 let iterator_slot = 2 + extra;
9689 // An exhausted iterator is replaced by `undefined` (see below), so a
9690 // second step must not call `next` again — `Array.from` and a
9691 // destructuring pattern both keep stepping past the end.
9692 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
9693 (Value::Undefined, true)
9694 } else {
9695 let iterator = Iterator {
9696 object: self.peek(iterator_slot),
9697 next: self.peek(1 + extra),
9698 };
9699 self.iterator_step(&iterator)?
9700 };
9701 if done {
9702 // The result's `value` is meaningless once the iterator is done:
9703 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
9704 // rather than binding the generator's return value.
9705 let top = self.frame().stack.len() - 1 - iterator_slot;
9706 self.frame_mut().stack[top] = Value::Undefined;
9707 self.push(Value::Undefined);
9708 self.push(Value::Bool(true));
9709 } else {
9710 self.push(value);
9711 self.push(Value::Bool(false));
9712 }
9713 }
9714 IteratorNext => {
9715 // `iter next catch val -> iter next catch val'`: replace the argument with
9716 // the result of `next(val)`. The triple below stays put, which is why the
9717 // three instructions of the `yield*` loop all address the stack the same way.
9718 let value = self.pop();
9719 let object = self.peek(2);
9720 let next = self.peek(1);
9721 let result = self.call_value(next, object, vec![value])?;
9722 self.push(result);
9723 }
9724 IteratorCall => {
9725 // `iter next catch val -> iter next catch val' flag`.
9726 //
9727 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
9728 // The flag is `true` when the method was missing, which is how the
9729 // caller learns that the inner iterator cannot take part in the
9730 // unwinding.
9731 let value = self.pop();
9732 let object = self.peek(2);
9733 let key = if a & 1 != 0 { "throw" } else { "return" };
9734 let method = self.read_field(&object, key)?;
9735 if matches!(method, Value::Undefined | Value::Null) {
9736 self.push(value);
9737 self.push(Value::Bool(true));
9738 } else {
9739 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
9740 let result = self.call_value(method, object, argument)?;
9741 self.push(result);
9742 self.push(Value::Bool(false));
9743 }
9744 }
9745 IteratorCheckObject => {
9746 if !matches!(self.peek(0), Value::Object(_)) {
9747 return Err(Signal::Throw(
9748 self.make_error("TypeError", "iterator must return an object"),
9749 ));
9750 }
9751 }
9752 IteratorClose => {
9753 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
9754 // calling the iterator's `return` so it can release whatever it holds.
9755 //
9756 // The catch offset goes first, so an exception from `return` is not caught
9757 // by the loop being abandoned. This used to pop the three operands and call
9758 // nothing at all, which made `break` out of a `for of` invisible to an
9759 // iterator with a `return` method.
9760 self.pop();
9761 self.pop();
9762 let iterator = self.pop();
9763 if !matches!(iterator, Value::Undefined) {
9764 let method = self.read_field(&iterator, "return")?;
9765 if !matches!(method, Value::Undefined | Value::Null) {
9766 let result = self.call_value(method, iterator.clone(), Vec::new())?;
9767 // §7.4.6: a `return` that answers a non-object is a TypeError.
9768 if !matches!(result, Value::Object(_)) {
9769 return Err(Signal::Throw(
9770 self.make_error("TypeError", "iterator must return an object"),
9771 ));
9772 }
9773 }
9774 }
9775 }
9776 Import => {
9777 // `import(specifier)`: the options slot is on top and is not read yet.
9778 let _options = self.pop();
9779 let specifier = self.pop();
9780 let promise = self.dynamic_import(specifier)?;
9781 self.push(promise);
9782 }
9783 ForAwaitOfStart => {
9784 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
9785 // `Symbol.iterator` fallback.
9786 let value = self.pop();
9787 let iterator = self.get_async_iterator(&value)?;
9788 self.push(iterator.object);
9789 self.push(iterator.next);
9790 self.push(Value::CatchOffset(0));
9791 }
9792 ForAwaitOfNext => {
9793 // `for await` steps the iterator and leaves the *result* wrapped in a
9794 // promise, so the `await` the compiler emits right after this can suspend
9795 // on it. Unwrapping happens in `iterator_get_value_done`.
9796 let extra = a as usize;
9797 let iterator_slot = 2 + extra;
9798 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
9799 Value::Undefined
9800 } else {
9801 let iterator = Iterator {
9802 object: self.peek(iterator_slot),
9803 next: self.peek(1 + extra),
9804 };
9805 let next = iterator.next.clone();
9806 self.call_value(next, iterator.object, Vec::new())?
9807 };
9808 let promise = self.promise_resolve_value(result)?;
9809 self.push(promise);
9810 }
9811 IteratorGetValueDone => {
9812 // `result -> value done`. A missing result object means the iterator was
9813 // already exhausted, which the loop treats as `done`.
9814 let result = self.pop();
9815 let done = match &result {
9816 Value::Object(object) => self
9817 .get_property(object, "done")?
9818 .is_some_and(|value| value.to_boolean()),
9819 _ => true,
9820 };
9821 if done {
9822 // Clear the iterator object so the `iterator_close` the loop emits on
9823 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
9824 // on normal completion, and this is where a normal completion is
9825 // recognised — the same trick `for_of_next` uses, which also replaces
9826 // the slot with `undefined`.
9827 //
9828 // The layout is fixed because only `for await` emits this opcode:
9829 // `iter next catch [result]`, so the iterator is three below the top.
9830 let depth = self.frame().stack.len();
9831 if depth >= 3 {
9832 self.frame_mut().stack[depth - 3] = Value::Undefined;
9833 }
9834 self.push(Value::Undefined);
9835 self.push(Value::Bool(true));
9836 } else {
9837 let Value::Object(object) = &result else {
9838 self.push(Value::Undefined);
9839 self.push(Value::Bool(true));
9840 return Ok(Step::Continue);
9841 };
9842 let value = self
9843 .get_property(object, "value")?
9844 .unwrap_or(Value::Undefined);
9845 self.push(value);
9846 self.push(Value::Bool(false));
9847 }
9848 }
9849
9850 Delete => {
9851 // `delete obj[key]`, where the key was just pushed. Deleting an array
9852 // index leaves a *hole* rather than closing the gap, and a
9853 // non-configurable property answers `false` and stays.
9854 let key = self.pop();
9855 let target = self.pop();
9856 let key = self.propkey(&key)?;
9857 let text_label = key.as_str().unwrap_or("").to_string();
9858 let deleted = match &target {
9859 Value::Object(object) => {
9860 let object = object.clone();
9861 self.delete_property_key(&object, &key)?
9862 }
9863 // A string's `length` and its index properties are
9864 // non-configurable, so deleting one answers `false`.
9865 Value::String(text) => {
9866 !(text_label == "length"
9867 || array_index(&text_label)
9868 .is_some_and(|index| (index as usize) < text.utf16_len()))
9869 }
9870 // "delete null.a" is a TypeError, not a no-op: the operator needs an
9871 // object to delete from, and only a *boxable* primitive has one.
9872 Value::Undefined | Value::Null => {
9873 return Err(Signal::Throw(
9874 self.make_error("TypeError", "cannot convert to object"),
9875 ));
9876 }
9877 // Any other primitive has no own properties; deleting nothing
9878 // succeeds.
9879 _ => true,
9880 };
9881 self.push(Value::Bool(deleted));
9882 }
9883
9884 // -- exceptions and bookkeeping ---------------------------------
9885 Fclosure | Fclosure8 => {
9886 let value = self.closure(a as usize)?;
9887 self.push(value);
9888 }
9889
9890 other => {
9891 let name = other.info().name;
9892 return Err(Signal::Throw(self.make_error(
9893 "InternalError",
9894 &format!("{name} is not implemented yet"),
9895 )));
9896 }
9897 }
9898 Ok(Step::Continue)
9899 }
9900
9901 // -- operand helpers ----------------------------------------------------
9902
9903 /// The slot index an operand names, taking short forms into account.
9904 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
9905 use Opcode::*;
9906 match op {
9907 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
9908 | SetVarRef0 => 0,
9909 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
9910 | SetVarRef1 => 1,
9911 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
9912 | SetVarRef2 => 2,
9913 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
9914 | SetVarRef3 => 3,
9915 _ => a as usize,
9916 }
9917 }
9918
9919 /// The argument count of a call, taking `call0`…`call3` into account.
9920 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
9921 use Opcode::*;
9922 match op {
9923 Call0 => 0,
9924 Call1 => 1,
9925 Call2 => 2,
9926 Call3 => 3,
9927 _ => a as usize,
9928 }
9929 }
9930
9931 /// The atom's name as a property key.
9932 ///
9933 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
9934 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
9935 /// `String::clone` was a heap allocation and a copy — per property access.
9936 /// The atom at `index`, as a property key.
9937 ///
9938 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
9939 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
9940 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
9941 /// 5.3% of `property:monomorphic`.
9942 /// The atom's text, exactly — including an unpaired surrogate.
9943 ///
9944 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
9945 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
9946 /// `atom_text` below is for the other kind of use, where the atom is a key in the
9947 /// engine's own tables.
9948 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
9949 self.frame()
9950 .code
9951 .code
9952 .atoms
9953 .get(index)
9954 .map(|atom| match atom {
9955 Atom::Str(text) => text.clone(),
9956 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
9957 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
9958 Atom::Null => crate::value::Wtf8::new(String::new()),
9959 })
9960 .unwrap_or_default()
9961 }
9962
9963 fn atom_text(&self, index: usize) -> String {
9964 self.frame()
9965 .code
9966 .code
9967 .atoms
9968 .get(index)
9969 .map(|atom| match atom {
9970 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
9971 // compare it to an identifier, and a surrogate-bearing name is reachable
9972 // through `atom_wtf8` where it matters.
9973 Atom::Str(text) => text.to_string_lossy().into_owned(),
9974 Atom::Index(value) => value.to_string(),
9975 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
9976 // `throw_error`, `delete super.x`) never read it.
9977 Atom::Null => String::new(),
9978 })
9979 .unwrap_or_default()
9980 }
9981
9982 fn constant(&mut self, index: usize) -> JsResult<Value> {
9983 let constant = self.frame().code.code.cpool.get(index).cloned();
9984 Ok(match &constant {
9985 Some(Constant::Number(number)) => Value::Float(*number),
9986 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
9987 Some(Constant::BigInt { digits, radix }) => {
9988 match crate::bigint::BigInt::from_radix(digits, *radix) {
9989 Some(big) => self.bigint(big),
9990 // A literal the parser accepted is always parseable; a failure here
9991 // would be a compiler bug, so it reads as an `InternalError`.
9992 None => {
9993 return Err(Signal::Throw(
9994 self.make_error("InternalError", "unparseable bigint literal"),
9995 ));
9996 }
9997 }
9998 }
9999 Some(Constant::Function(_)) => {
10000 return Err(Signal::Throw(
10001 self.make_error("InternalError", "a bare function constant"),
10002 ));
10003 }
10004 // A tagged template's call site: a frozen array of the cooked chunks with a
10005 // frozen `raw` array beside it, which is what `String.raw` reads back.
10006 Some(Constant::Template { cooked, raw }) => {
10007 let cooked_values: Vec<Value> = cooked
10008 .iter()
10009 .map(|chunk| match chunk {
10010 Some(text) => self.string_wtf8(text.clone()),
10011 None => Value::Undefined,
10012 })
10013 .collect();
10014 let raw_values: Vec<Value> =
10015 raw.iter().map(|text| self.string(text.clone())).collect();
10016 let raw_array = self.new_array(raw_values);
10017 raw_array.set_extensible(false);
10018 let template = self.new_array(cooked_values);
10019 template.define(
10020 "raw",
10021 Property::with_attributes(Value::Object(raw_array), false, false),
10022 );
10023 template.set_extensible(false);
10024 Value::Object(template)
10025 }
10026 _ => Value::Undefined,
10027 })
10028 }
10029
10030 /// The reference cell a closure-variable slot names.
10031 ///
10032 /// Two kinds of binding share this addressing: a genuine closure variable
10033 /// (captured from an enclosing function) lives in this frame's environment,
10034 /// while a *declared global* lives in the realm so that a script, a function
10035 /// declaration and their uses all see one binding. A plain `Global` — an
10036 /// undeclared name that may be satisfied by the global object — has no cell at
10037 /// all, which is how `typeof x` still works for a name that does not exist.
10038 /// The reference cell a closure-variable slot names.
10039 ///
10040 /// The environment is resolved once, when the closure is built, and this is
10041 /// just the lookup afterwards. A *declared global* is in there too, pointing at
10042 /// the realm's cell, so a script, a hoisted function declaration and their uses
10043 /// all share one binding. A plain `Global` — a name the script never declared —
10044 /// is read and written through `get_var`/`put_var` by name instead, which is
10045 /// what lets the global object satisfy it.
10046 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10047 self.frame().env.cells.get(slot).cloned()
10048 }
10049
10050 /// Whether `slot` refers to a global binding through the reference table.
10051 ///
10052 /// A global's cell in the closure environment only exists so the slot has
10053 /// something to point at; the binding itself lives on the global object (a `var`)
10054 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10055 /// be routed, not performed on the placeholder.
10056 fn is_global_slot(&self, slot: usize) -> bool {
10057 self.frame()
10058 .code
10059 .code
10060 .closure_vars
10061 .get(slot)
10062 .is_some_and(|c| {
10063 // A module's declarations and imports are *not* globals: their cells are
10064 // the module environment's, filled by the host, so the placeholder routing
10065 // must not apply to them.
10066 matches!(
10067 c.closure_type,
10068 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10069 )
10070 })
10071 }
10072
10073 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10074 if self.is_global_slot(slot) {
10075 return self.get_global(slot);
10076 }
10077 Ok(self
10078 .var_ref_cell(slot)
10079 .map(|cell| cell.get())
10080 .unwrap_or(Value::Undefined))
10081 }
10082
10083 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10084 // A function declaration is hoisted by storing into a global reference before
10085 // the body runs, so this path is also what puts it on the global object.
10086 if self.is_global_slot(slot) {
10087 return self.put_global(slot, value);
10088 }
10089 if let Some(cell) = self.var_ref_cell(slot) {
10090 cell.set(value);
10091 }
10092 Ok(())
10093 }
10094
10095 // -- closures -----------------------------------------------------------
10096
10097 /// Build the closure for the function constant `index`.
10098 ///
10099 /// Every entry in the child's closure table names where its binding lives in
10100 /// *this* frame: a local or argument slot that was marked captured, or a cell
10101 /// this frame is itself holding. That is how a variable three functions deep
10102 /// stays one binding.
10103 fn closure(&mut self, index: usize) -> JsResult<Value> {
10104 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10105 else {
10106 return Err(Signal::Throw(
10107 self.make_error("InternalError", "fclosure of a non-function"),
10108 ));
10109 };
10110 let mut cells = Vec::with_capacity(function.closure_vars.len());
10111 for closure_var in &function.closure_vars {
10112 let cell = match closure_var.closure_type {
10113 ClosureType::Arg => {
10114 let slot = closure_var.var_idx as usize;
10115 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10116 }
10117 ClosureType::Local => {
10118 let slot = closure_var.var_idx as usize;
10119 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10120 }
10121 ClosureType::Ref | ClosureType::GlobalRef => {
10122 // A `Ref` names a cell in this frame's own closure table; a
10123 // `GlobalRef` also starts there, then resolves by name below.
10124 let slot = closure_var.var_idx as usize;
10125 if let Some(cell) = self.frame().env.cells.get(slot) {
10126 cells.push(cell.clone());
10127 continue;
10128 }
10129 -1
10130 }
10131 _ => -1,
10132 };
10133 if cell >= 0 {
10134 let cell = self.frame().cells[cell as usize].clone();
10135 cells.push(cell);
10136 continue;
10137 }
10138 // A global: the cell is created on demand and shared through the realm,
10139 // so every function sees one binding.
10140 let name = closure_var.name.clone();
10141 let cell = match self.realm.globals.get(&name) {
10142 Some(cell) => cell.clone(),
10143 None => {
10144 let cell = self.new_cell(Value::Undefined);
10145 self.realm.globals.insert(name.clone(), cell.clone());
10146 cell
10147 }
10148 };
10149 cells.push(cell);
10150 }
10151 let name = function.name.clone();
10152 // `.length` is the arity before any default or rest parameter, not the number
10153 // of slots a pattern parameter needs.
10154 let length = function.defined_args;
10155 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10156 // function and an arrow function do not. A *method* also does not, but that is not
10157 // known here — the method is marked when the `[[HomeObject]]` is attached (see
10158 // `set_home_object`), which is the moment it becomes a method.
10159 let function_kind = function.kind;
10160 let constructible =
10161 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10162 let code = Gc::new(self.heap, CompiledCode::new(*function));
10163 // A closure built inside an `eval` inherits the eval's view of the enclosing
10164 // bindings, so it can still read them once the eval has returned.
10165 let eval_scope = self
10166 .active_eval_scope
10167 .clone()
10168 .or_else(|| self.frame().env.eval_scope.clone());
10169 // A closure sees the variables a direct `eval` declared in the frame it was
10170 // created in — the ones declared before *and after* it, so the same object is
10171 // shared; only the phase bounds which of them are visible.
10172 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10173 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10174 let env = Gc::new(
10175 self.heap,
10176 ClosureEnv {
10177 cells,
10178 eval_scope,
10179 local_vars,
10180 local_phase,
10181 },
10182 );
10183 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10184 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10185 // the only thing that carries `Symbol.toStringTag`, so without it
10186 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10187 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10188 let proto = match function_kind {
10189 js_compile::bytecode::FunctionKind::AsyncGenerator => self
10190 .realm
10191 .async_generator_function_proto
10192 .clone()
10193 .or_else(|| self.realm.function_proto.clone().into()),
10194 js_compile::bytecode::FunctionKind::Generator => self
10195 .realm
10196 .generator_function_proto
10197 .clone()
10198 .or_else(|| self.realm.function_proto.clone().into()),
10199 js_compile::bytecode::FunctionKind::Async => self
10200 .realm
10201 .async_function_proto
10202 .clone()
10203 .or_else(|| self.realm.function_proto.clone().into()),
10204 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10205 };
10206 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10207 object.set_constructible(constructible);
10208 object.define(
10209 "length",
10210 Property::name_or_length(Value::Int(length as i32)),
10211 );
10212 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10213 // that checks the own-property descriptor fails if the property is missing.
10214 object.define("name", Property::name_or_length(self.string(name)));
10215 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10216 // when `[[Construct]]` is created, so a generator, an async function and an arrow
10217 // function have none of their own. Installing it unconditionally gave
10218 // `Array.fromAsync` (an async function) an own `prototype` property, which
10219 // `builtin.js` checks for absence.
10220 if constructible {
10221 self.install_function_prototype(&object);
10222 }
10223 Ok(Value::Object(object))
10224 }
10225
10226 // -- conversions used by the operators ----------------------------------
10227
10228 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10229 // `+x` is `ToNumber`, which for a string parses it and for an object runs
10230 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10231 // string, which then behaves differently in every later comparison.
10232 match value {
10233 Value::Int(_) | Value::Float(_) => Ok(value),
10234 other => Ok(Value::Float(self.to_js_number(&other)?)),
10235 }
10236 }
10237
10238 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10239 ///
10240 /// Returns the *converted* old value and the new one, because the two callers need
10241 /// different halves: `++x` yields the new value, while `x++` yields the old one and
10242 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10243 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10244 /// boolean.
10245 ///
10246 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10247 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10248 /// a bigint algorithm then ran exactly once.
10249 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10250 if let Value::BigInt(big) = &value {
10251 let one = crate::bigint::BigInt::from_i64(1);
10252 let next = if up { big.add(&one) } else { big.sub(&one) };
10253 return Ok((value, self.bigint(next)));
10254 }
10255 let old = self.numeric(value)?;
10256 let new = if up {
10257 increment(old.clone())
10258 } else {
10259 decrement(old.clone())
10260 };
10261 Ok((old, new))
10262 }
10263
10264 fn numeric(&mut self, value: Value) -> JsResult<Value> {
10265 // `ToNumber` on an object runs `ToPrimitive` first, which is how
10266 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10267 // heard at all. Reading the object's own tag instead (`other.to_number()`)
10268 // turned the whole operand into `NaN` and swallowed the exception.
10269 match value {
10270 Value::Int(_) | Value::Float(_) => Ok(value),
10271 other => Ok(Value::Float(self.to_js_number(&other)?)),
10272 }
10273 }
10274
10275 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10276 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10277 match value {
10278 Value::BigInt(big) => Ok((**big).clone()),
10279 // The reference words this the same way for every operator, so a failing
10280 // script reads identically; the operator itself adds nothing a caller can use.
10281 _ => Err(Signal::Throw(
10282 self.make_error("TypeError", "cannot convert bigint to number"),
10283 )),
10284 }
10285 }
10286
10287 /// Arithmetic where at least one operand is a `BigInt`.
10288 ///
10289 /// The two numeric types never mix, so a bigint paired with anything else is an error
10290 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10291 /// that the relational operators handle it separately.
10292 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10293 use Opcode::*;
10294 let a = self.bigint_operand(&left)?;
10295 let b = self.bigint_operand(&right)?;
10296 let result = match op {
10297 Add => a.add(&b),
10298 Sub => a.sub(&b),
10299 Mul => a.mul(&b),
10300 Div | Mod => {
10301 let Some((quotient, remainder)) = a.div_rem(&b) else {
10302 return Err(Signal::Throw(
10303 self.make_error("RangeError", "division by zero"),
10304 ));
10305 };
10306 if op == Div { quotient } else { remainder }
10307 }
10308 Pow => {
10309 let Some(value) = a.pow(&b) else {
10310 return Err(Signal::Throw(self.make_error(
10311 "RangeError",
10312 "BigInt exponent must be non-negative and not absurdly large",
10313 )));
10314 };
10315 value
10316 }
10317 And => a.bitand(&b),
10318 Or => a.bitor(&b),
10319 Xor => a.bitxor(&b),
10320 Shl | Sar => {
10321 // A shift count is a `BigInt` here, and both directions are exact; a
10322 // negative count would be the other direction, which the spec forbids.
10323 let Some(count) = b.to_i64() else {
10324 return Err(Signal::Throw(
10325 self.make_error("RangeError", "BigInt shift count is too large"),
10326 ));
10327 };
10328 if count < 0 {
10329 return Err(Signal::Throw(self.make_error(
10330 "RangeError",
10331 "BigInt shift count must be non-negative",
10332 )));
10333 }
10334 if op == Shl {
10335 a.shl(count as u64)
10336 } else {
10337 a.shr(count as u64)
10338 }
10339 }
10340 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10341 _ => {
10342 return Err(Signal::Throw(self.make_error(
10343 "TypeError",
10344 "BigInts have no unsigned right shift, use >> instead",
10345 )));
10346 }
10347 };
10348 Ok(self.bigint(result))
10349 }
10350
10351 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
10352 ///
10353 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
10354 /// is on the mathematical values, and nothing is rounded first.
10355 /// `<`, `<=`, `>`, `>=`.
10356 ///
10357 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
10358 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
10359 /// It is a `?`-returning function for exactly that reason: an object operand can run
10360 /// script, and script can throw. The old version compared `to_number` of the raw
10361 /// values, which answered `false` for every object instead of calling `valueOf` —
10362 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
10363 /// never ran.
10364 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10365 // The hot arm first: `i < n` with both sides already integers. No conversion, no
10366 // call, nothing that can throw.
10367 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10368 let ordering = Some(left.cmp(right));
10369 return Ok(ordering_answer(op, ordering));
10370 }
10371 // Anything that can run script has to be converted first, in this order.
10372 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
10373 {
10374 (
10375 self.to_primitive(left, Hint::Number)?,
10376 self.to_primitive(right, Hint::Number)?,
10377 )
10378 } else {
10379 (left, right)
10380 };
10381 let ordering = match (&left, &right) {
10382 // The loop condition `i < n` is integer against integer, and it runs once
10383 // per iteration of every loop in every program. Without this arm it took the
10384 // `to_number` path twice, which is a `match` plus a conversion each.
10385 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
10386 (Value::String(a), Value::String(b)) => {
10387 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
10388 }
10389 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
10390 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
10391 // is true even though `2.5` has no bigint form.
10392 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
10393 let b = other.to_number();
10394 if b.is_nan() {
10395 None
10396 } else {
10397 compare_bigint_and_f64(a, b)
10398 }
10399 }
10400 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
10401 let a = other.to_number();
10402 if a.is_nan() {
10403 None
10404 } else {
10405 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
10406 }
10407 }
10408 _ => left.to_number().partial_cmp(&right.to_number()),
10409 };
10410 Ok(ordering_answer(op, ordering))
10411 }
10412
10413 fn binary_add(&mut self) -> JsResult<()> {
10414 let right = self.pop();
10415 let left = self.pop();
10416 // Two integers add without any of the machinery below: no `ToPrimitive` (an
10417 // `Int` is already primitive), no string check, no bigint check, no allocation.
10418 // `x += 1` in a loop is the single most common instruction sequence in real
10419 // script, and it used to walk every one of those checks before reaching the
10420 // same `checked_add`.
10421 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10422 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
10423 return Ok(());
10424 }
10425 let left = self.primitive_of(left)?;
10426 let right = self.primitive_of(right)?;
10427 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
10428 // that check comes before the bigint one: `"" + 1n` is a string, not a
10429 // mixed-type error.
10430 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
10431 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
10432 // `TypeError`, the one place a symbol and a string do not mix.
10433 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
10434 // between a copy and a rope from their lengths, and a rope is what turns
10435 // `text += "abc"` in a loop from quadratic into linear.
10436 if let (Value::String(left), Value::String(right)) = (&left, &right) {
10437 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
10438 // reports as `InternalError: string too long`.
10439 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
10440 return Err(Signal::Throw(
10441 self.make_error("InternalError", "string too long"),
10442 ));
10443 };
10444 self.push(Value::String(Gc::new(self.heap, joined)));
10445 return Ok(());
10446 }
10447 // At least one operand was not a string, so `ToString` it. This rejects a
10448 // symbol, which is the one place a symbol and a string do not mix.
10449 let left = self.checked_to_wtf8(&left)?;
10450 let right = self.checked_to_wtf8(&right)?;
10451 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
10452 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
10453 let text = left.concat(&right);
10454 self.push(self.string_wtf8(text));
10455 return Ok(());
10456 }
10457 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
10458 // not a conversion.
10459 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
10460 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
10461 self.push(value);
10462 return Ok(());
10463 }
10464 let left = self.numeric(left)?;
10465 let right = self.numeric(right)?;
10466 self.push(add_numbers(left, right));
10467 Ok(())
10468 }
10469
10470 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
10471 self.to_primitive(value, Hint::Default)
10472 }
10473
10474 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
10475 ///
10476 /// The order depends on the hint: the "number" order tries `valueOf` first and
10477 /// `toString` second, the "string" order the other way round, and the default
10478 /// hint uses the number order. A result that is still an object is a `TypeError`,
10479 /// because no built-in `valueOf`/`toString` returns one.
10480 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
10481 let Value::Object(object) = &value else {
10482 return Ok(value);
10483 };
10484 // A Date overrides the default hint to mean "string", which is what
10485 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
10486 // this, `"" + new Date()` would print the milliseconds, not the date.
10487 let hint = if hint == Hint::Default && is_date_object(self, object) {
10488 Hint::String
10489 } else {
10490 hint
10491 };
10492 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
10493 // handed the hint as a string. This is the hook a Date uses for its default hint
10494 // and a script uses to take over conversion entirely.
10495 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
10496 if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
10497 if !function.is_callable() {
10498 return Err(self.type_error("Symbol.toPrimitive is not a function"));
10499 }
10500 let hint = match hint {
10501 Hint::String => "string",
10502 Hint::Number => "number",
10503 Hint::Default => "default",
10504 };
10505 let hint = self.string(hint);
10506 let result = self.call_value(
10507 Value::Object(function),
10508 Value::Object(object.clone()),
10509 vec![hint],
10510 )?;
10511 if matches!(result, Value::Object(_)) {
10512 return Err(self.type_error("cannot convert object to primitive value"));
10513 }
10514 return Ok(result);
10515 }
10516 let order: [&str; 2] = match hint {
10517 Hint::String => ["toString", "valueOf"],
10518 Hint::Number | Hint::Default => ["valueOf", "toString"],
10519 };
10520 let receiver = object.clone();
10521 for method in order {
10522 if let Some(function) = self.get_property(&receiver, method)?
10523 && matches!(&function, Value::Object(object) if object.is_callable())
10524 {
10525 let result =
10526 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
10527 if !matches!(result, Value::Object(_)) {
10528 return Ok(result);
10529 }
10530 }
10531 }
10532 Err(self.type_error("cannot convert object to primitive value"))
10533 }
10534
10535 /// `ToString` with the object case going through `ToPrimitive`.
10536 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
10537 if matches!(value, Value::Object(_)) {
10538 let primitive = self.to_primitive(value.clone(), Hint::String)?;
10539 return Ok(primitive.to_js_string());
10540 }
10541 Ok(value.to_js_string())
10542 }
10543
10544 /// `ToString` that keeps the string's code units instead of flattening them.
10545 ///
10546 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
10547 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
10548 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10549 if matches!(value, Value::Symbol(_)) {
10550 return Err(Signal::Throw(
10551 self.make_error("TypeError", "cannot convert symbol to string"),
10552 ));
10553 }
10554 // An object runs `ToPrimitive` first, which may itself produce a symbol.
10555 let value = self.to_primitive(value.clone(), Hint::String)?;
10556 match value {
10557 Value::Symbol(_) => Err(Signal::Throw(
10558 self.make_error("TypeError", "cannot convert symbol to string"),
10559 )),
10560 Value::String(text) => Ok(text.wtf8().clone()),
10561 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
10562 }
10563 }
10564
10565 /// `ToNumber` with the object case going through `ToPrimitive`.
10566 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
10567 let value = if matches!(value, Value::Object(_)) {
10568 self.to_primitive(value.clone(), Hint::Number)?
10569 } else {
10570 value.clone()
10571 };
10572 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
10573 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
10574 // `NaN` to stay total, and the operators check for the bigint themselves — but
10575 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
10576 // refuse, and answering `NaN` made them silently wrong instead.
10577 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
10578 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
10579 match value {
10580 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
10581 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
10582 other => Ok(other.to_number()),
10583 }
10584 }
10585
10586 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
10587 /// [`ElementType::write`].
10588 ///
10589 /// This is separated from the write because both conversions are observable script —
10590 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
10591 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
10592 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
10593 /// setters, and a plain `a[i] = v`.
10594 pub(crate) fn element_value(
10595 &mut self,
10596 element: crate::builtins::typedarray::ElementType,
10597 value: Value,
10598 ) -> JsResult<Value> {
10599 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
10600 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
10601 let primitive = match &value {
10602 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
10603 _ => value,
10604 };
10605 if element.is_bigint() {
10606 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
10607 Ok(Value::BigInt(Gc::new(self.heap, big)))
10608 } else {
10609 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
10610 Ok(Value::Float(self.to_js_number(&primitive)?))
10611 }
10612 }
10613
10614 /// `ToPropertyKey`: what a computed member access uses as its key.
10615 ///
10616 /// A symbol is returned as itself, never stringified — that is what keeps
10617 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
10618 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
10619 match value {
10620 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
10621 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
10622 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
10623 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
10624 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10625 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
10626 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
10627 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
10628 other.to_js_string(),
10629 ))),
10630 },
10631 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
10632 }
10633 }
10634
10635 /// `ToPropertyKey` for the callers that can only use a string key.
10636 ///
10637 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
10638 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
10639 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
10640 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
10641 /// program continues with a value nobody asked for.
10642 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10643 use crate::value::Wtf8;
10644 Ok(match value {
10645 // A string key keeps its code units. Going through a lossy `String` would make
10646 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
10647 Value::String(text) => text.wtf8().clone(),
10648 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
10649 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
10650 // falling back to its `ToString` would print `[object Object]`.
10651 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10652 Value::String(text) => text.wtf8().clone(),
10653 other => Wtf8::new(other.to_js_string()),
10654 },
10655 other => Wtf8::new(other.to_js_string()),
10656 })
10657 }
10658
10659 // -- object operations used by instructions -----------------------------
10660
10661 /// Read `object[key]`, returning `undefined` when the property is missing.
10662 ///
10663 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
10664 /// primitive (looking through its prototype) as well as an object — which is what
10665 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
10666 /// argument needs too.
10667 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
10668 self.read_field_key(object, &PropertyKey::from(key))
10669 }
10670
10671 /// [`Interp::read_field`] with a key that may be a symbol.
10672 ///
10673 /// A symbol key never reaches the string shortcuts: a string's `length` and its
10674 /// indices are string properties, and a symbol named `length` is a different
10675 /// property that a string primitive cannot have.
10676 /// [`Interp::read_field_key`], with an inline cache in front of it.
10677 ///
10678 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
10679 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
10680 /// without this the engine walked the chain and compared ~40 property names on each
10681 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
10682 ///
10683 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
10684 /// missing property. Those answers depend on running code or on state the guard below
10685 /// does not cover, and a wrong answer here is far more expensive than a lookup.
10686 ///
10687 /// A hit is re-validated against the *whole* walked chain, not just the level that
10688 /// answered: the receiver and every prototype down to that level must still be the same
10689 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
10690 /// property-table *lengths* — which is what catches a property appearing on an
10691 /// intermediate prototype and shadowing the cached one.
10692 pub fn read_field_cached(
10693 &mut self,
10694 object: &Value,
10695 key: &PropertyKey,
10696 slot: usize,
10697 ) -> JsResult<Value> {
10698 let index = Self::field_cache_slot(object, key, slot);
10699 let Value::Object(target) = object else {
10700 return self.read_field_key(object, key);
10701 };
10702 if target.proxy_state().is_some() {
10703 return self.read_field_key(object, key);
10704 }
10705 if let Some(cached) = &self.field_cache[index]
10706 && cached.key == *key
10707 && let Some(value) = Self::cached_hit(target, cached)
10708 {
10709 return Ok(value);
10710 }
10711 let value = self.read_field_key(object, key)?;
10712 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
10713 Ok(value)
10714 }
10715
10716 /// Whether a cache entry still describes this lookup, and if so the value.
10717 ///
10718 /// The guard is the whole point of the entry: identity plus property-table length for
10719 /// every level walked. Re-checked per level rather than once at the receiving end,
10720 /// because a shadowing property can appear anywhere along the chain.
10721 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
10722 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
10723 // starts with: a clone is a reference-count bump and a drop, and for
10724 // `property:monomorphic` every single hit takes only this arm.
10725 let (weak, len) = cached.chain[0].as_ref()?;
10726 if !target.upgrades_to(weak) {
10727 return None;
10728 }
10729 if cached.level == 0 {
10730 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
10731 return target.cached_property_at(cached.index, &cached.key, *len);
10732 }
10733 if target.props_len() != *len {
10734 return None;
10735 }
10736 let mut level = 1;
10737 let mut current = target.proto()?;
10738 loop {
10739 let (weak, len) = cached.chain[level].as_ref()?;
10740 if !current.upgrades_to(weak) || current.props_len() != *len {
10741 return None;
10742 }
10743 if level == cached.level as usize {
10744 // The level that answered: the value is only reusable while the key is
10745 // still there and still a plain data property.
10746 return current.cached_data_property(cached.index, &cached.key);
10747 }
10748 current = current.proto()?;
10749 level += 1;
10750 }
10751 }
10752
10753 /// Build a cache entry for a lookup that just went through the slow path.
10754 ///
10755 /// Records the chain only when the answer came from a plain data property at a level
10756 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
10757 /// costs the next lookup the walk it would have cost anyway.
10758 fn record_field_lookup(
10759 target: &Gc<JsObject>,
10760 key: &PropertyKey,
10761 _value: Value,
10762 ) -> Option<FieldCache> {
10763 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
10764 [None, None, None];
10765 let mut current = target.clone();
10766 for level in 0..MAX_CACHED_CHAIN {
10767 chain[level] = Some((current.downgrade(), current.props_len()));
10768 if let Some((found, _)) = current.own_property_index(key) {
10769 // `own_property_index` declines an accessor and a hole, which is exactly
10770 // the set that must not be cached.
10771 return Some(FieldCache {
10772 key: key.clone(),
10773 index: found,
10774 level: level as u8,
10775 chain,
10776 });
10777 }
10778 current = current.proto()?;
10779 }
10780 None
10781 }
10782
10783 /// Which cache slot a lookup uses.
10784 ///
10785 /// Mixes the object's address, the name and the site, so that two properties of one
10786 /// object, and one property of two objects, land in different slots — which is what lets
10787 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
10788 /// other iteration.
10789 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
10790 let mut hash = match object {
10791 Value::Object(object) => object.address(),
10792 _ => 0,
10793 };
10794 hash = hash
10795 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
10796 .rotate_left(17)
10797 .wrapping_add(key.hash_code());
10798 hash = hash.wrapping_add(site.wrapping_mul(31));
10799 // The table is a power of two, so the low bits are the slot.
10800 hash & (FIELD_CACHE_SLOTS - 1)
10801 }
10802
10803 /// Read `key` from `object`, without the inline cache.
10804 ///
10805 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
10806 /// prototype chain, while the cached form answers an own data property from memory.
10807 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
10808 let text = key.as_str().unwrap_or("");
10809 let Value::Object(object) = object else {
10810 // Reading a property of `undefined`/`null` is the classic TypeError.
10811 if object.is_nullish() {
10812 return Err(Signal::Throw(self.make_error(
10813 "TypeError",
10814 &format!("cannot read property '{key}' of {}", object.to_js_string()),
10815 )));
10816 }
10817 // A string has `length` and index access without being boxed.
10818 if let Value::String(value) = object {
10819 if text == "length" {
10820 return Ok(Value::Int(value.utf16_len() as i32));
10821 }
10822 if let Some(index) = array_index(text) {
10823 return Ok(match value.wtf8().unit_at(index as usize) {
10824 Some(unit) => self.string_wtf8(unit),
10825 None => Value::Undefined,
10826 });
10827 }
10828 }
10829 // A property of a primitive is looked up on its prototype: this is what
10830 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
10831 let prototype = match object {
10832 Value::String(_) => self.realm.string_proto.clone(),
10833 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
10834 Value::Bool(_) => self.realm.boolean_proto.clone(),
10835 // A symbol's methods live on `Symbol.prototype`, reached the same way —
10836 // `sym.description` reads through the prototype, not off the symbol.
10837 Value::Symbol(_) => self.realm.symbol_proto.clone(),
10838 // …and a bigint's on `BigInt.prototype`, which is how
10839 // `(255n).toString(16)` reaches its method.
10840 Value::BigInt(_) => self.realm.bigint_proto.clone(),
10841 _ => None,
10842 };
10843 if let Some(prototype) = prototype
10844 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
10845 {
10846 return Ok(value);
10847 }
10848 return Ok(Value::Undefined);
10849 };
10850 Ok(self
10851 .get_property_key(object, key)?
10852 .unwrap_or(Value::Undefined))
10853 }
10854
10855 /// The `#name` a private symbol stands for, for error messages.
10856 ///
10857 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
10858 /// was made from.
10859 fn private_name(symbol: &Value) -> Option<String> {
10860 match symbol {
10861 Value::Symbol(symbol) if symbol.is_private() => Some(
10862 symbol
10863 .description()
10864 .map(|text| text.to_string())
10865 .unwrap_or_default(),
10866 ),
10867 _ => None,
10868 }
10869 }
10870
10871 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
10872 ///
10873 /// Every private-field opcode takes the symbol the class stored in its own scope; a
10874 /// non-symbol here would be a compiler bug, and the reference guards it with
10875 /// `JS_ThrowTypeErrorNotASymbol`.
10876 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
10877 match symbol {
10878 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
10879 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
10880 }
10881 }
10882
10883 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
10884 ///
10885 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
10886 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
10887 /// would hit if the parser did not reject it first.
10888 fn define_private_field(
10889 &mut self,
10890 object: &Value,
10891 symbol: &Value,
10892 value: Value,
10893 ) -> JsResult<()> {
10894 let key = self.private_key(symbol)?;
10895 let Some(target) = object.as_object() else {
10896 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10897 };
10898 if !target.is_extensible() {
10899 return Err(Signal::Throw(
10900 self.make_error("TypeError", "object is not extensible"),
10901 ));
10902 }
10903 if target.own_property_key(&key).is_some() {
10904 let name = Self::private_name(symbol).unwrap_or_default();
10905 return Err(Signal::Throw(self.make_error(
10906 "TypeError",
10907 &format!("private class field '{name}' already exists"),
10908 )));
10909 }
10910 target.define_data_key(&key, value);
10911 Ok(())
10912 }
10913
10914 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
10915 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
10916 let key = self.private_key(symbol)?;
10917 let Some(target) = object.as_object() else {
10918 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10919 };
10920 match target.own_property_key(&key) {
10921 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
10922 None => {
10923 let name = Self::private_name(symbol).unwrap_or_default();
10924 Err(Signal::Throw(self.make_error(
10925 "TypeError",
10926 &format!("private class field '{name}' does not exist"),
10927 )))
10928 }
10929 }
10930 }
10931
10932 /// `JS_SetPrivateField`: the store half of the same rule.
10933 fn write_private_field(
10934 &mut self,
10935 object: &Value,
10936 symbol: &Value,
10937 value: Value,
10938 ) -> JsResult<()> {
10939 let key = self.private_key(symbol)?;
10940 let Some(target) = object.as_object() else {
10941 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10942 };
10943 if target.write_value_key(&key, value) {
10944 return Ok(());
10945 }
10946 let name = Self::private_name(symbol).unwrap_or_default();
10947 Err(Signal::Throw(self.make_error(
10948 "TypeError",
10949 &format!("private class field '{name}' does not exist"),
10950 )))
10951 }
10952
10953 /// The `in` half: does `object` have this private field?
10954 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
10955 ///
10956 /// The symbol is created once per class — the first `add_brand` on a given home object
10957 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
10958 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
10959 /// emit for the *instance* brand passes null because all it wants is the symbol.
10960 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
10961 let Some(home_object) = home.as_object() else {
10962 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10963 };
10964 let symbol = match home_object.private_brand() {
10965 Some(symbol) => symbol,
10966 None => {
10967 let symbol = Gc::new(
10968 self.heap,
10969 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
10970 );
10971 home_object.set_private_brand(symbol.clone());
10972 symbol
10973 }
10974 };
10975 let Some(target) = object.as_object() else {
10976 // Not an object: nothing to brand. The reference does the same, and `undefined`
10977 // here would otherwise turn a field initialiser into a TypeError.
10978 return Ok(());
10979 };
10980 if !target.is_extensible() {
10981 return Err(Signal::Throw(
10982 self.make_error("TypeError", "object is not extensible"),
10983 ));
10984 }
10985 if target.carries_brand(&symbol) {
10986 return Err(Signal::Throw(
10987 self.make_error("TypeError", "private method is already present"),
10988 ));
10989 }
10990 target.add_brand(symbol);
10991 Ok(())
10992 }
10993
10994 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
10995 ///
10996 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
10997 /// decides whether to throw.
10998 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
10999 let Some(function) = function.as_object() else {
11000 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11001 };
11002 let Some(home) = function.home_object() else {
11003 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11004 };
11005 let Some(brand) = home.private_brand() else {
11006 return Err(Signal::Throw(
11007 self.make_error("TypeError", "expecting <brand> private field"),
11008 ));
11009 };
11010 Ok(object.carries_brand(&brand))
11011 }
11012
11013 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11014 let Value::Object(object) = object else {
11015 return Err(Signal::Throw(self.make_error(
11016 "TypeError",
11017 &format!("cannot set property '{key}' of {}", object.to_js_string()),
11018 )));
11019 };
11020 // The write half of the property inline cache, in effect: an own, writable,
11021 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11022 // decide — no prototype walk (an own property shadows the chain before a setter
11023 // there could matter), no extensibility check (the object already has the key),
11024 // and no `[[DefineOwnProperty]]`.
11025 //
11026 // `this.value = …` inside a method is the whole write side of
11027 // `property:method-call`, and it was reaching `set_property_with_key` with its
11028 // proxy test, its typed-array test, its array-index test and finally a linear
11029 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11030 //
11031 // Every disqualifier is checked here: a proxy traps the set, an array index and
11032 // `length` live outside the property table, and a typed array's element is stored
11033 // through its view's element type.
11034 if object.proxy_state().is_none()
11035 && !object.is_array()
11036 && object.typed_array_element_type().is_none()
11037 && object.write_value_key(key, value.clone())
11038 {
11039 return Ok(());
11040 }
11041 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11042 let on_failure = if self.frame().code.code.strict {
11043 DeleteFailure::Throw
11044 } else {
11045 DeleteFailure::Ignore
11046 };
11047 self.set_property_with_key(object, key, value, on_failure)
11048 }
11049
11050 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11051 ///
11052 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11053 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11054 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11055 /// `Number.parseInt(sym)` — so those callers use this instead.
11056 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11057 if matches!(value, Value::Symbol(_)) {
11058 return Err(Signal::Throw(
11059 self.make_error("TypeError", "cannot convert symbol to string"),
11060 ));
11061 }
11062 // An object runs `ToPrimitive` first, which may itself produce a symbol —
11063 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11064 let value = self.to_primitive(value.clone(), Hint::String)?;
11065 if matches!(value, Value::Symbol(_)) {
11066 return Err(Signal::Throw(
11067 self.make_error("TypeError", "cannot convert symbol to string"),
11068 ));
11069 }
11070 Ok(value.to_js_string())
11071 }
11072
11073 /// `ToPropertyKey` for a builtin that takes a key argument.
11074 ///
11075 /// Fallible: a key whose `toString` throws has to propagate that error, both for
11076 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11077 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11078 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11079 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11080 self.propkey(value)
11081 }
11082
11083 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11084 ///
11085 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11086 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11087 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11088 /// `RangeError` — and why this cannot be a plain `ToNumber`.
11089 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11090 let number = match value {
11091 Value::Int(number) => *number as f64,
11092 Value::Float(number) => *number,
11093 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11094 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11095 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11096 // reference answers 0.
11097 Value::Null | Value::Bool(_) => value.to_number(),
11098 _ => {
11099 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11100 match primitive {
11101 Value::Int(number) => number as f64,
11102 Value::Float(number) => number,
11103 other => {
11104 // `ToString` then `ToNumber`, so a string length goes through the
11105 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
11106 // `Value::to_number` on the string already implements exactly that.
11107 let text = self.to_js_string(&other)?;
11108 crate::value::string_to_number(&text)
11109 }
11110 }
11111 }
11112 };
11113 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11114 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11115 // is a `RangeError`, not `0`.
11116 if !number.is_finite()
11117 || number.fract() != 0.0
11118 || !(0.0..=u32::MAX as f64).contains(&number)
11119 {
11120 return Err(self.range_error("invalid array length"));
11121 }
11122 Ok(number as u32)
11123 }
11124
11125 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11126 /// `Object.getOwnPropertySymbols` put in their result array.
11127 pub fn key_value(&self, key: &PropertyKey) -> Value {
11128 match key {
11129 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11130 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11131 }
11132 }
11133
11134 /// Fill in a String exotic object: `_value`, `length` and the index properties.
11135 ///
11136 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11137 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11138 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11139 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11140 /// the two paths had drifted; this is the one both now use.
11141 ///
11142 /// The indices are *code units*, so an astral character occupies two of them — the
11143 /// same rule `s.length` and `s[i]` follow.
11144 /// Give an already-created object the internal slot that makes it a wrapper of
11145 /// `value`, so the primitive's prototype methods work on it.
11146 ///
11147 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11148 /// which are wrappers of their own type holding the empty value.
11149 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11150 self.internal_set(object, "_value", value);
11151 }
11152
11153 pub(crate) fn init_string_wrapper(
11154 &mut self,
11155 object: &Gc<JsObject>,
11156 text: &Gc<crate::value::JsString>,
11157 ) {
11158 object.define(
11159 "length",
11160 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11161 );
11162 for index in 0..text.utf16_len() {
11163 if let Some(unit) = text.wtf8().unit_at(index) {
11164 object.define(
11165 &index.to_string(),
11166 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11167 Property::with_attributes(self.string_wtf8(unit), false, true),
11168 );
11169 }
11170 }
11171 object.define_key(
11172 &self.internal_slot("_value"),
11173 Property::with_attributes(Value::String(text.clone()), false, false),
11174 );
11175 }
11176
11177 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11178 ///
11179 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11180 /// throws. The wrapper carries its primitive in `_value` — the same slot
11181 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11182 /// on a boxed value no constructor ever built.
11183 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11184 let (prototype, primitive) = match value {
11185 Value::Object(object) => return Ok(object.clone()),
11186 Value::String(text) => {
11187 let object = self.new_object(self.realm.string_proto.clone());
11188 self.init_string_wrapper(&object, text);
11189 return Ok(object);
11190 }
11191 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11192 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11193 // A symbol and a bigint box into wrappers whose methods live on
11194 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11195 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11196 // branch below instead produced an object with *no* prototype, so those
11197 // methods were unreachable on a box.
11198 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11199 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11200 Value::Undefined | Value::Null => {
11201 return Err(Signal::Throw(self.make_error(
11202 "TypeError",
11203 &format!("cannot convert {} to object", value.to_js_string()),
11204 )));
11205 }
11206 _ => (None, value.clone()),
11207 };
11208 let object = self.new_object(prototype);
11209 self.internal_set(&object, "_value", primitive);
11210 Ok(object)
11211 }
11212
11213 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11214 ///
11215 /// Split out for a reader that has to create the object *before* it knows what it wraps:
11216 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11217 /// written before its primitive, so the placeholder has to exist first and be filled in
11218 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11219 /// than a second in the deserialiser.
11220 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11221 let prototype = match value {
11222 Value::String(_) => self.realm.string_proto.clone(),
11223 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11224 Value::Bool(_) => self.realm.boolean_proto.clone(),
11225 Value::Symbol(_) => self.realm.symbol_proto.clone(),
11226 Value::BigInt(_) => self.realm.bigint_proto.clone(),
11227 _ => {
11228 return Err(Signal::Throw(self.make_error(
11229 "TypeError",
11230 &format!("cannot box {}", value.to_js_string()),
11231 )));
11232 }
11233 };
11234 object.set_proto(prototype);
11235 if let Value::String(text) = value {
11236 self.init_string_wrapper(object, text);
11237 return Ok(());
11238 }
11239 self.internal_set(object, "_value", value.clone());
11240 Ok(())
11241 }
11242
11243 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11244 ///
11245 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11246 /// through the `Symbol` function object, so the registry is reachable as a method rather
11247 /// than only from `builtins::symbol`.
11248 pub fn symbol_for(&mut self, key: &str) -> Value {
11249 if let Some(existing) = self.realm.symbol_registry.get(key) {
11250 return existing.clone();
11251 }
11252 let symbol = crate::builtins::symbol::symbol_value(
11253 self,
11254 crate::value::JsSymbol::registered(key.to_string()),
11255 );
11256 self.realm
11257 .symbol_registry
11258 .insert(key.to_string(), symbol.clone());
11259 symbol
11260 }
11261
11262 /// `a == b`, the coercing comparison.
11263 ///
11264 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11265 /// which is what makes `[] == ""` true: `[]` becomes `""` via
11266 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11267 /// because the conversion is allowed to call script code, so the two primitive
11268 /// operands are handed back to it.
11269 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11270 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11271 return Ok(left.loose_equals(&right));
11272 }
11273 // `null == undefined` holds even though neither is an object.
11274 if matches!(left, Value::Undefined | Value::Null)
11275 && matches!(right, Value::Undefined | Value::Null)
11276 {
11277 return Ok(true);
11278 }
11279 if matches!(left, Value::Undefined | Value::Null)
11280 || matches!(right, Value::Undefined | Value::Null)
11281 {
11282 return Ok(false);
11283 }
11284 // Two objects compare by identity. Only an object *against a primitive* is
11285 // converted, which is why `{} == {}` is false while `[] == ""` is true.
11286 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11287 return Ok(a.ptr_eq(b));
11288 }
11289 let left = self.to_primitive(left, Hint::Default)?;
11290 let right = self.to_primitive(right, Hint::Default)?;
11291 Ok(left.loose_equals(&right))
11292 }
11293
11294 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11295 let Value::Object(object) = object else {
11296 return Err(Signal::Throw(
11297 self.make_error("TypeError", "cannot use 'in' on a non-object"),
11298 ));
11299 };
11300 let key = self.propkey(key)?;
11301 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11302 // trap. One implementation, so an array's derived `length` and its inherited holes
11303 // cannot be right in one caller and wrong in another.
11304 self.has_own_or_inherited(object, &key)
11305 }
11306
11307 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11308 ///
11309 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11310 /// whole reason the operator is a hook rather than a prototype walk.
11311 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11312 if let Value::Object(function) = constructor {
11313 let key = self.realm.well_known_key(WellKnown::HasInstance);
11314 let method = self.get_property_key(function, &key)?;
11315 if let Some(method) = method
11316 && !matches!(method, Value::Undefined)
11317 {
11318 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11319 return Ok(answer.to_boolean());
11320 }
11321 }
11322 self.instance_of(object, constructor)
11323 }
11324
11325 /// `OrdinaryHasInstance`: the prototype walk on its own.
11326 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11327 self.instance_of(object, constructor)
11328 }
11329
11330 /// `IsArray`: an array, or a proxy whose target is one.
11331 ///
11332 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11333 /// makes `Array.isArray(new Proxy([], {}))` true.
11334 pub fn is_array_value(&self, value: &Value) -> bool {
11335 match value {
11336 Value::Object(object) => {
11337 if let Some(state) = object.proxy_state() {
11338 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11339 }
11340 object.is_array()
11341 }
11342 _ => false,
11343 }
11344 }
11345
11346 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
11347 ///
11348 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
11349 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
11350 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
11351 /// see [`Interp::enqueue_job_function`].
11352 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
11353 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
11354 // the handler is reported rather than lost — the same reason a `then` reaction needs a
11355 // promise to settle.
11356 let promise = self.new_promise();
11357 self.fulfill_promise(&promise, Value::Undefined);
11358 self.jobs.push_back(Job::Reaction {
11359 handler: Some(function),
11360 argument: Value::Undefined,
11361 rejected: false,
11362 promise,
11363 });
11364 Ok(())
11365 }
11366
11367 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11368 let Value::Object(target) = object else {
11369 return Ok(false);
11370 };
11371 let Value::Object(function) = constructor else {
11372 return Err(Signal::Throw(self.make_error(
11373 "TypeError",
11374 "right-hand side of 'instanceof' is not callable",
11375 )));
11376 };
11377 let prototype = self.get_property(function, "prototype")?;
11378 let Some(Value::Object(prototype)) = prototype else {
11379 return Ok(false);
11380 };
11381 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
11382 // which is also what makes `proxyOfInstance instanceof C` work.
11383 let mut current = Some(target.clone());
11384 while let Some(object) = current {
11385 if object.ptr_eq(&prototype) {
11386 return Ok(true);
11387 }
11388 current = self.object_prototype_of(&object)?;
11389 }
11390 Ok(false)
11391 }
11392
11393 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
11394 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
11395 if let Some(proto) = self.proxy_get_prototype_of(object)? {
11396 return Ok(proto);
11397 }
11398 if let Some(exotic) = object.exotic()
11399 && let Some(proto) = exotic.get_prototype(self, object)?
11400 {
11401 return Ok(proto);
11402 }
11403 Ok(object.proto())
11404 }
11405
11406 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
11407 pub fn object_set_prototype_of(
11408 &mut self,
11409 object: &Gc<JsObject>,
11410 proto: Option<Gc<JsObject>>,
11411 ) -> JsResult<bool> {
11412 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
11413 return Ok(answer);
11414 }
11415 if let Some(exotic) = object.exotic()
11416 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
11417 {
11418 return Ok(answer);
11419 }
11420 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
11421 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
11422 // inheriting from itself, which every later prototype walk then had to defend
11423 // against — and `Reflect.setPrototypeOf` reported success for an operation the
11424 // language says is impossible.
11425 if let Some(proto) = &proto {
11426 let mut current = Some(proto.clone());
11427 let mut guard = 0;
11428 while let Some(node) = current {
11429 if node.ptr_eq(object) {
11430 return Err(Signal::Throw(
11431 self.make_error("TypeError", "circular prototype chain"),
11432 ));
11433 }
11434 guard += 1;
11435 if guard > 1000 {
11436 break;
11437 }
11438 current = node.proto();
11439 }
11440 }
11441 object.set_proto(proto);
11442 Ok(true)
11443 }
11444
11445 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
11446 ///
11447 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
11448 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
11449 /// already one.
11450 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
11451 let mut current = Some(object.clone());
11452 // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
11453 let mut guard = 0;
11454 while let Some(node) = current {
11455 guard += 1;
11456 if guard > 1000 {
11457 return Ok(false);
11458 }
11459 let own = self.object_get_own_property(&node, key)?;
11460 if own.is_some() {
11461 return Ok(true);
11462 }
11463 current = self.object_prototype_of(&node)?;
11464 }
11465 Ok(false)
11466 }
11467
11468 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
11469 ///
11470 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
11471 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
11472 /// boolean as well, and it needs the receiver to be the one the caller named.
11473 pub fn set_property_with_key_receiver(
11474 &mut self,
11475 object: &Gc<JsObject>,
11476 key: &PropertyKey,
11477 value: Value,
11478 receiver: Option<&Value>,
11479 on_failure: DeleteFailure,
11480 ) -> JsResult<bool> {
11481 let receiver = receiver
11482 .cloned()
11483 .unwrap_or_else(|| Value::Object(object.clone()));
11484 if object.proxy_state().is_some() {
11485 return match self.proxy_set(object, key, value, &receiver)? {
11486 Some(accepted) => Ok(accepted),
11487 None => Ok(true),
11488 };
11489 }
11490 // An own accessor, or one found up the chain, receives the call with `receiver` as
11491 // `this` — which is the whole reason this variant exists.
11492 if let Some(setter) = self.lookup_setter(object, key)? {
11493 self.call_value(setter, receiver, vec![value])?;
11494 return Ok(true);
11495 }
11496 // Otherwise it is an ordinary create-or-write, which the plain path already does.
11497 self.set_property_with_key(object, key, value, on_failure)?;
11498 Ok(true)
11499 }
11500
11501 /// The setter `key` resolves to, if it resolves to an accessor.
11502 fn lookup_setter(
11503 &mut self,
11504 object: &Gc<JsObject>,
11505 key: &PropertyKey,
11506 ) -> JsResult<Option<Value>> {
11507 let mut current = Some(object.clone());
11508 let mut guard = 0;
11509 while let Some(node) = current {
11510 guard += 1;
11511 if guard > 1000 {
11512 return Ok(None);
11513 }
11514 if let Some(property) = self.object_get_own_property(&node, key)? {
11515 if property.is_accessor() {
11516 return Ok(property.setter);
11517 }
11518 // A data property stops the walk: the store writes here, not further up.
11519 return Ok(None);
11520 }
11521 current = self.object_prototype_of(&node)?;
11522 }
11523 Ok(None)
11524 }
11525
11526 /// `[[IsExtensible]]`, with the proxy trap when there is one.
11527 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11528 if let Some(answer) = self.proxy_is_extensible(object)? {
11529 return Ok(answer);
11530 }
11531 if let Some(exotic) = object.exotic()
11532 && let Some(answer) = exotic.is_extensible(self, object)?
11533 {
11534 return Ok(answer);
11535 }
11536 Ok(object.is_extensible())
11537 }
11538
11539 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
11540 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11541 if let Some(answer) = self.proxy_prevent_extensions(object)? {
11542 return Ok(answer);
11543 }
11544 if let Some(exotic) = object.exotic()
11545 && let Some(answer) = exotic.prevent_extensions(self, object)?
11546 {
11547 return Ok(answer);
11548 }
11549 object.set_extensible(false);
11550 Ok(true)
11551 }
11552
11553 fn copy_properties(
11554 &mut self,
11555 target: &Value,
11556 source: &Value,
11557 exclusion: &Value,
11558 ) -> JsResult<()> {
11559 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
11560 // does contribute: its index properties are own, enumerable and writable, which
11561 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
11562 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
11563 // is a no-op.
11564 let Some(target) = target.as_object() else {
11565 return Ok(());
11566 };
11567 let source_object = match source {
11568 Value::Object(object) => object.clone(),
11569 Value::String(text) => {
11570 // Untaken keys are the string's indices, which are code units.
11571 for index in 0..text.utf16_len() {
11572 if let Some(unit) = text.wtf8().unit_at(index) {
11573 target.define_data(&index.to_string(), self.string_wtf8(unit));
11574 }
11575 }
11576 return Ok(());
11577 }
11578 _ => return Ok(()),
11579 };
11580 // An object *rest* element passes the keys already taken by the literal part as
11581 // an array of strings; a spread passes `null`, which excludes nothing. Only the
11582 // string keys of the exclusion array are meaningful, so an array is read by its
11583 // elements rather than by its own property names.
11584 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
11585 if let Value::Object(list) = exclusion
11586 && let Some(length) = list.array_length()
11587 {
11588 for index in 0..length {
11589 if let Some(value) = list.array_get(index) {
11590 excluded.push(self.propkey_of(&value)?);
11591 }
11592 }
11593 }
11594 let source = &source_object;
11595 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
11596 // Reading the property table directly made every spread of a proxy empty.
11597 let keys = self.object_own_property_keys(source)?;
11598 for as_key in keys {
11599 if as_key.is_symbol() {
11600 // A spread copies string-keyed properties only.
11601 continue;
11602 }
11603 if excluded.contains(&crate::value::Wtf8::new(
11604 as_key.as_str().unwrap_or_default(),
11605 )) {
11606 continue;
11607 }
11608 let enumerable = self
11609 .object_get_own_property(source, &as_key)?
11610 .is_some_and(|property| property.enumerable);
11611 if !enumerable {
11612 continue;
11613 }
11614 let value = self
11615 .get_property_key(source, &as_key)?
11616 .unwrap_or(Value::Undefined);
11617 target.define_data_key(&as_key, value);
11618 }
11619 Ok(())
11620 }
11621
11622 // -- iteration ---------------------------------------------------------
11623
11624 /// One object's own keys in enumeration order: array indices ascending, then the
11625 /// rest in insertion order.
11626 ///
11627 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
11628 /// whether the key is enumerable, which the caller resolves per key because an
11629 /// array's elements are not in the same store as its named properties.
11630 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
11631 // An index can arrive twice, once from the array's element store and once from
11632 // its property map, so the numeric keys go through a map that keeps the
11633 // enumerable answer if either source gave one.
11634 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
11635 for (key, enumerable) in &own {
11636 if let Some(index) = key.as_str().and_then(array_index) {
11637 let entry = numeric.entry(index).or_insert(false);
11638 *entry = *entry || *enumerable;
11639 }
11640 }
11641 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
11642 .into_iter()
11643 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
11644 .collect();
11645 ordered.extend(
11646 own.into_iter()
11647 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
11648 );
11649 ordered
11650 }
11651
11652 /// Build the key list a `for-in` loop walks.
11653 ///
11654 /// The order is the specification's: own properties before inherited ones, and
11655 /// within one object the integer-like keys in ascending numeric order ahead of the
11656 /// string keys in insertion order. A shadowed key only appears once, and a key that
11657 /// is a non-enumerable own property anywhere nearer is skipped entirely.
11658 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11659 let record = self.new_object(None);
11660 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
11661 // A proxy supplies its own key list, and — the reason this is not just another
11662 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
11663 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
11664 // descriptor there.
11665 if let Value::Object(object) = value
11666 && object.proxy_state().is_some()
11667 {
11668 let own = self
11669 .proxy_own_keys(object)?
11670 .unwrap_or_else(|| object.own_property_keys());
11671 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
11672 let mut numeric: Vec<u32> = Vec::new();
11673 let mut rest: Vec<PropertyKey> = Vec::new();
11674 for key in own {
11675 match key.as_str().and_then(array_index) {
11676 Some(index) => numeric.push(index),
11677 None => rest.push(key),
11678 }
11679 }
11680 numeric.sort_unstable();
11681 ordered.extend(
11682 numeric
11683 .into_iter()
11684 .map(|index| PropertyKey::from(index.to_string())),
11685 );
11686 ordered.extend(rest);
11687 for (index, key) in ordered.into_iter().enumerate() {
11688 record.define_data(&index.to_string(), self.key_value(&key));
11689 }
11690 record.define_data("__index", Value::Int(0));
11691 // The mark that makes `for_in_advance` re-ask the proxy per key.
11692 record.define_data("__proxy", Value::Object(object.clone()));
11693 return Ok(record);
11694 }
11695 if let Value::Object(object) = value {
11696 let mut chain = vec![object.clone()];
11697 chain.extend(object.chain());
11698 // Every own string key the walk has seen, enumerable or not. A
11699 // non-enumerable own property still hides a same-named enumerable one
11700 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
11701 // keeps `x` out of the loop even when the prototype has one.
11702 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
11703 for object in chain {
11704 let mut own: Vec<(crate::value::Wtf8, bool)> = object
11705 .own_property_keys()
11706 .iter()
11707 .filter_map(|key| key.as_wtf8().cloned())
11708 .map(|key| {
11709 let enumerable = object
11710 .own_property(&key.to_string_lossy())
11711 .map(|property| property.enumerable)
11712 .unwrap_or(false);
11713 (key, enumerable)
11714 })
11715 .collect();
11716 if let Some(length) = object.array_length() {
11717 own.retain(|(key, _)| key.as_str() != Some("length"));
11718 for index in 0..length {
11719 if object.array_get(index).is_some() {
11720 own.push((crate::value::Wtf8::new(index.to_string()), true));
11721 }
11722 }
11723 }
11724 // Integer-like keys come first in ascending order, then the rest in
11725 // insertion order — and the ordering is *per object*, not for the chain
11726 // as a whole: one pass over every collected key lifted a prototype's
11727 // `"4"` above the target's own `x`/`y`, which is not the order
11728 // `for…in` reports.
11729 for (key, enumerable) in Self::order_own_keys(own) {
11730 if visited.contains(&key) {
11731 continue;
11732 }
11733 visited.push(key.clone());
11734 if enumerable {
11735 keys.push(key);
11736 }
11737 }
11738 }
11739 }
11740 for (index, key) in keys.into_iter().enumerate() {
11741 record.define_data(&index.to_string(), self.string_wtf8(key));
11742 }
11743 record.define_data("__index", Value::Int(0));
11744 Ok(record)
11745 }
11746
11747 /// The next key of a `for…in` record, `None` when the loop is done.
11748 ///
11749 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
11750 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
11751 /// the loop reaches it, so a handler that stops reporting a key partway through drops
11752 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
11753 /// key the handler had already withdrawn.
11754 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
11755 let Value::Object(record) = record else {
11756 return Ok(None);
11757 };
11758 let proxy = record
11759 .own_property("__proxy")
11760 .and_then(|property| property.value);
11761 loop {
11762 let index = record
11763 .own_property("__index")
11764 .and_then(|property| property.value)
11765 .map(|value| value.to_int32())
11766 .unwrap_or(0);
11767 let Some(candidate) = record
11768 .own_property(&index.to_string())
11769 .and_then(|property| property.value)
11770 else {
11771 return Ok(None);
11772 };
11773 record.define_data("__index", Value::Int(index + 1));
11774 let text = candidate.to_js_string();
11775 let Some(Value::Object(proxy)) = &proxy else {
11776 return Ok(Some(text));
11777 };
11778 // The candidate is already a key string here, so the lookup does not need a
11779 // second `ToPropertyKey` conversion.
11780 let key = PropertyKey::from(text.as_str());
11781 let live = match self.proxy_get_own_property(proxy, &key)? {
11782 Some(descriptor) => descriptor,
11783 // Not a proxy after all, or it lost its state: fall back to the target.
11784 None => proxy.own_property_key(&key),
11785 };
11786 if live.is_some_and(|property| property.enumerable) {
11787 return Ok(Some(text));
11788 }
11789 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
11790 // next one.
11791 }
11792 }
11793
11794 /// The iterator for `for-of`: the object and its `next` method.
11795 ///
11796 /// An object that already carries a `next` method is used as it is — that is what
11797 /// `arr.values()` returns — and only arrays and strings get the built-in
11798 /// sequence iterator.
11799 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
11800 ///
11801 /// Callers that must choose between the iterable and the array-like protocol — the
11802 /// typed-array constructor is the main one — need to ask *before* committing to one.
11803 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
11804 let key = self.realm.well_known_key(WellKnown::Iterator);
11805 let method = self.read_field_key(value, &key)?;
11806 if matches!(method, Value::Undefined | Value::Null) {
11807 return Ok(false);
11808 }
11809 if !matches!(&method, Value::Object(object) if object.is_callable()) {
11810 return Err(Signal::Throw(
11811 self.make_error("TypeError", "Symbol.iterator is not callable"),
11812 ));
11813 }
11814 Ok(true)
11815 }
11816
11817 /// Collect everything an iterable yields, closing it if the walk is abandoned.
11818 ///
11819 /// The cap is a guard against a generator that never ends: an unbounded collect would
11820 /// be an out-of-memory abort rather than a catchable error.
11821 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
11822 const MAX_ITEMS: usize = 1 << 24;
11823 let iterator = self.get_iterator(value)?;
11824 let mut out = Vec::new();
11825 loop {
11826 let (element, done) = self.iterator_step(&iterator)?;
11827 if done {
11828 return Ok(out);
11829 }
11830 out.push(element);
11831 if out.len() > MAX_ITEMS {
11832 return Err(self.range_error("iterable is too long to collect"));
11833 }
11834 }
11835 }
11836
11837 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
11838 ///
11839 /// A native constructor calls this once it has validated its arguments, which is the
11840 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
11841 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
11842 /// never reached. The prototype comes from `new.target` when it is an object, and from
11843 /// `default_proto` otherwise.
11844 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
11845 let Some(target) = self.pending_new_target.clone() else {
11846 return Ok(self.new_object(Some(default_proto)));
11847 };
11848 let Some(target) = target.as_object().cloned() else {
11849 return Ok(self.new_object(Some(default_proto)));
11850 };
11851 let proto = match self.get_property(&target, "prototype")? {
11852 Some(Value::Object(proto)) => proto,
11853 _ => default_proto,
11854 };
11855 Ok(self.new_object(Some(proto)))
11856 }
11857
11858 /// Whether this call is a construction, i.e. `new.target` is defined.
11859 ///
11860 /// A native constructor receives `this = undefined` (it builds its own instance), so it
11861 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
11862 /// The native function currently executing, if any.
11863 pub fn current_native(&self) -> Option<Gc<JsObject>> {
11864 self.current_native.clone()
11865 }
11866
11867 /// Whether this call is a construction, i.e. `new.target` is defined.
11868 pub fn is_constructing(&self) -> bool {
11869 self.pending_new_target.is_some()
11870 }
11871
11872 /// The `TypeError` a constructor too primitive to have a wrapper raises.
11873 ///
11874 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
11875 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
11876 /// happens inside the native function, which is why the trace carries an
11877 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
11878 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
11879 /// constructor`, and an unnamed one reports the leading space of `" is not a
11880 /// constructor"` because the reference formats the empty name as it is.
11881 ///
11882 /// It is also the answer for a `new.target` that cannot be named at all — not a
11883 /// function, or a throwing `name` getter — where the reference falls back to the bare
11884 /// `not a constructor`.
11885 pub fn not_a_constructor_error(&mut self) -> Signal {
11886 let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
11887 self.not_a_constructor_error_for(target)
11888 }
11889
11890 /// The same `TypeError` for an explicit target, for the callers that check
11891 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
11892 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
11893 let target = match target {
11894 Value::Object(target) if target.is_callable() => target,
11895 _ => return self.type_error("not a constructor"),
11896 };
11897 let name = match self.get_property(&target, "name") {
11898 Ok(Some(value)) => value.to_js_string(),
11899 _ => return self.type_error("not a constructor"),
11900 };
11901 self.type_error(format!("{name} is not a constructor"))
11902 }
11903
11904 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
11905 ///
11906 /// True whenever `new.target` is not the callee itself, or when it has no usable
11907 /// `prototype` — the cases where reading the property is observable at all.
11908 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
11909 match &self.pending_new_target {
11910 Some(Value::Object(target)) => !target.ptr_eq(callee),
11911 Some(_) => true,
11912 None => false,
11913 }
11914 }
11915
11916 /// The symbol key for one of the engine's own hidden slots.
11917 ///
11918 /// Cached on the realm, so every object of a kind shares one key and a slot can be
11919 /// read back by name.
11920 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
11921 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
11922 return PropertyKey::Symbol(symbol.clone());
11923 }
11924 let symbol = Gc::new(
11925 self.heap,
11926 crate::value::JsSymbol::new(Some(name.to_string())),
11927 );
11928 self.realm
11929 .internal_slots
11930 .borrow_mut()
11931 .insert(name, Value::Symbol(symbol.clone()));
11932 PropertyKey::Symbol(symbol)
11933 }
11934
11935 /// Read a hidden slot, or `None` when the object has none of that name.
11936 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
11937 let slots = self.realm.internal_slots.borrow();
11938 let Value::Symbol(symbol) = slots.get(name)? else {
11939 return None;
11940 };
11941 object
11942 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
11943 .and_then(|property| property.value)
11944 }
11945
11946 /// Define a hidden slot.
11947 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
11948 let key = self.internal_slot(name);
11949 object.define_key(&key, Property::with_attributes(value, false, false));
11950 }
11951
11952 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
11953 ///
11954 /// The method is looked up on the value (through its prototype), called with no
11955 /// arguments, and its result becomes the iterator. A generator gets here through
11956 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
11957 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
11958 ///
11959 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
11960 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
11961 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
11962 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
11963 /// does, and a user-defined iterable works without a special case.
11964 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
11965 /// `Symbol.iterator`.
11966 ///
11967 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
11968 /// iterable is legal there, and each value it produces is simply already settled by
11969 /// the time the `await` around it runs.
11970 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
11971 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
11972 let method = self.read_field_key(value, &async_key)?;
11973 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
11974 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
11975 // is *present but not callable* is a TypeError — it does not mean "try the other
11976 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
11977 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
11978 // guard is there to catch.
11979 let absent = matches!(method, Value::Undefined | Value::Null);
11980 if !absent {
11981 let Value::Object(object) = &method else {
11982 return Err(Signal::Throw(
11983 self.make_error("TypeError", "value is not iterable"),
11984 ));
11985 };
11986 if !object.is_callable() {
11987 return Err(Signal::Throw(
11988 self.make_error("TypeError", "value is not iterable"),
11989 ));
11990 }
11991 }
11992 if absent {
11993 return self.get_iterator(value);
11994 }
11995 let iterator = self.call_value(method, value.clone(), Vec::new())?;
11996 if !matches!(iterator, Value::Object(_)) {
11997 return Err(Signal::Throw(
11998 self.make_error("TypeError", "iterator is not an object"),
11999 ));
12000 }
12001 let next = self.read_field(&iterator, "next")?;
12002 Ok(Iterator {
12003 object: iterator,
12004 next,
12005 })
12006 }
12007
12008 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12009 let key = self.realm.well_known_key(WellKnown::Iterator);
12010 let method = self.read_field_key(value, &key)?;
12011 let Value::Object(function) = &method else {
12012 return Err(Signal::Throw(self.make_error(
12013 "TypeError",
12014 &format!("{} is not iterable", value.to_js_string()),
12015 )));
12016 };
12017 if !function.is_callable() {
12018 return Err(Signal::Throw(self.make_error(
12019 "TypeError",
12020 &format!("{} is not iterable", value.to_js_string()),
12021 )));
12022 }
12023 let iterator = self.call_value(method, value.clone(), Vec::new())?;
12024 // The spec requires an object here; a primitive iterator has no `next` to call
12025 // and would fail one step later with a confusing message.
12026 if !matches!(iterator, Value::Object(_)) {
12027 return Err(Signal::Throw(
12028 self.make_error("TypeError", "iterator is not an object"),
12029 ));
12030 }
12031 let next = self.read_field(&iterator, "next")?;
12032 Ok(Iterator {
12033 object: iterator,
12034 next,
12035 })
12036 }
12037
12038 /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
12039 /// not iterable.
12040 ///
12041 /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
12042 /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
12043 /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
12044 /// was `[]`.
12045 pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
12046 let key = self.realm.well_known_key(WellKnown::Iterator);
12047 let method = self.read_field_key(value, &key)?;
12048 if !matches!(&method, Value::Object(object) if object.is_callable()) {
12049 return Ok(None);
12050 }
12051 let iterator = self.get_iterator(value)?;
12052 let mut out = Vec::new();
12053 loop {
12054 let (element, done) = self.iterator_step(&iterator)?;
12055 if done {
12056 return Ok(Some(out));
12057 }
12058 out.push(element);
12059 }
12060 }
12061
12062 /// One step of an internal iterator: the value and whether it is exhausted.
12063 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12064 // A real iterator (`next` is a function) answers with a result object.
12065 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12066 let result =
12067 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12068 let Some(result) = result.as_object().cloned() else {
12069 return Err(self.type_error("iterator result is not an object"));
12070 };
12071 let done = self
12072 .get_property(&result, "done")?
12073 .is_some_and(|value| value.to_boolean());
12074 let value = self
12075 .get_property(&result, "value")?
12076 .unwrap_or(Value::Undefined);
12077 return Ok((value, done));
12078 }
12079 // An iterator whose `next` is not callable is treated as exhausted, which is
12080 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12081 // that are not iterable at all.
12082 Ok((Value::Undefined, true))
12083 }
12084
12085 /// `[...iterable]`: append everything the iterator yields, and answer the next
12086 /// index.
12087 ///
12088 /// This goes through the same iterator machinery `for-of` uses rather than copying
12089 /// an array's elements, because a spread source is any iterable: a string spreads
12090 /// into its characters and an array iterator spreads into its results. Handling
12091 /// only arrays made `[..."ab"]` come out empty with no error at all.
12092 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12093 let Some(target) = array.as_object().cloned() else {
12094 return Ok(0);
12095 };
12096 let start = target.array_length().unwrap_or(0);
12097 let mut added = 0;
12098 let iterator = self.get_iterator(iterable)?;
12099 loop {
12100 let (value, done) = self.iterator_step(&iterator)?;
12101 if done {
12102 break;
12103 }
12104 target.array_set(self.heap, start + added, value);
12105 added += 1;
12106 }
12107 Ok((start + added) as i32)
12108 }
12109
12110 /// How an uncaught exception is reported.
12111 ///
12112 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12113 /// with `ToString` — `js_std_dump_error` is three lines that end in
12114 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12115 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12116 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12117 ///
12118 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12119 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12120 /// `toString`"; it does call it, but only for objects of a class it does not know how
12121 /// to walk, and never for errors, arrays or plain objects.
12122 ///
12123 /// A printer that fails must not take the reporter down with it, so that case falls
12124 /// back to the `ToString` rendering.
12125 pub fn describe_exception(&mut self, value: &Value) -> String {
12126 match crate::print::sprint(self, value) {
12127 Ok(text) => text,
12128 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
12129 }
12130 }
12131
12132 /// The file name of whatever is running, innermost frame first.
12133 ///
12134 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
12135 /// innermost frame's file name, without distinguishing a module body from a plain
12136 /// script. `import()` uses it as the base for a relative specifier, which is why
12137 /// `import('./x.js')` inside a script resolves next to the script and not next to the
12138 /// process's working directory.
12139 pub fn script_or_module_name(&self) -> Option<String> {
12140 self.script_or_module_name_at(0)
12141 }
12142
12143 /// [`Interp::script_or_module_name`] `level` frames further out.
12144 ///
12145 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
12146 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
12147 /// frame without a file name is skipped rather than counted, because a native call
12148 /// pushes no frame of its own and so cannot be a level.
12149 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
12150 self.frames
12151 .iter()
12152 .rev()
12153 .filter_map(|frame| frame.code.code.filename.clone())
12154 .nth(level)
12155 }
12156
12157 /// The current call stack, formatted the way `qjs` prints `error.stack`.
12158 ///
12159 /// One ` at name (file:line:col)` line per active frame, innermost first. The
12160 /// position is the one recorded for the instruction each frame is stopped on, which
12161 /// is why the compiler builds a pc-to-position table per function: without it a
12162 /// trace could only name the function, not the line inside it.
12163 ///
12164 /// A frame whose code has no positions prints just `(file)`, matching the
12165 /// reference's output for stripped bytecode.
12166 pub fn stack_trace(&self) -> String {
12167 self.stack_trace_skipping(0)
12168 }
12169
12170 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
12171 fn stack_trace_skipping(&self, skip: usize) -> String {
12172 // One ordered list, innermost first, so `skip` counts the same thing whether the
12173 // frames it leaves out are native or bytecode. Indices rather than references: a
12174 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
12175 let depth = self.frames.len();
12176 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
12177 // A native entered while `at` bytecode frames were live was called *from* the
12178 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
12179 // entered at the current depth are therefore innermost of all.
12180 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
12181 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
12182 if *at == wanted {
12183 order.push((true, index));
12184 }
12185 }
12186 };
12187 push_natives(&mut order, depth);
12188 for index in (0..depth).rev() {
12189 order.push((false, index));
12190 push_natives(&mut order, index);
12191 }
12192 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
12193 // barrier. Natives entered at exactly the barrier depth are the eval entry point
12194 // itself (`evalScript (native)`), and the reference leaves those out too.
12195 if let Some(barrier) = self.trace_barriers.last().copied() {
12196 order.retain(|(is_native, index)| match is_native {
12197 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
12198 false => *index >= barrier,
12199 });
12200 }
12201
12202 let mut out = String::new();
12203 for (is_native, index) in order.into_iter().skip(skip) {
12204 match is_native {
12205 true => {
12206 out.push_str(" at ");
12207 let (native, _) = &self.native_frames[index];
12208 let name = native
12209 .own_property("name")
12210 .and_then(|property| property.value)
12211 .map(|value| value.to_js_string())
12212 .unwrap_or_default();
12213 out.push_str(&name);
12214 out.push_str(" (native)\n");
12215 }
12216 false => {
12217 let frame = &self.frames[index];
12218 let code = &frame.code.code;
12219 let file = code.filename.as_deref().unwrap_or("<input>");
12220 // The name comes from the function *object*, not from the compiled code:
12221 // an anonymous function expression is named by the property it is stored
12222 // in (`{valueOf: function(){}}`), which only the object knows.
12223 let bound_name = match &frame.callee {
12224 Value::Object(object) => {
12225 object
12226 .own_property("name")
12227 .and_then(|property| match property.value {
12228 Some(Value::String(text)) if !text.wtf8().is_empty() => {
12229 Some(text.to_string_lossy().into_owned())
12230 }
12231 _ => None,
12232 })
12233 }
12234 _ => None,
12235 };
12236 // No callee object means the body was entered by the host, so the
12237 // name has to come from the compiled code. Two cases differ:
12238 //
12239 // * an *unnamed* function of any kind — the reference reads the
12240 // `name` property, finds it empty, and prints `<anonymous>`;
12241 // * a *module* body, which has no `name` property at all: the
12242 // reference builds that function object with `js_closure2` and
12243 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
12244 // so a trace reaching it also prints `<anonymous>` — while a
12245 // *script* body prints `<eval>`, its `name`.
12246 let unnamed = code.name.is_empty() || code.module.is_some();
12247 out.push_str(" at ");
12248 match bound_name.as_deref() {
12249 Some(name) => out.push_str(name),
12250 None if unnamed => out.push_str("<anonymous>"),
12251 None => out.push_str(&code.name),
12252 }
12253 match code.position_at(frame.at as u32) {
12254 Some((line, column)) => {
12255 out.push_str(&format!(" ({file}:{line}:{column})\n"));
12256 }
12257 None => out.push_str(&format!(" ({file})\n")),
12258 }
12259 }
12260 }
12261 }
12262 out
12263 }
12264
12265 /// Give an anonymous function the name of the property it is stored in.
12266 ///
12267 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
12268 /// enumerable and not configurable, and a function that already has a real name
12269 /// keeps it.
12270 ///
12271 /// "Already named" means a *non-empty* name: every function object is created with
12272 /// a `name` of `""` so the property exists on all of them, and treating that empty
12273 /// string as a name left every anonymous function nameless — which is how a stack
12274 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
12275 /// `SetFunctionName`, for a name that came from source text.
12276 fn set_function_name(&mut self, function: &Value, name: &str) {
12277 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
12278 }
12279
12280 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
12281 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
12282 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
12283 let Value::Object(object) = function else {
12284 return;
12285 };
12286 // `SetFunctionName` applies to *functions* and classes only, and only when they are
12287 // anonymous. Without the callability guard, `{value: someObject}` renamed
12288 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
12289 // on the right-hand side of a property. That is how a `zipKeyed` result object
12290 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
12291 // has no `NamedEvaluation` at all.
12292 if !object.is_callable() {
12293 return;
12294 }
12295 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
12296 && !existing.wtf8().is_empty()
12297 {
12298 return;
12299 }
12300 let text = self.string_wtf8(name.clone());
12301 object.define("name", Property::name_or_length(text));
12302 }
12303
12304 // -- global declarations -----------------------------------------------
12305
12306 /// Declare a global binding, creating its reference cell.
12307 /// Declare a `var` or function global, whose home is the global object.
12308 ///
12309 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
12310 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
12311 /// such as `print`, or a redeclaration — is left alone.
12312 pub fn declare_var_global(&mut self, name: &str) {
12313 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
12314 // global object is exactly the leak `typeof my_var === "undefined"` after
12315 // `eval("var my_var=2")` rules out.
12316 if let Some(scope) = self.eval_scope.as_mut() {
12317 scope.entry(name.to_string()).or_insert(Value::Undefined);
12318 return;
12319 }
12320 // A sloppy direct eval declares into its *caller's* variable environment. Doing
12321 // this on the global object instead made `eval("var c = 1")` inside a parameter
12322 // list overwrite a global `c`, and made two calls to the same function share one
12323 // binding.
12324 if let Some(cell) = self.declare_eval_local(name) {
12325 cell.set(Value::Undefined);
12326 return;
12327 }
12328 let global = self.realm.global.clone();
12329 if global.own_property(name).is_some() {
12330 return;
12331 }
12332 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
12333 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
12334 // whole point of that trick and what lets `Object.defineProperty` reshape it
12335 // afterwards. `eval_scope` is `Some` while an eval is running.
12336 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
12337 global.define(
12338 name,
12339 Property {
12340 value: Some(Value::Undefined),
12341 writable: true,
12342 enumerable: true,
12343 configurable: from_eval,
12344 ..Property::default()
12345 },
12346 );
12347 }
12348
12349 /// Declare a *lexical* global binding, which starts in its dead zone.
12350 ///
12351 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
12352 /// global object and is created when its initialiser runs.
12353 pub fn declare_global(&mut self, name: &str, is_const: bool) {
12354 if is_const {
12355 self.realm.lexical_consts.insert(name.to_string());
12356 }
12357 if !self.realm.globals.contains_key(name) {
12358 // `Uninitialized` rather than `Undefined`: the binding exists but is not
12359 // readable until its initialiser runs, and that is what `let x` before
12360 // `x = 1` has to observe.
12361 let cell = self.new_cell(Value::Uninitialized);
12362 self.realm.globals.insert(name.to_string(), cell);
12363 self.realm.declared.push(name.to_string());
12364 }
12365 }
12366}
12367
12368/// The bytecode and environment of a function object, if it is a bytecode function.
12369///
12370/// Extracted before a call so no borrow of the object is held across it.
12371fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
12372 function.with(|data| match &data.kind {
12373 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
12374 _ => None,
12375 })
12376}
12377
12378/// A native call target, extracted before the call so no borrow is held.
12379enum NativeCall {
12380 Native(NativeFn),
12381 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
12382 /// not hold that object's `RefCell` borrow.
12383 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
12384 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
12385 Bound {
12386 target: Value,
12387 this: Value,
12388 leading: Vec<Value>,
12389 },
12390 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
12391 Revoker(crate::object::ProxyRef),
12392 /// A promise's `resolve`.
12393 PromiseResolve(Gc<JsObject>),
12394 /// A promise's `reject`.
12395 PromiseReject(Gc<JsObject>),
12396 /// One continuation of an `await`.
12397 AwaitResume {
12398 coroutine: Gc<JsObject>,
12399 promise: Gc<JsObject>,
12400 kind: ResumeKind,
12401 },
12402 /// One element of a `Promise` combinator settling.
12403 CombinatorSettle {
12404 state: Gc<JsObject>,
12405 index: usize,
12406 fulfilled: bool,
12407 },
12408 /// One of `Promise.prototype.finally`'s two shims.
12409 FinallyShim {
12410 callback: Option<Value>,
12411 fulfilled: bool,
12412 },
12413 /// Settle a promise with a fixed outcome.
12414 SettlePromise {
12415 promise: Gc<JsObject>,
12416 value: Value,
12417 rejected: bool,
12418 },
12419 /// Continue an async generator after its `await` settled.
12420 GeneratorResume {
12421 generator: Gc<JsObject>,
12422 promise: Gc<JsObject>,
12423 kind: ResumeKind,
12424 },
12425 /// Read a module namespace's binding out of its cell.
12426 ModuleBinding(Gc<Cell>),
12427 /// Finish a completed async generator's `return(v)` once `v` has settled.
12428 CompletedReturn {
12429 generator: Gc<JsObject>,
12430 promise: Gc<JsObject>,
12431 rejected: bool,
12432 },
12433 /// Answer a pending async-generator method with `{value, done}`.
12434 YieldResult {
12435 generator: Gc<JsObject>,
12436 promise: Gc<JsObject>,
12437 done: bool,
12438 },
12439 /// One step of `AsyncDisposableStack.disposeAsync`.
12440 DisposeStep {
12441 remaining: Gc<JsObject>,
12442 promise: Gc<JsObject>,
12443 error: Value,
12444 rejected: bool,
12445 },
12446}
12447
12448/// What a store does when the object refuses the write.
12449#[derive(Clone, Copy, PartialEq, Eq)]
12450pub enum DeleteFailure {
12451 /// Raise a `TypeError`, which is what strict mode and every built-in does.
12452 Throw,
12453 /// Ignore the write, which is what a sloppy-mode assignment does.
12454 Ignore,
12455}
12456
12457/// Whether `object` is a `Date` instance, by the class tag it carries.
12458///
12459/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
12460/// builtins module depending on the interpreter's conversion order.
12461fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
12462 interp
12463 .internal_get(object, "_class")
12464 .is_some_and(|value| value.to_js_string() == "Date")
12465}
12466
12467/// Which type `ToPrimitive` prefers when it converts an object.
12468#[derive(Clone, Copy, PartialEq, Eq)]
12469pub enum Hint {
12470 /// The default hint, which behaves like [`Hint::Number`].
12471 Default,
12472 /// `Number(obj)` and the arithmetic operators.
12473 Number,
12474 /// `String(obj)` and `ToPropertyKey`.
12475 String,
12476}
12477
12478/// Which table a binding slot indexes, for the messages that name it.
12479#[derive(Clone, Copy)]
12480enum VarSlot {
12481 Loc,
12482 Closure,
12483}
12484
12485/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
12486fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
12487 Ok(this)
12488}
12489
12490/// An internal iterator: the sequence plus a cursor.
12491pub(crate) struct Iterator {
12492 pub(crate) object: Value,
12493 pub(crate) next: Value,
12494}
12495
12496/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
12497/// and plain `a` for a method.
12498///
12499/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
12500/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
12501/// reads `at get a (file:1:2)`.
12502/// The same prefixing, for a name that may hold an unpaired surrogate.
12503fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
12504 let prefix = match flags & 3 {
12505 1 => "get ",
12506 2 => "set ",
12507 _ => return key.clone(),
12508 };
12509 let mut units: Vec<u16> = prefix.encode_utf16().collect();
12510 units.extend_from_slice(&key.to_units());
12511 crate::value::Wtf8::from_units(&units)
12512}
12513
12514fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
12515 match flags & 3 {
12516 1 => format!("get {key}"),
12517 2 => format!("set {key}"),
12518 _ => key.to_string(),
12519 }
12520}
12521
12522/// Define a method or accessor property, per the `define_method` flag byte.
12523///
12524/// The low two bits pick value/getter/setter and bit 2 marks the property
12525/// enumerable.
12526///
12527/// A getter and a setter arrive as two separate `define_method` instructions, and the
12528/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
12529/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
12530/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
12531/// `JS_DefineProperty`, which leaves the other half alone.
12532fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
12533 let enumerable = flags & 4 != 0;
12534 let kind = flags & 3;
12535 let existing = object.own_property_key(key);
12536 let property = match kind {
12537 1 => Property {
12538 getter: Some(function),
12539 // The setter half, if this literal already defined one.
12540 setter: existing
12541 .filter(Property::is_accessor)
12542 .and_then(|p| p.setter),
12543 enumerable,
12544 configurable: true,
12545 ..Property::default()
12546 },
12547 2 => Property {
12548 getter: existing
12549 .filter(Property::is_accessor)
12550 .and_then(|p| p.getter),
12551 setter: Some(function),
12552 enumerable,
12553 configurable: true,
12554 ..Property::default()
12555 },
12556 _ => Property {
12557 value: Some(function),
12558 writable: true,
12559 enumerable,
12560 configurable: true,
12561 ..Property::default()
12562 },
12563 };
12564 object.define_key(key, property);
12565}
12566
12567// ---------------------------------------------------------------------------
12568// Operand decoding
12569// ---------------------------------------------------------------------------
12570
12571/// How `print` renders a value: the reference's `JS_PrintValue`.
12572///
12573/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
12574/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
12575/// The format is reproduced closely because the test suite compares output text:
12576///
12577/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
12578/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
12579/// * a cycle prints `[circular N]` with `N` the stack index of the object;
12580/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
12581/// end print as `<N empty item(s)>`;
12582/// * a string is quoted inside a container but raw at the top level, which is why
12583/// `print("x")` and `print(["x"])` differ.
12584pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
12585 // A string argument is printed raw: `js_print` converts it with `ToString`
12586 // instead of dumping it, and the quoting only appears inside a container.
12587 if let Value::String(text) = value {
12588 return text.to_string_lossy().into_owned();
12589 }
12590 let mut printer = Printer {
12591 interp,
12592 out: String::new(),
12593 stack: Vec::new(),
12594 };
12595 printer.value(value, 0);
12596 printer.out
12597}
12598
12599/// The internal class name an object carries, when it has one.
12600fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
12601 interp
12602 .internal_get(object, "_class")
12603 .map(|value| value.to_js_string())
12604}
12605
12606/// A string property, looked up the way `GetProperty` does: own first, then the
12607/// prototype chain. Needed because the print formatter holds the interpreter
12608/// immutably and so cannot run getters.
12609fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
12610 let mut current = Some(object.clone());
12611 // Bounded, because a prototype cycle would otherwise loop forever.
12612 for _ in 0..100 {
12613 let node = current?;
12614 if let Some(property) = node.own_property(name)
12615 && let Some(value) = property.value
12616 {
12617 return Some(value.to_js_string());
12618 }
12619 current = node.with(|data| data.proto.clone());
12620 }
12621 None
12622}
12623
12624/// The `JS_PrintValue` state: output, and the objects currently being printed.
12625struct Printer<'a, 'rt> {
12626 /// Kept for the class-name lookups that typed arrays and `Date` will need.
12627 #[allow(dead_code)]
12628 interp: &'a Interp<'rt>,
12629 out: String,
12630 stack: Vec<Gc<JsObject>>,
12631}
12632
12633impl Printer<'_, '_> {
12634 /// Depth past which a container is summarised by its class name.
12635 const MAX_DEPTH: usize = 2;
12636
12637 fn value(&mut self, value: &Value, level: usize) {
12638 match value {
12639 Value::Undefined
12640 | Value::Uninitialized
12641 | Value::Hole
12642 | Value::CatchOffset(_)
12643 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
12644 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
12645 // The printer writes a bigint the way the language spells one, so a dump is
12646 // unambiguous about which kind of number it is showing.
12647 Value::BigInt(big) => {
12648 self.out.push_str(&big.to_decimal_string());
12649 self.out.push('n');
12650 }
12651 Value::Null => self.out.push_str("null"),
12652 Value::Bool(true) => self.out.push_str("true"),
12653 Value::Bool(false) => self.out.push_str("false"),
12654 Value::Int(number) => self.out.push_str(&number.to_string()),
12655 Value::Float(number) => {
12656 self.out
12657 .push_str(&crate::value::number_to_string_for_print(*number));
12658 }
12659 Value::String(text) => self.print_string(&text.to_string_lossy()),
12660 Value::Object(object) => self.object(object, level),
12661 }
12662 }
12663
12664 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
12665 // A cycle is reported rather than followed; the index is where the object
12666 // already sits in the print stack, which is what the reference shows.
12667 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
12668 self.out.push_str(&format!("[circular {index}]"));
12669 return;
12670 }
12671 if object.is_callable() {
12672 let name = object
12673 .own_property("name")
12674 .and_then(|property| property.value)
12675 .map(|value| value.to_js_string())
12676 .unwrap_or_default();
12677 if name.is_empty() {
12678 self.out.push_str("[Function (anonymous)]");
12679 } else {
12680 self.out.push_str(&format!("[Function {name}]"));
12681 }
12682 return;
12683 }
12684 if level >= Self::MAX_DEPTH {
12685 let class = if object.is_array() { "Array" } else { "Object" };
12686 self.out.push_str(&format!("[{class}]"));
12687 return;
12688 }
12689 // `Date` and `Error` print as themselves rather than as bags of properties:
12690 // the ISO string, and `Name: message` followed by the trace.
12691 if let Some(class) = class_of(self.interp, object) {
12692 if class == "Date" {
12693 self.date(object);
12694 return;
12695 }
12696 if class == "Error" {
12697 self.error(object);
12698 return;
12699 }
12700 }
12701 self.stack.push(object.clone());
12702 if object.is_array() {
12703 self.array(object, level);
12704 } else {
12705 self.plain_object(object, level);
12706 }
12707 self.stack.pop();
12708 }
12709
12710 /// A Date prints as its ISO string; an invalid one falls through to the plain
12711 /// object form, the way the reference falls back when `toISOString` throws.
12712 fn date(&mut self, object: &Gc<JsObject>) {
12713 let value = self
12714 .interp
12715 .internal_get(object, "_date_value")
12716 .map(|value| value.to_number());
12717 match value.and_then(crate::builtins::date::iso_string) {
12718 Some(text) => self.out.push_str(&text),
12719 None => self.plain_object(object, 0),
12720 }
12721 }
12722
12723 /// `Name: message`, then the trace with its trailing newline removed.
12724 fn error(&mut self, object: &Gc<JsObject>) {
12725 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
12726 self.out.push_str(&name);
12727 if let Some(message) = inherited(object, "message")
12728 && !message.is_empty()
12729 {
12730 self.out.push_str(": ");
12731 self.out.push_str(&message);
12732 }
12733 if let Some(stack) = inherited(object, "stack") {
12734 self.out.push('\n');
12735 self.out.push_str(stack.trim_end_matches('\n'));
12736 }
12737 }
12738
12739 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
12740 let elements = object.array_elements().unwrap_or_default();
12741 self.out.push_str("[ ");
12742 // An interior hole means the array is "sparse": the reference prints those
12743 // as `index: value` pairs and says nothing about the holes themselves, while
12744 // a hole run at the end becomes a single `<N empty items>` note.
12745 let last_present = elements
12746 .iter()
12747 .rposition(|value| !matches!(value, Value::Hole));
12748 let has_interior_hole = match last_present {
12749 Some(last) => elements[..last]
12750 .iter()
12751 .any(|value| matches!(value, Value::Hole)),
12752 None => false,
12753 };
12754 let mut first = true;
12755 if has_interior_hole {
12756 let mut index = 0;
12757 while index < elements.len() {
12758 let value = &elements[index];
12759 if matches!(value, Value::Hole) {
12760 index += 1;
12761 continue;
12762 }
12763 if !first {
12764 self.out.push_str(", ");
12765 }
12766 first = false;
12767 self.out.push_str(&format!("{index}: "));
12768 self.value(value, level + 1);
12769 index += 1;
12770 }
12771 } else {
12772 for (index, value) in elements.iter().enumerate() {
12773 if matches!(value, Value::Hole) {
12774 continue;
12775 }
12776 if !first {
12777 self.out.push_str(", ");
12778 }
12779 first = false;
12780 let _ = index;
12781 self.value(value, level + 1);
12782 }
12783 if let Some(last) = last_present {
12784 let trailing = elements.len() - last - 1;
12785 if trailing > 0 {
12786 if !first {
12787 self.out.push_str(", ");
12788 }
12789 self.out.push_str(&format!(
12790 "<{trailing} empty item{}>",
12791 if trailing > 1 { "s" } else { "" }
12792 ));
12793 }
12794 } else if !elements.is_empty() {
12795 let count = elements.len();
12796 self.out.push_str(&format!(
12797 "<{count} empty item{}>",
12798 if count > 1 { "s" } else { "" }
12799 ));
12800 }
12801 }
12802 self.out.push_str(" ]");
12803 }
12804
12805 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
12806 self.out.push_str("{ ");
12807 let mut first = true;
12808 for key in object.own_keys() {
12809 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
12810 continue;
12811 };
12812 if !property.enumerable {
12813 continue;
12814 }
12815 if !first {
12816 self.out.push_str(", ");
12817 }
12818 first = false;
12819 self.out
12820 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
12821 &key.to_string_lossy(),
12822 )));
12823 self.out.push_str(": ");
12824 // An accessor has no value to dump; the reference names the half that
12825 // exists instead of calling it.
12826 if property.is_accessor() {
12827 let text = match (property.getter.is_some(), property.setter.is_some()) {
12828 (true, true) => "[Getter/Setter]",
12829 (false, true) => "[Setter]",
12830 _ => "[Getter]",
12831 };
12832 self.out.push_str(text);
12833 } else {
12834 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
12835 }
12836 }
12837 self.out.push_str(" }");
12838 }
12839
12840 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
12841 fn print_string(&mut self, text: &str) {
12842 self.out.push('"');
12843 for character in text.chars() {
12844 match character {
12845 '"' => self.out.push_str("\\\""),
12846 '\\' => self.out.push_str("\\\\"),
12847 '\n' => self.out.push_str("\\n"),
12848 '\r' => self.out.push_str("\\r"),
12849 '\t' => self.out.push_str("\\t"),
12850 c if (c as u32) < 0x20 => {
12851 self.out.push_str(&format!("\\u{:04x}", c as u32));
12852 }
12853 c => self.out.push(c),
12854 }
12855 }
12856 self.out.push('"');
12857 }
12858}
12859
12860/// How `print` renders a value.
12861///
12862/// `ToString`, except that negative zero keeps its sign — the reference's host
12863/// printer does that while `String(-0)` is `"0"`.
12864pub fn display(value: &Value) -> String {
12865 match value {
12866 Value::Float(number) => crate::value::number_to_string_for_print(*number),
12867 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
12868 "undefined".to_string()
12869 }
12870 other => other.to_js_string(),
12871 }
12872}
12873
12874// ---------------------------------------------------------------------------
12875// Numeric operators
12876// ---------------------------------------------------------------------------
12877
12878/// `a + b` keeping the `Int` representation when it fits.
12879fn add_numbers(left: Value, right: Value) -> Value {
12880 match (&left, &right) {
12881 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
12882 Some(sum) => Value::Int(sum),
12883 None => Value::Float(*a as f64 + *b as f64),
12884 },
12885 _ => Value::Float(left.to_number() + right.to_number()),
12886 }
12887}
12888
12889/// The arithmetic operators other than `+`, which needs string concatenation.
12890fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12891 use Opcode::*;
12892 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
12893 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
12894 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
12895 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
12896 return Ok(match op {
12897 And => Value::Int(x & y),
12898 Or => Value::Int(x | y),
12899 Xor => Value::Int(x ^ y),
12900 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
12901 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
12902 Shr => match (*x as u32) >> ((*y as u32) & 31) {
12903 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
12904 shifted => Value::Float(shifted as f64),
12905 },
12906 Sub => match x.checked_sub(*y) {
12907 Some(value) => Value::Int(value),
12908 None => Value::Float(*x as f64 - *y as f64),
12909 },
12910 _ => return arithmetic_slow(op, left, right),
12911 });
12912 }
12913 arithmetic_slow(op, left, right)
12914}
12915
12916/// [`arithmetic`] for everything the integer fast path above does not take.
12917fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12918 use Opcode::*;
12919 let (a, b) = (left.to_number(), right.to_number());
12920 Ok(match op {
12921 Sub => match (&left, &right) {
12922 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
12923 Some(value) => Value::Int(value),
12924 None => Value::Float(a - b),
12925 },
12926 _ => Value::Float(a - b),
12927 },
12928 Mul => Value::Float(a * b),
12929 Div => Value::Float(a / b),
12930 Mod => Value::Float(js_mod(a, b)),
12931 Pow => Value::Float(a.powf(b)),
12932 And => Value::Int(left.to_int32() & right.to_int32()),
12933 Or => Value::Int(left.to_int32() | right.to_int32()),
12934 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
12935 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
12936 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
12937 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
12938 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
12939 // fits the small-integer representation stays an `Int`; the rest become a
12940 // float, which is how the reference keeps `n >>> 0` non-negative.
12941 Shr => {
12942 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
12943 match i32::try_from(shifted) {
12944 Ok(value) => Value::Int(value),
12945 Err(_) => Value::Float(shifted as f64),
12946 }
12947 }
12948 _ => Value::Float(a),
12949 })
12950}
12951
12952/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
12953///
12954/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
12955/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
12956/// slow path where the rules live.
12957fn is_number(value: &Value) -> bool {
12958 matches!(value, Value::Int(_) | Value::Float(_))
12959}
12960
12961/// The `Value::Bool` a comparison operator answers for `ordering`.
12962///
12963/// `None` is the unordered case — a `NaN` on either side — and every operator answers
12964/// false for it, including `<=` and `>=`.
12965fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
12966 use Opcode::*;
12967 let answer = match (op, ordering) {
12968 (_, None) => false,
12969 (Lt, Some(ordering)) => ordering.is_lt(),
12970 (Lte, Some(ordering)) => ordering.is_le(),
12971 (Gt, Some(ordering)) => ordering.is_gt(),
12972 (Gte, Some(ordering)) => ordering.is_ge(),
12973 _ => false,
12974 };
12975 Value::Bool(answer)
12976}
12977
12978/// `%`, which follows the sign of the dividend rather than Rust's.
12979fn js_mod(left: f64, right: f64) -> f64 {
12980 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
12981 return f64::NAN;
12982 }
12983 if right.is_infinite() {
12984 return left;
12985 }
12986 let remainder = left % right;
12987 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
12988 // the spec makes the sign match the dividend.
12989 if remainder == 0.0 {
12990 0.0f64.copysign(left)
12991 } else {
12992 remainder
12993 }
12994}
12995
12996fn negate(value: Value) -> Value {
12997 match value {
12998 Value::Int(0) => Value::Float(-0.0),
12999 Value::Int(i) => Value::Int(-i),
13000 other => Value::Float(-other.to_number()),
13001 }
13002}
13003
13004fn increment(value: Value) -> Value {
13005 match value {
13006 Value::Int(i) => match i.checked_add(1) {
13007 Some(next) => Value::Int(next),
13008 None => Value::Float(i as f64 + 1.0),
13009 },
13010 other => Value::Float(other.to_number() + 1.0),
13011 }
13012}
13013
13014fn decrement(value: Value) -> Value {
13015 match value {
13016 Value::Int(i) => match i.checked_sub(1) {
13017 Some(next) => Value::Int(next),
13018 None => Value::Float(i as f64 - 1.0),
13019 },
13020 other => Value::Float(other.to_number() - 1.0),
13021 }
13022}
13023
13024/// Compare a `BigInt` with an `f64` on their mathematical values.
13025///
13026/// Neither side is rounded to the other's precision: the number is split into its integer
13027/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13028/// when the integer parts are equal. An infinite value is larger than every bigint.
13029fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13030 use std::cmp::Ordering;
13031 if number.is_nan() {
13032 return None;
13033 }
13034 if number.is_infinite() {
13035 return Some(if number > 0.0 {
13036 Ordering::Less
13037 } else {
13038 Ordering::Greater
13039 });
13040 }
13041 let truncated = number.trunc();
13042 // A number wider than `i128` still has an exact integer part, but no bigint form we can
13043 // build cheaply; the sign of the difference is all that is needed, so compare against
13044 // the bigint's own magnitude instead.
13045 if truncated.abs() >= 1.7e38 {
13046 let big_as_f64 = big.to_f64();
13047 return big_as_f64.partial_cmp(&number);
13048 }
13049 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13050 match big.cmp(&integer) {
13051 Ordering::Equal => {
13052 // Same integer part: the fraction decides, and a negative number's fraction is
13053 // below the integer (`-1.5` truncates to `-1`).
13054 if number > truncated {
13055 Some(Ordering::Less)
13056 } else if number < truncated {
13057 Some(Ordering::Greater)
13058 } else {
13059 Some(Ordering::Equal)
13060 }
13061 }
13062 other => Some(other),
13063 }
13064}