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::{OpFormat, Opcode};
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25 Callable, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars, NativeFn, ObjectKind,
26 Property, PropertyKey, array_index, has_own, lookup_key, same_proto,
27};
28use crate::value::{Cell, Value, number_to_string};
29
30/// Why execution stopped.
31#[derive(Debug, Clone)]
32pub enum Signal {
33 /// A JavaScript exception carrying the thrown value.
34 Throw(Value),
35 /// The runtime ran out of memory.
36 OutOfMemory,
37}
38
39/// What an execution step produced.
40pub type JsResult<T> = std::result::Result<T, Signal>;
41
42/// The result of one instruction.
43enum Step {
44 /// Keep executing the current frame.
45 Continue,
46 /// The current frame returned this value.
47 Return(Value),
48 /// The frame parked at a suspension point, with the yielded value on its stack.
49 ///
50 /// Only a generator or an async function can produce this, and only its own frame —
51 /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
52 /// detached and handed to the generator object, which is what lets it resume later
53 /// with its locals and operand stack intact.
54 Suspend(SuspendKind),
55}
56
57/// Why a frame parked, which decides how the resumption is delivered.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum SuspendKind {
60 /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
61 /// without passing a value, because there is no `yield` expression to receive one.
62 Initial,
63 /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
64 Yield,
65 /// `yield* expr`: like `Yield`, but the value is already an `{value, done}` object
66 /// from the inner iterator and is handed straight back.
67 YieldStar,
68 /// `await expr`: the value is a promise the async machinery has to settle first.
69 Await,
70}
71
72/// Everything one JavaScript realm owns.
73///
74/// A realm is the set of objects a script can reach without naming them: the global
75/// object, the prototype chain roots, and the global binding cells.
76pub struct Realm {
77 /// The global object.
78 pub global: Gc<JsObject>,
79 /// `Object.prototype`.
80 pub object_proto: Gc<JsObject>,
81 /// `Function.prototype`, which is itself callable.
82 pub function_proto: Gc<JsObject>,
83 /// `Array.prototype`.
84 pub array_proto: Gc<JsObject>,
85 /// Reference cells for globals declared by the script.
86 ///
87 /// A declared global is read with `get_var` (by name) but written with
88 /// `put_var_ref` (through the cell), so the cell is what makes a function
89 /// declaration and its uses agree on one binding.
90 pub globals: BTreeMap<String, Gc<Cell>>,
91 /// Names of the globals that came from a *declaration*, which are
92 /// non-configurable properties of the global object.
93 pub declared: Vec<String>,
94 /// Names among the lexical globals that are `const`.
95 ///
96 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
97 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
98 /// path does not carry, so a store through it would look like a plain `let`. The
99 /// realm records it once, at declaration, and answers for every reader.
100 pub lexical_consts: BTreeSet<String>,
101 /// The error constructors by class name, so a runtime error can throw a real
102 /// `TypeError` instance rather than a look-alike object.
103 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
104 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
105 pub string_proto: Option<Gc<JsObject>>,
106 /// `Number.prototype`.
107 pub number_proto: Option<Gc<JsObject>>,
108 /// `Boolean.prototype`.
109 pub boolean_proto: Option<Gc<JsObject>>,
110 /// `BigInt.prototype`.
111 pub bigint_proto: Option<Gc<JsObject>>,
112 /// `Error.prototype`, the prototype of every error instance.
113 pub error_proto: Gc<JsObject>,
114 /// `Date.prototype`, so the constructor can build an instance in the
115 /// function-call form (`Date()` returns a string) without going through `new`.
116 pub date_proto: Gc<JsObject>,
117 /// `%GeneratorPrototype%`, the prototype of every generator object.
118 pub generator_proto: Gc<JsObject>,
119 /// `Promise.prototype`, the prototype of every promise.
120 pub promise_proto: Option<Gc<JsObject>>,
121 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
122 pub async_generator_proto: Option<Gc<JsObject>>,
123 /// `Symbol.prototype`.
124 pub symbol_proto: Option<Gc<JsObject>>,
125 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
126 /// `_date_value`.
127 ///
128 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
129 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
130 /// language does not have and `new Error()` listed `_class` beside `message` and
131 /// `stack` — and a caller that copies every own property (which
132 /// `Object.create(null, props)` effectively does) tried to write an internal name and
133 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
134 /// and `JSON.stringify`, while remaining an ordinary traced property.
135 pub internal_slots: BTreeMap<&'static str, Value>,
136
137 /// The `Symbol.for` registry: `key -> symbol`.
138 ///
139 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
140 /// symbol every time within one script while a fresh realm starts empty.
141 pub symbol_registry: BTreeMap<String, Value>,
142 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
143 pub regexp_proto: Option<Gc<JsObject>>,
144 /// The `RegExp` constructor.
145 pub regexp_ctor: Option<Gc<JsObject>>,
146 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
147 ///
148 /// The prototype rather than the constructor on purpose: a script that replaces
149 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
150 /// error wrapping, which the `using` test suite checks explicitly.
151 pub suppressed_error_proto: Option<Gc<JsObject>>,
152 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
153 pub disposable_stack_proto: Option<Gc<JsObject>>,
154 /// `Map.prototype`.
155 pub map_proto: Option<Gc<JsObject>>,
156 /// `Set.prototype`.
157 pub set_proto: Option<Gc<JsObject>>,
158 /// Every live `FinalizationRegistry`, held weakly.
159 ///
160 /// The cleanup callback has to run from a *safe point* — a place where script is not
161 /// already executing and no engine borrow is held — and the collector cannot enumerate
162 /// heap objects by type. Registering each registry here gives the drain a list to walk.
163 ///
164 /// The handles are weak on purpose: a registry the script dropped must be collectable,
165 /// and it must not be resurrected merely because the drain knew about it. Entries whose
166 /// target has expired are swept out as the drain walks, so the vector does not grow
167 /// without bound in a program that creates many short-lived registries.
168 pub finalization_registries: Vec<WeakGc<JsObject>>,
169 /// `ArrayBuffer.prototype`.
170 pub array_buffer_proto: Option<Gc<JsObject>>,
171 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
172 pub typed_array_proto: Option<Gc<JsObject>>,
173 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
174 ///
175 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
176 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
177 /// `"Object"` and `r instanceof Int32Array` is false.
178 pub typed_array_protos: Vec<Gc<JsObject>>,
179 /// `DataView.prototype`.
180 pub data_view_proto: Option<Gc<JsObject>>,
181 /// The `AsyncDisposableStack` prototype.
182 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
183 /// `Iterator.prototype`.
184 pub iterator_proto: Option<Gc<JsObject>>,
185 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
186 ///
187 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
188 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
189 /// `[object Iterator Helper]`).
190 pub iterator_helper_proto: Option<Gc<JsObject>>,
191 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
192 /// that was not already an `Iterator`.
193 ///
194 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
195 /// untouched and does *not* override `@@toStringTag`, so
196 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
197 pub iterator_wrap_proto: Option<Gc<JsObject>>,
198 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
199 pub generator_function_proto: Option<Gc<JsObject>>,
200 /// `%AsyncFunction.prototype%`.
201 pub async_function_proto: Option<Gc<JsObject>>,
202 /// `%AsyncGeneratorFunction.prototype%`.
203 pub async_generator_function_proto: Option<Gc<JsObject>>,
204 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
205 ///
206 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
207 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
208 /// prototype per iterator made every array iterator's prototype distinct.
209 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
210 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
211 ///
212 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
213 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
214 /// both faster and impossible to break from a script.
215 well_known_symbols: WellKnownSymbols,
216}
217
218/// One binding of the frame that called `eval`, so the eval'd code can read and
219/// write it by name.
220struct EvalBinding {
221 /// The name it was declared with.
222 name: String,
223 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
224 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
225 /// a function that declares `a` must find that `a`.
226 frame: usize,
227 /// Which table of that frame it lives in.
228 slot: EvalSlot,
229 /// The slot index within that table.
230 index: usize,
231}
232
233/// Which table of a frame an [`EvalBinding`] indexes.
234#[derive(Clone, Copy)]
235enum EvalSlot {
236 Arg,
237 Local,
238}
239
240/// One activation record.
241struct Frame {
242 /// The bytecode being run.
243 code: Gc<CompiledCode>,
244 /// The cells this closure captured.
245 env: Gc<ClosureEnv>,
246 /// The `this` binding.
247 this: Value,
248 /// Argument slots, sized to the declared parameter count.
249 args: Vec<Value>,
250 /// The values the caller actually passed, which is what `arguments` exposes.
251 passed: Vec<Value>,
252 /// Local slots.
253 locals: Vec<Value>,
254 /// Reference cells for this frame's own captured bindings.
255 cells: Vec<Gc<Cell>>,
256 /// The operand stack.
257 stack: Vec<Value>,
258 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
259 local_vars: Option<Gc<LocalVars>>,
260
261 /// Byte offset of the next instruction.
262 pc: usize,
263 /// Byte offset of the instruction being executed, which is what a stack trace
264 /// reports. `pc` has already moved past it by the time an instruction runs.
265 at: usize,
266 /// The callee, so a native builtin can tell which constructor it is.
267 callee: Value,
268 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
269 new_target: Value,
270 /// Whether this frame's body ended in a `tail_call`.
271 ///
272 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
273 /// with its own frame just like `call` does and only skips storing the result
274 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
275 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
276 /// pushed as usual, and this marker makes its return value the *caller's* return
277 /// value without running the instructions after the call.
278 tail: bool,
279}
280
281impl js_gc::Trace for Frame {
282 fn trace(&self, tracer: &mut js_gc::Tracer) {
283 self.code.trace(tracer);
284 self.env.trace(tracer);
285 self.this.trace(tracer);
286 for value in &self.args {
287 value.trace(tracer);
288 }
289 for value in &self.passed {
290 value.trace(tracer);
291 }
292 for value in &self.locals {
293 value.trace(tracer);
294 }
295 for cell in &self.cells {
296 cell.trace(tracer);
297 }
298 if let Some(local_vars) = &self.local_vars {
299 tracer.visit(local_vars);
300 }
301 for value in &self.stack {
302 value.trace(tracer);
303 }
304 self.callee.trace(tracer);
305 self.new_target.trace(tracer);
306 }
307}
308
309/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
310/// emitted `if_false` treats as "keep going".
311const RESUME_NEXT: i32 = 0;
312/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
313/// generator fall into its `return_async`.
314const RESUME_RETURN: i32 = 1;
315
316/// One microtask.
317///
318/// The queue holds *data* rather than closures because its contents are GC values: a
319/// closure would be invisible to the collector, and a pending reaction is exactly the
320/// kind of thing that must keep its handlers and its promise alive.
321pub enum Job {
322 /// A `then` reaction about to run.
323 Reaction {
324 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
325 handler: Option<Value>,
326 /// The value or reason to call it with.
327 argument: Value,
328 /// Whether the source promise rejected, which decides the pass-through kind.
329 rejected: bool,
330 /// The promise the answer settles.
331 promise: Gc<JsObject>,
332 },
333 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
334 Thenable {
335 /// The `then` that was found on the value.
336 then: Value,
337 /// The thenable itself, which becomes `then`'s `this`.
338 value: Value,
339 /// The promise being resolved.
340 promise: Gc<JsObject>,
341 },
342 /// A pending `import(specifier)`.
343 Import {
344 /// The specifier, already converted to a string.
345 specifier: String,
346 /// The module that asked, which the specifier resolves against.
347 referrer: String,
348 /// The promise `import()` handed back.
349 promise: Gc<JsObject>,
350 },
351 /// An async generator resuming after the value it awaited settled.
352 GeneratorResume {
353 /// The async generator to continue.
354 generator: Gc<JsObject>,
355 /// The promise the pending method returned.
356 promise: Gc<JsObject>,
357 /// Whether this delivers the value or raises the reason.
358 kind: ResumeKind,
359 /// The settled value, or the rejection reason.
360 value: Value,
361 },
362 /// An async function resuming after the value it awaited settled.
363 Resume {
364 /// The body, parked in a coroutine.
365 coroutine: Gc<JsObject>,
366 /// The promise the async function handed its caller.
367 promise: Gc<JsObject>,
368 /// Whether this resumption delivers a value or raises one.
369 kind: ResumeKind,
370 /// The settled value, or the rejection reason.
371 value: Value,
372 },
373}
374
375impl js_gc::Trace for Job {
376 fn trace(&self, tracer: &mut js_gc::Tracer) {
377 match self {
378 Job::Reaction {
379 handler,
380 argument,
381 promise,
382 ..
383 } => {
384 if let Some(handler) = handler {
385 handler.trace(tracer);
386 }
387 argument.trace(tracer);
388 tracer.visit(promise);
389 }
390 Job::Thenable {
391 then,
392 value,
393 promise,
394 } => {
395 then.trace(tracer);
396 value.trace(tracer);
397 tracer.visit(promise);
398 }
399 Job::Resume {
400 coroutine,
401 promise,
402 value,
403 ..
404 } => {
405 tracer.visit(coroutine);
406 tracer.visit(promise);
407 value.trace(tracer);
408 }
409 Job::Import { promise, .. } => tracer.visit(promise),
410 Job::GeneratorResume {
411 generator,
412 promise,
413 value,
414 ..
415 } => {
416 tracer.visit(generator);
417 tracer.visit(promise);
418 value.trace(tracer);
419 }
420 }
421 }
422}
423
424/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
425#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426pub enum ResumeKind {
427 /// The generator was just created and is being run to its first suspension.
428 Start,
429 /// `next(v)`.
430 Next,
431 /// `return(v)`.
432 Return,
433 /// `throw(e)`.
434 Throw,
435}
436
437/// A generator object's saved execution.
438///
439/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
440/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
441/// separately allocated buffers.
442pub struct GeneratorState {
443 /// The detached frame, or `None` once the generator has finished or while it runs.
444 frame: Option<Frame>,
445 /// How far it got.
446 phase: GeneratorPhase,
447 /// Whether the last suspension was an `await` rather than a `yield`.
448 ///
449 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
450 /// value and a magic number, because the emitted code branches on which method
451 /// resumed it, while an `await` simply continues with its value. Getting this wrong
452 /// leaves an extra value on the operand stack that the next instruction then
453 /// consumes — a wrong answer rather than a crash.
454 parked_on_await: bool,
455}
456
457/// Which of §27.5.3.3's states a generator is in.
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459enum GeneratorPhase {
460 /// Created, `initial_yield` reached, body not entered.
461 SuspendedStart,
462 /// Parked at a `yield`.
463 SuspendedYield,
464 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
465 Executing,
466 /// Finished; the frame is gone.
467 Completed,
468}
469
470impl js_gc::Trace for GeneratorState {
471 fn trace(&self, tracer: &mut js_gc::Tracer) {
472 if let Some(frame) = &self.frame {
473 frame.trace(tracer);
474 }
475 }
476}
477
478/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
479/// them in.
480///
481/// Each is a field rather than a map entry because the runtime reads them on hot paths
482/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
483/// failure — reaching a default here means the builtin did not install, and every
484/// accessor panics rather than silently answering `undefined`.
485///
486/// [`builtins::symbol`]: crate::builtins::symbol
487#[derive(Default)]
488pub struct WellKnownSymbols {
489 /// The symbol values, positionally. Empty until `Symbol` installs.
490 symbols: Vec<Value>,
491}
492
493/// Which well-known symbol a caller wants.
494///
495/// A typed accessor beats passing a name around: a typo is a compile error rather than
496/// an `undefined` key that quietly matches nothing.
497#[derive(Debug, Clone, Copy, PartialEq, Eq)]
498pub enum WellKnown {
499 /// `Symbol.toPrimitive`.
500 ToPrimitive,
501 /// `Symbol.iterator`.
502 Iterator,
503 /// `Symbol.match`.
504 Match,
505 /// `Symbol.matchAll`.
506 MatchAll,
507 /// `Symbol.replace`.
508 Replace,
509 /// `Symbol.search`.
510 Search,
511 /// `Symbol.split`.
512 Split,
513 /// `Symbol.toStringTag`.
514 ToStringTag,
515 /// `Symbol.isConcatSpreadable`.
516 IsConcatSpreadable,
517 /// `Symbol.hasInstance`.
518 HasInstance,
519 /// `Symbol.species`.
520 Species,
521 /// `Symbol.unscopables`.
522 Unscopables,
523 /// `Symbol.asyncIterator`.
524 AsyncIterator,
525 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
526 Disposable,
527 /// `Symbol.asyncDispose` — the awaited form.
528 AsyncDisposable,
529}
530
531impl WellKnown {
532 /// The index `Symbol`'s installer creates this symbol at.
533 fn index(self) -> usize {
534 match self {
535 WellKnown::ToPrimitive => 0,
536 WellKnown::Iterator => 1,
537 WellKnown::Match => 2,
538 WellKnown::MatchAll => 3,
539 WellKnown::Replace => 4,
540 WellKnown::Search => 5,
541 WellKnown::Split => 6,
542 WellKnown::ToStringTag => 7,
543 WellKnown::IsConcatSpreadable => 8,
544 WellKnown::HasInstance => 9,
545 WellKnown::Species => 10,
546 WellKnown::Unscopables => 11,
547 WellKnown::AsyncIterator => 12,
548 WellKnown::Disposable => 13,
549 WellKnown::AsyncDisposable => 14,
550 }
551 }
552}
553
554impl Realm {
555 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
556 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
557 self.well_known_symbols.symbols = symbols;
558 }
559
560 /// A well-known symbol.
561 pub fn well_known(&self, which: WellKnown) -> Value {
562 self.well_known_symbols
563 .symbols
564 .get(which.index())
565 .cloned()
566 .unwrap_or(Value::Undefined)
567 }
568
569 /// The well-known symbol as a property key.
570 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
571 match self.well_known(which) {
572 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
573 // Unreachable once `Symbol` has installed; an empty string key matches
574 // nothing, which degrades to "the object has no such method".
575 _ => PropertyKey::from(String::new()),
576 }
577 }
578}
579
580/// The interpreter: a realm plus a frame stack.
581pub struct Interp<'a> {
582 /// The heap everything is allocated on.
583 pub heap: &'a Heap,
584 /// The realm.
585 pub realm: Realm,
586 /// Active frames, outermost first.
587 frames: Vec<Frame>,
588 /// A strict-mode `eval`'s own variable scope, while its script runs.
589 ///
590 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
591 /// become a global. Name lookups still fall through to the realm, which is why
592 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
593 eval_scope: Option<BTreeMap<String, Value>>,
594 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
595 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
596 eval_depth: usize,
597 /// The calling frame's own bindings, which the running `eval` can read and write.
598 ///
599 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
600 /// come from the frame, and a write is applied back to the frame (or to the cell
601 /// the frame captured) when the eval finishes. That is what makes
602 /// `f("a = 3")` visible to the caller as `a === 3`.
603 eval_bindings: Vec<EvalBinding>,
604 /// The calling frame's `arguments`, while an `eval` runs.
605 ///
606 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
607 /// own yet still has to see the caller's `arguments`.
608 eval_arguments: Option<Value>,
609 /// The `with` objects live at the moment the running `eval` started, innermost first.
610 ///
611 /// `None` outside an eval, which is what keeps a finished block's object from
612 /// shadowing ordinary bytecode reads.
613 eval_with: Option<Vec<Gc<JsObject>>>,
614 /// The bindings the running direct `eval` makes visible, as name → cell.
615 ///
616 /// Set for the duration of an eval and then restored, but every closure created
617 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
618 /// `eval("f = () => i")` work after the eval has returned.
619 active_eval_scope: Option<Gc<EvalScope>>,
620 /// The frame that called the direct `eval` currently running, if any.
621 ///
622 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
623 /// on the global object, which is what keeps
624 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
625 /// gives each call its own `x`.
626 eval_caller: Option<Option<usize>>,
627 /// The caller's `new.target`, while an `eval` runs.
628 ///
629 /// The eval'd code is a script with no constructor of its own, so it inherits the
630 /// one the enclosing function was called with.
631 eval_new_target: Option<Value>,
632 /// `new.target` for the frame about to be pushed.
633 ///
634 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
635 /// value reaches the frame without threading a parameter through every call site.
636 pending_new_target: Option<Value>,
637 /// Names of the native functions currently executing, outermost first.
638 ///
639 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
640 /// trace still names it with `(native)` instead of a position, so the names are
641 /// tracked separately and stitched into [`Interp::stack_trace`].
642 native_frames: Vec<(String, Gc<JsObject>)>,
643 /// The native function currently executing, for the ones that have to know *which*
644 /// function they are — a typed-array constructor reads its element type off itself.
645 ///
646 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
647 /// reports whatever the enclosing bytecode frame was called with.
648 current_native: Option<Gc<JsObject>>,
649 /// Text written by `print` and friends, in order.
650 ///
651 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
652 /// once at the end, which is also when upstream's line buffering becomes
653 /// visible for the cases compared here.
654 pub output: String,
655 /// The most frames that may be live at once.
656 pub max_frames: usize,
657 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
658 ///
659 /// Script execution does not return until this has drained, which is what makes
660 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
661 /// than never. Reactions append to it while it drains, so the loop is a `while` and
662 /// not a `for`.
663 pub(crate) jobs: std::collections::VecDeque<Job>,
664 /// The module registry, keyed by canonical name.
665 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
666 /// How the host turns a specifier into bytes.
667 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
668 /// The module the host was asked to run, for `import.meta.main`.
669 pub main_module_name: Option<String>,
670 /// Module bodies currently running, innermost last.
671 ///
672 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
673 /// this is the only place that knows which module that is.
674 pub module_stack: Vec<String>,
675 /// Rejections that no handler has claimed, with the promise they belong to.
676 ///
677 /// A `then` registered later prunes its entry, which is why the promise is kept: the
678 /// reason alone cannot say whether somebody eventually listened.
679 unhandled: Vec<(Gc<JsObject>, Value)>,
680}
681
682impl<'a> Interp<'a> {
683 /// Build an interpreter over `heap`, with a fresh realm.
684 pub fn new(heap: &'a Heap) -> Interp<'a> {
685 let object_proto = JsObject::ordinary(heap, None);
686 let function_proto = JsObject::function(
687 heap,
688 Some(object_proto.clone()),
689 Callable::Native {
690 func: |_, _, _| Ok(Value::Undefined),
691 own_instance: false,
692 },
693 );
694 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
695 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
696 let mut interp = Interp {
697 heap,
698 realm: Realm {
699 global,
700 object_proto,
701 function_proto,
702 array_proto,
703 globals: BTreeMap::new(),
704 declared: Vec::new(),
705 lexical_consts: BTreeSet::new(),
706 errors: BTreeMap::new(),
707 string_proto: None,
708 number_proto: None,
709 boolean_proto: None,
710 bigint_proto: None,
711 error_proto: JsObject::ordinary(heap, None),
712 date_proto: JsObject::ordinary(heap, None),
713 generator_proto: JsObject::ordinary(heap, None),
714 promise_proto: None,
715 async_generator_proto: None,
716 symbol_proto: None,
717 symbol_registry: BTreeMap::new(),
718 internal_slots: BTreeMap::new(),
719 regexp_proto: None,
720 regexp_ctor: None,
721 suppressed_error_proto: None,
722 disposable_stack_proto: None,
723 map_proto: None,
724 set_proto: None,
725 finalization_registries: Vec::new(),
726 array_buffer_proto: None,
727 typed_array_proto: None,
728 typed_array_protos: Vec::new(),
729 data_view_proto: None,
730 async_disposable_stack_proto: None,
731 iterator_proto: None,
732 iterator_helper_proto: None,
733 iterator_wrap_proto: None,
734 generator_function_proto: None,
735 async_function_proto: None,
736 async_generator_function_proto: None,
737 iterator_protos: std::collections::BTreeMap::new(),
738 well_known_symbols: WellKnownSymbols::default(),
739 },
740 frames: Vec::new(),
741 eval_scope: None,
742 eval_depth: 0,
743 eval_bindings: Vec::new(),
744 eval_arguments: None,
745 eval_with: None,
746 active_eval_scope: None,
747 eval_caller: None,
748 pending_new_target: None,
749 eval_new_target: None,
750 native_frames: Vec::new(),
751 current_native: None,
752 output: String::new(),
753 max_frames: 4096,
754 jobs: std::collections::VecDeque::new(),
755 modules: std::collections::BTreeMap::new(),
756 module_loader: None,
757 main_module_name: None,
758 module_stack: Vec::new(),
759 unhandled: Vec::new(),
760 };
761 crate::builtins::install(&mut interp);
762 interp
763 }
764
765 // -- allocation helpers -------------------------------------------------
766
767 /// A new string value.
768 /// A `BigInt` value from a computed big integer.
769 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
770 Value::BigInt(Gc::new(self.heap, value))
771 }
772
773 /// A string value from bytes that are already WTF-8, which is how a string with an
774 /// unpaired surrogate reaches a `Value`.
775 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
776 Value::string_wtf8(self.heap, text)
777 }
778
779 /// A new string value, from text that is valid UTF-8.
780 pub fn string(&self, text: impl Into<String>) -> Value {
781 Value::string(self.heap, text)
782 }
783
784 /// A new ordinary object with the given prototype.
785 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
786 JsObject::ordinary(self.heap, proto)
787 }
788
789 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
790 ///
791 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
792 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
793 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
794 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
795 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
796 /// said `[object Object]` instead of `[object Array Iterator]`.
797 ///
798 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
799 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
800 /// its own.
801 pub fn new_iterator_prototype(
802 &mut self,
803 tag: &str,
804 next: crate::object::NativeFn,
805 ) -> Gc<JsObject> {
806 if let Some(existing) = self.realm.iterator_protos.get(tag) {
807 return existing.clone();
808 }
809 let parent = self.realm.iterator_proto.clone();
810 let proto = self.new_object(parent);
811 let next = self.new_native("next", 0, next);
812 proto.define(
813 "next",
814 Property::with_attributes(Value::Object(next), true, false),
815 );
816 let key = self.realm.well_known_key(WellKnown::Iterator);
817 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
818 proto.define_key(
819 &key,
820 Property::with_attributes(Value::Object(identity), true, false),
821 );
822 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
823 let tag_value = self.string(tag);
824 proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
825 self.realm
826 .iterator_protos
827 .insert(tag.to_string(), proto.clone());
828 proto
829 }
830
831 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
832 ///
833 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
834 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
835 /// produced. That is why the two branches are not merged.
836 pub fn object_own_property_keys(
837 &mut self,
838 object: &Gc<JsObject>,
839 ) -> JsResult<Vec<PropertyKey>> {
840 if let Some(keys) = self.proxy_own_keys(object)? {
841 return Ok(keys);
842 }
843 // Integer-like keys ascending, then the string keys in insertion order, then the
844 // symbols — the order every schema that walks an object expects.
845 let entries = object.property_entries();
846 let mut numeric: Vec<u32> = Vec::new();
847 let mut strings: Vec<PropertyKey> = Vec::new();
848 let mut symbols: Vec<PropertyKey> = Vec::new();
849 for (key, _) in entries {
850 match &key {
851 PropertyKey::Symbol(_) => symbols.push(key),
852 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
853 Some(index) => {
854 if !numeric.contains(&index) {
855 numeric.push(index);
856 }
857 }
858 None => strings.push(key),
859 },
860 }
861 }
862 numeric.sort_unstable();
863 let mut keys: Vec<PropertyKey> = numeric
864 .into_iter()
865 .map(|index| PropertyKey::from(index.to_string()))
866 .collect();
867 keys.extend(strings);
868 keys.extend(symbols);
869 Ok(keys)
870 }
871
872 /// The state behind a promise object, or `None` when `object` is not one.
873 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
874 object.with(|data| match &data.kind {
875 ObjectKind::Promise(state) => Some(state.clone()),
876 _ => None,
877 })
878 }
879
880 /// A new pending promise.
881 pub fn new_promise(&mut self) -> Gc<JsObject> {
882 let proto = self.realm.promise_proto.clone();
883 let promise = JsObject::ordinary(self.heap, proto);
884 promise.with_mut(|data| {
885 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
886 crate::object::PromiseState::default(),
887 )));
888 });
889 promise
890 }
891
892 /// Fulfil `promise`, unless it has already settled.
893 ///
894 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
895 /// after `reject`, changes nothing.
896 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
897 let Some(state) = self.promise_state(promise) else {
898 return;
899 };
900 let reactions = {
901 let mut state = state.borrow_mut();
902 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
903 return;
904 }
905 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
906 std::mem::take(&mut state.reactions)
907 };
908 self.queue_reactions(reactions, value, false);
909 }
910
911 /// Reject `promise`, unless it has already settled.
912 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
913 let Some(state) = self.promise_state(promise) else {
914 return;
915 };
916 let reactions = {
917 let mut state = state.borrow_mut();
918 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
919 return;
920 }
921 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
922 std::mem::take(&mut state.reactions)
923 };
924 // Remember it only when nothing is listening *now*; a `then` registered later
925 // prunes the entry in `perform_then`.
926 if reactions.is_empty() {
927 self.unhandled.push((promise.clone(), reason.clone()));
928 }
929 self.queue_reactions(reactions, reason, true);
930 }
931
932 /// Queue one job per reaction.
933 ///
934 /// This is what makes `then` asynchronous even on an already-settled promise:
935 /// `p.then(f); g()` calls `g` first.
936 fn queue_reactions(
937 &mut self,
938 reactions: Vec<crate::object::PromiseReaction>,
939 argument: Value,
940 rejected: bool,
941 ) {
942 for reaction in reactions {
943 let handler = if rejected {
944 reaction.on_rejected.clone()
945 } else {
946 reaction.on_fulfilled.clone()
947 };
948 self.jobs.push_back(Job::Reaction {
949 handler,
950 argument: argument.clone(),
951 rejected,
952 promise: reaction.promise,
953 });
954 }
955 }
956
957 /// `NewPromiseCapability` as the executor receives it: the promise plus its
958 /// resolve/reject pair.
959 ///
960 /// The pair are callable objects rather than Rust closures, because the script gets
961 /// them and may stash them for later.
962 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
963 let promise = self.new_promise();
964 let resolve = JsObject::function(
965 self.heap,
966 Some(self.realm.function_proto.clone()),
967 Callable::PromiseResolve(promise.clone()),
968 );
969 let reject = JsObject::function(
970 self.heap,
971 Some(self.realm.function_proto.clone()),
972 Callable::PromiseReject(promise.clone()),
973 );
974 (promise, Value::Object(resolve), Value::Object(reject))
975 }
976
977 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
978 /// new promise resolved with it.
979 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
980 if let Value::Object(object) = &value
981 && self.promise_state(object).is_some()
982 {
983 return Ok(value);
984 }
985 let promise = self.new_promise();
986 self.resolve_promise_with(&promise, value)?;
987 Ok(Value::Object(promise))
988 }
989
990 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
991 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
992 // Resolving a promise with itself is a `TypeError`. The check exists because the
993 // alternative is a chain of self-reactions that never settles.
994 if let Value::Object(object) = &value
995 && object.ptr_eq(promise)
996 {
997 // The spec rejects *and* throws, so both the promise and the caller see it.
998 let thrown = self.type_error("cannot resolve a promise with itself");
999 let Signal::Throw(error) = thrown.clone() else {
1000 unreachable!("type_error always throws")
1001 };
1002 self.reject_promise(promise, error);
1003 return Err(thrown);
1004 }
1005 let then = match &value {
1006 Value::Object(object) => self.get_property(object, "then")?,
1007 _ => None,
1008 };
1009 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1010 if !callable_then {
1011 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1012 self.fulfill_promise(promise, value);
1013 return Ok(());
1014 }
1015 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1016 // inside `resolve`, so a script cannot make a promise settle synchronously.
1017 self.jobs.push_back(Job::Thenable {
1018 then: then.expect("checked callable"),
1019 value,
1020 promise: promise.clone(),
1021 });
1022 Ok(())
1023 }
1024
1025 /// `Promise.prototype.then`: register a reaction and answer the derived promise.
1026 pub fn perform_then(
1027 &mut self,
1028 promise: &Gc<JsObject>,
1029 on_fulfilled: Option<Value>,
1030 on_rejected: Option<Value>,
1031 ) -> JsResult<Value> {
1032 let Some(state) = self.promise_state(promise) else {
1033 return Err(self.type_error("not a promise"));
1034 };
1035 // Whether a rejection handler is being attached decides whether a recorded
1036 // rejection stops being unhandled, so it is read before the values are moved.
1037 let has_rejection_handler = on_rejected.is_some();
1038 let derived = self.new_promise();
1039 let reaction = crate::object::PromiseReaction {
1040 on_fulfilled,
1041 on_rejected,
1042 promise: derived.clone(),
1043 };
1044 let settled = {
1045 let mut state = state.borrow_mut();
1046 // A rejection somebody reacts to is no longer unhandled.
1047 state.handled = true;
1048 match &state.status {
1049 crate::object::PromiseStatus::Pending => {
1050 state.reactions.push(reaction.clone());
1051 None
1052 }
1053 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1054 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1055 }
1056 };
1057 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1058 // later, means somebody is listening after all.
1059 if has_rejection_handler {
1060 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1061 }
1062 if let Some((argument, rejected)) = settled {
1063 let handler = if rejected {
1064 reaction.on_rejected
1065 } else {
1066 reaction.on_fulfilled
1067 };
1068 self.jobs.push_back(Job::Reaction {
1069 handler,
1070 argument,
1071 rejected,
1072 promise: reaction.promise,
1073 });
1074 }
1075 Ok(Value::Object(derived))
1076 }
1077
1078 /// The rejections nobody listened to, formatted the way the reference reports them.
1079 ///
1080 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
1081 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
1082 /// unhandled at the point the queue drains, because a `then` may still be attached
1083 /// before the host acts on it.
1084 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
1085 let entries = std::mem::take(&mut self.unhandled);
1086 // Somebody may have attached a handler after the rejection was recorded, so the
1087 // promise is the authority rather than the list.
1088 let still_unhandled: Vec<Value> = entries
1089 .into_iter()
1090 .filter_map(|(promise, reason)| {
1091 let handled = self
1092 .promise_state(&promise)
1093 .map(|state| state.borrow().handled)
1094 .unwrap_or(true);
1095 (!handled).then_some(reason)
1096 })
1097 .collect();
1098 still_unhandled
1099 .into_iter()
1100 .map(|reason| {
1101 let text = self.describe_exception(&reason);
1102 let stack = match &reason {
1103 Value::Object(object) => self
1104 .get_property(object, "stack")
1105 .ok()
1106 .flatten()
1107 .map(|value| value.to_js_string())
1108 // `stack` carries a trailing newline of its own, which would leave
1109 // a blank line between two reported rejections.
1110 .map(|text| text.trim_end().to_string())
1111 .unwrap_or_default(),
1112 _ => String::new(),
1113 };
1114 if stack.is_empty() {
1115 format!("Possibly unhandled promise rejection: {text}")
1116 } else {
1117 format!("Possibly unhandled promise rejection: {text}\n{stack}")
1118 }
1119 })
1120 .collect()
1121 }
1122
1123 /// Run the microtask queue to exhaustion.
1124 ///
1125 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
1126 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
1127 pub fn drain_jobs(&mut self) -> JsResult<()> {
1128 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
1129 // would spin forever, so the drain is bounded the way the call stack is.
1130 let mut budget = 1_000_000usize;
1131 while let Some(job) = self.jobs.pop_front() {
1132 if budget == 0 {
1133 return Err(Signal::Throw(
1134 self.make_error("InternalError", "promise job queue did not drain"),
1135 ));
1136 }
1137 budget -= 1;
1138 self.run_job(job)?;
1139 // `FinalizationRegistry` at the job boundary: this is the safe point where the
1140 // engine may run script that the script itself did not ask for. Doing it here
1141 // rather than from a drop hook is what keeps the callback out of arbitrary
1142 // engine bookkeeping — see `builtins::weak`'s header.
1143 crate::builtins::weak::drain_finalizers(self)?;
1144 }
1145 // A script that queued no jobs may still have dropped targets, so the checkpoint
1146 // runs once more after the queue empties.
1147 crate::builtins::weak::drain_finalizers(self)?;
1148 Ok(())
1149 }
1150
1151 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
1152 ///
1153 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
1154 /// `None` and is swept out here. This is also where the realm learns that a registry
1155 /// died, which is why it is a mutation rather than a read.
1156 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
1157 let handles = std::mem::take(&mut self.realm.finalization_registries);
1158 let mut live = Vec::with_capacity(handles.len());
1159 for handle in handles {
1160 let Some(object) = handle.upgrade() else {
1161 continue;
1162 };
1163 let Some(state) = object.finalization_state() else {
1164 continue;
1165 };
1166 live.push((object.clone(), *state));
1167 self.realm.finalization_registries.push(object.downgrade());
1168 }
1169 live
1170 }
1171
1172 /// Run one microtask.
1173 fn run_job(&mut self, job: Job) -> JsResult<()> {
1174 match job {
1175 Job::Reaction {
1176 handler: None,
1177 argument,
1178 rejected,
1179 promise,
1180 } => {
1181 // No handler: the settlement passes straight through to the derived
1182 // promise, which is why `p.catch(f)` ignores fulfilments.
1183 if rejected {
1184 self.reject_promise(&promise, argument);
1185 } else {
1186 self.fulfill_promise(&promise, argument);
1187 }
1188 Ok(())
1189 }
1190 Job::Reaction {
1191 handler: Some(handler),
1192 argument,
1193 promise,
1194 ..
1195 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
1196 Ok(answer) => {
1197 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
1198 self.reject_promise(&promise, error);
1199 }
1200 Ok(())
1201 }
1202 Err(Signal::Throw(reason)) => {
1203 self.reject_promise(&promise, reason);
1204 Ok(())
1205 }
1206 Err(other) => Err(other),
1207 },
1208 Job::Thenable {
1209 then,
1210 value,
1211 promise,
1212 } => {
1213 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
1214 // the value it produces settles `promise`.
1215 // The thenable's `then` gets this promise's own pair, so whatever it
1216 // produces settles `promise`.
1217 let resolve = JsObject::function(
1218 self.heap,
1219 Some(self.realm.function_proto.clone()),
1220 Callable::PromiseResolve(promise.clone()),
1221 );
1222 let reject = JsObject::function(
1223 self.heap,
1224 Some(self.realm.function_proto.clone()),
1225 Callable::PromiseReject(promise.clone()),
1226 );
1227 match self.call_value(
1228 then,
1229 value,
1230 vec![Value::Object(resolve), Value::Object(reject)],
1231 ) {
1232 Ok(_) => Ok(()),
1233 Err(Signal::Throw(reason)) => {
1234 self.reject_promise(&promise, reason);
1235 Ok(())
1236 }
1237 Err(other) => Err(other),
1238 }
1239 }
1240 Job::Resume {
1241 coroutine,
1242 promise,
1243 kind,
1244 value,
1245 } => self.drive_async(&coroutine, &promise, kind, value),
1246 Job::GeneratorResume {
1247 generator,
1248 promise,
1249 kind,
1250 value,
1251 } => self.step_async_generator(&generator, &promise, kind, value),
1252 Job::Import {
1253 specifier,
1254 referrer,
1255 promise,
1256 } => {
1257 self.run_dynamic_import(&specifier, &referrer, &promise);
1258 Ok(())
1259 }
1260 }
1261 }
1262
1263 /// One element of a `Promise` combinator settled.
1264 ///
1265 /// The shared state object holds the results array, the number still outstanding, and
1266 /// the combinator's own resolve/reject pair. `all` fills by index so the answer keeps
1267 /// the input order; `race` settles on the first element and ignores the rest, which a
1268 /// one-shot settle gives for free.
1269 fn settle_combinator(
1270 &mut self,
1271 state: &Gc<JsObject>,
1272 index: usize,
1273 fulfilled: bool,
1274 value: Value,
1275 ) -> JsResult<()> {
1276 let kind = state
1277 .own_property("kind")
1278 .and_then(|property| property.value)
1279 .map(|value| value.to_int32())
1280 .unwrap_or(0);
1281 let outcome = state
1282 .own_property("outcome")
1283 .and_then(|property| property.value);
1284 let Some(Value::Object(outcome)) = outcome else {
1285 return Ok(());
1286 };
1287 if kind == 3 {
1288 // `race`: the first settlement wins; the rest are ignored by the one-shot rule.
1289 if fulfilled {
1290 self.resolve_promise_with(&outcome, value)?;
1291 } else {
1292 self.reject_promise(&outcome, value);
1293 }
1294 return Ok(());
1295 }
1296 let results = state
1297 .own_property("results")
1298 .and_then(|property| property.value)
1299 .and_then(|value| value.as_object().cloned());
1300 let remaining = state
1301 .own_property("remaining")
1302 .and_then(|property| property.value)
1303 .map(|value| value.to_int32())
1304 .unwrap_or(0);
1305 match kind {
1306 0 => {
1307 // `all`: the first rejection wins outright.
1308 if !fulfilled {
1309 self.reject_promise(&outcome, value);
1310 return Ok(());
1311 }
1312 let Some(results) = &results else {
1313 return Ok(());
1314 };
1315 results.array_set(index, value);
1316 }
1317 1 => {
1318 // `allSettled`: never rejects; each slot records what happened.
1319 let Some(results) = &results else {
1320 return Ok(());
1321 };
1322 let record = self.new_object(Some(self.realm.object_proto.clone()));
1323 if fulfilled {
1324 record.define_data("status", self.string("fulfilled"));
1325 record.define_data("value", value);
1326 } else {
1327 record.define_data("status", self.string("rejected"));
1328 record.define_data("reason", value);
1329 }
1330 results.array_set(index, Value::Object(record));
1331 }
1332 2 => {
1333 // `any`: the first fulfilment wins; a full sweep of rejections does not
1334 // settle here — it is handled by the count below.
1335 if fulfilled {
1336 self.resolve_promise_with(&outcome, value)?;
1337 return Ok(());
1338 }
1339 }
1340 _ => {}
1341 }
1342 let left = remaining - 1;
1343 state.define_data("remaining", Value::Int(left));
1344 if left != 0 {
1345 return Ok(());
1346 }
1347 match kind {
1348 0 | 1 => {
1349 let Some(results) = results else {
1350 return Ok(());
1351 };
1352 self.resolve_promise_with(&outcome, Value::Object(results))?;
1353 }
1354 2 => {
1355 let error = self.make_error("AggregateError", "all promises were rejected");
1356 self.reject_promise(&outcome, error);
1357 }
1358 _ => {}
1359 }
1360 Ok(())
1361 }
1362
1363 /// Build an async function's result: a promise whose body runs as a coroutine.
1364 pub fn new_async_function(
1365 &mut self,
1366 function: Value,
1367 this: Value,
1368 args: Vec<Value>,
1369 ) -> JsResult<Value> {
1370 let promise = self.new_promise();
1371 let coroutine = self.new_coroutine(function, this, args)?;
1372 if let Err(Signal::Throw(reason)) =
1373 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1374 {
1375 self.reject_promise(&promise, reason);
1376 }
1377 Ok(Value::Object(promise))
1378 }
1379
1380 /// The coroutine an async body runs in.
1381 ///
1382 /// Generator-shaped and never exposed to the script: what makes `await` work is the
1383 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
1384 /// than growing a second state machine. The difference is only in the ending — a
1385 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
1386 /// Run `code` as an async function body, answering the promise it settles.
1387 ///
1388 /// Used for a module with top-level `await`: its body is an async function whose
1389 /// caller is the host, so there is no function object to pass through
1390 /// [`Interp::new_async_function`].
1391 pub fn run_async_body(
1392 &mut self,
1393 code: Gc<CompiledCode>,
1394 env: Gc<ClosureEnv>,
1395 ) -> JsResult<Value> {
1396 let promise = self.new_promise();
1397 let coroutine = self.new_coroutine_from(code, env, Value::Undefined, Vec::new())?;
1398 if let Err(Signal::Throw(reason)) =
1399 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1400 {
1401 self.reject_promise(&promise, reason);
1402 }
1403 Ok(Value::Object(promise))
1404 }
1405
1406 fn new_coroutine(
1407 &mut self,
1408 function: Value,
1409 this: Value,
1410 args: Vec<Value>,
1411 ) -> JsResult<Gc<JsObject>> {
1412 let Some(object) = function.as_object().cloned() else {
1413 return Err(self.type_error("not a function"));
1414 };
1415 let Some((code, env)) = bytecode_of(&object) else {
1416 return Err(self.type_error("not a function"));
1417 };
1418 self.new_coroutine_from(code, env, this, args)
1419 }
1420
1421 /// Build a coroutine over an already-resolved body.
1422 fn new_coroutine_from(
1423 &mut self,
1424 code: Gc<CompiledCode>,
1425 env: Gc<ClosureEnv>,
1426 this: Value,
1427 args: Vec<Value>,
1428 ) -> JsResult<Gc<JsObject>> {
1429 let function = Value::Undefined;
1430 self.push_frame(code, env, this, args, function)?;
1431 let frame = self.frames.pop().expect("push_frame just pushed it");
1432 let state = GeneratorState {
1433 frame: Some(frame),
1434 phase: GeneratorPhase::SuspendedStart,
1435 parked_on_await: false,
1436 };
1437 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
1438 coroutine.with_mut(|data| {
1439 data.kind = ObjectKind::Generator(Box::new(state));
1440 });
1441 Ok(coroutine)
1442 }
1443
1444 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
1445 /// `await` and `value` is what it awaited.
1446 fn resume_coroutine(
1447 &mut self,
1448 coroutine: &Gc<JsObject>,
1449 kind: ResumeKind,
1450 value: Value,
1451 ) -> JsResult<(Value, bool)> {
1452 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
1453 ObjectKind::Generator(state) => Some(std::mem::replace(
1454 state.as_mut(),
1455 GeneratorState {
1456 frame: None,
1457 phase: GeneratorPhase::Executing,
1458 parked_on_await: false,
1459 },
1460 )),
1461 _ => None,
1462 }) else {
1463 return Err(self.type_error("not a coroutine"));
1464 };
1465 let result = self.step_generator(&mut state, kind, value);
1466 coroutine.with_mut(|data| {
1467 data.kind = ObjectKind::Generator(Box::new(state));
1468 });
1469 let (value, done, _ready, _reason) = result?;
1470 Ok((value, done))
1471 }
1472
1473 /// Advance an async body and settle its promise with the outcome.
1474 fn drive_async(
1475 &mut self,
1476 coroutine: &Gc<JsObject>,
1477 promise: &Gc<JsObject>,
1478 kind: ResumeKind,
1479 value: Value,
1480 ) -> JsResult<()> {
1481 match self.resume_coroutine(coroutine, kind, value) {
1482 Ok((value, true)) => {
1483 // `Ok` with `done` means the body finished *normally*, even when it was
1484 // resumed by a `throw` — `try { await p } catch {}` completes by
1485 // returning. Only the `Err` arm below is a rejection.
1486 //
1487 // Resolving rather than fulfilling matters: `return promise` in an async
1488 // body adopts the inner promise, so `async function f(){ return
1489 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
1490 // promise.
1491 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
1492 self.reject_promise(promise, reason);
1493 }
1494 Ok(())
1495 }
1496 Ok((value, false)) => {
1497 // Parked on `await`: follow what it awaited and resume with the outcome.
1498 let awaited = match self.promise_resolve_value(value) {
1499 Ok(awaited) => awaited,
1500 Err(Signal::Throw(error)) => {
1501 self.reject_promise(promise, error);
1502 return Ok(());
1503 }
1504 Err(other) => return Err(other),
1505 };
1506 self.hook_await(awaited, coroutine, promise)
1507 }
1508 Err(Signal::Throw(reason)) => {
1509 self.reject_promise(promise, reason);
1510 Ok(())
1511 }
1512 Err(other) => Err(other),
1513 }
1514 }
1515
1516 /// Arrange for `coroutine` to resume when `awaited` settles.
1517 fn hook_await(
1518 &mut self,
1519 awaited: Value,
1520 coroutine: &Gc<JsObject>,
1521 promise: &Gc<JsObject>,
1522 ) -> JsResult<()> {
1523 let resumed = JsObject::function(
1524 self.heap,
1525 Some(self.realm.function_proto.clone()),
1526 Callable::AwaitResume {
1527 coroutine: coroutine.clone(),
1528 promise: promise.clone(),
1529 kind: ResumeKind::Next,
1530 },
1531 );
1532 let raised = JsObject::function(
1533 self.heap,
1534 Some(self.realm.function_proto.clone()),
1535 Callable::AwaitResume {
1536 coroutine: coroutine.clone(),
1537 promise: promise.clone(),
1538 kind: ResumeKind::Throw,
1539 },
1540 );
1541 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
1542 // guarantees one; the fallback keeps a mis-shaped value from panicking.
1543 let Value::Object(awaited) = &awaited else {
1544 self.jobs.push_back(Job::Resume {
1545 coroutine: coroutine.clone(),
1546 promise: promise.clone(),
1547 kind: ResumeKind::Next,
1548 value: awaited,
1549 });
1550 return Ok(());
1551 };
1552 self.perform_then(
1553 awaited,
1554 Some(Value::Object(resumed)),
1555 Some(Value::Object(raised)),
1556 )?;
1557 Ok(())
1558 }
1559
1560 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
1561 /// things an engine keeps outside it — array elements and an array's `length`.
1562 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
1563 if let Some(property) = object.own_property_key(key) {
1564 return Some(property);
1565 }
1566 // An array's elements live in their own vector rather than the property table, so
1567 // a descriptor for one has to be synthesized — with the attributes an element has.
1568 if let Some(index) = key.as_str().and_then(array_index)
1569 && let Some(value) = object.array_get(index as usize)
1570 && !matches!(value, Value::Hole)
1571 {
1572 return Some(Property::data(value));
1573 }
1574 // `length` is an own property of an array that is not in its property table
1575 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
1576 // and non-enumerable.
1577 if key.as_str() == Some("length")
1578 && let Some(length) = object.array_length()
1579 {
1580 return Some(Property {
1581 value: Some(crate::object::length_value(length)),
1582 writable: object.length_writable(),
1583 enumerable: false,
1584 configurable: false,
1585 getter: None,
1586 setter: None,
1587 });
1588 }
1589 None
1590 }
1591
1592 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
1593 pub fn object_get_own_property(
1594 &mut self,
1595 object: &Gc<JsObject>,
1596 key: &PropertyKey,
1597 ) -> JsResult<Option<Property>> {
1598 if let Some(answer) = self.proxy_get_own_property(object, key)? {
1599 return Ok(answer);
1600 }
1601 Ok(Self::ordinary_own_property(object, key))
1602 }
1603
1604 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
1605 pub fn object_define_own_property(
1606 &mut self,
1607 object: &Gc<JsObject>,
1608 key: &PropertyKey,
1609 property: Property,
1610 ) -> JsResult<bool> {
1611 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
1612 return Ok(accepted);
1613 }
1614 // An array index is stored in the element vector, which can hold a plain value and
1615 // nothing else. An accessor — or a data property with non-default attributes —
1616 // therefore has to live in the property table, and the element slot is blanked so
1617 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
1618 // {get})` stored the accessor where no read ever looked, and the array kept
1619 // answering its old value.
1620 // An array's `length` is not stored in the property table, so defining it has to
1621 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
1622 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
1623 // {value: 1})` reported success and changed nothing.
1624 if key.as_str() == Some("length") && object.is_array() {
1625 // `{writable: false}` on `length` does not change the length, but it does make
1626 // it read-only — after which neither a later `{writable: true}` nor a store
1627 // past the end may succeed.
1628 if property.value.is_none() {
1629 if !object.length_writable() && property.writable {
1630 return Ok(false);
1631 }
1632 object.set_length_writable(property.writable);
1633 return Ok(true);
1634 }
1635 if !object.length_writable() {
1636 return Ok(false);
1637 }
1638 }
1639 if key.as_str() == Some("length")
1640 && object.is_array()
1641 && let Some(value) = property.value.clone()
1642 {
1643 let requested = value.to_number();
1644 let valid = requested.is_finite()
1645 && requested >= 0.0
1646 && requested.fract() == 0.0
1647 && requested <= u32::MAX as f64;
1648 if !valid {
1649 return Err(self.range_error("invalid array length"));
1650 }
1651 // Truncating deletes the elements above the new length, and a non-configurable
1652 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
1653 // makes `a.length = 2` fail rather than quietly drop it.
1654 let current = object.array_length().unwrap_or(0);
1655 let requested = requested as usize;
1656 if requested < current
1657 && (requested..current).any(|index| object.element_is_undeletable(index as u32))
1658 {
1659 return Ok(false);
1660 }
1661 object.array_set_length(requested);
1662 return Ok(true);
1663 }
1664 let plain = property.writable
1665 && property.enumerable
1666 && property.configurable
1667 && !property.is_accessor();
1668 if let Some(index) = key.as_str().and_then(array_index)
1669 && object.is_array()
1670 {
1671 // Growing the array needs a writable `length`: after
1672 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
1673 // be added.
1674 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
1675 return Ok(false);
1676 }
1677 if plain && let Some(value) = property.value {
1678 // An ordinary element: the vector is where a read looks first, so it has
1679 // to be the vector that changes.
1680 object.delete_key(key);
1681 object.array_set(index as usize, value);
1682 return Ok(true);
1683 }
1684 object.define_key(key, property);
1685 // The slot stays, so `length` does not shrink; a hole is not an element, so
1686 // the table entry is now what a read finds.
1687 object.array_set(index as usize, Value::Hole);
1688 return Ok(true);
1689 }
1690 object.define_key(key, property);
1691 Ok(true)
1692 }
1693
1694 /// Build a proxy object over `target`, with its traps read from `handler`.
1695 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
1696 JsObject::proxy(self.heap, target, handler)
1697 }
1698
1699 /// The `revoke` function for a proxy's slots.
1700 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
1701 JsObject::function(
1702 self.heap,
1703 Some(self.realm.function_proto.clone()),
1704 Callable::Revoker(slots),
1705 )
1706 }
1707
1708 /// A new array.
1709 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
1710 let array = JsObject::array(
1711 self.heap,
1712 Some(self.realm.array_proto.clone()),
1713 elements.len(),
1714 );
1715 for (index, element) in elements.into_iter().enumerate() {
1716 array.array_set(index, element);
1717 }
1718 array
1719 }
1720
1721 /// A new native function object.
1722 ///
1723 /// The observable `name` and `length` are installed as properties here, which is
1724 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
1725 /// so `f.name = "x"` behaves like the writable property it is.
1726 /// A native constructor that builds its own instance after validating its arguments.
1727 ///
1728 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
1729 /// check runs before `new.target.prototype` is read.
1730 pub fn new_native_ctor(
1731 &self,
1732 name: impl Into<String>,
1733 length: u32,
1734 func: NativeFn,
1735 ) -> Gc<JsObject> {
1736 let function = JsObject::function(
1737 self.heap,
1738 Some(self.realm.function_proto.clone()),
1739 Callable::Native {
1740 func,
1741 own_instance: true,
1742 },
1743 );
1744 function.set_constructible(true);
1745 function.define(
1746 "length",
1747 Property::name_or_length(Value::Int(length as i32)),
1748 );
1749 function.define("name", Property::name_or_length(self.string(name)));
1750 function
1751 }
1752
1753 /// A native constructor that lets `new` build the instance first.
1754 ///
1755 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
1756 /// validation that must precede reading `new.target.prototype`, so the object can be
1757 /// created before the implementation runs. Distinct from [`Interp::new_native`],
1758 /// which makes a *method* and therefore not a constructor at all.
1759 pub fn new_native_constructor(
1760 &self,
1761 name: impl Into<String>,
1762 length: u32,
1763 func: NativeFn,
1764 ) -> Gc<JsObject> {
1765 let function = self.new_native(name, length, func);
1766 function.set_constructible(true);
1767 function
1768 }
1769
1770 /// A new native function object.
1771 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
1772 let function = JsObject::function(
1773 self.heap,
1774 Some(self.realm.function_proto.clone()),
1775 Callable::Native {
1776 func,
1777 own_instance: false,
1778 },
1779 );
1780 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
1781 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
1782 // `length,name` and this listed `name,length`. A bytecode function already gets it
1783 // the right way round; only native ones were built backwards.
1784 function.define(
1785 "length",
1786 Property::name_or_length(Value::Int(length as i32)),
1787 );
1788 function.define("name", Property::name_or_length(self.string(name)));
1789 function
1790 }
1791
1792 /// A new bound function.
1793 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
1794 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
1795 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
1796 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
1797 let constructible = target
1798 .as_object()
1799 .is_some_and(|target| target.is_constructor());
1800 let bound = JsObject::function(
1801 self.heap,
1802 Some(self.realm.function_proto.clone()),
1803 Callable::Bound { target, this, args },
1804 );
1805 bound.set_constructible(constructible);
1806 bound
1807 }
1808
1809 /// A new reference cell.
1810 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
1811 Gc::new(self.heap, Cell::new(value))
1812 }
1813
1814 // -- running ------------------------------------------------------------
1815
1816 /// Evaluate `code` as a script body and return its completion value.
1817 /// Compile and run `source` for the engine's own use, returning its completion value.
1818 ///
1819 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
1820 /// needs to be a real async function, and the engine already runs those as coroutines,
1821 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
1822 ///
1823 /// Differences from [`Self::eval_in_global`], both deliberate:
1824 ///
1825 /// * It does **not** drain the microtask queue. Install runs while the realm is still
1826 /// being built, and the source is an IIFE that only constructs a closure, so there
1827 /// is nothing to drain — and draining here would run script-queued jobs in the
1828 /// middle of `install`.
1829 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
1830 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
1831 /// and it should not look like the user wrote something wrong.
1832 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
1833 let program = match js_parse::parse_script(source) {
1834 Ok(program) => program,
1835 Err(error) => {
1836 let message = format!("builtin source does not parse: {error}");
1837 return Err(Signal::Throw(self.make_error("InternalError", &message)));
1838 }
1839 };
1840 let mut code = match js_compile::compile_script(&program) {
1841 Ok(code) => code,
1842 Err(error) => {
1843 let message = format!("builtin source does not compile: {}", error.message);
1844 return Err(Signal::Throw(self.make_error("InternalError", &message)));
1845 }
1846 };
1847 // The frame has to name something, and `<builtin>` is what a stack trace through
1848 // this code should say.
1849 code.set_filename("<builtin>");
1850 let compiled = Gc::new(self.heap, CompiledCode::new(code));
1851 let closure_vars = compiled.code.closure_vars.clone();
1852 let env = self.global_env(&closure_vars);
1853 let this = Value::Object(self.realm.global.clone());
1854 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
1855 }
1856
1857 /// Run an already-parsed script and drain the microtasks it queued.
1858 ///
1859 /// The drain is what lets an `async` function's body advance past its first `await`
1860 /// before the host sees the result: nothing else pumps the job queue.
1861 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
1862 let compiled = Gc::new(self.heap, CompiledCode::new(code));
1863 let closure_vars = compiled.code.closure_vars.clone();
1864 let env = self.global_env(&closure_vars);
1865 let this = Value::Object(self.realm.global.clone());
1866 let callee = Value::Undefined;
1867 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
1868 // The script is done, so the microtasks it queued run before the host sees the
1869 // result. Without this an `async` function's body would never advance past its
1870 // first `await`, because nothing else drains the queue.
1871 self.drain_jobs()?;
1872 Ok(result)
1873 }
1874
1875 /// Compile and run `source` in global scope, returning its completion value.
1876 ///
1877 /// This is what `eval` and `new Function` use. Running it as a script means it
1878 /// sees the global object and nothing else, which is right for `eval("1+1")` and
1879 /// for a `Function` body; a *direct* eval that reads a local variable would need
1880 /// the compiler to hand its variable environment over, which is not implemented.
1881 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
1882 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
1883 // eval-created global binding — configurable, unlike a script's own `var`.
1884 self.eval_depth += 1;
1885 let result = self.eval_in_global_inner(source);
1886 self.eval_depth -= 1;
1887 result
1888 }
1889
1890 fn eval_in_global_inner(&mut self, source: &str) -> JsResult<Value> {
1891 // The reference names eval'd code `<input>` rather than inheriting the caller's
1892 // file name, and stack traces show it, so `eval("1 + x")` failing reports
1893 // `(<input>:1:5)`.
1894 const EVAL_FILE: &str = "<input>";
1895 // A *direct* eval inherits the strictness of the code that called it, which is
1896 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
1897 // implicit global. The caller's frame is the innermost one here, because a
1898 // native function does not push a frame of its own.
1899 let strict = self.current_strict();
1900 // `eval` runs in the caller's function context, so `new.target` is legal here
1901 // even though the source is a bare script — and so is `super.x` when the caller
1902 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
1903 // caller's, which is what `special_object 4` already does.
1904 let context = js_parse::EvalContext {
1905 in_method: self.enclosing_home_object().is_some(),
1906 // `super()` belongs to a derived constructor, and an eval'd body is not a
1907 // constructor at all: the caller frame's `this` is already built.
1908 in_derived_constructor: false,
1909 };
1910 let parsed = js_parse::parse_eval_script_in(source, strict, context);
1911 let program = match parsed {
1912 Ok(program) => program,
1913 Err(error) => {
1914 return Err(Signal::Throw(self.syntax_error_at(
1915 EVAL_FILE,
1916 error.span.start.line,
1917 error.span.start.column,
1918 &format!("invalid source: {error}"),
1919 )));
1920 }
1921 };
1922 let mut compiled = match js_compile::compile_script(&program) {
1923 Ok(compiled) => compiled,
1924 // A construct the compiler does not handle yet is reported the same way a
1925 // parse error is: it happens before anything runs, so the trace is the
1926 // position in the source followed by the caller.
1927 Err(error) => {
1928 return Err(Signal::Throw(self.syntax_error_at(
1929 EVAL_FILE,
1930 error.span.start.line,
1931 error.span.start.column,
1932 &error.message,
1933 )));
1934 }
1935 };
1936 compiled.set_filename(EVAL_FILE);
1937 let strict = compiled.strict;
1938 self.run_eval_script(compiled, strict)
1939 }
1940
1941 /// Run an `eval`'d script in the caller's scope.
1942 ///
1943 /// Three things have to come from the calling frame, because the eval'd code is a
1944 /// script and would otherwise see only the global object:
1945 ///
1946 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
1947 /// * `arguments`, exposed as a binding of the eval's own scope, so
1948 /// `f("arguments.length", 1)` sees the caller's arguments;
1949 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
1950 /// `eval("var v = 1")` into the global object.
1951 ///
1952 /// Locals of the calling function are *not* reachable: that needs the compiler to
1953 /// hand its variable environment over, which this milestone does not do.
1954 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
1955 // `this` and `arguments` come from the innermost frame only — those are not
1956 // lexical — while the name bindings come from the whole chain of frames, part
1957 // of it being ordinary scope resolution.
1958 // An arrow has no `this` of its own, so an `eval` inside one inherits the
1959 // enclosing function's receiver — the lexical `this` the arrow was compiled to
1960 // read from its closure.
1961 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
1962 // variable environment is the innermost frame of all: an arrow's own body is where
1963 // `var`s declared by an `eval` inside it belong.
1964 let caller_index = self
1965 .frames
1966 .iter()
1967 .rposition(|frame| !frame.code.code.is_arrow)
1968 .or_else(|| self.frames.len().checked_sub(1));
1969 let env_index = self.frames.len().checked_sub(1);
1970 let caller = caller_index.and_then(|index| self.frames.get(index));
1971 let (this, passed) = match caller {
1972 Some(frame) => (frame.this.clone(), frame.passed.clone()),
1973 // No frame at all: the eval is running at the top level, so there is
1974 // nothing to inherit and the global receiver is right.
1975 None => (Value::Object(self.realm.global.clone()), Vec::new()),
1976 };
1977 // Innermost frame first, so the first binding found for a name is the one that
1978 // shadows the rest. A script frame (`<eval>`) contributes nothing.
1979 let mut bindings: Vec<EvalBinding> = Vec::new();
1980 // The calling function's own bindings, resolved by the compiler at the call
1981 // site. That table is the only reliable answer when a name is declared twice in
1982 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
1983 // body means, and guessing by declaration order picks the wrong one as soon as
1984 // two loops in a row use the same name.
1985 // Only a *direct* eval sees the caller's scope. The compiler records a site for
1986 // every direct call — a bare `eval(...)` callee — so finding one at the current
1987 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
1988 // callee to a value first and leave no site behind.
1989 let mut direct = false;
1990 let mut resolved_here = false;
1991 if let Some(frame) = self.frames.last() {
1992 let (line, column) = frame
1993 .code
1994 .code
1995 .position_at(frame.at as u32)
1996 .unwrap_or_default();
1997 // The nearest site at or before the current position, not an exact match:
1998 // the recorded position of the `call` instruction is the callee's, which
1999 // sits a few columns inside the call expression the compiler recorded. A
2000 // site is unique per call, so "the closest one behind us" identifies it.
2001 if let Some(site) = frame
2002 .code
2003 .code
2004 .eval_sites
2005 .iter()
2006 .filter(|site| (site.line, site.column) <= (line, column))
2007 .max_by_key(|site| (site.line, site.column))
2008 {
2009 direct = true;
2010 resolved_here = true;
2011 for binding in &site.bindings {
2012 // An enclosing function's frame sits `owner` levels below the one
2013 // running the call.
2014 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
2015 else {
2016 continue;
2017 };
2018 bindings.push(EvalBinding {
2019 name: binding.name.clone(),
2020 frame,
2021 slot: if binding.is_arg {
2022 EvalSlot::Arg
2023 } else {
2024 EvalSlot::Local
2025 },
2026 index: binding.index as usize,
2027 });
2028 }
2029 }
2030 }
2031 for frame_index in (0..self.frames.len()).rev() {
2032 // Skip the innermost frame's flat scan when the compiler already answered
2033 // for it; an enclosing frame still needs one, because the eval resolves
2034 // those names dynamically.
2035 if resolved_here && frame_index == self.frames.len() - 1 {
2036 continue;
2037 }
2038 let frame = &self.frames[frame_index];
2039 for (index, arg) in frame.code.code.args.iter().enumerate() {
2040 bindings.push(EvalBinding {
2041 name: arg.name.clone(),
2042 frame: frame_index,
2043 slot: EvalSlot::Arg,
2044 index,
2045 });
2046 }
2047 for (index, local) in frame.code.code.vars.iter().enumerate() {
2048 bindings.push(EvalBinding {
2049 name: local.name.clone(),
2050 frame: frame_index,
2051 slot: EvalSlot::Local,
2052 index,
2053 });
2054 }
2055 }
2056 let mut seen = BTreeSet::new();
2057 bindings.retain(|binding| seen.insert(binding.name.clone()));
2058
2059 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
2060 // elements is all the spec's ordinary uses need.
2061 let arguments = Value::Object(self.new_array(passed));
2062
2063 // Only a *strict* eval gets a variable environment of its own. A sloppy one
2064 // declares its `var`s in the caller's — which for a top-level eval is the global
2065 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
2066 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
2067 // vanish into a scope nobody reads back from.
2068 let previous_scope = if code_strict {
2069 self.eval_scope.replace(BTreeMap::new())
2070 } else {
2071 None
2072 };
2073 let previous_arguments = self.eval_arguments.replace(arguments);
2074 let previous_with = self.eval_with.replace(self.with_objects());
2075 let inherited_new_target = self
2076 .frames
2077 .iter()
2078 .rev()
2079 .find(|frame| !frame.code.code.is_arrow)
2080 .map(|frame| frame.new_target.clone());
2081 let previous_new_target = self
2082 .eval_new_target
2083 .replace(inherited_new_target.unwrap_or(Value::Undefined));
2084 let eval_cells = self.eval_cells_for(&bindings);
2085 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
2086 // A sloppy direct eval declares its `var`s in the caller's variable environment;
2087 // `declare_eval_local` needs to know which frame that is.
2088 // An indirect eval gets the global environment, so nothing of the caller's is
2089 // recorded as the place its `var`s belong.
2090 let previous_caller = self
2091 .eval_caller
2092 .replace(if direct { env_index } else { None });
2093 // The cell-based view of the same bindings, which is what a closure created
2094 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
2095 // whose compiler did not put a binding in a cell simply does not appear here —
2096 // reads and writes still work through `eval_bindings`, they just cannot outlive
2097 // the eval.
2098 let previous_eval_scope = self
2099 .active_eval_scope
2100 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
2101 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2102 let closure_vars = compiled.code.closure_vars.clone();
2103 let env = self.global_env(&closure_vars);
2104 let callee = Value::Undefined;
2105 let result = self.execute(compiled, env, this, Vec::new(), callee);
2106 self.eval_scope = previous_scope;
2107 self.eval_arguments = previous_arguments;
2108 self.eval_with = previous_with;
2109 self.eval_new_target = previous_new_target;
2110 self.eval_bindings = previous_bindings;
2111 self.eval_caller = previous_caller;
2112 self.active_eval_scope = previous_eval_scope;
2113 result
2114 }
2115
2116 /// The cell-backed subset of `bindings`, in the same priority order.
2117 ///
2118 /// Both lookup routes have to agree — the eval's own reads go through
2119 /// [`Interp::eval_binding_value`] and the closures it builds go through
2120 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
2121 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
2122 /// is not in a cell simply does not appear: reads and writes still work, they just
2123 /// cannot be handed to a closure that outlives the eval.
2124 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
2125 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
2126 for binding in bindings {
2127 let Some(frame) = self.frames.get(binding.frame) else {
2128 continue;
2129 };
2130 let cell = match binding.slot {
2131 EvalSlot::Arg => frame
2132 .code
2133 .arg_cell
2134 .get(binding.index)
2135 .copied()
2136 .unwrap_or(-1),
2137 EvalSlot::Local => frame
2138 .code
2139 .loc_cell
2140 .get(binding.index)
2141 .copied()
2142 .unwrap_or(-1),
2143 };
2144 if cell < 0 {
2145 continue;
2146 }
2147 if let Some(cell) = frame.cells.get(cell as usize) {
2148 names.push((binding.name.clone(), cell.clone()));
2149 }
2150 }
2151 names
2152 }
2153
2154 /// A `SyntaxError` that reports where in the source it happened.
2155 ///
2156 /// Compile-time failures never run, so they have no frame of their own; the
2157 /// reference still puts the position first in the trace, with no function name and
2158 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
2159 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
2160 /// reference borrows), which is how a script reads the position without parsing
2161 /// the trace.
2162 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
2163 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
2164 let value = self.make_error("SyntaxError", message);
2165 if let Value::Object(object) = &value {
2166 let text = self.string(blamed);
2167 object.define("stack", Property::with_attributes(text, true, true));
2168 let name = self.string(file);
2169 object.define("fileName", Property::with_attributes(name, true, true));
2170 object.define(
2171 "lineNumber",
2172 Property::with_attributes(Value::Int(line as i32), true, true),
2173 );
2174 object.define(
2175 "columnNumber",
2176 Property::with_attributes(Value::Int(column as i32), true, true),
2177 );
2178 }
2179 value
2180 }
2181
2182 /// Run a compiled script whose completion value is a function, returning it.
2183 ///
2184 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
2185 /// get the closure out, which keeps the constant-pool plumbing in one place.
2186 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
2187 self.run_script(code)
2188 }
2189
2190 /// The environment of a script or of any function compiled at global scope:
2191 /// every entry is a global binding, so each one resolves to the realm's cell.
2192 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
2193 let mut cells = Vec::with_capacity(closure_vars.len());
2194 for closure_var in closure_vars {
2195 let cell = match closure_var.closure_type {
2196 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
2197 if closure_var.is_lexical =>
2198 {
2199 // A lexical declaration: the cell is created here holding the
2200 // dead-zone marker, which is what makes the binding exist and
2201 // unreadable before its initialiser runs.
2202 self.declare_global(&closure_var.name, closure_var.is_const);
2203 self.realm.globals[&closure_var.name].clone()
2204 }
2205 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
2206 // A `var` or function declaration becomes a property of the global
2207 // object, and it exists from here on — which is why
2208 // `print(v); var v = 1` prints `undefined` instead of raising.
2209 // Declaring it at instantiation time (rather than at the
2210 // initialiser) is also what makes it non-configurable: the store
2211 // then lands on an existing property instead of creating one.
2212 self.declare_var_global(&closure_var.name);
2213 // The cell is a placeholder that nothing indexes; it cannot be
2214 // omitted because the slot has to hold something.
2215 self.new_cell(Value::Undefined)
2216 }
2217 _ => {
2218 // An undeclared global is read by name; the cell is a
2219 // placeholder that nothing indexes.
2220 self.new_cell(Value::Undefined)
2221 }
2222 };
2223 cells.push(cell);
2224 }
2225 Gc::new(
2226 self.heap,
2227 ClosureEnv {
2228 cells,
2229 eval_scope: None,
2230 local_vars: None,
2231 local_phase: 1,
2232 },
2233 )
2234 }
2235
2236 /// Push a frame and run until it returns.
2237 pub(crate) fn execute(
2238 &mut self,
2239 code: Gc<CompiledCode>,
2240 env: Gc<ClosureEnv>,
2241 this: Value,
2242 args: Vec<Value>,
2243 callee: Value,
2244 ) -> JsResult<Value> {
2245 let depth = self.frames.len();
2246 self.push_frame(code, env, this, args, callee)?;
2247 loop {
2248 match self.step() {
2249 Ok(Step::Continue) => {}
2250 Ok(Step::Return(value)) => {
2251 self.frames.pop();
2252 // A frame that ended in a `tail_call` hands its value straight to
2253 // its caller: nothing after the call can run, so every frame above
2254 // the callee unwinds with the same value. See [`Frame::tail`] —
2255 // the reference does not reuse frames either, so recursion depth
2256 // and the stack-overflow limit behave the same way.
2257 while self.frames.len() > depth && self.frame().tail {
2258 self.frames.pop();
2259 }
2260 if self.frames.len() == depth {
2261 return Ok(value);
2262 }
2263 // The caller resumes with the value on its stack.
2264 self.frames
2265 .last_mut()
2266 .expect("a caller is live")
2267 .stack
2268 .push(value);
2269 }
2270 Err(Signal::Throw(value)) => {
2271 // A handler lives on the stack of the frame that is throwing —
2272 // `catch` pushed it there — so this frame gets the first chance
2273 // to catch before it is popped.
2274 let value = value;
2275 loop {
2276 if self.frames.len() <= depth {
2277 return Err(Signal::Throw(value));
2278 }
2279 if self.catch_here(value.clone()).is_some() {
2280 break;
2281 }
2282 self.frames.pop();
2283 }
2284 }
2285 // A `yield` in a frame that `execute` is running directly means a
2286 // generator body was entered as an ordinary call, which only happens if
2287 // the generator check in `call_or_push` was bypassed.
2288 Ok(Step::Suspend(_)) => {
2289 return Err(Signal::Throw(self.make_error(
2290 "InternalError",
2291 "a generator body ran as an ordinary call",
2292 )));
2293 }
2294 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2295 }
2296 }
2297 }
2298
2299 /// Install a handler for `value` if this frame has one, resuming at it.
2300 ///
2301 /// The scan is the reference's: walk the frame's stack downwards looking for the
2302 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
2303 /// `0` is an enumerator marker rather than a handler — it exists so that a
2304 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
2305 /// here and the unwinding continues.
2306 fn catch_here(&mut self, value: Value) -> Option<()> {
2307 let frame = self.frames.last_mut()?;
2308 while let Some(top) = frame.stack.pop() {
2309 if let Value::CatchOffset(offset) = top {
2310 if offset == 0 {
2311 continue;
2312 }
2313 frame.stack.push(value);
2314 frame.pc = offset as usize;
2315 return Some(());
2316 }
2317 }
2318 None
2319 }
2320
2321 fn push_frame(
2322 &mut self,
2323 code: Gc<CompiledCode>,
2324 env: Gc<ClosureEnv>,
2325 this: Value,
2326 mut args: Vec<Value>,
2327 callee: Value,
2328 ) -> JsResult<()> {
2329 if self.frames.len() >= self.max_frames {
2330 return Err(Signal::Throw(
2331 self.string("Maximum call stack size exceeded"),
2332 ));
2333 }
2334 let arg_count = code.code.args.len();
2335 // How many were actually passed, which `arguments.length` reports and
2336 // `assert(x)` depends on: a call with one argument must not look like a call
2337 // with one argument and an explicit `undefined`.
2338 let passed = args.len();
2339 // Missing arguments are `undefined` in their slots; extra ones are dropped
2340 // from the slots but still reachable through `arguments`.
2341 let mut passed_values = args.clone();
2342 args.resize(arg_count, Value::Undefined);
2343 args.truncate(arg_count);
2344 let cell_count = code.code.var_ref_count as usize;
2345 let mut cells = Vec::with_capacity(cell_count);
2346 for _ in 0..cell_count {
2347 cells.push(self.new_cell(Value::Undefined));
2348 }
2349 let locals = vec![Value::Undefined; code.code.vars.len()];
2350 // A captured argument lives in its cell, not in the argument slot, so the
2351 // incoming value has to be moved there before the body runs.
2352 for (slot, cell) in code.arg_cell.iter().enumerate() {
2353 if *cell >= 0
2354 && let Some(value) = args.get(slot).cloned()
2355 {
2356 cells[*cell as usize].set(value);
2357 }
2358 }
2359 // Sloppy mode substitutes the global object for a missing receiver and boxes a
2360 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
2361 // reports `object`. Strict mode passes the value through untouched.
2362 let this = if code.code.strict {
2363 this
2364 } else if this.is_nullish() {
2365 Value::Object(self.realm.global.clone())
2366 } else if matches!(this, Value::Object(_)) {
2367 this
2368 } else {
2369 match crate::builtins::this_object(self, &this) {
2370 Ok(boxed) => Value::Object(boxed),
2371 Err(_) => this,
2372 }
2373 };
2374 self.frames.push(Frame {
2375 code,
2376 env,
2377 this,
2378 args,
2379 passed: passed_values.drain(..passed).collect(),
2380 locals,
2381 cells,
2382 local_vars: None,
2383 stack: Vec::with_capacity(16),
2384 pc: 0,
2385 at: 0,
2386 callee,
2387 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
2388 tail: false,
2389 });
2390 Ok(())
2391 }
2392
2393 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
2394 ///
2395 /// Only names the eval created are here: a name the frame already declared statically
2396 /// is written through to its own slot instead, so this cannot shadow a real local.
2397 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
2398 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
2399 let (local_vars, phase) = self.visible_local_vars()?;
2400 if !local_vars.contains(name) {
2401 return None;
2402 }
2403 local_vars.get(name, phase)
2404 }
2405
2406 /// The variables a direct `eval` declared, as the code currently running sees them.
2407 ///
2408 /// Inside an eval that is the *caller's* set — the eval's own variable environment
2409 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
2410 /// else it is the current frame's, falling back to the frame the closure was created
2411 /// in.
2412 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
2413 // While an `eval` runs, its own frame is on top but its variable environment is
2414 // the *caller's* — so the caller is what the lookup has to start from.
2415 let (index, phase) = match self.eval_caller.flatten() {
2416 Some(caller) => (
2417 caller,
2418 if self.in_parameter_list_at(caller) {
2419 0
2420 } else {
2421 1
2422 },
2423 ),
2424 None => (
2425 self.frames.len().checked_sub(1)?,
2426 if self.in_parameter_list() { 0 } else { 1 },
2427 ),
2428 };
2429 let frame = self.frames.get(index)?;
2430 // The frame's own variables, or — for an arrow, which has no variable environment
2431 // of its own — the one it was created in, which `ClosureEnv` carries.
2432 if let Some(local_vars) = frame.local_vars.clone() {
2433 return Some((local_vars, phase));
2434 }
2435 frame
2436 .env
2437 .local_vars
2438 .clone()
2439 .map(|local_vars| (local_vars, frame.env.local_phase))
2440 }
2441
2442 /// Whether the innermost frame is still evaluating its parameter list.
2443 ///
2444 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
2445 /// and a closure created there may only see that much of [`LocalVars`].
2446 fn in_parameter_list(&self) -> bool {
2447 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
2448 }
2449
2450 /// [`Interp::in_parameter_list`] for a specific frame.
2451 fn in_parameter_list_at(&self, frame: usize) -> bool {
2452 let Some(frame) = self.frames.get(frame) else {
2453 return false;
2454 };
2455 let code = &frame.code.code;
2456 if !code.has_parameter_expressions {
2457 return false;
2458 }
2459 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
2460 // function as its body and let a direct `eval` act accordingly.
2461 if code.body_start == (0, 0) {
2462 return false;
2463 }
2464 match code.position_at(frame.at as u32) {
2465 Some(position) => position < code.body_start,
2466 None => false,
2467 }
2468 }
2469
2470 fn frame(&self) -> &Frame {
2471 self.frames.last().expect("a frame is live")
2472 }
2473
2474 fn frame_mut(&mut self) -> &mut Frame {
2475 self.frames.last_mut().expect("a frame is live")
2476 }
2477
2478 // -- slot access --------------------------------------------------------
2479
2480 fn read_slot(&self, cell: i32, value: &Value) -> Value {
2481 match cell {
2482 -1 => value.clone(),
2483 index => self
2484 .frame()
2485 .cells
2486 .get(index as usize)
2487 .expect("a cell index in range")
2488 .get(),
2489 }
2490 }
2491
2492 fn get_arg(&self, slot: usize) -> Value {
2493 let frame = self.frame();
2494 let cell = frame.code.arg_cell.get(slot).copied().unwrap_or(-1);
2495 let value = frame.args.get(slot).cloned().unwrap_or(Value::Undefined);
2496 self.read_slot(cell, &value)
2497 }
2498
2499 fn put_arg(&mut self, slot: usize, value: Value) {
2500 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
2501 if cell == -1 {
2502 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
2503 *slot = value;
2504 }
2505 } else {
2506 self.frame().cells[cell as usize].set(value);
2507 }
2508 }
2509
2510 fn get_loc(&self, slot: usize) -> Value {
2511 let frame = self.frame();
2512 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
2513 let value = frame.locals.get(slot).cloned().unwrap_or(Value::Undefined);
2514 self.read_slot(cell, &value)
2515 }
2516
2517 fn put_loc(&mut self, slot: usize, value: Value) {
2518 let cell = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
2519 if cell == -1 {
2520 if let Some(slot) = self.frame_mut().locals.get_mut(slot) {
2521 *slot = value;
2522 }
2523 } else {
2524 self.frame().cells[cell as usize].set(value);
2525 }
2526 }
2527
2528 // -- globals ------------------------------------------------------------
2529
2530 /// The name a global-slot operand refers to.
2531 fn global_name(&self, slot: usize) -> String {
2532 self.frame()
2533 .code
2534 .code
2535 .closure_vars
2536 .get(slot)
2537 .map(|c| c.name.clone())
2538 .unwrap_or_default()
2539 }
2540
2541 /// The facts about a global binding that decide where it lives.
2542 ///
2543 /// A script's globals split in two, and the split is observable: `var` and
2544 /// function declarations become properties of the global object (`globalThis.v`
2545 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
2546 /// declarations live in the global *lexical* environment and are invisible there
2547 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
2548 /// `is_lexical` flag means the answer is already in the bytecode.
2549 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
2550 let name = self.global_name(slot);
2551 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
2552 // while forwarding a reference through a nested function is built with the
2553 // flags cleared, so `const c` would look like an ordinary `var` from inside a
2554 // closure. Presence in the realm's lexical table is the same fact, recorded
2555 // once, and every slot sees it.
2556 let lexical = self.realm.globals.contains_key(&name);
2557 let is_const = self.realm.lexical_consts.contains(&name);
2558 (name, lexical, is_const)
2559 }
2560
2561 /// The value of `name` in the innermost active `with` object, if any.
2562 ///
2563 /// The active objects are the [`VarKind::With`] locals of every frame still running,
2564 /// innermost frame first and innermost block first within one. Walking frames rather
2565 /// than keeping a separate stack is what makes a closure called from inside a `with`
2566 /// see it, and what keeps the object alive only as long as the block is.
2567 /// The innermost active `with` object that has `name`, if any.
2568 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
2569 let objects = self.eval_with.clone().unwrap_or_default();
2570 for object in objects {
2571 let key = self.string(name.to_string());
2572 if self
2573 .has_property(&key, &Value::Object(object.clone()))
2574 .ok()?
2575 {
2576 return Some(object);
2577 }
2578 }
2579 None
2580 }
2581
2582 /// Every active `with` object, innermost first.
2583 fn with_objects(&self) -> Vec<Gc<JsObject>> {
2584 let mut objects = Vec::new();
2585 for frame in self.frames.iter().rev() {
2586 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
2587 if var.kind != js_compile::VarKind::With {
2588 continue;
2589 }
2590 // A captured binding lives in its cell and not in the slot list, so the
2591 // cell is consulted first — a closure created inside the block is exactly
2592 // what makes the object captured. Before the store runs the slot still
2593 // holds `undefined`, and a `with` object is always boxed, so a non-object
2594 // entry is simply not in scope yet.
2595 let value = frame
2596 .code
2597 .loc_cell
2598 .get(index)
2599 .copied()
2600 .filter(|cell| *cell >= 0)
2601 .and_then(|cell| frame.cells.get(cell as usize))
2602 .map(|cell| cell.get())
2603 .or_else(|| frame.locals.get(index).cloned());
2604 if let Some(Value::Object(object)) = value {
2605 objects.push(object);
2606 }
2607 }
2608 }
2609 objects
2610 }
2611
2612 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
2613 for object in self.eval_with.clone().unwrap_or_default() {
2614 let key = self.string(name.to_string());
2615 if self.has_property(&key, &Value::Object(object.clone()))? {
2616 return Ok(Some(self.read_field(&Value::Object(object), name)?));
2617 }
2618 }
2619 Ok(None)
2620 }
2621
2622 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
2623 let (name, lexical, _) = self.global_binding(slot);
2624 if name == "arguments"
2625 && let Some(arguments) = &self.eval_arguments
2626 {
2627 return Ok(arguments.clone());
2628 }
2629 // A `with` block around the *call site* is part of the scope an `eval` sees, so
2630 // the objects live when the eval started are consulted before anything else. The
2631 // snapshot is taken at entry rather than scanning the frames on every read: a
2632 // block that has already finished still leaves its object in the slot, and a
2633 // bytecode read outside the block must not see it.
2634 if let Some(value) = self.with_lookup(&name)? {
2635 return Ok(value);
2636 }
2637 // A variable a direct `eval` declared shadows everything the compiler resolved,
2638 // including an enclosing function's binding: the eval put it in the caller's own
2639 // variable environment, which is nearer than any captured scope.
2640 if let Some((local_vars, phase)) = self.visible_local_vars()
2641 && let Some(cell) = local_vars.get(&name, phase)
2642 {
2643 return Ok(cell.get());
2644 }
2645 // The frame that called `eval` is the innermost scope the eval'd code sees, so
2646 // its local `a` wins over a global `a`.
2647 if let Some(value) = self.eval_binding_value(&name) {
2648 return Ok(value);
2649 }
2650 // A closure created by an `eval` resolves its free names against the bindings
2651 // that eval saw, even after the eval (and its frames) are gone.
2652 if let Some(cell) = self
2653 .frame()
2654 .env
2655 .eval_scope
2656 .as_ref()
2657 .and_then(|scope| scope.get(&name))
2658 {
2659 let value = cell.get();
2660 if matches!(value, Value::Uninitialized) {
2661 return Err(self.throw_reference(&name));
2662 }
2663 return Ok(value);
2664 }
2665 // A binding declared by the strict `eval` currently running shadows anything
2666 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
2667 if let Some(scope) = &self.eval_scope
2668 && let Some(value) = scope.get(&name)
2669 {
2670 return Ok(value.clone());
2671 }
2672 if lexical {
2673 // A lexical global is a binding in a side table, so the dead zone is
2674 // visible and it is nowhere on the global object.
2675 if let Some(cell) = self.realm.globals.get(&name) {
2676 let value = cell.get();
2677 if matches!(value, Value::Uninitialized) {
2678 return Err(self.throw_reference(&name));
2679 }
2680 return Ok(value);
2681 }
2682 return Err(self.throw_reference(&name));
2683 }
2684 // A `var` global is an ordinary property, so the prototype chain and the
2685 // global object's own builtins are all reachable through it.
2686 match self.get_property(&self.realm.global.clone(), &name)? {
2687 Some(value) => Ok(value),
2688 None => Err(self.throw_reference(&name)),
2689 }
2690 }
2691
2692 /// Store to a global binding.
2693 ///
2694 /// Returns a signal when the store is refused: a `const` global may only be
2695 /// written by its initialiser, and a non-configurable `var` global may not be
2696 /// deleted but is always writable.
2697 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
2698 let (name, lexical, is_const) = self.global_binding(slot);
2699
2700 // An assignment inside a `with` writes through to the object that supplies the
2701 // name, which for an `eval` means consulting the same chain `get_global` does.
2702 if let Some(owner) = self.with_owner(&name) {
2703 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
2704 return Ok(());
2705 }
2706 // A variable the running eval *declared* takes the write before any caller
2707 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
2708 // environment even when an enclosing function has a `var c` of its own.
2709 if self.eval_caller.flatten().is_some()
2710 && let Some((local_vars, phase)) = self.visible_local_vars()
2711 && local_vars.contains(&name)
2712 && let Some(cell) = local_vars.get(&name, phase)
2713 {
2714 cell.set(value);
2715 return Ok(());
2716 }
2717 // A binding of the frame that called `eval` takes the write, which is what
2718 // makes `f("a = 3")` change the caller's `a`.
2719 if self.set_eval_binding(&name, &value)? {
2720 return Ok(());
2721 }
2722 // A closure that outlived its `eval` writes through to the same cell it reads.
2723 if let Some(cell) = self
2724 .frame()
2725 .env
2726 .eval_scope
2727 .as_ref()
2728 .and_then(|scope| scope.get(&name))
2729 .cloned()
2730 {
2731 cell.set(value);
2732 return Ok(());
2733 }
2734 // Inside a strict `eval`, a name it declared itself is stored there. An
2735 // *assignment* to a name nobody declared is not a declaration, so it falls
2736 // through: strict mode raises `ReferenceError` for it, which is what
2737 // `eval("1 + (@not_def = 1)")` has to do.
2738 if let Some(scope) = self.eval_scope.as_mut()
2739 && scope.contains_key(&name)
2740 {
2741 scope.insert(name, value);
2742 return Ok(());
2743 }
2744 if lexical {
2745 if let Some(cell) = self.realm.globals.get(&name).cloned() {
2746 if is_const && !matches!(cell.get(), Value::Uninitialized) {
2747 return Err(self.read_only_global(&name));
2748 }
2749 cell.set(value);
2750 return Ok(());
2751 }
2752 // Writing an undeclared lexical global is a `ReferenceError` in strict
2753 // mode and a silent global creation otherwise; creating the cell here
2754 // keeps both paths from losing the value.
2755 let cell = self.new_cell(value);
2756 self.realm.globals.insert(name, cell);
2757 return Ok(());
2758 }
2759 // A variable a direct `eval` declared in this call shadows the global object, even
2760 // when the global already has a property of that name — `var c = "global"` at the
2761 // top level must not capture `eval("var c = 1")` inside a function.
2762 if let Some((local_vars, phase)) = self.visible_local_vars()
2763 && local_vars.contains(&name)
2764 && let Some(cell) = local_vars.get(&name, phase)
2765 {
2766 cell.set(value);
2767 return Ok(());
2768 }
2769 let global = self.realm.global.clone();
2770 match global.own_property(&name) {
2771 // A `var` global is writable, so the store goes straight through — but
2772 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
2773 // store (a non-writable or accessor-without-setter global) is a silent
2774 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
2775 // split every other assignment has.
2776 Some(_) => {
2777 let on_failure = if self.current_strict() {
2778 DeleteFailure::Throw
2779 } else {
2780 DeleteFailure::Ignore
2781 };
2782 self.set_property_with(&global, &name, value, on_failure)
2783 }
2784 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
2785 // declaration creates a *configurable* property, which is what makes it
2786 // deletable and is the one way a global differs from a declared `var`.
2787 // In strict mode the same store is a `ReferenceError` instead: that is the
2788 // whole point of strict mode, and creating the global silently meant
2789 // `"use strict"; x = 1` looked like it worked.
2790 None => {
2791 if self.current_strict() {
2792 return Err(self.throw_reference(&name));
2793 }
2794 // A direct eval declares here rather than on the global object: its
2795 // `var`s belong to the caller's variable environment. `declare_eval_local`
2796 // also covers a plain assignment to a variable an earlier eval made.
2797 if let Some(cell) = self.declare_eval_local(&name) {
2798 cell.set(value);
2799 return Ok(());
2800 }
2801 global.define_data(&name, value);
2802 Ok(())
2803 }
2804 }
2805 }
2806
2807 /// The value of a binding of the frame that called `eval`, if there is one.
2808 fn eval_binding_value(&self, name: &str) -> Option<Value> {
2809 let binding = self
2810 .eval_bindings
2811 .iter()
2812 .find(|binding| binding.name == name)?;
2813 let owner = self.frames.get(binding.frame)?;
2814 let (slot, index) = (binding.slot, binding.index);
2815 Some(match slot {
2816 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
2817 cell if cell >= 0 => owner
2818 .cells
2819 .get(cell as usize)
2820 .map(|cell| cell.get())
2821 .unwrap_or(Value::Undefined),
2822 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
2823 },
2824 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
2825 cell if cell >= 0 => owner
2826 .cells
2827 .get(cell as usize)
2828 .map(|cell| cell.get())
2829 .unwrap_or(Value::Undefined),
2830 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
2831 },
2832 })
2833 }
2834
2835 /// Write to a binding of the frame that called `eval`.
2836 ///
2837 /// `Ok(false)` means no binding matched and the caller should keep looking. A
2838 /// matched binding can still refuse the store, which is why this is fallible: a
2839 /// `const` is read-only everywhere, and a named function expression's own name is
2840 /// read-only in strict mode.
2841 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
2842 let Some(binding) = self
2843 .eval_bindings
2844 .iter()
2845 .find(|binding| binding.name == name)
2846 else {
2847 return Ok(false);
2848 };
2849 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
2850 let strict = self.current_strict();
2851 let Some(owner) = self.frames.get_mut(frame) else {
2852 return Ok(false);
2853 };
2854 match slot {
2855 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
2856 cell if cell >= 0 => {
2857 if let Some(cell) = owner.cells.get(cell as usize) {
2858 cell.set(value.clone());
2859 }
2860 }
2861 _ => {
2862 if let Some(slot) = owner.args.get_mut(index) {
2863 *slot = value.clone();
2864 }
2865 }
2866 },
2867 EvalSlot::Local => {
2868 let declared = owner.code.code.vars.get(index);
2869 // A `const` is read-only even through `eval`. The realm records this for
2870 // globals (see `lexical_consts`), but a local's `const`-ness is only in
2871 // the bytecode, so this is where it has to be enforced.
2872 if declared.is_some_and(|var| var.is_const) {
2873 return Err(self.read_only_local(name));
2874 }
2875 // The name of a named function expression is read-only too, but only
2876 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
2877 // such a name is ignored, the same as a direct store would be.
2878 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
2879 return if strict {
2880 Err(self.read_only_local(name))
2881 } else {
2882 Ok(true)
2883 };
2884 }
2885 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
2886 cell if cell >= 0 => {
2887 if let Some(cell) = owner.cells.get(cell as usize) {
2888 cell.set(value.clone());
2889 }
2890 }
2891 _ => {
2892 if let Some(slot) = owner.locals.get_mut(index) {
2893 *slot = value.clone();
2894 }
2895 }
2896 }
2897 }
2898 }
2899 Ok(true)
2900 }
2901
2902 /// The `TypeError` an assignment to a read-only binding raises.
2903 fn read_only_local(&self, name: &str) -> Signal {
2904 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
2905 }
2906
2907 /// Declare `name` as a variable of the frame that called the running `eval`.
2908 ///
2909 /// `None` when there is no direct eval in progress, or it was called from the top
2910 /// level — then the caller's variable environment *is* the global one and the
2911 /// existing path is right.
2912 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
2913 let caller = self.eval_caller.flatten()?;
2914 // The bottom frame is the top-level script, whose variable environment *is* the
2915 // global one — so `eval("var x = 1")` at the top level still creates a global.
2916 if caller == 0 {
2917 return None;
2918 }
2919 // A name the eval's *own* variable environment already binds is not a new
2920 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
2921 // `arguments`, and creating a second binding would leave the first — the one
2922 // closures read — untouched. A binding of an *outer* frame does not count: a
2923 // declaration shadows it rather than writing through.
2924 if self
2925 .eval_bindings
2926 .iter()
2927 .any(|binding| binding.name == name && binding.frame == caller)
2928 {
2929 return None;
2930 }
2931 let phase = if self.in_parameter_list_at(caller) {
2932 0
2933 } else {
2934 1
2935 };
2936 self.frame_local_vars(caller)?;
2937 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
2938 if let Some(cell) = local_vars.get(name, 1) {
2939 return Some(cell);
2940 }
2941 let cell = self.new_cell(Value::Undefined);
2942 Some(local_vars.declare(name, phase, cell))
2943 }
2944
2945 /// Make sure `frame` has a `LocalVars`, creating it on demand.
2946 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
2947 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
2948 return Some(local_vars.clone());
2949 }
2950 let local_vars = Gc::new(self.heap, LocalVars::new());
2951 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
2952 Some(local_vars)
2953 }
2954
2955 /// Whether the realm already has a binding for `name`, lexically or as an *own*
2956 /// property of the global object. Used to decide whether a store inside an
2957 /// `eval` writes through to the realm or declares a binding of its own.
2958 ///
2959 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
2960 /// write to `Object.prototype.toString`, and must not shadow it either.
2961 fn global_knows(&mut self, name: &str) -> bool {
2962 if self.realm.globals.contains_key(name) {
2963 return true;
2964 }
2965 self.realm.global.own_property(name).is_some()
2966 }
2967
2968 /// Whether the code currently running is strict.
2969 ///
2970 /// Read off the frame's function, which is where the parser's answer ended up; a
2971 /// native function never runs strict-only checks, and there is no frame at all
2972 /// before the first script.
2973 pub fn current_strict(&self) -> bool {
2974 self.frames
2975 .last()
2976 .is_some_and(|frame| frame.code.code.strict)
2977 }
2978
2979 /// Initialise a declared global, which is what ends its dead zone.
2980 ///
2981 /// A `var` global becomes a property of the global object: writable, so a later
2982 /// assignment goes through, and non-configurable, so `delete` refuses.
2983 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
2984 let (name, lexical, _) = self.global_binding(slot);
2985 // A `var` declared by the strict `eval` currently running belongs to the
2986 // eval's scope, not to the global object: `eval("var v = 1")` must not make
2987 // `typeof v` answer `"number"` afterwards. A name the realm already has is
2988 // initialised in place, which is what a re-declaration inside eval does.
2989 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
2990 self.eval_scope
2991 .as_mut()
2992 .expect("checked above")
2993 .insert(name, value);
2994 return Ok(());
2995 }
2996 if let Some(scope) = self.eval_scope.as_mut()
2997 && scope.contains_key(&name)
2998 {
2999 scope.insert(name, value);
3000 return Ok(());
3001 }
3002 if lexical {
3003 // The cell exists (created at declaration time) holding the dead-zone
3004 // marker; storing the value is what makes the binding readable.
3005 if let Some(cell) = self.realm.globals.get(&name).cloned() {
3006 cell.set(value);
3007 return Ok(());
3008 }
3009 let cell = self.new_cell(value);
3010 self.realm.globals.insert(name, cell);
3011 return Ok(());
3012 }
3013 let global = self.realm.global.clone();
3014 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
3015 // to answer `false` and leave the binding in place. `with_attributes` ties
3016 // `configurable` to `writable`, so the property is built field by field.
3017 global.define(
3018 &name,
3019 Property {
3020 value: Some(value),
3021 writable: true,
3022 enumerable: true,
3023 configurable: false,
3024 ..Property::default()
3025 },
3026 );
3027 Ok(())
3028 }
3029
3030 /// The `TypeError` a store to a `const` global raises.
3031 fn read_only_global(&self, name: &str) -> Signal {
3032 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
3033 }
3034
3035 // -- properties ---------------------------------------------------------
3036
3037 /// Read `object[key]`, following the prototype chain.
3038 ///
3039 /// An inherited accessor runs with the *receiver* as `this`, which is why the
3040 /// lookup returns the owner rather than just the value.
3041 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
3042 self.get_property_key(object, &PropertyKey::from(key))
3043 }
3044
3045 /// [`Interp::get_property`] with a key that may be a symbol.
3046 pub fn get_property_key(
3047 &mut self,
3048 object: &Gc<JsObject>,
3049 key: &PropertyKey,
3050 ) -> JsResult<Option<Value>> {
3051 self.get_property_key_for(object, None, key)
3052 }
3053
3054 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
3055 ///
3056 /// The receiver matters when the property is found on a *prototype*: a getter has to
3057 /// see the object the read started from. For a primitive that is the primitive
3058 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
3059 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
3060 /// the owner.
3061 pub fn get_property_key_for(
3062 &mut self,
3063 object: &Gc<JsObject>,
3064 receiver: Option<&Value>,
3065 key: &PropertyKey,
3066 ) -> JsResult<Option<Value>> {
3067 // A proxy answers for itself, before any of the shortcuts below: `new
3068 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
3069 // have.
3070 if object.proxy_state().is_some() {
3071 let receiver = receiver
3072 .cloned()
3073 .unwrap_or_else(|| Value::Object(object.clone()));
3074 return self.proxy_get(object, &receiver, key);
3075 }
3076 // The element-vector and `length` shortcuts are string-only: an array index
3077 // has no symbol spelling.
3078 if let Some(text) = key.as_str() {
3079 if let Some(value) = self.own_element(object, text) {
3080 return Ok(Some(value));
3081 }
3082 // `length` is not stored as a property: an array's length is its element
3083 // count, and keeping one copy of it is what makes `push`/`pop` and
3084 // `a.length = n` agree.
3085 if let Some(length) = object.array_length()
3086 && text == "length"
3087 {
3088 // Not `Value::Int(length as i32)`: see [`length_value`].
3089 return Ok(Some(crate::object::length_value(length)));
3090 }
3091 }
3092 match lookup_key(object, key) {
3093 Some((_, property)) => {
3094 if property.is_accessor() {
3095 match &property.getter {
3096 Some(getter) if !matches!(getter, Value::Undefined) => {
3097 let receiver = receiver
3098 .cloned()
3099 .unwrap_or_else(|| Value::Object(object.clone()));
3100 self.call_value(getter.clone(), receiver, Vec::new())
3101 .map(Some)
3102 }
3103 // An accessor with no getter reads as `undefined`.
3104 _ => Ok(Some(Value::Undefined)),
3105 }
3106 } else {
3107 Ok(property.value)
3108 }
3109 }
3110 None => Ok(None),
3111 }
3112 }
3113
3114 /// `super.key` — start the search at `proto`, but report to `receiver`.
3115 ///
3116 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
3117 /// found on the prototype of a class has to see the *instance* as `this`, and a
3118 /// plain property read off `proto` would lose that.
3119 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
3120 let start = self.require_object(proto)?;
3121 let key = self.propkey(key);
3122 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
3123 if matches!(proto, Value::Null) {
3124 return Ok(Value::Undefined);
3125 }
3126 match lookup_key(&start, &key) {
3127 Some((_, property)) if property.is_accessor() => match &property.getter {
3128 Some(getter) if !matches!(getter, Value::Undefined) => {
3129 self.call_value(getter.clone(), receiver.clone(), Vec::new())
3130 }
3131 _ => Ok(Value::Undefined),
3132 },
3133 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
3134 None => Ok(Value::Undefined),
3135 }
3136 }
3137
3138 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
3139 ///
3140 /// A setter found on the prototype runs with `receiver` as `this`; a data property
3141 /// is shadowed by a new own property on the receiver, the same rule an ordinary
3142 /// assignment follows.
3143 fn super_write(
3144 &mut self,
3145 receiver: &Value,
3146 proto: &Value,
3147 key: &Value,
3148 value: Value,
3149 ) -> JsResult<()> {
3150 let target = self.require_object(receiver)?;
3151 let key = self.propkey(key);
3152 if !matches!(proto, Value::Null)
3153 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
3154 {
3155 if property.is_accessor() {
3156 if let Some(setter) = &property.setter
3157 && !matches!(setter, Value::Undefined)
3158 {
3159 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
3160 }
3161 return Ok(());
3162 }
3163 // A data property on the prototype is writable or not; reading `owner` at
3164 // all is only for the attribute check.
3165 if !property.writable {
3166 return Err(self.type_error(format!("'{key}' is read-only")));
3167 }
3168 let _ = owner;
3169 }
3170 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
3171 }
3172
3173 /// The object a `super` operation needs, or the `TypeError` the spec raises.
3174 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
3175 match value.as_object() {
3176 Some(object) => Ok(object.clone()),
3177 None => Err(Signal::Throw(
3178 self.make_error("TypeError", "value is not an object"),
3179 )),
3180 }
3181 }
3182
3183 /// Build the class object `define_class` produces.
3184 ///
3185 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
3186 /// whose prototype property is a fresh object inheriting from the parent's
3187 /// prototype, and whose own prototype is the parent constructor — which is what makes
3188 /// a static method inherited too.
3189 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
3190 let ctor = self.pop();
3191 let parent = self.pop();
3192 let Value::Object(function) = &ctor else {
3193 return Err(Signal::Throw(
3194 self.make_error("TypeError", "class constructor must be a function"),
3195 ));
3196 };
3197 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
3198 // but gives the instances no prototype at all.
3199 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
3200 match &parent {
3201 Value::Null => (Some(self.realm.function_proto.clone()), None),
3202 Value::Object(parent_class) => {
3203 if !parent_class.is_callable() {
3204 return Err(Signal::Throw(
3205 self.make_error("TypeError", "parent class must be constructor"),
3206 ));
3207 }
3208 let proto = self.get_property(parent_class, "prototype")?;
3209 match proto {
3210 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
3211 Some(Value::Null) => (Some(parent_class.clone()), None),
3212 _ => {
3213 return Err(Signal::Throw(self.make_error(
3214 "TypeError",
3215 "parent prototype must be an object or null",
3216 )));
3217 }
3218 }
3219 }
3220 _ => {
3221 return Err(Signal::Throw(
3222 self.make_error("TypeError", "parent class must be constructor"),
3223 ));
3224 }
3225 }
3226 } else {
3227 (
3228 Some(self.realm.function_proto.clone()),
3229 Some(self.realm.object_proto.clone()),
3230 )
3231 };
3232 let proto = self.new_object(parent_proto);
3233 function.set_proto(parent_ctor);
3234 // A class is not callable without `new`, and its `prototype` is not writable —
3235 // both follow from being a class and are what `class A {}; A()` throws on.
3236 function.set_class_constructor(true);
3237 function.set_home_object(None);
3238 self.set_function_name(&ctor, name);
3239 self.define_class_properties(function, &ctor, &proto)?;
3240 Ok((ctor, proto))
3241 }
3242
3243 /// Give the constructor its `prototype` and `length`, and the prototype its
3244 /// `constructor` back-pointer.
3245 fn define_class_properties(
3246 &mut self,
3247 function: &Gc<JsObject>,
3248 ctor: &Value,
3249 proto: &Gc<JsObject>,
3250 ) -> JsResult<()> {
3251 proto.define(
3252 "constructor",
3253 Property::with_attributes(ctor.clone(), true, false),
3254 );
3255 function.define(
3256 "prototype",
3257 Property::prototype_of(Value::Object(proto.clone()), false),
3258 );
3259 if let Some((code, _)) = bytecode_of(function) {
3260 let length = code.code.defined_args;
3261 function.define(
3262 "length",
3263 Property::name_or_length(Value::Int(length as i32)),
3264 );
3265 }
3266 Ok(())
3267 }
3268
3269 /// The own array element `key` names, if this object has one.
3270 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
3271 let index = array_index(key)?;
3272 // A typed array's elements live in its buffer, not in a property list: reading one
3273 // goes through the view's element type so a bounds check and a detached buffer are
3274 // both handled there.
3275 if object.typed_array_parts().is_some() {
3276 return object.typed_array_element(index as usize);
3277 }
3278 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
3279 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
3280 // search early, which is why `Array.prototype[1] = 9` could not be seen through
3281 // `[1,,3][1]`.
3282 match object.array_get(index as usize) {
3283 Some(Value::Hole) | None => None,
3284 other => other,
3285 }
3286 }
3287
3288 /// Store `object[key] = value`, honouring setters and inherited properties.
3289 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
3290 self.set_property_with(object, key, value, DeleteFailure::Throw)
3291 }
3292
3293 /// Store a property, choosing what to do when the object refuses.
3294 ///
3295 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
3296 /// mode, which is the one place assignment differs by mode. Native code (the array
3297 /// methods, `JSON`) always asks for the throw.
3298 pub fn set_property_with(
3299 &mut self,
3300 object: &Gc<JsObject>,
3301 key: &str,
3302 value: Value,
3303 on_failure: DeleteFailure,
3304 ) -> JsResult<()> {
3305 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
3306 }
3307
3308 /// [`Interp::set_property_with`] with a key that may be a symbol.
3309 pub fn set_property_with_key(
3310 &mut self,
3311 object: &Gc<JsObject>,
3312 key: &PropertyKey,
3313 value: Value,
3314 on_failure: DeleteFailure,
3315 ) -> JsResult<()> {
3316 // A proxy's `set` trap decides, and its `false` means the same thing an
3317 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
3318 if object.proxy_state().is_some() {
3319 let receiver = Value::Object(object.clone());
3320 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
3321 return match (accepted, on_failure) {
3322 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
3323 (false, DeleteFailure::Throw) => {
3324 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
3325 }
3326 };
3327 }
3328 }
3329 // The element and `length` shortcuts only exist for string keys: an array
3330 // index has no symbol spelling, and a symbol named `length` is an ordinary
3331 // property.
3332 let text = key.as_str();
3333 // A typed array's elements are a window onto its buffer: the store has to go
3334 // through the view's element type so the value is wrapped (or clamped) and so an
3335 // out-of-range or detached write is a silent no-op, as the spec says.
3336 if let Some(text) = text
3337 && let Some(index) = array_index(text)
3338 && let Some(element) = object.typed_array_element_type()
3339 {
3340 // §10.4.5.5: an out-of-bounds index answers `true` *before* `V` is converted,
3341 // so a `valueOf` with a side effect must not run. Checking the length first is
3342 // what keeps `valueOfCalled` at 0 in `key-is-out-of-bounds-receiver-is-…`.
3343 let length = object.typed_array_length().unwrap_or(0);
3344 if index as usize >= length {
3345 return Ok(());
3346 }
3347 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
3348 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
3349 // in `Interp`, because it is script-observable and the storage borrow inside
3350 // `typed_array_set` must not be held across it.
3351 let stored = self.element_value(element, value)?;
3352 if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
3353 return Err(self.type_error(reason));
3354 }
3355 return Ok(());
3356 }
3357 if let Some(text) = text
3358 && let Some(index) = array_index(text)
3359 && object.is_array()
3360 {
3361 // An accessor defined on an index lives in the property table while the
3362 // element slot is a hole, so the store has to go through the property first.
3363 // Writing the vector directly skipped the setter entirely.
3364 if let Some(existing) = object.own_property_key(key) {
3365 if existing.is_accessor() {
3366 return match existing.setter.clone() {
3367 Some(setter) if !matches!(setter, Value::Undefined) => {
3368 let receiver = Value::Object(object.clone());
3369 self.call_value(setter, receiver, vec![value]).map(|_| ())
3370 }
3371 _ => match on_failure {
3372 DeleteFailure::Throw => Err(self.type_error(format!(
3373 "cannot set property '{text}', it has only a getter"
3374 ))),
3375 DeleteFailure::Ignore => Ok(()),
3376 },
3377 };
3378 }
3379 if !existing.writable {
3380 return match on_failure {
3381 DeleteFailure::Throw => {
3382 Err(self.type_error(format!("'{text}' is read-only")))
3383 }
3384 DeleteFailure::Ignore => Ok(()),
3385 };
3386 }
3387 }
3388 {
3389 // Growing the array needs a writable `length`.
3390 if (index as usize) >= object.array_length().unwrap_or(0)
3391 && !object.length_writable()
3392 {
3393 return match on_failure {
3394 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
3395 DeleteFailure::Ignore => Ok(()),
3396 };
3397 }
3398 // Adding an index past the end makes the array longer, which a
3399 // non-extensible array refuses.
3400 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
3401 return match on_failure {
3402 DeleteFailure::Throw => Err(self.type_error(format!(
3403 "cannot add property '{key}', object is not extensible"
3404 ))),
3405 DeleteFailure::Ignore => Ok(()),
3406 };
3407 }
3408 if object.element_is_locked(index) {
3409 return match on_failure {
3410 DeleteFailure::Throw => {
3411 Err(self.type_error(format!("'{key}' is read-only")))
3412 }
3413 DeleteFailure::Ignore => Ok(()),
3414 };
3415 }
3416 object.array_set(index as usize, value);
3417 return Ok(());
3418 }
3419 }
3420 if text == Some("length") && object.is_array() {
3421 if !object.length_writable() {
3422 return match on_failure {
3423 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
3424 DeleteFailure::Ignore => Ok(()),
3425 };
3426 }
3427 let length = value.to_number();
3428 if length.is_finite() && length >= 0.0 {
3429 let length = length as usize;
3430 // `a.length = n` with `n` below a non-configurable element cannot
3431 // drop that element, so the whole assignment fails. The spec makes
3432 // this a `TypeError` rather than a silent no-op, in any mode.
3433 if let Some(blocked) = (length..object.array_length().unwrap_or(0))
3434 .find(|index| object.element_is_undeletable(*index as u32))
3435 {
3436 // Sloppy mode stops the truncation at the blocking element
3437 // instead of failing; strict mode raises.
3438 // Both modes stop at the blocking element; they differ in
3439 // whether that is reported. The reference truncates *then*
3440 // throws, so the array is left in the shortened state.
3441 object.array_truncate(blocked + 1);
3442 return match on_failure {
3443 DeleteFailure::Throw => {
3444 Err(self.type_error(format!("cannot delete property '{blocked}'")))
3445 }
3446 DeleteFailure::Ignore => Ok(()),
3447 };
3448 }
3449 object.array_set_length(length);
3450 return Ok(());
3451 }
3452 }
3453 if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
3454 {
3455 return match on_failure {
3456 DeleteFailure::Throw => Err(self.type_error(format!(
3457 "cannot add property {}, object is not extensible",
3458 key
3459 ))),
3460 DeleteFailure::Ignore => Ok(()),
3461 };
3462 }
3463 if let Some((owner, property)) = lookup_key(object, key) {
3464 if property.is_accessor() {
3465 if let Some(setter) = &property.setter
3466 && !matches!(setter, Value::Undefined)
3467 {
3468 let receiver = Value::Object(object.clone());
3469 self.call_value(setter.clone(), receiver, vec![value])?;
3470 }
3471 return Ok(());
3472 }
3473 // An inherited *data* property is shadowed by an own property on the
3474 // receiver; a non-writable one is not.
3475 if owner.ptr_eq(object) && !property.writable {
3476 return match on_failure {
3477 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
3478 DeleteFailure::Ignore => Ok(()),
3479 };
3480 }
3481 // An existing writable own property keeps its attributes: only the value
3482 // moves. Redefining instead would reset them, which is how a
3483 // non-configurable global `var` used to become deletable.
3484 if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
3485 return Ok(());
3486 }
3487 }
3488 // No own data property: create one, shadowing whatever the prototype holds.
3489 object.define_data_key(key, value);
3490 Ok(())
3491 }
3492
3493 /// Delete `object[key]`.
3494 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
3495 self.delete_property_key(object, &PropertyKey::from(key))
3496 }
3497
3498 /// [`Interp::delete_property`] with a key that may be a symbol.
3499 pub fn delete_property_key(
3500 &mut self,
3501 object: &Gc<JsObject>,
3502 key: &PropertyKey,
3503 ) -> JsResult<bool> {
3504 // A proxy decides for itself, and may even throw; the invariant checks live in
3505 // `proxy_delete`.
3506 if let Some(answer) = self.proxy_delete(object, key)? {
3507 return Ok(answer);
3508 }
3509 if let Some(index) = key.as_str().and_then(array_index)
3510 && let Some(length) = object.array_length()
3511 && (index as usize) < length
3512 {
3513 // An accessor defined on an index lives in the property table rather than the
3514 // element vector, so both have to be cleared: `delete` after
3515 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
3516 object.delete_key(key);
3517 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
3518 // index stops answering `in`.
3519 if object.element_is_undeletable(index) {
3520 return Ok(false);
3521 }
3522 object.array_set(index as usize, Value::Hole);
3523 return Ok(true);
3524 }
3525 Ok(object.delete_key(key))
3526 }
3527
3528 // -- proxy traps --------------------------------------------------------
3529 //
3530 // A proxy's internal methods all look the same: ask the handler for the trap, call it
3531 // with the target and the operation's own arguments, then check the answer against
3532 // the target. The checks are not decoration — they are what stops a proxy from
3533 // reporting a `non-configurable` property as missing, which would let a frozen object
3534 // be rewritten by standing in front of it.
3535
3536 /// The target and handler of `object`, or `None` when it is not a proxy.
3537 ///
3538 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
3539 /// one has to fail: the slots the traps would have been read from are gone.
3540 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
3541 let Some(state) = object.proxy_state() else {
3542 return Ok(None);
3543 };
3544 let state = state.borrow();
3545 match (&state.target, &state.handler) {
3546 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
3547 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
3548 }
3549 }
3550
3551 /// Call `handler[name]`, or answer `None` when the trap is absent.
3552 ///
3553 /// A trap that is present but not callable is a `TypeError` rather than "no trap":
3554 /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
3555 /// back to the target.
3556 fn proxy_trap(
3557 &mut self,
3558 handler: &Value,
3559 name: &str,
3560 args: Vec<Value>,
3561 ) -> JsResult<Option<Value>> {
3562 let Value::Object(table) = handler else {
3563 return Err(self.type_error("proxy handler is not an object"));
3564 };
3565 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
3566 match trap {
3567 Value::Undefined => Ok(None),
3568 Value::Object(function) if function.is_callable() => {
3569 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
3570 Ok(Some(answer))
3571 }
3572 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
3573 }
3574 }
3575
3576 /// Whether `object`'s own property `key` is one the target refuses to lose.
3577 ///
3578 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
3579 /// its value behind the target's back. This goes through
3580 /// [`Self::ordinary_own_property`] rather than the property table so that an array's
3581 /// elements and its `length` — both fixed, both outside the table — are covered.
3582 fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3583 Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
3584 }
3585
3586 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
3587 fn proxy_get(
3588 &mut self,
3589 object: &Gc<JsObject>,
3590 receiver: &Value,
3591 key: &PropertyKey,
3592 ) -> JsResult<Option<Value>> {
3593 let Some((target, handler)) = self.proxy_parts(object)? else {
3594 return Ok(None);
3595 };
3596 let key_value = self.key_value(key);
3597 let Some(result) = self.proxy_trap(
3598 &handler,
3599 "get",
3600 vec![Value::Object(target.clone()), key_value, receiver.clone()],
3601 )?
3602 else {
3603 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
3604 // inherited getter still sees the proxy.
3605 return Ok(Some(
3606 self.get_property_key_for(&target, Some(receiver), key)?
3607 .unwrap_or(Value::Undefined),
3608 ));
3609 };
3610 if let Some(fixed) = Self::is_fixed_property(&target, key) {
3611 if fixed.is_accessor() {
3612 // A fixed accessor with no getter must read as `undefined`.
3613 let has_getter = fixed
3614 .getter
3615 .as_ref()
3616 .is_some_and(|getter| !matches!(getter, Value::Undefined));
3617 if !has_getter && !matches!(result, Value::Undefined) {
3618 return Err(self.type_error(format!(
3619 "proxy 'get' must report undefined for the non-configurable property '{key}'"
3620 )));
3621 }
3622 } else if !fixed.writable {
3623 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
3624 if !fixed_value.same_value(&result) {
3625 return Err(self.type_error(format!(
3626 "proxy 'get' disagrees with the non-configurable property '{key}'"
3627 )));
3628 }
3629 }
3630 }
3631 Ok(Some(result))
3632 }
3633
3634 /// `[[Set]]` on a proxy.
3635 ///
3636 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
3637 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
3638 /// read-only store has.
3639 fn proxy_set(
3640 &mut self,
3641 object: &Gc<JsObject>,
3642 key: &PropertyKey,
3643 value: Value,
3644 receiver: &Value,
3645 ) -> JsResult<Option<bool>> {
3646 let Some((target, handler)) = self.proxy_parts(object)? else {
3647 return Ok(None);
3648 };
3649 let key_value = self.key_value(key);
3650 let Some(result) = self.proxy_trap(
3651 &handler,
3652 "set",
3653 vec![
3654 Value::Object(target.clone()),
3655 key_value,
3656 value.clone(),
3657 receiver.clone(),
3658 ],
3659 )?
3660 else {
3661 // No trap: store on the target, which is where an ordinary proxy write lands.
3662 self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
3663 return Ok(Some(true));
3664 };
3665 if !result.to_boolean() {
3666 return Ok(Some(false));
3667 }
3668 if let Some(fixed) = Self::is_fixed_property(&target, key) {
3669 if fixed.is_accessor() {
3670 let has_setter = fixed
3671 .setter
3672 .as_ref()
3673 .is_some_and(|setter| !matches!(setter, Value::Undefined));
3674 if !has_setter {
3675 return Err(self.type_error(format!(
3676 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
3677 )));
3678 }
3679 } else if !fixed.writable {
3680 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
3681 if !fixed_value.same_value(&value) {
3682 return Err(self.type_error(format!(
3683 "proxy 'set' changed the non-configurable property '{key}'"
3684 )));
3685 }
3686 }
3687 }
3688 // A new property cannot appear on a target that refuses new properties.
3689 if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
3690 return Err(self.type_error(format!(
3691 "proxy 'set' added '{key}' to a non-extensible target"
3692 )));
3693 }
3694 Ok(Some(true))
3695 }
3696
3697 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
3698 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
3699 let Some((target, handler)) = self.proxy_parts(object)? else {
3700 return Ok(None);
3701 };
3702 let key_value = self.key_value(key);
3703 let Some(result) = self.proxy_trap(
3704 &handler,
3705 "has",
3706 vec![Value::Object(target.clone()), key_value],
3707 )?
3708 else {
3709 return Ok(Some(self.has_own_or_inherited(&target, key)?));
3710 };
3711 if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
3712 return Err(self.type_error(format!(
3713 "proxy 'has' denied the non-configurable property '{key}'"
3714 )));
3715 }
3716 // A non-extensible target cannot grow, so every own property it *has* is fixed.
3717 if !result.to_boolean()
3718 && !target.is_extensible()
3719 && Self::ordinary_own_property(&target, key).is_some()
3720 {
3721 return Err(self.type_error(format!(
3722 "proxy 'has' denied the own property '{key}' of a non-extensible target"
3723 )));
3724 }
3725 Ok(Some(result.to_boolean()))
3726 }
3727
3728 /// `[[Delete]]` on a proxy.
3729 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
3730 let Some((target, handler)) = self.proxy_parts(object)? else {
3731 return Ok(None);
3732 };
3733 let key_value = self.key_value(key);
3734 let Some(result) = self.proxy_trap(
3735 &handler,
3736 "deleteProperty",
3737 vec![Value::Object(target.clone()), key_value],
3738 )?
3739 else {
3740 return Ok(Some(self.delete_property_key(&target, key)?));
3741 };
3742 if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
3743 return Err(self.type_error(format!(
3744 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
3745 )));
3746 }
3747 if result.to_boolean()
3748 && !target.is_extensible()
3749 && Self::ordinary_own_property(&target, key).is_some()
3750 {
3751 return Err(self.type_error(format!(
3752 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
3753 )));
3754 }
3755 Ok(Some(result.to_boolean()))
3756 }
3757
3758 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
3759 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
3760 let Some((target, handler)) = self.proxy_parts(object)? else {
3761 return Ok(None);
3762 };
3763 let Some(result) =
3764 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
3765 else {
3766 // No trap: the target's own keys, already in the order an object reports.
3767 return Ok(Some(self.object_own_property_keys(&target)?));
3768 };
3769 // `CreateListFromArrayLike` with the string-or-symbol restriction.
3770 let list = self.list_from_array_like(&result, true)?;
3771 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
3772 for value in list {
3773 let key = self.propkey(&value);
3774 if keys.contains(&key) {
3775 return Err(self.type_error(format!(
3776 "proxy 'ownKeys' returned the duplicate key '{key}'"
3777 )));
3778 }
3779 keys.push(key);
3780 }
3781 for (key, property) in target.property_entries() {
3782 if !property.configurable && !keys.contains(&key) {
3783 return Err(self.type_error(format!(
3784 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
3785 )));
3786 }
3787 if !target.is_extensible() && !keys.contains(&key) {
3788 return Err(self.type_error(format!(
3789 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
3790 )));
3791 }
3792 }
3793 if !target.is_extensible() {
3794 let own = target.property_entries().len();
3795 if keys.len() != own {
3796 return Err(
3797 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
3798 );
3799 }
3800 }
3801 Ok(Some(keys))
3802 }
3803
3804 /// `[[GetOwnProperty]]` on a proxy.
3805 fn proxy_get_own_property(
3806 &mut self,
3807 object: &Gc<JsObject>,
3808 key: &PropertyKey,
3809 ) -> JsResult<Option<Option<Property>>> {
3810 let Some((target, handler)) = self.proxy_parts(object)? else {
3811 return Ok(None);
3812 };
3813 let key_value = self.key_value(key);
3814 let Some(result) = self.proxy_trap(
3815 &handler,
3816 "getOwnPropertyDescriptor",
3817 vec![Value::Object(target.clone()), key_value],
3818 )?
3819 else {
3820 // No trap: the target's own descriptor is the answer. This has to go through
3821 // the same synthesis an ordinary object gets, because a proxy's own property
3822 // table is empty by design — reading it directly reported `undefined` for
3823 // every key, including an array's indices and `length`.
3824 return Ok(Some(Self::ordinary_own_property(&target, key)));
3825 };
3826 let answer = if matches!(result, Value::Undefined) {
3827 None
3828 } else {
3829 Some(self.property_from_descriptor(&result)?)
3830 };
3831 let fixed = Self::is_fixed_property(&target, key);
3832 match (&answer, &fixed) {
3833 // A non-configurable property cannot be reported as absent.
3834 (None, Some(_)) => {
3835 return Err(self.type_error(format!(
3836 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
3837 )));
3838 }
3839 (Some(descriptor), Some(fixed)) => {
3840 if descriptor.configurable {
3841 return Err(self.type_error(format!(
3842 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
3843 )));
3844 }
3845 if fixed.is_accessor() != descriptor.is_accessor() {
3846 return Err(self.type_error(format!(
3847 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
3848 )));
3849 }
3850 if !fixed.is_accessor() && !fixed.writable {
3851 let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
3852 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
3853 if !fixed_value.same_value(&reported) {
3854 return Err(self.type_error(format!(
3855 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
3856 )));
3857 }
3858 }
3859 }
3860 _ => {}
3861 }
3862 Ok(Some(answer))
3863 }
3864
3865 /// `[[DefineOwnProperty]]` on a proxy.
3866 fn proxy_define_property(
3867 &mut self,
3868 object: &Gc<JsObject>,
3869 key: &PropertyKey,
3870 property: Property,
3871 ) -> JsResult<Option<bool>> {
3872 let Some((target, handler)) = self.proxy_parts(object)? else {
3873 return Ok(None);
3874 };
3875 let key_value = self.key_value(key);
3876 let descriptor = self.descriptor_from_property(&property);
3877 let Some(result) = self.proxy_trap(
3878 &handler,
3879 "defineProperty",
3880 vec![Value::Object(target.clone()), key_value, descriptor],
3881 )?
3882 else {
3883 return Ok(None);
3884 };
3885 if !result.to_boolean() {
3886 return Ok(Some(false));
3887 }
3888 let fixed = Self::is_fixed_property(&target, key);
3889 let creating = Self::ordinary_own_property(&target, key).is_none();
3890 if creating && !target.is_extensible() {
3891 return Err(self.type_error(format!(
3892 "proxy 'defineProperty' added '{key}' to a non-extensible target"
3893 )));
3894 }
3895 if let Some(fixed) = fixed {
3896 if property.configurable {
3897 return Err(self.type_error(format!(
3898 "proxy 'defineProperty' made the non-configurable '{key}' configurable"
3899 )));
3900 }
3901 if !fixed.writable && property.writable && !fixed.is_accessor() {
3902 return Err(self.type_error(format!(
3903 "proxy 'defineProperty' made the read-only '{key}' writable"
3904 )));
3905 }
3906 }
3907 Ok(Some(true))
3908 }
3909
3910 /// `[[GetPrototypeOf]]` on a proxy.
3911 fn proxy_get_prototype_of(
3912 &mut self,
3913 object: &Gc<JsObject>,
3914 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
3915 let Some((target, handler)) = self.proxy_parts(object)? else {
3916 return Ok(None);
3917 };
3918 let Some(result) = self.proxy_trap(
3919 &handler,
3920 "getPrototypeOf",
3921 vec![Value::Object(target.clone())],
3922 )?
3923 else {
3924 return Ok(Some(target.proto()));
3925 };
3926 let proto = match &result {
3927 Value::Null => None,
3928 Value::Object(proto) => Some(proto.clone()),
3929 _ => {
3930 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
3931 }
3932 };
3933 if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
3934 return Err(self.type_error(
3935 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
3936 ));
3937 }
3938 Ok(Some(proto))
3939 }
3940
3941 /// `[[SetPrototypeOf]]` on a proxy.
3942 fn proxy_set_prototype_of(
3943 &mut self,
3944 object: &Gc<JsObject>,
3945 proto: Option<Gc<JsObject>>,
3946 ) -> JsResult<Option<bool>> {
3947 let Some((target, handler)) = self.proxy_parts(object)? else {
3948 return Ok(None);
3949 };
3950 let proto_value = match &proto {
3951 Some(proto) => Value::Object(proto.clone()),
3952 None => Value::Null,
3953 };
3954 let Some(result) = self.proxy_trap(
3955 &handler,
3956 "setPrototypeOf",
3957 vec![Value::Object(target.clone()), proto_value],
3958 )?
3959 else {
3960 target.set_proto(proto);
3961 return Ok(Some(true));
3962 };
3963 if result.to_boolean()
3964 && !target.is_extensible()
3965 && !same_proto(proto.as_ref(), target.proto().as_ref())
3966 {
3967 return Err(self.type_error(
3968 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
3969 ));
3970 }
3971 Ok(Some(result.to_boolean()))
3972 }
3973
3974 /// `[[IsExtensible]]` on a proxy.
3975 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
3976 let Some((target, handler)) = self.proxy_parts(object)? else {
3977 return Ok(None);
3978 };
3979 let Some(result) = self.proxy_trap(
3980 &handler,
3981 "isExtensible",
3982 vec![Value::Object(target.clone())],
3983 )?
3984 else {
3985 return Ok(Some(target.is_extensible()));
3986 };
3987 // The answer is not the proxy's to invent: it must agree with the target, or a
3988 // script could learn `false` while the target keeps accepting new properties.
3989 if result.to_boolean() != target.is_extensible() {
3990 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
3991 }
3992 Ok(Some(result.to_boolean()))
3993 }
3994
3995 /// `[[PreventExtensions]]` on a proxy.
3996 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
3997 let Some((target, handler)) = self.proxy_parts(object)? else {
3998 return Ok(None);
3999 };
4000 let Some(result) = self.proxy_trap(
4001 &handler,
4002 "preventExtensions",
4003 vec![Value::Object(target.clone())],
4004 )?
4005 else {
4006 target.set_extensible(false);
4007 return Ok(Some(true));
4008 };
4009 if result.to_boolean() && target.is_extensible() {
4010 return Err(self.type_error(
4011 "proxy 'preventExtensions' reported success but the target is still extensible",
4012 ));
4013 }
4014 Ok(Some(result.to_boolean()))
4015 }
4016
4017 /// `[[Call]]` on a proxy, through the `apply` trap.
4018 fn proxy_apply(
4019 &mut self,
4020 object: &Gc<JsObject>,
4021 this: Value,
4022 args: Vec<Value>,
4023 ) -> JsResult<Option<Value>> {
4024 let Some((target, handler)) = self.proxy_parts(object)? else {
4025 return Ok(None);
4026 };
4027 // The trap gets the arguments as one array, which is the shape the spec passes
4028 // and the shape `apply` traps are written against (`args[0]` is the first one).
4029 let arguments = self.new_array(args.clone());
4030 let this_for_trap = this.clone();
4031 let Some(result) = self.proxy_trap(
4032 &handler,
4033 "apply",
4034 vec![
4035 Value::Object(target.clone()),
4036 this_for_trap,
4037 Value::Object(arguments),
4038 ],
4039 )?
4040 else {
4041 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
4042 };
4043 Ok(Some(result))
4044 }
4045
4046 /// `[[Construct]]` on a proxy, through the `construct` trap.
4047 fn proxy_construct(
4048 &mut self,
4049 object: &Gc<JsObject>,
4050 args: Vec<Value>,
4051 new_target: &Value,
4052 ) -> JsResult<Option<Value>> {
4053 let Some((target, handler)) = self.proxy_parts(object)? else {
4054 return Ok(None);
4055 };
4056 if !target.is_callable() {
4057 return Err(self.type_error("proxy target is not a constructor"));
4058 }
4059 let arguments = self.new_array(args.clone());
4060 let Some(result) = self.proxy_trap(
4061 &handler,
4062 "construct",
4063 vec![
4064 Value::Object(target.clone()),
4065 Value::Object(arguments),
4066 new_target.clone(),
4067 ],
4068 )?
4069 else {
4070 return Ok(Some(self.construct(
4071 Value::Object(target),
4072 new_target.clone(),
4073 args,
4074 )?));
4075 };
4076 if !matches!(result, Value::Object(_)) {
4077 return Err(self.type_error("proxy 'construct' must return an object"));
4078 }
4079 Ok(Some(result))
4080 }
4081
4082 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
4083 pub(crate) fn has_own_or_inherited(
4084 &mut self,
4085 object: &Gc<JsObject>,
4086 key: &PropertyKey,
4087 ) -> JsResult<bool> {
4088 // The object itself first: it may be a proxy, and then the answer is its trap's.
4089 if let Some(answer) = self.proxy_has(object, key)? {
4090 return Ok(answer);
4091 }
4092 // `has_own` rather than `own_property_key`: an array's elements and its derived
4093 // `length` are invisible to the property table, and `Array.prototype` is an array.
4094 if has_own(object, key) {
4095 return Ok(true);
4096 }
4097 // A hole is *not* the end of the search: the chain may still have the key, which
4098 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
4099 for ancestor in object.chain() {
4100 // A proxy further up the chain answers for itself.
4101 if let Some(answer) = self.proxy_has(&ancestor, key)? {
4102 return Ok(answer);
4103 }
4104 if has_own(&ancestor, key) {
4105 return Ok(true);
4106 }
4107 }
4108 Ok(false)
4109 }
4110
4111 /// `CreateListFromArrayLike`, optionally restricted to property keys.
4112 ///
4113 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
4114 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
4115 /// `TypeError` instead of a property named `"1.5"`.
4116 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
4117 let object = self.object_from(value)?;
4118 let length = self
4119 .get_property(&object, "length")?
4120 .map(|value| value.to_number())
4121 .unwrap_or(0.0);
4122 if !length.is_finite() || length < 0.0 {
4123 return Err(self.type_error("invalid array-like length"));
4124 }
4125 let length = length as usize;
4126 let mut items = Vec::with_capacity(length.min(1024));
4127 for index in 0..length {
4128 let item = self
4129 .get_property(&object, &index.to_string())?
4130 .unwrap_or(Value::Undefined);
4131 if keys_only && matches!(&item, Value::Symbol(_)) {
4132 items.push(item);
4133 continue;
4134 }
4135 if keys_only && !matches!(&item, Value::String(_)) {
4136 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
4137 }
4138 items.push(item);
4139 }
4140 Ok(items)
4141 }
4142
4143 /// A `Property` from the descriptor object a trap returned.
4144 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
4145 let object = self.object_from(value)?;
4146 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
4147 interp.get_property(&object, name)
4148 };
4149 let getter = field(self, "get")?;
4150 let setter = field(self, "set")?;
4151 let accessor = getter.is_some() || setter.is_some();
4152 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
4153 Ok(interp
4154 .get_property(&object, name)?
4155 .is_some_and(|value| value.to_boolean()))
4156 };
4157 let enumerable = boolean(self, "enumerable")?;
4158 let configurable = boolean(self, "configurable")?;
4159 if accessor {
4160 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
4161 return Err(
4162 self.type_error("a descriptor cannot be both a data property and an accessor")
4163 );
4164 }
4165 Ok(Property {
4166 getter: getter.or(Some(Value::Undefined)),
4167 setter: setter.or(Some(Value::Undefined)),
4168 enumerable,
4169 configurable,
4170 writable: false,
4171 value: None,
4172 })
4173 } else {
4174 Ok(Property {
4175 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
4176 writable: boolean(self, "writable")?,
4177 enumerable,
4178 configurable,
4179 getter: None,
4180 setter: None,
4181 })
4182 }
4183 }
4184
4185 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
4186 fn descriptor_from_property(&mut self, property: &Property) -> Value {
4187 let object = self.new_object(None);
4188 if property.is_accessor() {
4189 let getter = property.getter.clone().unwrap_or(Value::Undefined);
4190 let setter = property.setter.clone().unwrap_or(Value::Undefined);
4191 object.define_data("get", getter);
4192 object.define_data("set", setter);
4193 } else {
4194 let value = property.value.clone().unwrap_or(Value::Undefined);
4195 object.define_data("value", value);
4196 object.define_data("writable", Value::Bool(property.writable));
4197 }
4198 object.define_data("enumerable", Value::Bool(property.enumerable));
4199 object.define_data("configurable", Value::Bool(property.configurable));
4200 Value::Object(object)
4201 }
4202
4203 // -- calling ------------------------------------------------------------
4204
4205 /// Call `callee` with `this` and `args`.
4206 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
4207 let Value::Object(function) = &callee else {
4208 // `typeof x === "function"` is not enough to make `x()` legal: only a
4209 // callable object is. `null` and `undefined` need no special wording
4210 // here — their `ToString` already reads the way the reference's does.
4211 let what = format!("{} is not a function", callee.to_js_string());
4212 return Err(Signal::Throw(self.make_error("TypeError", &what)));
4213 };
4214 // A proxy of a function is called through its `apply` trap. It has no
4215 // `ObjectKind::Function` of its own, so this has to come before the dispatch
4216 // below, and a proxy of a non-function has nothing to forward to.
4217 if function.proxy_state().is_some() {
4218 return match self.proxy_apply(function, this, args)? {
4219 Some(result) => Ok(result),
4220 None => Err(Signal::Throw(
4221 self.make_error("TypeError", "proxy target is not callable"),
4222 )),
4223 };
4224 }
4225 let callable = function.with(|data| match &data.kind {
4226 ObjectKind::Function(callable) => match callable {
4227 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
4228 Callable::Bound {
4229 target,
4230 this,
4231 args: leading,
4232 } => Some(NativeCall::Bound {
4233 target: target.clone(),
4234 this: this.clone(),
4235 leading: leading.clone(),
4236 }),
4237 Callable::Bytecode { code, env } => {
4238 Some(NativeCall::Bytecode(code.clone(), env.clone()))
4239 }
4240 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
4241 Callable::PromiseResolve(promise) => {
4242 Some(NativeCall::PromiseResolve(promise.clone()))
4243 }
4244 Callable::PromiseReject(promise) => {
4245 Some(NativeCall::PromiseReject(promise.clone()))
4246 }
4247 Callable::AwaitResume {
4248 coroutine,
4249 promise,
4250 kind,
4251 } => Some(NativeCall::AwaitResume {
4252 coroutine: coroutine.clone(),
4253 promise: promise.clone(),
4254 kind: *kind,
4255 }),
4256 Callable::CombinatorSettle {
4257 state,
4258 index,
4259 fulfilled,
4260 } => Some(NativeCall::CombinatorSettle {
4261 state: state.clone(),
4262 index: *index,
4263 fulfilled: *fulfilled,
4264 }),
4265 Callable::FinallyShim {
4266 callback,
4267 fulfilled,
4268 } => Some(NativeCall::FinallyShim {
4269 callback: callback.clone(),
4270 fulfilled: *fulfilled,
4271 }),
4272 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
4273 Callable::YieldResult { promise, done } => Some(NativeCall::YieldResult {
4274 promise: promise.clone(),
4275 done: *done,
4276 }),
4277 Callable::DisposeStep {
4278 remaining,
4279 promise,
4280 error,
4281 rejected,
4282 } => Some(NativeCall::DisposeStep {
4283 remaining: remaining.clone(),
4284 promise: promise.clone(),
4285 error: error.clone(),
4286 rejected: *rejected,
4287 }),
4288 Callable::GeneratorResume {
4289 generator,
4290 promise,
4291 kind,
4292 } => Some(NativeCall::GeneratorResume {
4293 generator: generator.clone(),
4294 promise: promise.clone(),
4295 kind: *kind,
4296 }),
4297 Callable::SettlePromise {
4298 promise,
4299 value,
4300 rejected,
4301 } => Some(NativeCall::SettlePromise {
4302 promise: promise.clone(),
4303 value: value.clone(),
4304 rejected: *rejected,
4305 }),
4306 },
4307 _ => None,
4308 });
4309 match callable {
4310 Some(NativeCall::Native(func)) => {
4311 // A function marked `_frame_less` is one the reference implements
4312 // without a call frame — `eval` is the only one so far.
4313 let frame_less = function
4314 .own_property("_frame_less")
4315 .and_then(|property| property.value)
4316 .is_some_and(|value| value.to_boolean());
4317 let name = function
4318 .own_property("name")
4319 .and_then(|property| property.value)
4320 .map(|value| value.to_js_string())
4321 .unwrap_or_default();
4322 let outer = if frame_less {
4323 None
4324 } else {
4325 self.native_frames.push((name, function.clone()));
4326 Some(self.current_native.replace(function.clone()))
4327 };
4328 let result = func(self, this, &args);
4329 if !frame_less {
4330 self.native_frames.pop();
4331 self.current_native = outer.flatten();
4332 }
4333 result
4334 }
4335 Some(NativeCall::Revoker(slots)) => {
4336 // Idempotent: revoking twice answers `undefined` again rather than
4337 // complaining, which is what the spec says and what a `finally` block
4338 // relies on.
4339 let mut state = slots.borrow_mut();
4340 state.target = None;
4341 state.handler = None;
4342 Ok(Value::Undefined)
4343 }
4344 Some(NativeCall::PromiseResolve(promise)) => {
4345 // One-shot: a second call is silently ignored, which
4346 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
4347 let value = args.first().cloned().unwrap_or(Value::Undefined);
4348 self.resolve_promise_with(&promise, value)?;
4349 Ok(Value::Undefined)
4350 }
4351 Some(NativeCall::PromiseReject(promise)) => {
4352 let reason = args.first().cloned().unwrap_or(Value::Undefined);
4353 self.reject_promise(&promise, reason);
4354 Ok(Value::Undefined)
4355 }
4356 Some(NativeCall::CombinatorSettle {
4357 state,
4358 index,
4359 fulfilled,
4360 }) => {
4361 let value = args.first().cloned().unwrap_or(Value::Undefined);
4362 self.settle_combinator(&state, index, fulfilled, value)?;
4363 Ok(Value::Undefined)
4364 }
4365 Some(NativeCall::AwaitResume {
4366 coroutine,
4367 promise,
4368 kind,
4369 }) => {
4370 // Resume *inline*, in the reaction that delivered the value. Deferring it
4371 // by another job inserts a tick between every `await` and its
4372 // continuation, which reorders `await` against unrelated `then` chains —
4373 // `f().then(g)` then runs before `f`'s own next statement.
4374 self.drive_async(
4375 &coroutine,
4376 &promise,
4377 kind,
4378 args.first().cloned().unwrap_or(Value::Undefined),
4379 )
4380 .map(|()| Value::Undefined)
4381 }
4382 Some(NativeCall::FinallyShim {
4383 callback,
4384 fulfilled,
4385 }) => {
4386 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
4387 // that settles with the *original* outcome once the callback's result has
4388 // settled. The callback's own value is discarded — that is the whole
4389 // difference between `finally` and `then`.
4390 let original = args.first().cloned().unwrap_or(Value::Undefined);
4391 let result = match &callback {
4392 Some(callback) => {
4393 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
4394 }
4395 None => Value::Undefined,
4396 };
4397 let resolved = self.promise_resolve_value(result)?;
4398 let Value::Object(resolved) = resolved else {
4399 return Ok(original);
4400 };
4401 // The wait is a chained promise rather than a bare return, so a callback
4402 // that returns a slow promise really does delay the continuation.
4403 let waiting = self.new_promise();
4404 let pass = JsObject::function(
4405 self.heap,
4406 Some(self.realm.function_proto.clone()),
4407 Callable::SettlePromise {
4408 promise: waiting.clone(),
4409 value: original,
4410 rejected: !fulfilled,
4411 },
4412 );
4413 let pass = Value::Object(pass);
4414 // Whichever way the callback's promise settles, the original outcome wins.
4415 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
4416 Ok(Value::Object(waiting))
4417 }
4418 Some(NativeCall::DisposeStep {
4419 remaining,
4420 promise,
4421 error,
4422 rejected,
4423 }) => {
4424 let error = if rejected {
4425 let reason = args.first().cloned().unwrap_or(Value::Undefined);
4426 self.merge_dispose_error(reason, error)
4427 } else {
4428 error
4429 };
4430 self.dispose_step(&remaining, &promise, error)?;
4431 Ok(Value::Undefined)
4432 }
4433 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
4434 Some(NativeCall::YieldResult { promise, done }) => {
4435 let value = args.first().cloned().unwrap_or(Value::Undefined);
4436 let result = self.iterator_result(value, done)?;
4437 self.fulfill_promise(&promise, result);
4438 Ok(Value::Undefined)
4439 }
4440 Some(NativeCall::GeneratorResume {
4441 generator,
4442 promise,
4443 kind,
4444 }) => {
4445 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
4446 // tick and reorders the generator against other chains.
4447 self.step_async_generator(
4448 &generator,
4449 &promise,
4450 kind,
4451 args.first().cloned().unwrap_or(Value::Undefined),
4452 )
4453 .map(|()| Value::Undefined)
4454 }
4455 Some(NativeCall::SettlePromise {
4456 promise,
4457 value,
4458 rejected,
4459 }) => {
4460 if rejected {
4461 self.reject_promise(&promise, value);
4462 } else {
4463 self.fulfill_promise(&promise, value);
4464 }
4465 Ok(Value::Undefined)
4466 }
4467 Some(NativeCall::Bound {
4468 target,
4469 this: bound_this,
4470 leading,
4471 }) => {
4472 let mut all = leading;
4473 all.extend(args);
4474 self.call_value(target, bound_this, all)
4475 }
4476 Some(NativeCall::Bytecode(code, env)) => {
4477 if code.code.kind.is_generator() {
4478 return self.new_generator(callee, this, args);
4479 }
4480 if code.code.kind.is_async() {
4481 // Same coroutine machinery as a generator; the difference is only in
4482 // what the completion does — see `new_async_function`.
4483 return self.new_async_function(callee, this, args);
4484 }
4485 self.execute(code, env, this, args, callee)
4486 }
4487 None => Err(Signal::Throw(
4488 self.make_error("TypeError", "not a function"),
4489 )),
4490 }
4491 }
4492
4493 /// Give a freshly built function its own `prototype` object.
4494 ///
4495 /// Every function that can be used with `new` carries one, and its
4496 /// `constructor` points back at the function — a reference cycle, which is
4497 /// exactly what the collector's cycle pass exists to reclaim.
4498 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
4499 let prototype = self.new_object(Some(self.realm.object_proto.clone()));
4500 let constructor = Value::Object(function.clone());
4501 prototype.define(
4502 "constructor",
4503 Property::with_attributes(constructor, true, false),
4504 );
4505 let value = Value::Object(prototype);
4506 function.define("prototype", Property::prototype_of(value, true));
4507 }
4508
4509 /// The object `special_object` builds.
4510 ///
4511 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
4512 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
4513 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
4514 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
4515 /// write through `arguments` does not reach the parameter.
4516 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
4517 match magic {
4518 0 | 1 => {
4519 let args = self.frame().passed.clone();
4520 let proto = self.realm.object_proto.clone();
4521 let object = self.new_object(Some(proto));
4522 // The marker `Object.prototype.toString` needs: an arguments object is an
4523 // ordinary object apart from reporting `[object Arguments]`, and that has
4524 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
4525 // show up ahead of them in a key listing anyway — it is non-enumerable.
4526 self.internal_set(&object, "_class", self.string("Arguments"));
4527 // `length` is writable and configurable but neither enumerable nor a
4528 // plain data property: `Object.keys(arguments)` lists the indices only,
4529 // which is how `{...arguments}` copies them without the length.
4530 object.define(
4531 "length",
4532 Property::with_attributes(Value::Int(args.len() as i32), true, false),
4533 );
4534 for (index, value) in args.into_iter().enumerate() {
4535 object.define_data(&index.to_string(), value);
4536 }
4537 // An arguments object is iterable: `[...arguments]` and
4538 // `for (const a of arguments)` both work, through the *array* iterator
4539 // because the object is array-like. Without this the whole spread form
4540 // reported "not iterable".
4541 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
4542 let values = self
4543 .realm
4544 .array_proto
4545 .own_property("values")
4546 .and_then(|property| property.value);
4547 if let Some(values) = values {
4548 object.define_key(
4549 &iterator_key,
4550 Property::with_attributes(values, true, false),
4551 );
4552 }
4553 Ok(Value::Object(object))
4554 }
4555 // `this function`: what a named function expression binds its own name to.
4556 2 => Ok(self
4557 .current_callee()
4558 .map_or(Value::Undefined, Value::Object)),
4559 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
4560 // inherited from the caller inside an `eval`.
4561 3 => Ok(self
4562 .eval_new_target
4563 .clone()
4564 .unwrap_or_else(|| self.frame().new_target.clone())),
4565 // `[[HomeObject]]` of the function being run: what `super` is relative to.
4566 // An arrow has none of its own, so the lookup walks out to the enclosing
4567 // method — which is why `super` works inside an arrow inside a method.
4568 4 => Ok(self
4569 .frames
4570 .iter()
4571 .rev()
4572 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
4573 .map_or(Value::Undefined, Value::Object)),
4574 // `import.meta`: the innermost module body's meta object. Outside a module
4575 // the compiler never emits this, so an empty fallback is unreachable rather
4576 // than permissive.
4577 6 => {
4578 let name = self.module_stack.last().cloned();
4579 let meta = name
4580 .and_then(|name| self.modules.get(&name).cloned())
4581 .and_then(|module| module.with(|r| r.import_meta.clone()));
4582 Ok(meta.map_or(Value::Undefined, Value::Object))
4583 }
4584 other => Err(Signal::Throw(self.make_error(
4585 "InternalError",
4586 &format!("special_object {other} is not implemented yet"),
4587 ))),
4588 }
4589 }
4590
4591 /// `[[HomeObject]]` of the innermost function that has one, if any.
4592 ///
4593 /// An arrow has none, so the search walks out to the enclosing method — the same
4594 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
4595 /// inside a method.
4596 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
4597 self.frames
4598 .iter()
4599 .rev()
4600 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
4601 }
4602
4603 /// The dispose method a `using` declaration should snapshot, or an error.
4604 ///
4605 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
4606 /// is what makes a resource that only knows the synchronous protocol usable in both
4607 /// forms.
4608 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
4609 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
4610 if value.is_nullish() {
4611 return Ok(Value::Undefined);
4612 }
4613 let Some(object) = value.as_object() else {
4614 return Err(self.type_error("value is not disposable: it is not an object"));
4615 };
4616 let mut method = if await_form {
4617 let found = self.get_property_key(
4618 object,
4619 &self.realm.well_known_key(WellKnown::AsyncDisposable),
4620 )?;
4621 match found {
4622 Some(found) if !found.is_nullish() => Some(found),
4623 _ => self
4624 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
4625 }
4626 } else {
4627 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
4628 };
4629 let Some(found) = method.take() else {
4630 return Err(self.type_error("value is not disposable"));
4631 };
4632 if found.is_nullish() {
4633 return Err(self.type_error("value is not disposable"));
4634 }
4635 let callable = found.as_object().is_some_and(|object| object.is_callable());
4636 if !callable {
4637 return Err(self.type_error("dispose method is not a function"));
4638 }
4639 Ok(found)
4640 }
4641
4642 /// Call one resource's disposer, folding a failure into `error_state`.
4643 ///
4644 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
4645 /// because a captured `using` binding lives in its reference cell and the local slot is
4646 /// stale — a closure over the resource is legal and must not change what is disposed.
4647 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
4648 let value = self.get_loc(slot);
4649 let method = self.get_loc(slot + 1);
4650 // A resource that was never initialised — its declaration threw — or that is
4651 // `null`/`undefined` has nothing to dispose.
4652 if value.is_nullish() || matches!(value, Value::Uninitialized) {
4653 return Ok(error_state);
4654 }
4655 if matches!(method, Value::Undefined | Value::Uninitialized) {
4656 return Ok(error_state);
4657 }
4658 match self.call_value(method, value, Vec::new()) {
4659 Ok(_) => Ok(error_state),
4660 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
4661 Err(other) => Err(other),
4662 }
4663 }
4664
4665 /// Combine a disposal failure with whatever was already going wrong.
4666 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
4667 if matches!(error_state, Value::Uninitialized) {
4668 return new_error;
4669 }
4670 self.new_suppressed_error(new_error, error_state)
4671 }
4672
4673 /// A `SuppressedError` instance built straight from its prototype.
4674 ///
4675 /// Not through the constructor: a script that rewrites
4676 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
4677 /// error wrapping.
4678 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
4679 let proto = self
4680 .realm
4681 .suppressed_error_proto
4682 .clone()
4683 .unwrap_or_else(|| self.realm.error_proto.clone());
4684 let object = self.new_object(Some(proto));
4685 object.define("error", Property::with_attributes(error, true, true));
4686 object.define(
4687 "suppressed",
4688 Property::with_attributes(suppressed, true, true),
4689 );
4690 object.define(
4691 "message",
4692 Property::with_attributes(self.string("SuppressedError"), true, true),
4693 );
4694 self.internal_set(&object, "_class", self.string("Error"));
4695 self.add_stack(&object);
4696 Value::Object(object)
4697 }
4698
4699 /// Call `callee`, or push its frame and let the main loop run it.
4700 ///
4701 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
4702 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
4703 /// continues, so `function f(){ return f() }` costs heap and stops at
4704 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
4705 /// is entered directly, and natives do not re-enter JavaScript in this
4706 /// milestone.
4707 ///
4708 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
4709 /// because the returning frame will.
4710 /// The elements of an array-like value, as a call argument list.
4711 ///
4712 /// `apply` accepts any array-like, not only a real array: the reference reads
4713 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
4714 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
4715 let Some(object) = value.as_object().cloned() else {
4716 if value.is_nullish() {
4717 // `f.apply(this, null)` passes no arguments at all.
4718 return Ok(Vec::new());
4719 }
4720 return Err(self.type_error("createListFromArrayLike called on non-object"));
4721 };
4722 let length = match self.get_property(&object, "length")? {
4723 Some(length) => length.to_number(),
4724 None => 0.0,
4725 };
4726 if !length.is_finite() || length <= 0.0 {
4727 return Ok(Vec::new());
4728 }
4729 let length = (length as usize).min(1_000_000);
4730 let mut args = Vec::with_capacity(length);
4731 for index in 0..length {
4732 let element = self.get_property(&object, &index.to_string())?;
4733 args.push(element.unwrap_or(Value::Undefined));
4734 }
4735 Ok(args)
4736 }
4737
4738 /// Turn a call to a generator function into a generator object.
4739 ///
4740 /// The frame is built exactly as an ordinary call would build it, then detached and
4741 /// stored in the generator before any body instruction runs — which is what makes
4742 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
4743 /// is `initial_yield`, the first instruction of every suspending body.
4744 pub fn new_generator(
4745 &mut self,
4746 function: Value,
4747 this: Value,
4748 args: Vec<Value>,
4749 ) -> JsResult<Value> {
4750 let Some(object) = function.as_object().cloned() else {
4751 return Err(self.type_error("not a generator function"));
4752 };
4753 let Some((code, env)) = bytecode_of(&object) else {
4754 return Err(self.type_error("not a generator function"));
4755 };
4756 let is_async = code.code.kind.is_async();
4757 self.push_frame(code, env, this, args, function)?;
4758 let frame = self.frames.pop().expect("push_frame just pushed it");
4759 // A fresh generator is *suspended at start*: the body has not run, so a
4760 // `return`/`throw` on it finishes without executing anything.
4761 let mut state = GeneratorState {
4762 frame: Some(frame),
4763 phase: GeneratorPhase::SuspendedStart,
4764 parked_on_await: false,
4765 };
4766 // Run to the first suspension. For a generator that is `initial_yield`, so no
4767 // body code runs; for a malformed body it would be the first `yield`.
4768 // An `async function*` answers an async generator: same coroutine, but its
4769 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
4770 let proto = if is_async {
4771 self.realm
4772 .async_generator_proto
4773 .clone()
4774 .unwrap_or_else(|| self.realm.generator_proto.clone())
4775 } else {
4776 self.realm.generator_proto.clone()
4777 };
4778 let generator = self.new_object(Some(proto));
4779 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
4780 Ok(_) => {}
4781 Err(error) => return Err(error),
4782 }
4783 generator.with_mut(|data| {
4784 data.kind = ObjectKind::Generator(Box::new(state));
4785 });
4786 Ok(Value::Object(generator))
4787 }
4788
4789 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
4790 ///
4791 /// Returns the `{value, done}` object itself rather than the pair, because a
4792 /// `yield*` suspension already has one — the inner iterator's own result — and the
4793 /// protocol says to hand that straight through rather than nest it.
4794 /// Advance a generator and report *why* it parked.
4795 ///
4796 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
4797 /// "hand this value to the caller" — but an async generator does: an `await` has to
4798 /// settle before it can answer, while a `yield` is the answer.
4799 fn resume_generator_detailed(
4800 &mut self,
4801 generator: &Gc<JsObject>,
4802 kind: ResumeKind,
4803 value: Value,
4804 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
4805 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
4806 ObjectKind::Generator(state) => Some(std::mem::replace(
4807 state.as_mut(),
4808 GeneratorState {
4809 frame: None,
4810 phase: GeneratorPhase::Executing,
4811 parked_on_await: false,
4812 },
4813 )),
4814 _ => None,
4815 }) else {
4816 return Err(self.type_error("not a generator"));
4817 };
4818 let result = self.step_generator(&mut state, kind, value);
4819 generator.with_mut(|data| {
4820 data.kind = ObjectKind::Generator(Box::new(state));
4821 });
4822 result
4823 }
4824
4825 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
4826 ///
4827 /// Returns the `{value, done}` object itself rather than the pair, because a
4828 /// `yield*` suspension already has one — the inner iterator's own result — and the
4829 /// protocol says to hand that straight through rather than nest it.
4830 pub fn resume_generator(
4831 &mut self,
4832 generator: &Gc<JsObject>,
4833 kind: ResumeKind,
4834 value: Value,
4835 ) -> JsResult<Value> {
4836 let (value, done, ready, _reason) =
4837 self.resume_generator_detailed(generator, kind, value)?;
4838 if ready {
4839 return Ok(value);
4840 }
4841 self.iterator_result(value, done)
4842 }
4843
4844 /// `next`/`return`/`throw` on an async generator, which answer a promise.
4845 ///
4846 /// The body is the same coroutine a sync generator runs; what changes is that an
4847 /// `await` inside it has to settle before the method can answer, so the step is
4848 /// driven off the job queue rather than returning inline.
4849 pub fn resume_async_generator(
4850 &mut self,
4851 generator: &Gc<JsObject>,
4852 kind: ResumeKind,
4853 value: Value,
4854 ) -> JsResult<Value> {
4855 let promise = self.new_promise();
4856 self.step_async_generator(generator, &promise, kind, value)?;
4857 Ok(Value::Object(promise))
4858 }
4859
4860 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
4861 ///
4862 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
4863 /// disposer runs **synchronously** — the reference starts it before returning, which
4864 /// a test can observe by logging after the call — and the rest follow once their
4865 /// predecessor settles.
4866 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
4867 let promise = self.new_promise();
4868 let mut pairs = Vec::with_capacity(resources.len());
4869 for (value, method) in resources {
4870 let pair = self.new_array(vec![value, method]);
4871 pairs.push(Value::Object(pair));
4872 }
4873 let remaining = self.new_array(pairs);
4874 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
4875 Ok(Value::Object(promise))
4876 }
4877
4878 /// One link of the `disposeAsync` chain.
4879 ///
4880 /// Loops while the disposers finish synchronously, and parks on the first thenable it
4881 /// meets — pushing itself back in as the continuation, with the accumulated error
4882 /// carried along so a later failure can still be folded into the `SuppressedError`.
4883 fn dispose_step(
4884 &mut self,
4885 remaining: &Gc<JsObject>,
4886 promise: &Gc<JsObject>,
4887 mut error: Value,
4888 ) -> JsResult<()> {
4889 loop {
4890 let length = remaining.array_length().unwrap_or(0);
4891 if length == 0 {
4892 if matches!(error, Value::Uninitialized) {
4893 self.fulfill_promise(promise, Value::Undefined);
4894 } else {
4895 self.reject_promise(promise, error);
4896 }
4897 return Ok(());
4898 }
4899 let Some(Value::Object(pair)) = remaining
4900 .array_get(length - 1)
4901 .filter(|v| !matches!(v, Value::Hole))
4902 else {
4903 remaining.array_truncate(length - 1);
4904 continue;
4905 };
4906 remaining.array_truncate(length - 1);
4907 let value = pair.array_get(0).unwrap_or(Value::Undefined);
4908 let Some(Value::Object(method)) = pair.array_get(1) else {
4909 continue;
4910 };
4911 if !method.is_callable() {
4912 continue;
4913 }
4914 match self.call_value(Value::Object(method), value, Vec::new()) {
4915 Ok(result) => {
4916 if !self.is_thenable(&result)? {
4917 // Finished synchronously; the next disposer is the next iteration.
4918 continue;
4919 }
4920 let awaited = match self.promise_resolve_value(result) {
4921 Ok(awaited) => awaited,
4922 Err(Signal::Throw(reason)) => {
4923 self.reject_promise(promise, reason);
4924 return Ok(());
4925 }
4926 Err(other) => return Err(other),
4927 };
4928 let Value::Object(awaited) = awaited else {
4929 continue;
4930 };
4931 let ok = JsObject::function(
4932 self.heap,
4933 Some(self.realm.function_proto.clone()),
4934 Callable::DisposeStep {
4935 remaining: remaining.clone(),
4936 promise: promise.clone(),
4937 error: error.clone(),
4938 rejected: false,
4939 },
4940 );
4941 let failed = JsObject::function(
4942 self.heap,
4943 Some(self.realm.function_proto.clone()),
4944 Callable::DisposeStep {
4945 remaining: remaining.clone(),
4946 promise: promise.clone(),
4947 error,
4948 rejected: true,
4949 },
4950 );
4951 self.perform_then(
4952 &awaited,
4953 Some(Value::Object(ok)),
4954 Some(Value::Object(failed)),
4955 )?;
4956 return Ok(());
4957 }
4958 Err(Signal::Throw(thrown)) => {
4959 error = self.merge_dispose_error(thrown, error);
4960 }
4961 Err(other) => return Err(other),
4962 }
4963 }
4964 }
4965
4966 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
4967 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
4968 let Value::Object(object) = value else {
4969 return Ok(false);
4970 };
4971 Ok(matches!(
4972 self.get_property(object, "then")?,
4973 Some(Value::Object(then)) if then.is_callable()
4974 ))
4975 }
4976
4977 /// One step of an async generator, settling `promise` with an `{value, done}` result.
4978 fn step_async_generator(
4979 &mut self,
4980 generator: &Gc<JsObject>,
4981 promise: &Gc<JsObject>,
4982 kind: ResumeKind,
4983 value: Value,
4984 ) -> JsResult<()> {
4985 let stepped = self.resume_generator_detailed(generator, kind, value);
4986 let (value, done, ready, reason) = match stepped {
4987 Ok(stepped) => stepped,
4988 Err(Signal::Throw(reason)) => {
4989 self.reject_promise(promise, reason);
4990 return Ok(());
4991 }
4992 Err(other) => return Err(other),
4993 };
4994 // Only an `await` has to wait before the method can answer.
4995 if !done && reason == Some(SuspendKind::Await) {
4996 let awaited = match self.promise_resolve_value(value) {
4997 Ok(awaited) => awaited,
4998 Err(Signal::Throw(reason)) => {
4999 self.reject_promise(promise, reason);
5000 return Ok(());
5001 }
5002 Err(other) => return Err(other),
5003 };
5004 let Value::Object(awaited) = awaited else {
5005 return Ok(());
5006 };
5007 let resumed = JsObject::function(
5008 self.heap,
5009 Some(self.realm.function_proto.clone()),
5010 Callable::GeneratorResume {
5011 generator: generator.clone(),
5012 promise: promise.clone(),
5013 kind: ResumeKind::Next,
5014 },
5015 );
5016 let raised = JsObject::function(
5017 self.heap,
5018 Some(self.realm.function_proto.clone()),
5019 Callable::GeneratorResume {
5020 generator: generator.clone(),
5021 promise: promise.clone(),
5022 kind: ResumeKind::Throw,
5023 },
5024 );
5025 self.perform_then(
5026 &awaited,
5027 Some(Value::Object(resumed)),
5028 Some(Value::Object(raised)),
5029 )?;
5030 return Ok(());
5031 }
5032 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
5033 // completes it — both arrive as the settled value rather than as the promise
5034 // object. A plain value skips the round trip, which is also what keeps `yield 1`
5035 // from costing an extra tick.
5036 let awaits_value = self.is_thenable(&value)?;
5037 if awaits_value {
5038 let awaited = match self.promise_resolve_value(value) {
5039 Ok(awaited) => awaited,
5040 Err(Signal::Throw(reason)) => {
5041 self.reject_promise(promise, reason);
5042 return Ok(());
5043 }
5044 Err(other) => return Err(other),
5045 };
5046 let Value::Object(awaited) = awaited else {
5047 return Ok(());
5048 };
5049 // A rejected yield throws *at the yield* inside the body, so the rejection
5050 // resumes the generator rather than the method's promise.
5051 let answer = JsObject::function(
5052 self.heap,
5053 Some(self.realm.function_proto.clone()),
5054 Callable::YieldResult {
5055 promise: promise.clone(),
5056 done,
5057 },
5058 );
5059 let raise = JsObject::function(
5060 self.heap,
5061 Some(self.realm.function_proto.clone()),
5062 Callable::GeneratorResume {
5063 generator: generator.clone(),
5064 promise: promise.clone(),
5065 kind: ResumeKind::Throw,
5066 },
5067 );
5068 self.perform_then(
5069 &awaited,
5070 Some(Value::Object(answer)),
5071 Some(Value::Object(raise)),
5072 )?;
5073 return Ok(());
5074 }
5075 let result = if ready {
5076 // `yield*` handed back the inner iterator's own result object.
5077 value
5078 } else {
5079 self.iterator_result(value, done)?
5080 };
5081 self.fulfill_promise(promise, result);
5082 Ok(())
5083 }
5084
5085 /// The `{value, done}` object an iterator method answers with.
5086 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
5087 let result = self.new_object(Some(self.realm.object_proto.clone()));
5088 result.define_data("value", value);
5089 result.define_data("done", Value::Bool(done));
5090 Ok(Value::Object(result))
5091 }
5092
5093 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
5094 fn step_generator(
5095 &mut self,
5096 state: &mut GeneratorState,
5097 kind: ResumeKind,
5098 value: Value,
5099 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
5100 match state.phase {
5101 GeneratorPhase::Executing => {
5102 return Err(self.type_error("cannot invoke a running generator"));
5103 }
5104 GeneratorPhase::Completed => {
5105 // A finished generator answers every resumption without running.
5106 return Ok(match kind {
5107 ResumeKind::Throw => return Err(Signal::Throw(value)),
5108 ResumeKind::Return => (value, true, false, None),
5109 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
5110 });
5111 }
5112 GeneratorPhase::SuspendedStart => {
5113 if kind != ResumeKind::Next && kind != ResumeKind::Start {
5114 // The body never started, so there is nothing to unwind or return
5115 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
5116 state.frame = None;
5117 state.phase = GeneratorPhase::Completed;
5118 return Ok(match kind {
5119 ResumeKind::Throw => return Err(Signal::Throw(value)),
5120 _ => (value, true, false, None),
5121 });
5122 }
5123 }
5124 GeneratorPhase::SuspendedYield => {}
5125 }
5126
5127 let Some(mut frame) = state.frame.take() else {
5128 return Ok((Value::Undefined, true, false, None));
5129 };
5130 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
5131 // number that says which method resumed it; the emitted `if_false` branches on
5132 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
5133 let mut raised = None;
5134 match kind {
5135 ResumeKind::Next | ResumeKind::Start => {
5136 if state.phase == GeneratorPhase::SuspendedYield {
5137 frame.stack.push(value);
5138 // An `await` resumes with its value alone; only a `yield` gets the
5139 // magic number that says which of `next`/`return` resumed it.
5140 if !state.parked_on_await {
5141 frame.stack.push(Value::Int(RESUME_NEXT));
5142 }
5143 }
5144 }
5145 ResumeKind::Return => {
5146 // A `return` on a not-yet-started generator is handled above, so this is
5147 // always a real resumption.
5148 frame.stack.push(value);
5149 frame.stack.push(Value::Int(RESUME_RETURN));
5150 }
5151 ResumeKind::Throw => raised = Some(value),
5152 }
5153 state.phase = GeneratorPhase::Executing;
5154
5155 let depth = self.frames.len();
5156 self.frames.push(frame);
5157 // A `throw` unwinds from where the frame parked, exactly as if the exception had
5158 // happened at the `yield`.
5159 if let Some(exception) = raised {
5160 if self.catch_here(exception.clone()).is_none() {
5161 self.frames.pop();
5162 state.phase = GeneratorPhase::Completed;
5163 return Err(Signal::Throw(exception));
5164 }
5165 }
5166
5167 // Only the generator's *own* frame ends the generator. The body may call ordinary
5168 // functions, and those push frames of their own: a `Step::Return` from one of them
5169 // is a nested call finishing, not the generator completing. Miscounting that is
5170 // silent — the generator reports the callee's value as its own result and marks
5171 // itself done — so the depth comparison is load-bearing, not defensive.
5172 let own_frame = depth + 1;
5173 loop {
5174 match self.step() {
5175 Ok(Step::Continue) => {}
5176 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
5177 let mut frame = self.frames.pop().expect("a frame is live");
5178 // `yield` left the value on the stack; `initial_yield` left nothing.
5179 let yielded = if reason == SuspendKind::Initial {
5180 Value::Undefined
5181 } else {
5182 frame.stack.pop().unwrap_or(Value::Undefined)
5183 };
5184 state.frame = Some(frame);
5185 state.parked_on_await = reason == SuspendKind::Await;
5186 state.phase = if reason == SuspendKind::Initial {
5187 GeneratorPhase::SuspendedStart
5188 } else {
5189 GeneratorPhase::SuspendedYield
5190 };
5191 // `yield*` hands the inner iterator's own result object straight
5192 // back, so the caller sees one `{value, done}` rather than a nested
5193 // one — which is why the third field says "already a result".
5194 return Ok((
5195 yielded,
5196 false,
5197 reason == SuspendKind::YieldStar,
5198 Some(reason),
5199 ));
5200 }
5201 Ok(Step::Suspend(_)) => {
5202 // A `yield` in a frame other than the generator's would mean a
5203 // generator body entered as an ordinary call, which
5204 // `call_or_push` prevents.
5205 self.unwind_to(depth);
5206 state.phase = GeneratorPhase::Completed;
5207 return Err(Signal::Throw(self.make_error(
5208 "InternalError",
5209 "a generator body ran as an ordinary call",
5210 )));
5211 }
5212 Ok(Step::Return(value)) => {
5213 self.frames.pop();
5214 if self.frames.len() > depth {
5215 // A nested call finished: hand the value back to its caller and
5216 // keep running the generator body.
5217 self.frames
5218 .last_mut()
5219 .expect("a caller is live")
5220 .stack
5221 .push(value);
5222 continue;
5223 }
5224 state.phase = GeneratorPhase::Completed;
5225 // The reference closes the generator's closure variables here; ours
5226 // live in cells the frame owned, which the drop below releases.
5227 return Ok((value, true, false, None));
5228 }
5229 Err(Signal::Throw(exception)) => {
5230 // The frame that threw gets the first chance to catch, exactly as in
5231 // the ordinary call loop; a frame above the generator's is popped and
5232 // the exception carries on down.
5233 let exception = exception;
5234 loop {
5235 if self.frames.len() <= depth {
5236 // The generator's own frame is gone, so nothing here caught it.
5237 state.phase = GeneratorPhase::Completed;
5238 return Err(Signal::Throw(exception));
5239 }
5240 if self.catch_here(exception.clone()).is_some() {
5241 break;
5242 }
5243 self.frames.pop();
5244 }
5245 }
5246 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
5247 }
5248 }
5249 }
5250
5251 /// Pop frames until `depth` are left.
5252 fn unwind_to(&mut self, depth: usize) {
5253 self.frames.truncate(depth);
5254 }
5255 fn call_or_push(
5256 &mut self,
5257 callee: Value,
5258 this: Value,
5259 args: Vec<Value>,
5260 ) -> JsResult<Option<Value>> {
5261 if let Value::Object(function) = &callee
5262 && let Some((code, env)) = bytecode_of(function)
5263 {
5264 // Calling a generator function does not run anything: it captures the
5265 // arguments in a frame and hands back the generator object.
5266 if code.code.kind.is_generator() {
5267 return self.new_generator(callee, this, args).map(Some);
5268 }
5269 // An async function answers a promise and runs its body as a coroutine, so it
5270 // takes the same path as a plain call into it.
5271 if code.code.kind.is_async() {
5272 return self.new_async_function(callee, this, args).map(Some);
5273 }
5274 self.push_frame(code, env, this, args, callee)?;
5275 return Ok(None);
5276 }
5277 self.call_value(callee, this, args).map(Some)
5278 }
5279
5280 /// `new callee(args)`.
5281 ///
5282 /// A constructor differs from a plain call in three ways: it gets a fresh object
5283 /// as `this` whose prototype is the constructor's `prototype` property, its
5284 /// return value is *replaced* by that object unless it returns an object itself,
5285 /// and a native constructor is expected to initialise the object it is given
5286 /// rather than build one.
5287 pub fn construct(
5288 &mut self,
5289 callee: Value,
5290 new_target: Value,
5291 args: Vec<Value>,
5292 ) -> JsResult<Value> {
5293 // `new` on a bound function constructs its *target*, prepending the arguments
5294 // the bind fixed and ignoring the bound `this` — a bound function is a
5295 // constructor only when its target is one, and `new` always makes a fresh
5296 // object of the target's prototype rather than reusing the bound receiver.
5297 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
5298 // ran the body with `this === null` and threw on `this.x = a`.
5299 let mut callee = callee;
5300 let mut new_target = new_target;
5301 let mut args = args;
5302 loop {
5303 let Some(object) = callee.as_object().cloned() else {
5304 return Err(Signal::Throw(
5305 self.make_error("TypeError", "not a constructor"),
5306 ));
5307 };
5308 // A proxy of a function constructs through its `construct` trap, and the
5309 // trap's answer is the result directly — no fresh object is made here.
5310 if object.proxy_state().is_some() {
5311 return match self.proxy_construct(&object, args, &new_target)? {
5312 Some(result) => Ok(result),
5313 None => Err(Signal::Throw(
5314 self.make_error("TypeError", "proxy target is not a constructor"),
5315 )),
5316 };
5317 }
5318 // A function can opt out of `[[Construct]]` outright. `Symbol` does: there is
5319 // no wrapper object to build, and `new Symbol()` is a `TypeError` naming it.
5320 if object
5321 .own_property("_not_a_constructor")
5322 .and_then(|property| property.value)
5323 .is_some_and(|value| value.to_boolean())
5324 {
5325 let name = object
5326 .own_property("name")
5327 .and_then(|property| property.value)
5328 .map(|value| value.to_js_string())
5329 .unwrap_or_default();
5330 return Err(Signal::Throw(
5331 self.make_error("TypeError", &format!("{name} is not a constructor")),
5332 ));
5333 }
5334 // A generator function has no `[[Construct]]`, and the reference names it in
5335 // the message: `new (function* G(){})()` reports "G is not a constructor".
5336 if object.with(|data| match &data.kind {
5337 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
5338 code.code.kind.is_generator()
5339 }
5340 _ => false,
5341 }) {
5342 let name = object
5343 .own_property("name")
5344 .and_then(|property| property.value)
5345 .map(|value| value.to_js_string())
5346 .unwrap_or_default();
5347 return Err(Signal::Throw(
5348 self.make_error("TypeError", &format!("{name} is not a constructor")),
5349 ));
5350 }
5351 let bound = object.with(|data| match &data.kind {
5352 ObjectKind::Function(Callable::Bound {
5353 target,
5354 args: leading,
5355 ..
5356 }) => Some((target.clone(), leading.clone())),
5357 _ => None,
5358 });
5359 let Some((target, leading)) = bound else {
5360 // Not a bound function, so this object is the callee. §7.2.4
5361 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
5362 // refusals above cover only the built-ins the reference also refuses by
5363 // name. Everything else — a method, an arrow, an async function — has no
5364 // `[[Construct]]` either, and answering "yes" here made
5365 // `new (Array.prototype.map)` build an object instead of throwing.
5366 if !object.is_constructor() {
5367 let name = object
5368 .own_property("name")
5369 .and_then(|property| property.value)
5370 .map(|value| value.to_js_string())
5371 .unwrap_or_default();
5372 return Err(Signal::Throw(
5373 self.make_error("TypeError", &format!("{name} is not a constructor")),
5374 ));
5375 }
5376 break;
5377 };
5378 let mut all = leading;
5379 all.extend(args);
5380 args = all;
5381 // A bound function that is its own `new.target` stands in for its target:
5382 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
5383 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
5384 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
5385 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
5386 _ => false,
5387 };
5388 if same_wrapper {
5389 new_target = target.clone();
5390 }
5391 callee = target;
5392 }
5393 let Value::Object(function) = &callee else {
5394 unreachable!("the loop above only breaks on an object");
5395 };
5396 // The fresh object's prototype comes from `new.target`, not from the callee: a
5397 // derived constructor reaches here through `super()`, and the instance must be a
5398 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
5399 // an object inheriting `D.prototype` rather than `C.prototype`.
5400 let prototype_source = match new_target.as_object() {
5401 Some(target) => target.clone(),
5402 None => function.clone(),
5403 };
5404 // A native constructor builds its own instance, through `new_ctor_instance`, once it
5405 // has validated its arguments. Pre-building one here would read
5406 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
5407 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
5408 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
5409 let is_native = function.native_creates_own_instance();
5410 let this = if is_native {
5411 Value::Undefined
5412 } else {
5413 let prototype = self.get_property(&prototype_source, "prototype")?;
5414 let prototype = match prototype {
5415 Some(Value::Object(proto)) => Some(proto),
5416 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
5417 // object, the answer is the realm's *intrinsic* prototype for this
5418 // constructor, not `%Object.prototype%`.
5419 _ => {
5420 let fallback = self.get_property(function, "prototype")?;
5421 match fallback {
5422 Some(Value::Object(proto)) => Some(proto),
5423 _ => Some(self.realm.object_proto.clone()),
5424 }
5425 }
5426 };
5427 Value::Object(self.new_object(prototype))
5428 };
5429 // `new.target` inside the body is the constructor that was written, so a bound
5430 // function's target sees itself rather than the bound wrapper.
5431 self.pending_new_target = Some(new_target);
5432 let result = self.call_value(callee, this.clone(), args)?;
5433 self.pending_new_target = None;
5434 // A constructor that returns an object overrides `this`; any other return
5435 // value (including `undefined`) is ignored.
5436 Ok(match result {
5437 Value::Object(_) => result,
5438 _ => this,
5439 })
5440 }
5441
5442 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
5443 ///
5444 /// The error classes themselves arrive with the builtins milestone; what
5445 /// matters here is that the thrown value stringifies the way a script printing
5446 /// the caught value expects.
5447 pub fn make_error(&self, name: &str, message: &str) -> Value {
5448 let proto = self
5449 .realm
5450 .errors
5451 .get(name)
5452 .map(|constructor| self.prototype_of(constructor))
5453 .unwrap_or_else(|| self.realm.error_proto.clone());
5454 let error = self.new_object(Some(proto));
5455 // `name` and `message` are own properties of the instance, which is what
5456 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
5457 // `Error`.
5458 error.define(
5459 "name",
5460 Property::with_attributes(self.string(name), true, false),
5461 );
5462 error.define(
5463 "message",
5464 Property::with_attributes(self.string(message), true, false),
5465 );
5466 // The trace is captured where the error is *made*, which is where the reference
5467 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
5468 // way out, so a caught engine error already has its stack even if the handler
5469 // never rethrows it.
5470 self.add_stack(&error);
5471 Value::Object(error)
5472 }
5473
5474 /// Give an error object its `stack` property, from the current frame stack.
5475 ///
5476 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
5477 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
5478 /// `stack` a script set, is not rewritten.
5479 pub fn add_stack(&self, object: &Gc<JsObject>) {
5480 self.add_stack_skipping(object, 0);
5481 }
5482
5483 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
5484 ///
5485 /// An `Error` constructor passes 1: the reference builds those traces with
5486 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
5487 /// constructor itself, while a `RangeError` raised inside `toISOString` does
5488 /// report `at toISOString (native)`.
5489 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
5490 if object.has_own("stack") {
5491 return;
5492 }
5493 let trace = self.stack_trace_skipping(skip);
5494 let text = self.string(trace);
5495 object.define("stack", Property::with_attributes(text, true, true));
5496 }
5497
5498 /// The function object currently being called, if any.
5499 ///
5500 /// A native function is a bare `fn` pointer, so it cannot capture which class
5501 /// it belongs to; it reads that from the callee instead. This is also what a
5502 /// stack trace would use.
5503 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
5504 match &self.frames.last()?.callee {
5505 Value::Object(object) => Some(object.clone()),
5506 _ => None,
5507 }
5508 }
5509
5510 /// The `prototype` property of a constructor, falling back to
5511 /// `Object.prototype` for anything that is not shaped like one.
5512 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
5513 constructor
5514 .own_property("prototype")
5515 .and_then(|property| property.value)
5516 .and_then(|value| value.as_object().cloned())
5517 .unwrap_or_else(|| self.realm.object_proto.clone())
5518 }
5519
5520 /// Throw a `TypeError` carrying `message`.
5521 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
5522 Signal::Throw(self.make_error("TypeError", message.as_ref()))
5523 }
5524
5525 /// Throw a `RangeError` carrying `message`.
5526 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
5527 Signal::Throw(self.make_error("RangeError", message.as_ref()))
5528 }
5529
5530 /// The `ReferenceError` a read of an uninitialised binding raises.
5531 /// The name of the binding `slot` refers to, for an error message.
5532 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
5533 match kind {
5534 VarSlot::Loc => self
5535 .frame()
5536 .code
5537 .code
5538 .vars
5539 .get(slot)
5540 .map(|v| v.name.clone()),
5541 VarSlot::Closure => self
5542 .frame()
5543 .code
5544 .code
5545 .closure_vars
5546 .get(slot)
5547 .map(|c| c.name.clone()),
5548 }
5549 .unwrap_or_default()
5550 }
5551
5552 /// Whether `slot` names a `const` binding, which rejects every store after its
5553 /// initialiser.
5554 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
5555 match kind {
5556 VarSlot::Loc => self
5557 .frame()
5558 .code
5559 .code
5560 .vars
5561 .get(slot)
5562 .is_some_and(|v| v.is_const),
5563 VarSlot::Closure => self
5564 .frame()
5565 .code
5566 .code
5567 .closure_vars
5568 .get(slot)
5569 .is_some_and(|c| c.is_const),
5570 }
5571 }
5572
5573 /// The `TypeError` a store to a `const` binding raises.
5574 ///
5575 /// `const` is enforced here rather than at compile time because the binding can be
5576 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
5577 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
5578 /// both halves of what "checked store" means: the dead zone is over, and the
5579 /// binding is writable.
5580 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
5581 let name = self.binding_name(slot, kind);
5582 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5583 }
5584
5585 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
5586 let name = match kind {
5587 VarSlot::Loc => self
5588 .frame()
5589 .code
5590 .code
5591 .vars
5592 .get(slot)
5593 .map(|v| v.name.clone()),
5594 VarSlot::Closure => self
5595 .frame()
5596 .code
5597 .code
5598 .closure_vars
5599 .get(slot)
5600 .map(|c| c.name.clone()),
5601 }
5602 .unwrap_or_default();
5603 Signal::Throw(self.make_error(
5604 "ReferenceError",
5605 &format!("cannot access '{name}' before initialization"),
5606 ))
5607 }
5608
5609 fn throw_reference(&self, name: &str) -> Signal {
5610 Signal::Throw(self.make_error("ReferenceError", &format!("{name} is not defined")))
5611 }
5612
5613 // -- the instruction loop -----------------------------------------------
5614
5615 fn step(&mut self) -> JsResult<Step> {
5616 let pc = self.frame().pc;
5617 let code = self.frame().code.clone();
5618 let bytes = &code.code.code;
5619 if pc >= bytes.len() {
5620 return Ok(Step::Return(Value::Undefined));
5621 }
5622 let Some(decoded) = decode(bytes, pc) else {
5623 return Err(Signal::Throw(
5624 self.make_error("InternalError", "undecodable bytecode"),
5625 ));
5626 };
5627 let (op, a, b, next) = decoded;
5628 self.frame_mut().at = pc;
5629 self.frame_mut().pc = next;
5630 self.execute_instruction(op, a, b, next)
5631 }
5632
5633 fn push(&mut self, value: Value) {
5634 self.frame_mut().stack.push(value);
5635 }
5636
5637 fn pop(&mut self) -> Value {
5638 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
5639 }
5640
5641 fn pop_n(&mut self, count: usize) -> Vec<Value> {
5642 let frame = self.frame_mut();
5643 let start = frame.stack.len().saturating_sub(count);
5644 frame.stack.split_off(start)
5645 }
5646
5647 fn peek(&self, back: usize) -> Value {
5648 let frame = self.frame();
5649 frame
5650 .stack
5651 .get(frame.stack.len().wrapping_sub(1 + back))
5652 .cloned()
5653 .unwrap_or(Value::Undefined)
5654 }
5655
5656 #[allow(clippy::too_many_lines)]
5657 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
5658 use Opcode::*;
5659 match op {
5660 // -- constants and stack shuffling -----------------------------
5661 Nop => {}
5662 PushMinus1 => self.push(Value::Int(-1)),
5663 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
5664 let value = match op {
5665 Push0 => 0,
5666 Push1 => 1,
5667 Push2 => 2,
5668 Push3 => 3,
5669 Push4 => 4,
5670 Push5 => 5,
5671 Push6 => 6,
5672 _ => 7,
5673 };
5674 self.push(Value::Int(value));
5675 }
5676 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
5677 PushBigintI32 => {
5678 // The immediate form of a `BigInt` literal; the reference has the same
5679 // split between this and a constant-pool entry.
5680 let value = crate::bigint::BigInt::from_i64(a as i64);
5681 self.push(self.bigint(value));
5682 }
5683 PushTrue => self.push(Value::Bool(true)),
5684 PushFalse => self.push(Value::Bool(false)),
5685 PushEmptyString => self.push(self.string("")),
5686 Undefined => self.push(Value::Undefined),
5687 Null => self.push(Value::Null),
5688 Object => {
5689 let proto = self.realm.object_proto.clone();
5690 self.push(Value::Object(self.new_object(Some(proto))));
5691 }
5692 PushThis => {
5693 let this = self.frame().this.clone();
5694 self.push(this);
5695 }
5696 PushConst | PushConst8 => {
5697 let value = self.constant(a as usize)?;
5698 self.push(value);
5699 }
5700 PushAtomValue => {
5701 let text = self.atom_text(a as usize);
5702 self.push(self.string(text));
5703 }
5704 Dup => {
5705 let value = self.peek(0);
5706 self.push(value);
5707 }
5708 Swap => {
5709 // `a b -> b a`
5710 let bottom = self.pop();
5711 let top = self.pop();
5712 self.push(bottom);
5713 self.push(top);
5714 }
5715 Perm3 => {
5716 // `a b c -> b a c`, the reference's reordering for a spread method
5717 // call: `obj func array` becomes the `func this array` that `apply`
5718 // takes.
5719 let c = self.pop();
5720 let b = self.pop();
5721 let a = self.pop();
5722 self.push(b);
5723 self.push(a);
5724 self.push(c);
5725 }
5726 Dup1 => {
5727 let value = self.peek(1);
5728 self.push(value);
5729 }
5730 Drop => {
5731 self.pop();
5732 }
5733 Nip => {
5734 // `a b -> b`
5735 let top = self.pop();
5736 self.pop();
5737 self.push(top);
5738 }
5739 Perm4 => {
5740 // `obj prop a b -> a obj prop b`, the reference's reordering for a
5741 // postfix update of a computed element: it puts the *old* value
5742 // underneath the receiver and key so `put_array_el` can consume them
5743 // and leave the old value as the expression's result.
5744 let d = self.pop();
5745 let c = self.pop();
5746 let b = self.pop();
5747 let a = self.pop();
5748 self.push(c);
5749 self.push(a);
5750 self.push(b);
5751 self.push(d);
5752 }
5753 Insert2 => {
5754 // `obj a -> a obj a`
5755 let value = self.pop();
5756 let object = self.pop();
5757 self.push(value.clone());
5758 self.push(object);
5759 self.push(value);
5760 }
5761 Insert3 => {
5762 // `obj prop a -> a obj prop a`
5763 let value = self.pop();
5764 let key = self.pop();
5765 let object = self.pop();
5766 self.push(value.clone());
5767 self.push(object);
5768 self.push(key);
5769 self.push(value);
5770 }
5771 Swap2 => {
5772 // `a b c d -> c d a b`
5773 let d = self.pop();
5774 let c = self.pop();
5775 let b = self.pop();
5776 let a = self.pop();
5777 self.push(c);
5778 self.push(d);
5779 self.push(a);
5780 self.push(b);
5781 }
5782 Rot3l => {
5783 // `x a b -> a b x`
5784 let b = self.pop();
5785 let a = self.pop();
5786 let x = self.pop();
5787 self.push(a);
5788 self.push(b);
5789 self.push(x);
5790 }
5791 Rot3r => {
5792 // `a b c -> c a b`
5793 let c = self.pop();
5794 let b = self.pop();
5795 let a_value = self.pop();
5796 self.push(c);
5797 self.push(a_value);
5798 self.push(b);
5799 }
5800
5801 Rest => {
5802 // `...rest` in a parameter list: the arguments from index `a` on, as a
5803 // real array. It takes nothing off the stack — the arguments are in the
5804 // frame, not on it.
5805 let frame = self.frame();
5806 let from = a as usize;
5807 let collected: Vec<Value> = frame.passed.iter().skip(from).cloned().collect();
5808 let array = self.new_array(collected);
5809 self.push(Value::Object(array));
5810 }
5811
5812 // -- slots ------------------------------------------------------
5813 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
5814 let slot = self.slot_operand(op, a);
5815 let value = self.get_loc(slot);
5816 self.push(value);
5817 }
5818 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
5819 let slot = self.slot_operand(op, a);
5820 let value = self.pop();
5821 self.put_loc(slot, value);
5822 }
5823 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
5824 let slot = self.slot_operand(op, a);
5825 let value = self.pop();
5826 self.put_loc(slot, value.clone());
5827 self.push(value);
5828 }
5829 // The `_check` forms are the temporal dead zone: they throw when the
5830 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
5831 // *reads*, so only the two writes may pop — mishandling that quietly
5832 // consumes the value the caller pushed just before.
5833 GetLocCheck => {
5834 let slot = self.slot_operand(op, a);
5835 let value = self.get_loc(slot);
5836 if matches!(value, Value::Uninitialized) {
5837 return Err(self.dead_zone(slot, VarSlot::Loc));
5838 }
5839 self.push(value);
5840 }
5841 PutLocCheck | SetLocCheck => {
5842 let slot = self.slot_operand(op, a);
5843 let value = self.pop();
5844 if matches!(value, Value::Uninitialized) {
5845 return Err(self.dead_zone(slot, VarSlot::Loc));
5846 }
5847 // The initialiser goes through `put_loc`, not this, so any store that
5848 // reaches here is a later assignment — which a `const` refuses.
5849 if self.is_read_only(slot, VarSlot::Loc) {
5850 return Err(self.read_only(slot, VarSlot::Loc));
5851 }
5852 if op == SetLocCheck {
5853 self.put_loc(slot, value.clone());
5854 self.push(value);
5855 } else {
5856 self.put_loc(slot, value);
5857 }
5858 }
5859 PutLocCheckInit => {
5860 // The one store that *initialises* a lexical slot: `this` in a derived
5861 // constructor, which only exists after `super()` has run. A second
5862 // initialisation is the error the reference reports as
5863 // "'this' can be initialized only once".
5864 let slot = self.slot_operand(op, a);
5865 let value = self.pop();
5866 if !matches!(self.get_loc(slot), Value::Uninitialized) {
5867 return Err(Signal::Throw(self.make_error(
5868 "ReferenceError",
5869 "'this' can be initialized only once",
5870 )));
5871 }
5872 self.put_loc(slot, value);
5873 }
5874 CheckCtor => {
5875 // A class constructor may only run under `new`, which is what makes
5876 // `class A {}; A()` a TypeError.
5877 if matches!(self.frame().new_target, Value::Undefined) {
5878 return Err(Signal::Throw(self.make_error(
5879 "TypeError",
5880 "class constructors must be invoked with 'new'",
5881 )));
5882 }
5883 }
5884 InitCtor => {
5885 // The body a derived class gets when it declares no constructor:
5886 // forward every argument to the parent constructor, keeping `new.target`.
5887 if matches!(self.frame().new_target, Value::Undefined) {
5888 return Err(Signal::Throw(self.make_error(
5889 "TypeError",
5890 "class constructors must be invoked with 'new'",
5891 )));
5892 }
5893 let Some(callee) = self.current_callee() else {
5894 return Err(Signal::Throw(
5895 self.make_error("TypeError", "no constructor to inherit from"),
5896 ));
5897 };
5898 let parent = callee.proto().map_or(Value::Null, Value::Object);
5899 let new_target = self.frame().new_target.clone();
5900 let args = self.frame().passed.clone();
5901 let result = self.construct(parent, new_target, args)?;
5902 self.push(result);
5903 }
5904 SetLocUninitialized => {
5905 let slot = self.slot_operand(op, a);
5906 self.put_loc(slot, Value::Uninitialized);
5907 }
5908 CloseLoc => {
5909 // "Close" a binding: give it a *fresh* cell holding the current
5910 // value. Closures created before this point keep the old cell and the
5911 // ones created after see the new one, which is what makes every
5912 // iteration of `for (let i ...)` capture its own `i`, and what freezes
5913 // a block-scoped binding when the block ends.
5914 //
5915 // Clearing the slot instead (which this used to do) broke both: a
5916 // closure over a captured block variable read `undefined`, and a loop
5917 // terminated after one iteration.
5918 let slot = self.slot_operand(op, a);
5919 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
5920 if index >= 0 {
5921 let current = self.frame().cells[index as usize].get();
5922 let fresh = self.new_cell(current);
5923 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
5924 *cell = fresh;
5925 }
5926 }
5927 }
5928 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
5929 let slot = self.slot_operand(op, a);
5930 let value = self.get_arg(slot);
5931 self.push(value);
5932 }
5933 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
5934 let slot = self.slot_operand(op, a);
5935 let value = self.pop();
5936 self.put_arg(slot, value);
5937 }
5938 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
5939 let slot = self.slot_operand(op, a);
5940 let value = self.pop();
5941 self.put_arg(slot, value.clone());
5942 self.push(value);
5943 }
5944
5945 // -- closure variables ------------------------------------------
5946 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
5947 let slot = self.slot_operand(op, a);
5948 // A name a direct `eval` created shadows the binding the compiler chose.
5949 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
5950 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
5951 // and only a runtime lookup can know that.
5952 if let Some(cell) = self.eval_created_local(slot) {
5953 self.push(cell.get());
5954 return self.step();
5955 }
5956 let value = self.cell_value(slot)?;
5957 self.push(value);
5958 }
5959 GetVarRefCheck => {
5960 let slot = self.slot_operand(op, a);
5961 let value = self.cell_value(slot)?;
5962 if matches!(value, Value::Uninitialized) {
5963 return Err(self.dead_zone(slot, VarSlot::Closure));
5964 }
5965 self.push(value);
5966 }
5967 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
5968 let slot = self.slot_operand(op, a);
5969 let value = self.pop();
5970 if let Some(cell) = self.eval_created_local(slot) {
5971 cell.set(value);
5972 return self.step();
5973 }
5974 // Same rule as `PutLocCheck`: a checked store to a captured binding
5975 // refuses a `const` once its initialiser has run.
5976 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
5977 return Err(self.read_only(slot, VarSlot::Closure));
5978 }
5979 self.set_cell(slot, value)?;
5980 }
5981 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
5982 let slot = self.slot_operand(op, a);
5983 let value = self.pop();
5984 if let Some(cell) = self.eval_created_local(slot) {
5985 cell.set(value.clone());
5986 self.push(value);
5987 return self.step();
5988 }
5989 self.set_cell(slot, value.clone())?;
5990 self.push(value);
5991 }
5992
5993 // -- globals ----------------------------------------------------
5994 GetVar => {
5995 let value = self.get_global(a as usize)?;
5996 self.push(value);
5997 }
5998 GetVarUndef => {
5999 let value = self
6000 .get_global(a as usize)
6001 .or_else(|_| Ok(Value::Undefined))?;
6002 self.push(value);
6003 }
6004 DeleteVar => {
6005 // `delete name` for a name that is not a declared binding. A lexical
6006 // global lives in the reference table and cannot be deleted; anything
6007 // reachable only as a property of the global object is *implicit* —
6008 // `x = 1` with no declaration — and goes away if it is configurable,
6009 // which is what `delete` on an implicit global answers.
6010 let name = self.atom_text(a as usize);
6011 let global = self.realm.global.clone();
6012 let deleted = if self.realm.globals.contains_key(&name) {
6013 false
6014 } else if global.own_property(&name).is_some() {
6015 self.delete_property(&global, &name)?
6016 } else {
6017 true
6018 };
6019 self.push(Value::Bool(deleted));
6020 }
6021 PutVar => {
6022 let value = self.pop();
6023 self.put_global(a as usize, value)?;
6024 }
6025 PutVarInit => {
6026 let slot = a as usize;
6027 let value = self.pop();
6028 self.init_global(slot, value)?;
6029 }
6030
6031 // -- arithmetic -------------------------------------------------
6032 Add => self.binary_add()?,
6033 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
6034 let raw_right = self.pop();
6035 let raw_left = self.pop();
6036 // BigInt arithmetic is a separate path, and not only for the type of the
6037 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
6038 // rather than a silent conversion.
6039 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
6040 let left = self.primitive_of(raw_left)?;
6041 let right = self.primitive_of(raw_right)?;
6042 let value = self.bigint_arithmetic(op, left, right)?;
6043 self.push(value);
6044 } else {
6045 let right = self.numeric(raw_right)?;
6046 let left = self.numeric(raw_left)?;
6047 self.push(arithmetic(op, left, right)?);
6048 }
6049 }
6050 Neg => {
6051 let raw = self.pop();
6052 match raw {
6053 // A bigint negates exactly, however wide it is.
6054 Value::BigInt(big) => {
6055 let negated = big.negate();
6056 self.push(self.bigint(negated));
6057 }
6058 other => {
6059 let value = self.numeric(other)?;
6060 self.push(negate(value));
6061 }
6062 }
6063 }
6064 Plus => {
6065 let value = self.pop();
6066 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
6067 // unary plus is defined to produce a *number*, which a bigint cannot
6068 // become without loss. It used to fall through to `NaN`.
6069 if matches!(value, Value::BigInt(_)) {
6070 return Err(self.type_error("cannot convert bigint to number"));
6071 }
6072 let numeric = self.numeric_of(value)?;
6073 self.push(numeric);
6074 }
6075 Inc => {
6076 let raw = self.pop();
6077 let (_, updated) = self.advance_numeric(raw, true)?;
6078 self.push(updated);
6079 }
6080 Dec => {
6081 let raw = self.pop();
6082 let (_, updated) = self.advance_numeric(raw, false)?;
6083 self.push(updated);
6084 }
6085 PostInc | PostDec => {
6086 // `x -> x x+1`: the *new* value ends up on top, so the store the
6087 // compiler emits right after (`put_var`) writes the incremented
6088 // one, while the old value stays underneath for the expression's
6089 // own result. Getting this backwards makes `i++` a no-op, which
6090 // turns `while (i < 3)` into an infinite loop.
6091 let raw = self.pop();
6092 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
6093 self.push(old);
6094 self.push(updated);
6095 }
6096 Not => {
6097 let raw = self.pop();
6098 match raw {
6099 // `~x` on a bigint is `-x - 1`, exact at any width.
6100 Value::BigInt(big) => {
6101 let inverted = big.bitnot();
6102 self.push(self.bigint(inverted));
6103 }
6104 other => {
6105 let value = self.numeric(other)?;
6106 self.push(Value::Int(!value.to_int32()));
6107 }
6108 }
6109 }
6110 Lnot => {
6111 let value = self.pop();
6112 self.push(Value::Bool(!value.to_boolean()));
6113 }
6114
6115 // -- comparison -------------------------------------------------
6116 Lt | Lte | Gt | Gte => {
6117 let right = self.pop();
6118 let left = self.pop();
6119 let answer = self.relational(op, left, right);
6120 self.push(answer);
6121 }
6122 Eq | Neq => {
6123 let right = self.pop();
6124 let left = self.pop();
6125 let equal = self.abstract_equals(left, right)?;
6126 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
6127 }
6128 StrictEq => {
6129 let right = self.pop();
6130 let left = self.pop();
6131 self.push(Value::Bool(left.strict_equals(&right)));
6132 }
6133 StrictNeq => {
6134 let right = self.pop();
6135 let left = self.pop();
6136 self.push(Value::Bool(!left.strict_equals(&right)));
6137 }
6138 IsUndefined => {
6139 // `=== undefined`, which is what a destructuring default tests. It is
6140 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
6141 let value = self.pop();
6142 self.push(Value::Bool(matches!(value, Value::Undefined)));
6143 }
6144 IsUndefinedOrNull => {
6145 let value = self.pop();
6146 self.push(Value::Bool(value.is_nullish()));
6147 }
6148 Typeof => {
6149 let value = self.pop();
6150 self.push(self.string(value.type_of()));
6151 }
6152 ToObject => {
6153 // A destructuring *object* pattern starts here, which is why
6154 // `var {} = null` throws. Only `undefined` and `null` are refused; a
6155 // primitive is boxed.
6156 let value = self.pop();
6157 let object = self.object_from(&value)?;
6158 self.push(Value::Object(object));
6159 }
6160 Instanceof => {
6161 let constructor = self.pop();
6162 let object = self.pop();
6163 let answer = self.instance_of(&object, &constructor)?;
6164 self.push(Value::Bool(answer));
6165 }
6166 In => {
6167 let object = self.pop();
6168 let key = self.pop();
6169 let answer = self.has_property(&key, &object)?;
6170 self.push(Value::Bool(answer));
6171 }
6172
6173 // -- control flow -----------------------------------------------
6174 Goto | Goto8 | Goto16 => {
6175 self.frame_mut().pc = a as usize;
6176 }
6177 IfTrue | IfTrue8 => {
6178 let value = self.pop();
6179 if value.to_boolean() {
6180 self.frame_mut().pc = a as usize;
6181 }
6182 }
6183 IfFalse | IfFalse8 => {
6184 let value = self.pop();
6185 if !value.to_boolean() {
6186 self.frame_mut().pc = a as usize;
6187 }
6188 }
6189 Catch => {
6190 // Pushes the handler target onto the value stack; `unwind` finds it.
6191 self.push(Value::CatchOffset(a));
6192 }
6193 Gosub => {
6194 self.push(Value::ReturnAddress(next as u32));
6195 self.frame_mut().pc = a as usize;
6196 }
6197 Ret => {
6198 let value = self.pop();
6199 match value {
6200 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
6201 _ => {
6202 return Err(Signal::Throw(
6203 self.make_error("InternalError", "invalid return address"),
6204 ));
6205 }
6206 }
6207 }
6208 NipCatch => {
6209 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
6210 // including the marker, keeping the top value.
6211 let top = self.pop();
6212 loop {
6213 match self.pop() {
6214 Value::CatchOffset(_) | Value::Undefined => break,
6215 _ => {}
6216 }
6217 if self.frame().stack.is_empty() {
6218 break;
6219 }
6220 }
6221 self.push(top);
6222 }
6223 Throw => {
6224 let value = self.pop();
6225 return Err(Signal::Throw(value));
6226 }
6227 ThrowError => {
6228 let name = self.atom_text(a as usize);
6229 let (class, message) = match b {
6230 0 => ("TypeError", format!("'{name}' is read-only")),
6231 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
6232 2 => ("ReferenceError", format!("'{name}' is not initialized")),
6233 // `delete super.x` is a syntax-level mistake the reference reports
6234 // with this wording, not a property-access failure.
6235 3 => (
6236 "ReferenceError",
6237 "unsupported reference to 'super'".to_string(),
6238 ),
6239 4 => (
6240 "TypeError",
6241 "iterator does not have a throw method".to_string(),
6242 ),
6243 5 => (
6244 "ReferenceError",
6245 "invalid assignment left-hand side".to_string(),
6246 ),
6247 _ => ("TypeError", format!("invalid operation on '{name}'")),
6248 };
6249 return Err(Signal::Throw(self.make_error(class, &message)));
6250 }
6251 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
6252 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
6253 YieldStar | AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
6254 Await => return Ok(Step::Suspend(SuspendKind::Await)),
6255 ReturnAsync => {
6256 // The reference's `return_async` returns `undefined` and lets the resume
6257 // machinery pick the real value off `sp[-1]`, which is how it tells a
6258 // completion from a suspension. Carrying the value explicitly says the
6259 // same thing without the implicit stack slot.
6260 let value = self.pop();
6261 return Ok(Step::Return(value));
6262 }
6263 Return => {
6264 let value = self.pop();
6265 return Ok(Step::Return(value));
6266 }
6267 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
6268
6269 // -- calls ------------------------------------------------------
6270 Call | Call0 | Call1 | Call2 | Call3 => {
6271 let argc = self.argc_operand(op, a);
6272 let args = self.pop_n(argc);
6273 let callee = self.pop();
6274 // A plain call has no receiver; the callee decides what to do with
6275 // `undefined` (a sloppy function substitutes the global object).
6276 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
6277 self.push(result);
6278 }
6279 }
6280 CallConstructor => {
6281 // `constructor this_obj args… -> object`. The duplicated
6282 // constructor is `new.target`; this milestone does not expose it,
6283 // so the extra copy is simply consumed here.
6284 let argc = a as usize;
6285 let args = self.pop_n(argc);
6286 let new_target = self.pop();
6287 let callee = self.pop();
6288 let result = self.construct(callee, new_target, args)?;
6289 self.push(result);
6290 }
6291 CallMethod => {
6292 let argc = a as usize;
6293 let args = self.pop_n(argc);
6294 let callee = self.pop();
6295 let this = self.pop();
6296 if let Some(result) = self.call_or_push(callee, this, args)? {
6297 self.push(result);
6298 }
6299 }
6300 Apply => {
6301 // `func this array -> result`, the spread-call form: the compiler
6302 // builds one array of arguments, and all that is left here is to
6303 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
6304 let array = self.pop();
6305 let this = self.pop();
6306 let callee = self.pop();
6307 let args = self.array_like_to_args(&array)?;
6308 if a & 1 != 0 {
6309 let result = self.construct(callee, this, args)?;
6310 self.push(result);
6311 } else if let Some(result) = self.call_or_push(callee, this, args)? {
6312 self.push(result);
6313 }
6314 }
6315 TailCall | TailCallMethod => {
6316 // `tail_call` is `call` whose result is returned immediately — the
6317 // reference jumps straight to `done` instead of storing the value and
6318 // running on. The callee still gets its own frame, so deep tail
6319 // recursion hits the stack limit exactly like plain recursion does;
6320 // marking this frame lets the return path unwind without needing
6321 // instructions after the call.
6322 let argc = if op == TailCallMethod {
6323 a as usize
6324 } else {
6325 self.argc_operand(op, a)
6326 };
6327 let args = self.pop_n(argc);
6328 let callee = self.pop();
6329 let this = if op == TailCallMethod {
6330 self.pop()
6331 } else {
6332 Value::Undefined
6333 };
6334 if let Value::Object(function) = &callee
6335 && let Some((code, env)) = bytecode_of(function)
6336 {
6337 // A generator or async body is not run here at all: calling it only
6338 // *creates* the generator/coroutine, so it must not inherit this
6339 // frame. Doing so made `function f(){ return g() }` push `g`'s body
6340 // onto `f`'s frame, and the first `yield`/`await` then reported
6341 // "a generator body ran as an ordinary call".
6342 if code.code.kind.is_generator() || code.code.kind.is_async() {
6343 let value = self.call_value(callee, this, args)?;
6344 return Ok(Step::Return(value));
6345 }
6346 self.frame_mut().tail = true;
6347 self.push_frame(code, env, this, args, callee)?;
6348 return Ok(Step::Continue);
6349 }
6350 // A native callee has no frame to reuse, so its value is simply
6351 // returned.
6352 let value = self.call_value(callee, this, args)?;
6353 return Ok(Step::Return(value));
6354 }
6355
6356 // -- objects ----------------------------------------------------
6357 SpecialObject => {
6358 let value = self.special_object(a)?;
6359 self.push(value);
6360 }
6361 GetLength => {
6362 // `get_length` is the `.length` read; an array and a string answer
6363 // from their own length, anything else from the property.
6364 let target = self.pop();
6365 let value = match &target {
6366 Value::Object(object) => match object.array_length() {
6367 Some(length) => crate::object::length_value(length),
6368 None => self.read_field(&target, "length")?,
6369 },
6370 Value::String(text) => Value::Int(text.utf16_len() as i32),
6371 _ => self.read_field(&target, "length")?,
6372 };
6373 self.push(value);
6374 }
6375 GetField | GetField2 => {
6376 let object = self.pop();
6377 let key = self.atom_text(a as usize);
6378 let value = self.read_field(&object, &key)?;
6379 if op == GetField2 {
6380 self.push(object);
6381 }
6382 self.push(value);
6383 }
6384 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
6385 let key = self.pop();
6386 let object = self.pop();
6387 let key = self.propkey(&key);
6388 let value = self.read_field_key(&object, &key)?;
6389 if matches!(op, GetArrayEl2 | GetArrayEl3) {
6390 self.push(object);
6391 }
6392 if op == GetArrayEl3 {
6393 // The key goes back in its *value* form, which the compiler stores
6394 // into the target of a destructuring assignment.
6395 self.push(match &key {
6396 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
6397 PropertyKey::String(text) => self.string_wtf8(text.clone()),
6398 });
6399 }
6400 self.push(value);
6401 }
6402 PutField => {
6403 let value = self.pop();
6404 let object = self.pop();
6405 let key = self.atom_text(a as usize);
6406 self.write_field(&object, &key, value)?;
6407 }
6408 PutArrayEl => {
6409 let value = self.pop();
6410 let key = self.pop();
6411 let object = self.pop();
6412 let key = self.propkey(&key);
6413 self.write_field_key(&object, &key, value)?;
6414 }
6415 DefineField => {
6416 let value = self.pop();
6417 let object = self.pop();
6418 let key = self.atom_text(a as usize);
6419 // `{m: function(){}}` names the function `m`, the same way assigning
6420 // it to a property does. Without this the frame is anonymous and a
6421 // stack trace reads `at (file:1:2)`.
6422 self.set_function_name(&value, &key);
6423 if let Some(target) = object.as_object() {
6424 // Only an *array* stores into the element vector. A numeric key
6425 // on an ordinary object is an ordinary property, which is what
6426 // makes `{1: 'a'}` iterate as a key rather than disappear.
6427 let stored = target.is_array()
6428 && array_index(&key)
6429 .is_some_and(|index| target.array_set(index as usize, value.clone()));
6430 if !stored {
6431 target.define_data(&key, value);
6432 }
6433 }
6434 self.push(object);
6435 }
6436 DefineArrayEl => {
6437 // `obj key value -> obj key`. The *value* form of the key is what goes
6438 // back on the stack — the compiler stores it into the pattern's binding —
6439 // so the symbol is not stringified on the way through.
6440 let value = self.pop();
6441 let key_value = self.pop();
6442 let object = self.peek(0);
6443 let key = self.propkey(&key_value);
6444 self.write_field_key(&object, &key, value)?;
6445 self.push(key_value);
6446 }
6447 SetHomeObject => {
6448 // `obj func -> obj func`: records the object a method was defined on so
6449 // `super` inside it resolves against that object's prototype.
6450 let function = self.peek(0);
6451 let home = self.peek(1);
6452 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
6453 function.set_home_object(Some(home.clone()));
6454 }
6455 }
6456 Regexp => {
6457 // `pattern flags -> regexp`. A literal compiles here rather than through the
6458 // constructor, which is both what the reference's dedicated opcode is for
6459 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
6460 let flags = self.pop();
6461 let pattern = self.pop();
6462 let pattern = self.to_js_string(&pattern)?;
6463 let flags = self.to_js_string(&flags)?;
6464 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
6465 self.push(Value::Object(object));
6466 }
6467 UsingDisposeInit => {
6468 // The error state a disposal accumulates into. Uninitialised means "no
6469 // failure yet"; anything else is the exception being propagated.
6470 self.push(Value::Uninitialized);
6471 }
6472 UsingCheck => {
6473 // `value -> value, method`: validate and snapshot the disposer now, so a
6474 // later change to `Symbol.dispose` cannot change what gets called, and so a
6475 // value that is not disposable fails before the body runs.
6476 let value = self.pop();
6477 let method = self.using_method_for(&value, a as u8 == 1)?;
6478 self.push(value);
6479 self.push(method);
6480 }
6481 UsingDispose => {
6482 // `error_state -> error_state'`: dispose the variable at `slot` — its value
6483 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
6484 // the pending error.
6485 let slot = self.slot_operand(op, a);
6486 let error_state = self.pop();
6487 let merged = self.using_dispose_once(slot, error_state)?;
6488 self.push(merged);
6489 }
6490 UsingDisposeMerge => {
6491 let new_error = self.pop();
6492 let error_state = self.pop();
6493 let merged = self.merge_dispose_error(new_error, error_state);
6494 self.push(merged);
6495 }
6496 UsingDisposeEnd => {
6497 // A disposal that failed replaces the block's normal completion, so the
6498 // error state becomes a real throw here rather than at the call site.
6499 let error_state = self.pop();
6500 if !matches!(error_state, Value::Uninitialized) {
6501 return Err(Signal::Throw(error_state));
6502 }
6503 }
6504 UsingDisposeAsync => {
6505 // `await using` needs a promise to await and this runtime has no
6506 // `Promise` builtin, so the disposer is called synchronously and its result
6507 // discarded. That is correct for a disposer that returns nothing and is
6508 // reported as a gap rather than silently skipped.
6509 let slot = self.slot_operand(op, a);
6510 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
6511 self.push(error_state);
6512 }
6513 GetSuper => {
6514 // `obj -> obj's prototype`: the starting point of a `super` lookup.
6515 let object = self.pop();
6516 let proto = match &object {
6517 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
6518 _ => Value::Null,
6519 };
6520 self.push(proto);
6521 }
6522 GetSuperValue => {
6523 // `receiver proto key -> value`, searching from `proto` but reporting to
6524 // `receiver`, which is what `super.g` must do for a getter to see `this`.
6525 let key = self.pop();
6526 let proto = self.pop();
6527 let receiver = self.peek(0);
6528 let value = self.super_read(&receiver, &proto, &key)?;
6529 self.push(value);
6530 }
6531 PutSuperValue => {
6532 // `receiver proto key value ->`: a store that starts at `proto` but
6533 // assigns to `receiver`.
6534 let value = self.pop();
6535 let key = self.pop();
6536 let proto = self.pop();
6537 let receiver = self.pop();
6538 self.super_write(&receiver, &proto, &key, value)?;
6539 }
6540 DefineClass => {
6541 // `parent ctor -> ctor proto`: the constructor becomes the class and a
6542 // fresh prototype object lands on top for the methods to go on.
6543 let name = self.atom_text(a as usize);
6544 let (ctor, proto) = self.define_class(&name, b)?;
6545 self.push(ctor);
6546 self.push(Value::Object(proto));
6547 }
6548 DefineClassComputed => {
6549 // `parent ctor key -> ctor proto key`: the computed name stays put so
6550 // `define_field`-style consumers can still read it.
6551 let key = self.pop();
6552 let name = self.propkey_of(&key).to_string_lossy().into_owned();
6553 let (ctor, proto) = self.define_class(&name, b)?;
6554 self.push(ctor);
6555 self.push(Value::Object(proto));
6556 self.push(key);
6557 }
6558 DefineMethod => {
6559 let function = self.pop();
6560 let object = self.pop();
6561 let key = self.atom_text(a as usize);
6562 // A method's `[[HomeObject]]` is the object it was defined on, which is
6563 // what `super` inside it resolves against.
6564 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
6565 function.set_home_object(Some(object.clone()));
6566 }
6567 self.set_function_name(&function, &key_with_accessor_prefix(&key, b));
6568 if let Some(array) = object.as_object() {
6569 define_function_property(array, &PropertyKey::from(key.as_str()), function, b);
6570 }
6571 self.push(object);
6572 }
6573 DefineMethodComputed => {
6574 let function = self.pop();
6575 let key = self.pop();
6576 let object = self.pop();
6577 let key = self.propkey(&key);
6578 self.set_function_name(&function, &key_with_accessor_prefix(&key.to_string(), a));
6579 if let Some(array) = object.as_object() {
6580 define_function_property(array, &key, function, a);
6581 }
6582 self.push(object);
6583 }
6584 SetProto => {
6585 let proto = self.pop();
6586 let object = self.pop();
6587 if let Some(target) = object.as_object() {
6588 target.set_proto(proto.as_object().cloned());
6589 }
6590 self.push(object);
6591 }
6592 CopyDataProperties => {
6593 let exclusion = self.pop();
6594 let source = self.pop();
6595 let target = self.peek(0);
6596 self.copy_properties(&target, &source, &exclusion)?;
6597 self.push(source);
6598 self.push(exclusion);
6599 }
6600 ToPropkey => {
6601 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
6602 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
6603 // ordinary `"Symbol(b)"` property.
6604 let value = self.pop();
6605 let key = match self.propkey(&value) {
6606 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
6607 PropertyKey::String(text) => self.string_wtf8(text),
6608 };
6609 self.push(key);
6610 }
6611 SetName => {
6612 let function = self.peek(0);
6613 let name = self.atom_text(a as usize);
6614 self.set_function_name(&function, &name);
6615 }
6616 SetNameComputed => {
6617 let key = self.peek(1);
6618 let function = self.peek(0);
6619 let name = self.propkey_of(&key).to_string_lossy().into_owned();
6620 self.set_function_name(&function, &name);
6621 }
6622
6623 // -- arrays -----------------------------------------------------
6624 ArrayFrom => {
6625 let count = a as usize;
6626 let elements = self.pop_n(count);
6627 let array = self.new_array(elements);
6628 self.push(Value::Object(array));
6629 }
6630 Append => {
6631 // `array index iterable -> array new_index`
6632 let iterable = self.pop();
6633 self.pop();
6634 let array = self.peek(0);
6635 let added = self.append_enumerate(&array, &iterable)?;
6636 self.push(Value::Int(added));
6637 }
6638
6639 // -- iteration --------------------------------------------------
6640 ForInStart => {
6641 let value = self.pop();
6642 let record = self.for_in_record(&value)?;
6643 self.push(Value::Object(record));
6644 }
6645 ForInNext => {
6646 // `record -> record key done`. The flag is *done*, not "found":
6647 // the compiler tests it with `if_false` to jump back into the body,
6648 // so reporting `true` while keys remain would end the loop at once.
6649 let record = self.peek(0);
6650 match self.for_in_advance(&record)? {
6651 Some(key) => {
6652 let text = self.string(key);
6653 self.push(text);
6654 self.push(Value::Bool(false));
6655 }
6656 None => {
6657 self.push(Value::Undefined);
6658 self.push(Value::Bool(true));
6659 }
6660 }
6661 }
6662 ForOfStart => {
6663 let value = self.pop();
6664 let iterator = self.get_iterator(&value)?;
6665 self.push(iterator.object);
6666 self.push(iterator.next);
6667 self.push(Value::CatchOffset(0));
6668 }
6669 ForOfNext => {
6670 // `iter next catch_offset -> iter next catch_offset value done`.
6671 //
6672 // The operand is how many values sit *above* the iterator triple: a
6673 // destructuring rest element keeps its target array and running index
6674 // there while draining the iterator, so the triple is not at the top.
6675 let extra = a as usize;
6676 let iterator_slot = 2 + extra;
6677 // An exhausted iterator is replaced by `undefined` (see below), so a
6678 // second step must not call `next` again — `Array.from` and a
6679 // destructuring pattern both keep stepping past the end.
6680 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
6681 (Value::Undefined, true)
6682 } else {
6683 let iterator = Iterator {
6684 object: self.peek(iterator_slot),
6685 next: self.peek(1 + extra),
6686 };
6687 self.iterator_step(&iterator)?
6688 };
6689 if done {
6690 // The result's `value` is meaningless once the iterator is done:
6691 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
6692 // rather than binding the generator's return value.
6693 let top = self.frame().stack.len() - 1 - iterator_slot;
6694 self.frame_mut().stack[top] = Value::Undefined;
6695 self.push(Value::Undefined);
6696 self.push(Value::Bool(true));
6697 } else {
6698 self.push(value);
6699 self.push(Value::Bool(false));
6700 }
6701 }
6702 IteratorNext => {
6703 // `iter next catch val -> iter next catch val'`: replace the argument with
6704 // the result of `next(val)`. The triple below stays put, which is why the
6705 // three instructions of the `yield*` loop all address the stack the same way.
6706 let value = self.pop();
6707 let object = self.peek(2);
6708 let next = self.peek(1);
6709 let result = self.call_value(next, object, vec![value])?;
6710 self.push(result);
6711 }
6712 IteratorCall => {
6713 // `iter next catch val -> iter next catch val' flag`.
6714 //
6715 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
6716 // The flag is `true` when the method was missing, which is how the
6717 // caller learns that the inner iterator cannot take part in the
6718 // unwinding.
6719 let value = self.pop();
6720 let object = self.peek(2);
6721 let key = if a & 1 != 0 { "throw" } else { "return" };
6722 let method = self.read_field(&object, key)?;
6723 if matches!(method, Value::Undefined | Value::Null) {
6724 self.push(value);
6725 self.push(Value::Bool(true));
6726 } else {
6727 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
6728 let result = self.call_value(method, object, argument)?;
6729 self.push(result);
6730 self.push(Value::Bool(false));
6731 }
6732 }
6733 IteratorCheckObject => {
6734 if !matches!(self.peek(0), Value::Object(_)) {
6735 return Err(Signal::Throw(
6736 self.make_error("TypeError", "iterator must return an object"),
6737 ));
6738 }
6739 }
6740 IteratorClose => {
6741 // `iter next catch_offset ->`
6742 self.pop();
6743 self.pop();
6744 self.pop();
6745 }
6746 Import => {
6747 // `import(specifier)`: the options slot is on top and is not read yet.
6748 let _options = self.pop();
6749 let specifier = self.pop();
6750 let promise = self.dynamic_import(specifier)?;
6751 self.push(promise);
6752 }
6753 ForAwaitOfStart => {
6754 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
6755 // `Symbol.iterator` fallback.
6756 let value = self.pop();
6757 let iterator = self.get_async_iterator(&value)?;
6758 self.push(iterator.object);
6759 self.push(iterator.next);
6760 self.push(Value::CatchOffset(0));
6761 }
6762 ForAwaitOfNext => {
6763 // `for await` steps the iterator and leaves the *result* wrapped in a
6764 // promise, so the `await` the compiler emits right after this can suspend
6765 // on it. Unwrapping happens in `iterator_get_value_done`.
6766 let extra = a as usize;
6767 let iterator_slot = 2 + extra;
6768 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
6769 Value::Undefined
6770 } else {
6771 let iterator = Iterator {
6772 object: self.peek(iterator_slot),
6773 next: self.peek(1 + extra),
6774 };
6775 let next = iterator.next.clone();
6776 self.call_value(next, iterator.object, Vec::new())?
6777 };
6778 let promise = self.promise_resolve_value(result)?;
6779 self.push(promise);
6780 }
6781 IteratorGetValueDone => {
6782 // `result -> value done`. A missing result object means the iterator was
6783 // already exhausted, which the loop treats as `done`.
6784 let result = self.pop();
6785 let Value::Object(object) = &result else {
6786 self.push(Value::Undefined);
6787 self.push(Value::Bool(true));
6788 return Ok(Step::Continue);
6789 };
6790 let done = self
6791 .get_property(object, "done")?
6792 .is_some_and(|value| value.to_boolean());
6793 if done {
6794 self.push(Value::Undefined);
6795 self.push(Value::Bool(true));
6796 } else {
6797 let value = self
6798 .get_property(object, "value")?
6799 .unwrap_or(Value::Undefined);
6800 self.push(value);
6801 self.push(Value::Bool(false));
6802 }
6803 }
6804
6805 Delete => {
6806 // `delete obj[key]`, where the key was just pushed. Deleting an array
6807 // index leaves a *hole* rather than closing the gap, and a
6808 // non-configurable property answers `false` and stays.
6809 let key = self.pop();
6810 let target = self.pop();
6811 let key = self.propkey(&key);
6812 let text_label = key.as_str().unwrap_or("").to_string();
6813 let deleted = match &target {
6814 Value::Object(object) => {
6815 let object = object.clone();
6816 self.delete_property_key(&object, &key)?
6817 }
6818 // A string's `length` and its index properties are
6819 // non-configurable, so deleting one answers `false`.
6820 Value::String(text) => {
6821 !(text_label == "length"
6822 || array_index(&text_label)
6823 .is_some_and(|index| (index as usize) < text.utf16_len()))
6824 }
6825 // "delete null.a" is a TypeError, not a no-op: the operator needs an
6826 // object to delete from, and only a *boxable* primitive has one.
6827 Value::Undefined | Value::Null => {
6828 return Err(Signal::Throw(
6829 self.make_error("TypeError", "cannot convert to object"),
6830 ));
6831 }
6832 // Any other primitive has no own properties; deleting nothing
6833 // succeeds.
6834 _ => true,
6835 };
6836 self.push(Value::Bool(deleted));
6837 }
6838
6839 // -- exceptions and bookkeeping ---------------------------------
6840 Fclosure | Fclosure8 => {
6841 let value = self.closure(a as usize)?;
6842 self.push(value);
6843 }
6844
6845 other => {
6846 let name = other.info().name;
6847 return Err(Signal::Throw(self.make_error(
6848 "InternalError",
6849 &format!("{name} is not implemented yet"),
6850 )));
6851 }
6852 }
6853 Ok(Step::Continue)
6854 }
6855
6856 // -- operand helpers ----------------------------------------------------
6857
6858 /// The slot index an operand names, taking short forms into account.
6859 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
6860 use Opcode::*;
6861 match op {
6862 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
6863 | SetVarRef0 => 0,
6864 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
6865 | SetVarRef1 => 1,
6866 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
6867 | SetVarRef2 => 2,
6868 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
6869 | SetVarRef3 => 3,
6870 _ => a as usize,
6871 }
6872 }
6873
6874 /// The argument count of a call, taking `call0`…`call3` into account.
6875 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
6876 use Opcode::*;
6877 match op {
6878 Call0 => 0,
6879 Call1 => 1,
6880 Call2 => 2,
6881 Call3 => 3,
6882 _ => a as usize,
6883 }
6884 }
6885
6886 fn atom_text(&self, index: usize) -> String {
6887 self.frame()
6888 .code
6889 .code
6890 .atoms
6891 .get(index)
6892 .map(|atom| match atom {
6893 Atom::Str(text) => text.clone(),
6894 Atom::Index(value) => value.to_string(),
6895 })
6896 .unwrap_or_default()
6897 }
6898
6899 fn constant(&mut self, index: usize) -> JsResult<Value> {
6900 let constant = self.frame().code.code.cpool.get(index).cloned();
6901 Ok(match &constant {
6902 Some(Constant::Number(number)) => Value::Float(*number),
6903 Some(Constant::String(text)) => self.string(text.clone()),
6904 Some(Constant::BigInt { digits, radix }) => {
6905 match crate::bigint::BigInt::from_radix(digits, *radix) {
6906 Some(big) => self.bigint(big),
6907 // A literal the parser accepted is always parseable; a failure here
6908 // would be a compiler bug, so it reads as an `InternalError`.
6909 None => {
6910 return Err(Signal::Throw(
6911 self.make_error("InternalError", "unparseable bigint literal"),
6912 ));
6913 }
6914 }
6915 }
6916 Some(Constant::Function(_)) => {
6917 return Err(Signal::Throw(
6918 self.make_error("InternalError", "a bare function constant"),
6919 ));
6920 }
6921 // A tagged template's call site: a frozen array of the cooked chunks with a
6922 // frozen `raw` array beside it, which is what `String.raw` reads back.
6923 Some(Constant::Template { cooked, raw }) => {
6924 let cooked_values: Vec<Value> = cooked
6925 .iter()
6926 .map(|chunk| match chunk {
6927 Some(text) => self.string(text.clone()),
6928 None => Value::Undefined,
6929 })
6930 .collect();
6931 let raw_values: Vec<Value> =
6932 raw.iter().map(|text| self.string(text.clone())).collect();
6933 let raw_array = self.new_array(raw_values);
6934 raw_array.set_extensible(false);
6935 let template = self.new_array(cooked_values);
6936 template.define(
6937 "raw",
6938 Property::with_attributes(Value::Object(raw_array), false, false),
6939 );
6940 template.set_extensible(false);
6941 Value::Object(template)
6942 }
6943 _ => Value::Undefined,
6944 })
6945 }
6946
6947 /// The reference cell a closure-variable slot names.
6948 ///
6949 /// Two kinds of binding share this addressing: a genuine closure variable
6950 /// (captured from an enclosing function) lives in this frame's environment,
6951 /// while a *declared global* lives in the realm so that a script, a function
6952 /// declaration and their uses all see one binding. A plain `Global` — an
6953 /// undeclared name that may be satisfied by the global object — has no cell at
6954 /// all, which is how `typeof x` still works for a name that does not exist.
6955 /// The reference cell a closure-variable slot names.
6956 ///
6957 /// The environment is resolved once, when the closure is built, and this is
6958 /// just the lookup afterwards. A *declared global* is in there too, pointing at
6959 /// the realm's cell, so a script, a hoisted function declaration and their uses
6960 /// all share one binding. A plain `Global` — a name the script never declared —
6961 /// is read and written through `get_var`/`put_var` by name instead, which is
6962 /// what lets the global object satisfy it.
6963 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
6964 self.frame().env.cells.get(slot).cloned()
6965 }
6966
6967 /// Whether `slot` refers to a global binding through the reference table.
6968 ///
6969 /// A global's cell in the closure environment only exists so the slot has
6970 /// something to point at; the binding itself lives on the global object (a `var`)
6971 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
6972 /// be routed, not performed on the placeholder.
6973 fn is_global_slot(&self, slot: usize) -> bool {
6974 self.frame()
6975 .code
6976 .code
6977 .closure_vars
6978 .get(slot)
6979 .is_some_and(|c| {
6980 // A module's declarations and imports are *not* globals: their cells are
6981 // the module environment's, filled by the host, so the placeholder routing
6982 // must not apply to them.
6983 matches!(
6984 c.closure_type,
6985 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
6986 )
6987 })
6988 }
6989
6990 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
6991 if self.is_global_slot(slot) {
6992 return self.get_global(slot);
6993 }
6994 Ok(self
6995 .var_ref_cell(slot)
6996 .map(|cell| cell.get())
6997 .unwrap_or(Value::Undefined))
6998 }
6999
7000 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
7001 // A function declaration is hoisted by storing into a global reference before
7002 // the body runs, so this path is also what puts it on the global object.
7003 if self.is_global_slot(slot) {
7004 return self.put_global(slot, value);
7005 }
7006 if let Some(cell) = self.var_ref_cell(slot) {
7007 cell.set(value);
7008 }
7009 Ok(())
7010 }
7011
7012 // -- closures -----------------------------------------------------------
7013
7014 /// Build the closure for the function constant `index`.
7015 ///
7016 /// Every entry in the child's closure table names where its binding lives in
7017 /// *this* frame: a local or argument slot that was marked captured, or a cell
7018 /// this frame is itself holding. That is how a variable three functions deep
7019 /// stays one binding.
7020 fn closure(&mut self, index: usize) -> JsResult<Value> {
7021 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
7022 else {
7023 return Err(Signal::Throw(
7024 self.make_error("InternalError", "fclosure of a non-function"),
7025 ));
7026 };
7027 let mut cells = Vec::with_capacity(function.closure_vars.len());
7028 for closure_var in &function.closure_vars {
7029 let cell = match closure_var.closure_type {
7030 ClosureType::Arg => {
7031 let slot = closure_var.var_idx as usize;
7032 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
7033 }
7034 ClosureType::Local => {
7035 let slot = closure_var.var_idx as usize;
7036 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
7037 }
7038 ClosureType::Ref | ClosureType::GlobalRef => {
7039 // A `Ref` names a cell in this frame's own closure table; a
7040 // `GlobalRef` also starts there, then resolves by name below.
7041 let slot = closure_var.var_idx as usize;
7042 if let Some(cell) = self.frame().env.cells.get(slot) {
7043 cells.push(cell.clone());
7044 continue;
7045 }
7046 -1
7047 }
7048 _ => -1,
7049 };
7050 if cell >= 0 {
7051 let cell = self.frame().cells[cell as usize].clone();
7052 cells.push(cell);
7053 continue;
7054 }
7055 // A global: the cell is created on demand and shared through the realm,
7056 // so every function sees one binding.
7057 let name = closure_var.name.clone();
7058 let cell = match self.realm.globals.get(&name) {
7059 Some(cell) => cell.clone(),
7060 None => {
7061 let cell = self.new_cell(Value::Undefined);
7062 self.realm.globals.insert(name.clone(), cell.clone());
7063 cell
7064 }
7065 };
7066 cells.push(cell);
7067 }
7068 let name = function.name.clone();
7069 // `.length` is the arity before any default or rest parameter, not the number
7070 // of slots a pattern parameter needs.
7071 let length = function.defined_args;
7072 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
7073 // function and an arrow function do not. A *method* also does not, but that is not
7074 // known here — the method is marked when the `[[HomeObject]]` is attached (see
7075 // `set_home_object`), which is the moment it becomes a method.
7076 let function_kind = function.kind;
7077 let constructible =
7078 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
7079 let code = Gc::new(self.heap, CompiledCode::new(*function));
7080 // A closure built inside an `eval` inherits the eval's view of the enclosing
7081 // bindings, so it can still read them once the eval has returned.
7082 let eval_scope = self
7083 .active_eval_scope
7084 .clone()
7085 .or_else(|| self.frame().env.eval_scope.clone());
7086 // A closure sees the variables a direct `eval` declared in the frame it was
7087 // created in — the ones declared before *and after* it, so the same object is
7088 // shared; only the phase bounds which of them are visible.
7089 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
7090 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
7091 let env = Gc::new(
7092 self.heap,
7093 ClosureEnv {
7094 cells,
7095 eval_scope,
7096 local_vars,
7097 local_phase,
7098 },
7099 );
7100 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
7101 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
7102 // the only thing that carries `Symbol.toStringTag`, so without it
7103 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
7104 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
7105 let proto = match function_kind {
7106 js_compile::bytecode::FunctionKind::AsyncGenerator => self
7107 .realm
7108 .async_generator_function_proto
7109 .clone()
7110 .or_else(|| self.realm.function_proto.clone().into()),
7111 js_compile::bytecode::FunctionKind::Generator => self
7112 .realm
7113 .generator_function_proto
7114 .clone()
7115 .or_else(|| self.realm.function_proto.clone().into()),
7116 js_compile::bytecode::FunctionKind::Async => self
7117 .realm
7118 .async_function_proto
7119 .clone()
7120 .or_else(|| self.realm.function_proto.clone().into()),
7121 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
7122 };
7123 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
7124 object.set_constructible(constructible);
7125 object.define(
7126 "length",
7127 Property::name_or_length(Value::Int(length as i32)),
7128 );
7129 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
7130 // that checks the own-property descriptor fails if the property is missing.
7131 object.define("name", Property::name_or_length(self.string(name)));
7132 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
7133 // when `[[Construct]]` is created, so a generator, an async function and an arrow
7134 // function have none of their own. Installing it unconditionally gave
7135 // `Array.fromAsync` (an async function) an own `prototype` property, which
7136 // `builtin.js` checks for absence.
7137 if constructible {
7138 self.install_function_prototype(&object);
7139 }
7140 Ok(Value::Object(object))
7141 }
7142
7143 // -- conversions used by the operators ----------------------------------
7144
7145 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
7146 // `+x` is `ToNumber`, which for a string parses it and for an object runs
7147 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
7148 // string, which then behaves differently in every later comparison.
7149 match value {
7150 Value::Int(_) | Value::Float(_) => Ok(value),
7151 other => Ok(Value::Float(self.to_js_number(&other)?)),
7152 }
7153 }
7154
7155 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
7156 ///
7157 /// Returns the *converted* old value and the new one, because the two callers need
7158 /// different halves: `++x` yields the new value, while `x++` yields the old one and
7159 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
7160 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
7161 /// boolean.
7162 ///
7163 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
7164 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
7165 /// a bigint algorithm then ran exactly once.
7166 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
7167 if let Value::BigInt(big) = &value {
7168 let one = crate::bigint::BigInt::from_i64(1);
7169 let next = if up { big.add(&one) } else { big.sub(&one) };
7170 return Ok((value, self.bigint(next)));
7171 }
7172 let old = self.numeric(value)?;
7173 let new = if up {
7174 increment(old.clone())
7175 } else {
7176 decrement(old.clone())
7177 };
7178 Ok((old, new))
7179 }
7180
7181 fn numeric(&mut self, value: Value) -> JsResult<Value> {
7182 // `ToNumber` on an object runs `ToPrimitive` first, which is how
7183 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
7184 // heard at all. Reading the object's own tag instead (`other.to_number()`)
7185 // turned the whole operand into `NaN` and swallowed the exception.
7186 match value {
7187 Value::Int(_) | Value::Float(_) => Ok(value),
7188 other => Ok(Value::Float(self.to_js_number(&other)?)),
7189 }
7190 }
7191
7192 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
7193 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
7194 match value {
7195 Value::BigInt(big) => Ok((**big).clone()),
7196 // The reference words this the same way for every operator, so a failing
7197 // script reads identically; the operator itself adds nothing a caller can use.
7198 _ => Err(Signal::Throw(
7199 self.make_error("TypeError", "cannot convert bigint to number"),
7200 )),
7201 }
7202 }
7203
7204 /// Arithmetic where at least one operand is a `BigInt`.
7205 ///
7206 /// The two numeric types never mix, so a bigint paired with anything else is an error
7207 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
7208 /// that the relational operators handle it separately.
7209 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
7210 use Opcode::*;
7211 let a = self.bigint_operand(&left)?;
7212 let b = self.bigint_operand(&right)?;
7213 let result = match op {
7214 Add => a.add(&b),
7215 Sub => a.sub(&b),
7216 Mul => a.mul(&b),
7217 Div | Mod => {
7218 let Some((quotient, remainder)) = a.div_rem(&b) else {
7219 return Err(Signal::Throw(
7220 self.make_error("RangeError", "division by zero"),
7221 ));
7222 };
7223 if op == Div { quotient } else { remainder }
7224 }
7225 Pow => {
7226 let Some(value) = a.pow(&b) else {
7227 return Err(Signal::Throw(self.make_error(
7228 "RangeError",
7229 "BigInt exponent must be non-negative and not absurdly large",
7230 )));
7231 };
7232 value
7233 }
7234 And => a.bitand(&b),
7235 Or => a.bitor(&b),
7236 Xor => a.bitxor(&b),
7237 Shl | Sar => {
7238 // A shift count is a `BigInt` here, and both directions are exact; a
7239 // negative count would be the other direction, which the spec forbids.
7240 let Some(count) = b.to_i64() else {
7241 return Err(Signal::Throw(
7242 self.make_error("RangeError", "BigInt shift count is too large"),
7243 ));
7244 };
7245 if count < 0 {
7246 return Err(Signal::Throw(self.make_error(
7247 "RangeError",
7248 "BigInt shift count must be non-negative",
7249 )));
7250 }
7251 if op == Shl {
7252 a.shl(count as u64)
7253 } else {
7254 a.shr(count as u64)
7255 }
7256 }
7257 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
7258 _ => {
7259 return Err(Signal::Throw(self.make_error(
7260 "TypeError",
7261 "BigInts have no unsigned right shift, use >> instead",
7262 )));
7263 }
7264 };
7265 Ok(self.bigint(result))
7266 }
7267
7268 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
7269 ///
7270 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
7271 /// is on the mathematical values, and nothing is rounded first.
7272 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> Value {
7273 use Opcode::*;
7274 let ordering = match (&left, &right) {
7275 (Value::String(a), Value::String(b)) => {
7276 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
7277 }
7278 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
7279 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
7280 // is true even though `2.5` has no bigint form.
7281 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
7282 let b = other.to_number();
7283 if b.is_nan() {
7284 None
7285 } else {
7286 compare_bigint_and_f64(a, b)
7287 }
7288 }
7289 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
7290 let a = other.to_number();
7291 if a.is_nan() {
7292 None
7293 } else {
7294 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
7295 }
7296 }
7297 _ => left.to_number().partial_cmp(&right.to_number()),
7298 };
7299 let _ = self;
7300 let answer = match (op, ordering) {
7301 (_, None) => false,
7302 (Lt, Some(ordering)) => ordering.is_lt(),
7303 (Lte, Some(ordering)) => ordering.is_le(),
7304 (Gt, Some(ordering)) => ordering.is_gt(),
7305 (Gte, Some(ordering)) => ordering.is_ge(),
7306 _ => false,
7307 };
7308 Value::Bool(answer)
7309 }
7310
7311 fn binary_add(&mut self) -> JsResult<()> {
7312 let right = self.pop();
7313 let left = self.pop();
7314 let left = self.primitive_of(left)?;
7315 let right = self.primitive_of(right)?;
7316 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
7317 // that check comes before the bigint one: `"" + 1n` is a string, not a
7318 // mixed-type error.
7319 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
7320 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
7321 // `TypeError`, the one place a symbol and a string do not mix.
7322 let left = self.checked_to_wtf8(&left)?;
7323 let right = self.checked_to_wtf8(&right)?;
7324 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
7325 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
7326 let text = left.concat(&right);
7327 self.push(self.string_wtf8(text));
7328 return Ok(());
7329 }
7330 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
7331 // not a conversion.
7332 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
7333 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
7334 self.push(value);
7335 return Ok(());
7336 }
7337 let left = self.numeric(left)?;
7338 let right = self.numeric(right)?;
7339 self.push(add_numbers(left, right));
7340 Ok(())
7341 }
7342
7343 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
7344 self.to_primitive(value, Hint::Default)
7345 }
7346
7347 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
7348 ///
7349 /// The order depends on the hint: the "number" order tries `valueOf` first and
7350 /// `toString` second, the "string" order the other way round, and the default
7351 /// hint uses the number order. A result that is still an object is a `TypeError`,
7352 /// because no built-in `valueOf`/`toString` returns one.
7353 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
7354 let Value::Object(object) = &value else {
7355 return Ok(value);
7356 };
7357 // A Date overrides the default hint to mean "string", which is what
7358 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
7359 // this, `"" + new Date()` would print the milliseconds, not the date.
7360 let hint = if hint == Hint::Default && is_date_object(self, object) {
7361 Hint::String
7362 } else {
7363 hint
7364 };
7365 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
7366 // handed the hint as a string. This is the hook a Date uses for its default hint
7367 // and a script uses to take over conversion entirely.
7368 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
7369 if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
7370 if !function.is_callable() {
7371 return Err(self.type_error("Symbol.toPrimitive is not a function"));
7372 }
7373 let hint = match hint {
7374 Hint::String => "string",
7375 Hint::Number => "number",
7376 Hint::Default => "default",
7377 };
7378 let hint = self.string(hint);
7379 let result = self.call_value(
7380 Value::Object(function),
7381 Value::Object(object.clone()),
7382 vec![hint],
7383 )?;
7384 if matches!(result, Value::Object(_)) {
7385 return Err(self.type_error("cannot convert object to primitive value"));
7386 }
7387 return Ok(result);
7388 }
7389 let order: [&str; 2] = match hint {
7390 Hint::String => ["toString", "valueOf"],
7391 Hint::Number | Hint::Default => ["valueOf", "toString"],
7392 };
7393 let receiver = object.clone();
7394 for method in order {
7395 if let Some(function) = self.get_property(&receiver, method)?
7396 && matches!(&function, Value::Object(object) if object.is_callable())
7397 {
7398 let result =
7399 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
7400 if !matches!(result, Value::Object(_)) {
7401 return Ok(result);
7402 }
7403 }
7404 }
7405 Err(self.type_error("cannot convert object to primitive value"))
7406 }
7407
7408 /// `ToString` with the object case going through `ToPrimitive`.
7409 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
7410 if matches!(value, Value::Object(_)) {
7411 let primitive = self.to_primitive(value.clone(), Hint::String)?;
7412 return Ok(primitive.to_js_string());
7413 }
7414 Ok(value.to_js_string())
7415 }
7416
7417 /// `ToString` that keeps the string's code units instead of flattening them.
7418 ///
7419 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
7420 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
7421 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
7422 if matches!(value, Value::Symbol(_)) {
7423 return Err(Signal::Throw(
7424 self.make_error("TypeError", "cannot convert symbol to string"),
7425 ));
7426 }
7427 // An object runs `ToPrimitive` first, which may itself produce a symbol.
7428 let value = self.to_primitive(value.clone(), Hint::String)?;
7429 match value {
7430 Value::Symbol(_) => Err(Signal::Throw(
7431 self.make_error("TypeError", "cannot convert symbol to string"),
7432 )),
7433 Value::String(text) => Ok(text.wtf8().clone()),
7434 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
7435 }
7436 }
7437
7438 /// `ToNumber` with the object case going through `ToPrimitive`.
7439 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
7440 let value = if matches!(value, Value::Object(_)) {
7441 self.to_primitive(value.clone(), Hint::Number)?
7442 } else {
7443 value.clone()
7444 };
7445 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
7446 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
7447 // `NaN` to stay total, and the operators check for the bigint themselves — but
7448 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
7449 // refuse, and answering `NaN` made them silently wrong instead.
7450 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
7451 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
7452 match value {
7453 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
7454 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
7455 other => Ok(other.to_number()),
7456 }
7457 }
7458
7459 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
7460 /// [`ElementType::write`].
7461 ///
7462 /// This is separated from the write because both conversions are observable script —
7463 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
7464 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
7465 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
7466 /// setters, and a plain `a[i] = v`.
7467 pub(crate) fn element_value(
7468 &mut self,
7469 element: crate::builtins::typedarray::ElementType,
7470 value: Value,
7471 ) -> JsResult<Value> {
7472 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
7473 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
7474 let primitive = match &value {
7475 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
7476 _ => value,
7477 };
7478 if element.is_bigint() {
7479 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
7480 Ok(Value::BigInt(Gc::new(self.heap, big)))
7481 } else {
7482 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
7483 Ok(Value::Float(self.to_js_number(&primitive)?))
7484 }
7485 }
7486
7487 /// `ToPropertyKey`: what a computed member access uses as its key.
7488 ///
7489 /// A symbol is returned as itself, never stringified — that is what keeps
7490 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
7491 fn propkey(&mut self, value: &Value) -> PropertyKey {
7492 match value {
7493 Value::Symbol(symbol) => PropertyKey::Symbol(symbol.clone()),
7494 _ => PropertyKey::String(self.propkey_of(value)),
7495 }
7496 }
7497
7498 /// `ToPropertyKey` for the callers that can only use a string key.
7499 fn propkey_of(&mut self, value: &Value) -> crate::value::Wtf8 {
7500 use crate::value::Wtf8;
7501 match value {
7502 // A string key keeps its code units. Going through a lossy `String` would make
7503 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
7504 Value::String(text) => text.wtf8().clone(),
7505 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
7506 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
7507 // falling back to its `ToString` would print `[object Object]`.
7508 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String) {
7509 Ok(Value::String(text)) => text.wtf8().clone(),
7510 Ok(other) => Wtf8::new(other.to_js_string()),
7511 Err(_) => Wtf8::new("[object Object]"),
7512 },
7513 other => Wtf8::new(other.to_js_string()),
7514 }
7515 }
7516
7517 // -- object operations used by instructions -----------------------------
7518
7519 /// Read `object[key]`, returning `undefined` when the property is missing.
7520 ///
7521 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
7522 /// primitive (looking through its prototype) as well as an object — which is what
7523 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
7524 /// argument needs too.
7525 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
7526 self.read_field_key(object, &PropertyKey::from(key))
7527 }
7528
7529 /// [`Interp::read_field`] with a key that may be a symbol.
7530 ///
7531 /// A symbol key never reaches the string shortcuts: a string's `length` and its
7532 /// indices are string properties, and a symbol named `length` is a different
7533 /// property that a string primitive cannot have.
7534 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
7535 let text = key.as_str().unwrap_or("");
7536 let Value::Object(object) = object else {
7537 // Reading a property of `undefined`/`null` is the classic TypeError.
7538 if object.is_nullish() {
7539 return Err(Signal::Throw(self.make_error(
7540 "TypeError",
7541 &format!("cannot read property '{key}' of {}", object.to_js_string()),
7542 )));
7543 }
7544 // A string has `length` and index access without being boxed.
7545 if let Value::String(value) = object {
7546 if text == "length" {
7547 return Ok(Value::Int(value.utf16_len() as i32));
7548 }
7549 if let Some(index) = array_index(text) {
7550 return Ok(match value.wtf8().unit_at(index as usize) {
7551 Some(unit) => self.string_wtf8(unit),
7552 None => Value::Undefined,
7553 });
7554 }
7555 }
7556 // A property of a primitive is looked up on its prototype: this is what
7557 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
7558 let prototype = match object {
7559 Value::String(_) => self.realm.string_proto.clone(),
7560 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
7561 Value::Bool(_) => self.realm.boolean_proto.clone(),
7562 // A symbol's methods live on `Symbol.prototype`, reached the same way —
7563 // `sym.description` reads through the prototype, not off the symbol.
7564 Value::Symbol(_) => self.realm.symbol_proto.clone(),
7565 // …and a bigint's on `BigInt.prototype`, which is how
7566 // `(255n).toString(16)` reaches its method.
7567 Value::BigInt(_) => self.realm.bigint_proto.clone(),
7568 _ => None,
7569 };
7570 if let Some(prototype) = prototype
7571 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
7572 {
7573 return Ok(value);
7574 }
7575 return Ok(Value::Undefined);
7576 };
7577 Ok(self
7578 .get_property_key(object, key)?
7579 .unwrap_or(Value::Undefined))
7580 }
7581
7582 fn write_field(&mut self, object: &Value, key: &str, value: Value) -> JsResult<()> {
7583 self.write_field_key(object, &PropertyKey::from(key), value)
7584 }
7585
7586 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
7587 let Value::Object(object) = object else {
7588 return Err(Signal::Throw(self.make_error(
7589 "TypeError",
7590 &format!("cannot set property '{key}' of {}", object.to_js_string()),
7591 )));
7592 };
7593 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
7594 let on_failure = if self.frame().code.code.strict {
7595 DeleteFailure::Throw
7596 } else {
7597 DeleteFailure::Ignore
7598 };
7599 self.set_property_with_key(object, key, value, on_failure)
7600 }
7601
7602 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
7603 ///
7604 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
7605 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
7606 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
7607 /// `Number.parseInt(sym)` — so those callers use this instead.
7608 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
7609 if matches!(value, Value::Symbol(_)) {
7610 return Err(Signal::Throw(
7611 self.make_error("TypeError", "cannot convert symbol to string"),
7612 ));
7613 }
7614 // An object runs `ToPrimitive` first, which may itself produce a symbol —
7615 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
7616 let value = self.to_primitive(value.clone(), Hint::String)?;
7617 if matches!(value, Value::Symbol(_)) {
7618 return Err(Signal::Throw(
7619 self.make_error("TypeError", "cannot convert symbol to string"),
7620 ));
7621 }
7622 Ok(value.to_js_string())
7623 }
7624
7625 /// `ToPropertyKey` for a builtin that takes a key argument.
7626 ///
7627 /// Distinct from [`Interp::propkey`], which is `fn`-private to the instruction
7628 /// loop; the builtins reach this one.
7629 pub fn property_key(&mut self, value: &Value) -> PropertyKey {
7630 self.propkey(value)
7631 }
7632
7633 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
7634 ///
7635 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
7636 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
7637 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
7638 /// `RangeError` — and why this cannot be a plain `ToNumber`.
7639 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
7640 let number = match value {
7641 Value::Int(number) => *number as f64,
7642 Value::Float(number) => *number,
7643 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
7644 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
7645 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
7646 // reference answers 0.
7647 Value::Null | Value::Bool(_) => value.to_number(),
7648 _ => {
7649 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
7650 match primitive {
7651 Value::Int(number) => number as f64,
7652 Value::Float(number) => number,
7653 other => {
7654 // `ToString` then `ToNumber`, so a string length goes through the
7655 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
7656 // `Value::to_number` on the string already implements exactly that.
7657 let text = self.to_js_string(&other)?;
7658 crate::value::string_to_number(&text)
7659 }
7660 }
7661 }
7662 };
7663 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
7664 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
7665 // is a `RangeError`, not `0`.
7666 if !number.is_finite()
7667 || number.fract() != 0.0
7668 || !(0.0..=u32::MAX as f64).contains(&number)
7669 {
7670 return Err(self.range_error("invalid array length"));
7671 }
7672 Ok(number as u32)
7673 }
7674
7675 /// `ToPropertyKey` that can fail.
7676 ///
7677 /// [`Interp::property_key`] swallows a throwing `ToPrimitive` and answers
7678 /// `"[object Object]"`, which is fine for a bytecode operand that has already been
7679 /// coerced but wrong for `Reflect.get`, where a key whose `toString` throws has to
7680 /// propagate that error (`return-abrupt-from-property-key`).
7681 pub fn property_key_checked(&mut self, value: &Value) -> JsResult<PropertyKey> {
7682 use crate::value::Wtf8;
7683 match value {
7684 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
7685 _ => match self.to_primitive(value.clone(), Hint::String)? {
7686 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
7687 // A `ToPrimitive` that lands on a symbol is a symbol key, not `String(sym)`.
7688 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
7689 other => Ok(PropertyKey::String(Wtf8::new(other.to_js_string()))),
7690 },
7691 }
7692 }
7693
7694 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
7695 /// `Object.getOwnPropertySymbols` put in their result array.
7696 pub fn key_value(&self, key: &PropertyKey) -> Value {
7697 match key {
7698 PropertyKey::String(text) => self.string_wtf8(text.clone()),
7699 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
7700 }
7701 }
7702
7703 /// Fill in a String exotic object: `_value`, `length` and the index properties.
7704 ///
7705 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
7706 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
7707 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
7708 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
7709 /// the two paths had drifted; this is the one both now use.
7710 ///
7711 /// The indices are *code units*, so an astral character occupies two of them — the
7712 /// same rule `s.length` and `s[i]` follow.
7713 /// Give an already-created object the internal slot that makes it a wrapper of
7714 /// `value`, so the primitive's prototype methods work on it.
7715 ///
7716 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
7717 /// which are wrappers of their own type holding the empty value.
7718 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
7719 self.internal_set(object, "_value", value);
7720 }
7721
7722 pub(crate) fn init_string_wrapper(
7723 &mut self,
7724 object: &Gc<JsObject>,
7725 text: &Gc<crate::value::JsString>,
7726 ) {
7727 object.define(
7728 "length",
7729 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
7730 );
7731 for index in 0..text.utf16_len() {
7732 if let Some(unit) = text.wtf8().unit_at(index) {
7733 object.define(
7734 &index.to_string(),
7735 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
7736 Property::with_attributes(self.string_wtf8(unit), false, true),
7737 );
7738 }
7739 }
7740 object.define_key(
7741 &self.internal_slot("_value"),
7742 Property::with_attributes(Value::String(text.clone()), false, false),
7743 );
7744 }
7745
7746 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
7747 ///
7748 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
7749 /// throws. The wrapper carries its primitive in `_value` — the same slot
7750 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
7751 /// on a boxed value no constructor ever built.
7752 pub(crate) fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
7753 let (prototype, primitive) = match value {
7754 Value::Object(object) => return Ok(object.clone()),
7755 Value::String(text) => {
7756 let object = self.new_object(self.realm.string_proto.clone());
7757 self.init_string_wrapper(&object, text);
7758 return Ok(object);
7759 }
7760 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
7761 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
7762 // A symbol and a bigint box into wrappers whose methods live on
7763 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
7764 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
7765 // branch below instead produced an object with *no* prototype, so those
7766 // methods were unreachable on a box.
7767 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
7768 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
7769 Value::Undefined | Value::Null => {
7770 return Err(Signal::Throw(self.make_error(
7771 "TypeError",
7772 &format!("cannot convert {} to object", value.to_js_string()),
7773 )));
7774 }
7775 _ => (None, value.clone()),
7776 };
7777 let object = self.new_object(prototype);
7778 self.internal_set(&object, "_value", primitive);
7779 Ok(object)
7780 }
7781
7782 /// `a == b`, the coercing comparison.
7783 ///
7784 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
7785 /// which is what makes `[] == ""` true: `[]` becomes `""` via
7786 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
7787 /// because the conversion is allowed to call script code, so the two primitive
7788 /// operands are handed back to it.
7789 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
7790 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
7791 return Ok(left.loose_equals(&right));
7792 }
7793 // `null == undefined` holds even though neither is an object.
7794 if matches!(left, Value::Undefined | Value::Null)
7795 && matches!(right, Value::Undefined | Value::Null)
7796 {
7797 return Ok(true);
7798 }
7799 if matches!(left, Value::Undefined | Value::Null)
7800 || matches!(right, Value::Undefined | Value::Null)
7801 {
7802 return Ok(false);
7803 }
7804 // Two objects compare by identity. Only an object *against a primitive* is
7805 // converted, which is why `{} == {}` is false while `[] == ""` is true.
7806 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
7807 return Ok(a.ptr_eq(b));
7808 }
7809 let left = self.to_primitive(left, Hint::Default)?;
7810 let right = self.to_primitive(right, Hint::Default)?;
7811 Ok(left.loose_equals(&right))
7812 }
7813
7814 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
7815 let Value::Object(object) = object else {
7816 return Err(Signal::Throw(
7817 self.make_error("TypeError", "cannot use 'in' on a non-object"),
7818 ));
7819 };
7820 let key = self.propkey(key);
7821 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
7822 // trap. One implementation, so an array's derived `length` and its inherited holes
7823 // cannot be right in one caller and wrong in another.
7824 self.has_own_or_inherited(object, &key)
7825 }
7826
7827 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
7828 let Value::Object(target) = object else {
7829 return Ok(false);
7830 };
7831 let Value::Object(function) = constructor else {
7832 return Err(Signal::Throw(self.make_error(
7833 "TypeError",
7834 "right-hand side of 'instanceof' is not callable",
7835 )));
7836 };
7837 let prototype = self.get_property(function, "prototype")?;
7838 let Some(Value::Object(prototype)) = prototype else {
7839 return Ok(false);
7840 };
7841 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
7842 // which is also what makes `proxyOfInstance instanceof C` work.
7843 let mut current = Some(target.clone());
7844 while let Some(object) = current {
7845 if object.ptr_eq(&prototype) {
7846 return Ok(true);
7847 }
7848 current = self.object_prototype_of(&object)?;
7849 }
7850 Ok(false)
7851 }
7852
7853 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
7854 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
7855 if let Some(proto) = self.proxy_get_prototype_of(object)? {
7856 return Ok(proto);
7857 }
7858 Ok(object.proto())
7859 }
7860
7861 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
7862 pub fn object_set_prototype_of(
7863 &mut self,
7864 object: &Gc<JsObject>,
7865 proto: Option<Gc<JsObject>>,
7866 ) -> JsResult<bool> {
7867 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
7868 return Ok(answer);
7869 }
7870 object.set_proto(proto);
7871 Ok(true)
7872 }
7873
7874 /// `[[IsExtensible]]`, with the proxy trap when there is one.
7875 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
7876 if let Some(answer) = self.proxy_is_extensible(object)? {
7877 return Ok(answer);
7878 }
7879 Ok(object.is_extensible())
7880 }
7881
7882 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
7883 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
7884 if let Some(answer) = self.proxy_prevent_extensions(object)? {
7885 return Ok(answer);
7886 }
7887 object.set_extensible(false);
7888 Ok(true)
7889 }
7890
7891 fn copy_properties(
7892 &mut self,
7893 target: &Value,
7894 source: &Value,
7895 exclusion: &Value,
7896 ) -> JsResult<()> {
7897 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
7898 // does contribute: its index properties are own, enumerable and writable, which
7899 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
7900 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
7901 // is a no-op.
7902 let Some(target) = target.as_object() else {
7903 return Ok(());
7904 };
7905 let source_object = match source {
7906 Value::Object(object) => object.clone(),
7907 Value::String(text) => {
7908 // Untaken keys are the string's indices, which are code units.
7909 for index in 0..text.utf16_len() {
7910 if let Some(unit) = text.wtf8().unit_at(index) {
7911 target.define_data(&index.to_string(), self.string_wtf8(unit));
7912 }
7913 }
7914 return Ok(());
7915 }
7916 _ => return Ok(()),
7917 };
7918 // An object *rest* element passes the keys already taken by the literal part as
7919 // an array of strings; a spread passes `null`, which excludes nothing. Only the
7920 // string keys of the exclusion array are meaningful, so an array is read by its
7921 // elements rather than by its own property names.
7922 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
7923 if let Value::Object(list) = exclusion
7924 && let Some(length) = list.array_length()
7925 {
7926 for index in 0..length {
7927 if let Some(value) = list.array_get(index) {
7928 excluded.push(self.propkey_of(&value));
7929 }
7930 }
7931 }
7932 let source = &source_object;
7933 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
7934 // Reading the property table directly made every spread of a proxy empty.
7935 let keys = self.object_own_property_keys(source)?;
7936 for as_key in keys {
7937 if as_key.is_symbol() {
7938 // A spread copies string-keyed properties only.
7939 continue;
7940 }
7941 if excluded.contains(&crate::value::Wtf8::new(
7942 as_key.as_str().unwrap_or_default(),
7943 )) {
7944 continue;
7945 }
7946 let enumerable = self
7947 .object_get_own_property(source, &as_key)?
7948 .is_some_and(|property| property.enumerable);
7949 if !enumerable {
7950 continue;
7951 }
7952 let value = self
7953 .get_property_key(source, &as_key)?
7954 .unwrap_or(Value::Undefined);
7955 target.define_data_key(&as_key, value);
7956 }
7957 Ok(())
7958 }
7959
7960 // -- iteration ---------------------------------------------------------
7961
7962 /// One object's own keys in enumeration order: array indices ascending, then the
7963 /// rest in insertion order.
7964 ///
7965 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
7966 /// whether the key is enumerable, which the caller resolves per key because an
7967 /// array's elements are not in the same store as its named properties.
7968 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
7969 // An index can arrive twice, once from the array's element store and once from
7970 // its property map, so the numeric keys go through a map that keeps the
7971 // enumerable answer if either source gave one.
7972 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
7973 for (key, enumerable) in &own {
7974 if let Some(index) = key.as_str().and_then(array_index) {
7975 let entry = numeric.entry(index).or_insert(false);
7976 *entry = *entry || *enumerable;
7977 }
7978 }
7979 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
7980 .into_iter()
7981 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
7982 .collect();
7983 ordered.extend(
7984 own.into_iter()
7985 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
7986 );
7987 ordered
7988 }
7989
7990 /// Build the key list a `for-in` loop walks.
7991 ///
7992 /// The order is the specification's: own properties before inherited ones, and
7993 /// within one object the integer-like keys in ascending numeric order ahead of the
7994 /// string keys in insertion order. A shadowed key only appears once, and a key that
7995 /// is a non-enumerable own property anywhere nearer is skipped entirely.
7996 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
7997 let record = self.new_object(None);
7998 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
7999 // A proxy supplies its own key list, and — the reason this is not just another
8000 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
8001 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
8002 // descriptor there.
8003 if let Value::Object(object) = value
8004 && object.proxy_state().is_some()
8005 {
8006 let own = self
8007 .proxy_own_keys(object)?
8008 .unwrap_or_else(|| object.own_property_keys());
8009 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
8010 let mut numeric: Vec<u32> = Vec::new();
8011 let mut rest: Vec<PropertyKey> = Vec::new();
8012 for key in own {
8013 match key.as_str().and_then(array_index) {
8014 Some(index) => numeric.push(index),
8015 None => rest.push(key),
8016 }
8017 }
8018 numeric.sort_unstable();
8019 ordered.extend(
8020 numeric
8021 .into_iter()
8022 .map(|index| PropertyKey::from(index.to_string())),
8023 );
8024 ordered.extend(rest);
8025 for (index, key) in ordered.into_iter().enumerate() {
8026 record.define_data(&index.to_string(), self.key_value(&key));
8027 }
8028 record.define_data("__index", Value::Int(0));
8029 // The mark that makes `for_in_advance` re-ask the proxy per key.
8030 record.define_data("__proxy", Value::Object(object.clone()));
8031 return Ok(record);
8032 }
8033 if let Value::Object(object) = value {
8034 let mut chain = vec![object.clone()];
8035 chain.extend(object.chain());
8036 // Every own string key the walk has seen, enumerable or not. A
8037 // non-enumerable own property still hides a same-named enumerable one
8038 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
8039 // keeps `x` out of the loop even when the prototype has one.
8040 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
8041 for object in chain {
8042 let mut own: Vec<(crate::value::Wtf8, bool)> = object
8043 .own_property_keys()
8044 .iter()
8045 .filter_map(|key| key.as_wtf8().cloned())
8046 .map(|key| {
8047 let enumerable = object
8048 .own_property(&key.to_string_lossy())
8049 .map(|property| property.enumerable)
8050 .unwrap_or(false);
8051 (key, enumerable)
8052 })
8053 .collect();
8054 if let Some(length) = object.array_length() {
8055 own.retain(|(key, _)| key.as_str() != Some("length"));
8056 for index in 0..length {
8057 if object.array_get(index).is_some() {
8058 own.push((crate::value::Wtf8::new(index.to_string()), true));
8059 }
8060 }
8061 }
8062 // Integer-like keys come first in ascending order, then the rest in
8063 // insertion order — and the ordering is *per object*, not for the chain
8064 // as a whole: one pass over every collected key lifted a prototype's
8065 // `"4"` above the target's own `x`/`y`, which is not the order
8066 // `for…in` reports.
8067 for (key, enumerable) in Self::order_own_keys(own) {
8068 if visited.contains(&key) {
8069 continue;
8070 }
8071 visited.push(key.clone());
8072 if enumerable {
8073 keys.push(key);
8074 }
8075 }
8076 }
8077 }
8078 for (index, key) in keys.into_iter().enumerate() {
8079 record.define_data(&index.to_string(), self.string_wtf8(key));
8080 }
8081 record.define_data("__index", Value::Int(0));
8082 Ok(record)
8083 }
8084
8085 /// The next key of a `for…in` record, `None` when the loop is done.
8086 ///
8087 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
8088 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
8089 /// the loop reaches it, so a handler that stops reporting a key partway through drops
8090 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
8091 /// key the handler had already withdrawn.
8092 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
8093 let Value::Object(record) = record else {
8094 return Ok(None);
8095 };
8096 let proxy = record
8097 .own_property("__proxy")
8098 .and_then(|property| property.value);
8099 loop {
8100 let index = record
8101 .own_property("__index")
8102 .and_then(|property| property.value)
8103 .map(|value| value.to_int32())
8104 .unwrap_or(0);
8105 let Some(candidate) = record
8106 .own_property(&index.to_string())
8107 .and_then(|property| property.value)
8108 else {
8109 return Ok(None);
8110 };
8111 record.define_data("__index", Value::Int(index + 1));
8112 let text = candidate.to_js_string();
8113 let Some(Value::Object(proxy)) = &proxy else {
8114 return Ok(Some(text));
8115 };
8116 // The candidate is already a key string here, so the lookup does not need a
8117 // second `ToPropertyKey` conversion.
8118 let key = PropertyKey::from(text.as_str());
8119 let live = match self.proxy_get_own_property(proxy, &key)? {
8120 Some(descriptor) => descriptor,
8121 // Not a proxy after all, or it lost its state: fall back to the target.
8122 None => proxy.own_property_key(&key),
8123 };
8124 if live.is_some_and(|property| property.enumerable) {
8125 return Ok(Some(text));
8126 }
8127 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
8128 // next one.
8129 }
8130 }
8131
8132 /// The iterator for `for-of`: the object and its `next` method.
8133 ///
8134 /// An object that already carries a `next` method is used as it is — that is what
8135 /// `arr.values()` returns — and only arrays and strings get the built-in
8136 /// sequence iterator.
8137 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
8138 ///
8139 /// Callers that must choose between the iterable and the array-like protocol — the
8140 /// typed-array constructor is the main one — need to ask *before* committing to one.
8141 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
8142 let key = self.realm.well_known_key(WellKnown::Iterator);
8143 let method = self.read_field_key(value, &key)?;
8144 if matches!(method, Value::Undefined | Value::Null) {
8145 return Ok(false);
8146 }
8147 if !matches!(&method, Value::Object(object) if object.is_callable()) {
8148 return Err(Signal::Throw(
8149 self.make_error("TypeError", "Symbol.iterator is not callable"),
8150 ));
8151 }
8152 Ok(true)
8153 }
8154
8155 /// Collect everything an iterable yields, closing it if the walk is abandoned.
8156 ///
8157 /// The cap is a guard against a generator that never ends: an unbounded collect would
8158 /// be an out-of-memory abort rather than a catchable error.
8159 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8160 const MAX_ITEMS: usize = 1 << 24;
8161 let iterator = self.get_iterator(value)?;
8162 let mut out = Vec::new();
8163 loop {
8164 let (element, done) = self.iterator_step(&iterator)?;
8165 if done {
8166 return Ok(out);
8167 }
8168 out.push(element);
8169 if out.len() > MAX_ITEMS {
8170 return Err(self.range_error("iterable is too long to collect"));
8171 }
8172 }
8173 }
8174
8175 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
8176 ///
8177 /// A native constructor calls this once it has validated its arguments, which is the
8178 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
8179 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
8180 /// never reached. The prototype comes from `new.target` when it is an object, and from
8181 /// `default_proto` otherwise.
8182 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
8183 let Some(target) = self.pending_new_target.clone() else {
8184 return Ok(self.new_object(Some(default_proto)));
8185 };
8186 let Some(target) = target.as_object().cloned() else {
8187 return Ok(self.new_object(Some(default_proto)));
8188 };
8189 let proto = match self.get_property(&target, "prototype")? {
8190 Some(Value::Object(proto)) => proto,
8191 _ => default_proto,
8192 };
8193 Ok(self.new_object(Some(proto)))
8194 }
8195
8196 /// Whether this call is a construction, i.e. `new.target` is defined.
8197 ///
8198 /// A native constructor receives `this = undefined` (it builds its own instance), so it
8199 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
8200 /// The native function currently executing, if any.
8201 pub fn current_native(&self) -> Option<Gc<JsObject>> {
8202 self.current_native.clone()
8203 }
8204
8205 /// Whether this call is a construction, i.e. `new.target` is defined.
8206 pub fn is_constructing(&self) -> bool {
8207 self.pending_new_target.is_some()
8208 }
8209
8210 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
8211 ///
8212 /// True whenever `new.target` is not the callee itself, or when it has no usable
8213 /// `prototype` — the cases where reading the property is observable at all.
8214 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
8215 match &self.pending_new_target {
8216 Some(Value::Object(target)) => !target.ptr_eq(callee),
8217 Some(_) => true,
8218 None => false,
8219 }
8220 }
8221
8222 /// The symbol key for one of the engine's own hidden slots.
8223 ///
8224 /// Cached on the realm, so every object of a kind shares one key and a slot can be
8225 /// read back by name.
8226 pub fn internal_slot(&mut self, name: &'static str) -> PropertyKey {
8227 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.get(name) {
8228 return PropertyKey::Symbol(symbol.clone());
8229 }
8230 let symbol = Gc::new(
8231 self.heap,
8232 crate::value::JsSymbol::new(Some(name.to_string())),
8233 );
8234 self.realm
8235 .internal_slots
8236 .insert(name, Value::Symbol(symbol.clone()));
8237 PropertyKey::Symbol(symbol)
8238 }
8239
8240 /// Read a hidden slot, or `None` when the object has none of that name.
8241 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
8242 let Value::Symbol(symbol) = self.realm.internal_slots.get(name)? else {
8243 return None;
8244 };
8245 object
8246 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
8247 .and_then(|property| property.value)
8248 }
8249
8250 /// Define a hidden slot.
8251 pub fn internal_set(&mut self, object: &Gc<JsObject>, name: &'static str, value: Value) {
8252 let key = self.internal_slot(name);
8253 object.define_key(&key, Property::with_attributes(value, false, false));
8254 }
8255
8256 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
8257 ///
8258 /// The method is looked up on the value (through its prototype), called with no
8259 /// arguments, and its result becomes the iterator. A generator gets here through
8260 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
8261 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
8262 ///
8263 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
8264 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
8265 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
8266 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
8267 /// does, and a user-defined iterable works without a special case.
8268 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
8269 /// `Symbol.iterator`.
8270 ///
8271 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
8272 /// iterable is legal there, and each value it produces is simply already settled by
8273 /// the time the `await` around it runs.
8274 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
8275 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
8276 let method = self.read_field_key(value, &async_key)?;
8277 let has_async = matches!(&method, Value::Object(object) if object.is_callable());
8278 if !has_async {
8279 return self.get_iterator(value);
8280 }
8281 let iterator = self.call_value(method, value.clone(), Vec::new())?;
8282 if !matches!(iterator, Value::Object(_)) {
8283 return Err(Signal::Throw(
8284 self.make_error("TypeError", "iterator is not an object"),
8285 ));
8286 }
8287 let next = self.read_field(&iterator, "next")?;
8288 Ok(Iterator {
8289 object: iterator,
8290 next,
8291 })
8292 }
8293
8294 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
8295 let key = self.realm.well_known_key(WellKnown::Iterator);
8296 let method = self.read_field_key(value, &key)?;
8297 let Value::Object(function) = &method else {
8298 return Err(Signal::Throw(self.make_error(
8299 "TypeError",
8300 &format!("{} is not iterable", value.to_js_string()),
8301 )));
8302 };
8303 if !function.is_callable() {
8304 return Err(Signal::Throw(self.make_error(
8305 "TypeError",
8306 &format!("{} is not iterable", value.to_js_string()),
8307 )));
8308 }
8309 let iterator = self.call_value(method, value.clone(), Vec::new())?;
8310 // The spec requires an object here; a primitive iterator has no `next` to call
8311 // and would fail one step later with a confusing message.
8312 if !matches!(iterator, Value::Object(_)) {
8313 return Err(Signal::Throw(
8314 self.make_error("TypeError", "iterator is not an object"),
8315 ));
8316 }
8317 let next = self.read_field(&iterator, "next")?;
8318 Ok(Iterator {
8319 object: iterator,
8320 next,
8321 })
8322 }
8323
8324 /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
8325 /// not iterable.
8326 ///
8327 /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
8328 /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
8329 /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
8330 /// was `[]`.
8331 pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
8332 let key = self.realm.well_known_key(WellKnown::Iterator);
8333 let method = self.read_field_key(value, &key)?;
8334 if !matches!(&method, Value::Object(object) if object.is_callable()) {
8335 return Ok(None);
8336 }
8337 let iterator = self.get_iterator(value)?;
8338 let mut out = Vec::new();
8339 loop {
8340 let (element, done) = self.iterator_step(&iterator)?;
8341 if done {
8342 return Ok(Some(out));
8343 }
8344 out.push(element);
8345 }
8346 }
8347
8348 /// One step of an internal iterator: the value and whether it is exhausted.
8349 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
8350 // A real iterator (`next` is a function) answers with a result object.
8351 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
8352 let result =
8353 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
8354 let Some(result) = result.as_object().cloned() else {
8355 return Err(self.type_error("iterator result is not an object"));
8356 };
8357 let done = self
8358 .get_property(&result, "done")?
8359 .is_some_and(|value| value.to_boolean());
8360 let value = self
8361 .get_property(&result, "value")?
8362 .unwrap_or(Value::Undefined);
8363 return Ok((value, done));
8364 }
8365 // An iterator whose `next` is not callable is treated as exhausted, which is
8366 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
8367 // that are not iterable at all.
8368 Ok((Value::Undefined, true))
8369 }
8370
8371 /// `[...iterable]`: append everything the iterator yields, and answer the next
8372 /// index.
8373 ///
8374 /// This goes through the same iterator machinery `for-of` uses rather than copying
8375 /// an array's elements, because a spread source is any iterable: a string spreads
8376 /// into its characters and an array iterator spreads into its results. Handling
8377 /// only arrays made `[..."ab"]` come out empty with no error at all.
8378 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
8379 let Some(target) = array.as_object().cloned() else {
8380 return Ok(0);
8381 };
8382 let start = target.array_length().unwrap_or(0);
8383 let mut added = 0;
8384 let iterator = self.get_iterator(iterable)?;
8385 loop {
8386 let (value, done) = self.iterator_step(&iterator)?;
8387 if done {
8388 break;
8389 }
8390 target.array_set(start + added, value);
8391 added += 1;
8392 }
8393 Ok((start + added) as i32)
8394 }
8395
8396 /// How an uncaught exception is reported.
8397 ///
8398 /// The reference reports a pending exception through `JS_PrintValue`, which ends
8399 /// up calling the thrown value's `toString`, so `throw new TypeError("x")` prints
8400 /// `TypeError: x`. Reading `name`/`message` off the object directly got this wrong
8401 /// two ways: `name` usually lives on the prototype rather than on the instance, and
8402 /// a thrown non-error object was not consulted at all, coming out as
8403 /// `[object Object]`. Routing through `ToString` keeps every case on one path and
8404 /// honours a user-defined `toString`, as the reference does.
8405 ///
8406 /// A `toString` that throws must not take the reporter down with it, so that case
8407 /// falls back to the type-level rendering. The reference's printer also walks into
8408 /// plain objects (`throw 1, {a:1}` prints `{ a: 1 }`); that formatting is a gap
8409 /// shared with `console.log`.
8410 pub fn describe_exception(&mut self, value: &Value) -> String {
8411 self.to_js_string(value).unwrap_or_else(|_| display(value))
8412 }
8413
8414 /// The current call stack, formatted the way `qjs` prints `error.stack`.
8415 ///
8416 /// One ` at name (file:line:col)` line per active frame, innermost first. The
8417 /// position is the one recorded for the instruction each frame is stopped on, which
8418 /// is why the compiler builds a pc-to-position table per function: without it a
8419 /// trace could only name the function, not the line inside it.
8420 ///
8421 /// A frame whose code has no positions prints just `(file)`, matching the
8422 /// reference's output for stripped bytecode.
8423 pub fn stack_trace(&self) -> String {
8424 self.stack_trace_skipping(0)
8425 }
8426
8427 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
8428 fn stack_trace_skipping(&self, skip: usize) -> String {
8429 let mut out = String::new();
8430 let mut skip = skip;
8431 // Natives run on the Rust stack, so they sit innermost. They never re-enter
8432 // JavaScript, which is what makes it correct to emit them all before the
8433 // bytecode frames rather than interleaved.
8434 for (name, _) in self.native_frames.iter().rev() {
8435 if skip > 0 {
8436 skip -= 1;
8437 continue;
8438 }
8439 out.push_str(" at ");
8440 out.push_str(name);
8441 out.push_str(" (native)\n");
8442 }
8443 for frame in self.frames.iter().rev() {
8444 if skip > 0 {
8445 skip -= 1;
8446 continue;
8447 }
8448 let code = &frame.code.code;
8449 let file = code.filename.as_deref().unwrap_or("<input>");
8450 // The name comes from the function *object*, not from the compiled code:
8451 // an anonymous function expression is named by the property it is stored
8452 // in (`{valueOf: function(){}}`), which only the object knows.
8453 let bound_name = match &frame.callee {
8454 Value::Object(object) => {
8455 object
8456 .own_property("name")
8457 .and_then(|property| match property.value {
8458 Some(Value::String(text)) if !text.wtf8().is_empty() => {
8459 Some(text.to_string_lossy().into_owned())
8460 }
8461 _ => None,
8462 })
8463 }
8464 _ => None,
8465 };
8466 out.push_str(" at ");
8467 out.push_str(bound_name.as_deref().unwrap_or(&code.name));
8468 match code.position_at(frame.at as u32) {
8469 Some((line, column)) => {
8470 out.push_str(&format!(" ({file}:{line}:{column})\n"));
8471 }
8472 None => out.push_str(&format!(" ({file})\n")),
8473 }
8474 }
8475 out
8476 }
8477
8478 /// Give an anonymous function the name of the property it is stored in.
8479 ///
8480 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
8481 /// enumerable and not configurable, and a function that already has a real name
8482 /// keeps it.
8483 ///
8484 /// "Already named" means a *non-empty* name: every function object is created with
8485 /// a `name` of `""` so the property exists on all of them, and treating that empty
8486 /// string as a name left every anonymous function nameless — which is how a stack
8487 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
8488 fn set_function_name(&mut self, function: &Value, name: &str) {
8489 let Value::Object(object) = function else {
8490 return;
8491 };
8492 // `SetFunctionName` applies to *functions* and classes only, and only when they are
8493 // anonymous. Without the callability guard, `{value: someObject}` renamed
8494 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
8495 // on the right-hand side of a property. That is how a `zipKeyed` result object
8496 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
8497 // has no `NamedEvaluation` at all.
8498 if !object.is_callable() {
8499 return;
8500 }
8501 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
8502 && !existing.wtf8().is_empty()
8503 {
8504 return;
8505 }
8506 let text = self.string(name);
8507 object.define("name", Property::name_or_length(text));
8508 }
8509
8510 // -- global declarations -----------------------------------------------
8511
8512 /// Declare a global binding, creating its reference cell.
8513 /// Declare a `var` or function global, whose home is the global object.
8514 ///
8515 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
8516 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
8517 /// such as `print`, or a redeclaration — is left alone.
8518 pub fn declare_var_global(&mut self, name: &str) {
8519 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
8520 // global object is exactly the leak `typeof my_var === "undefined"` after
8521 // `eval("var my_var=2")` rules out.
8522 if let Some(scope) = self.eval_scope.as_mut() {
8523 scope.entry(name.to_string()).or_insert(Value::Undefined);
8524 return;
8525 }
8526 // A sloppy direct eval declares into its *caller's* variable environment. Doing
8527 // this on the global object instead made `eval("var c = 1")` inside a parameter
8528 // list overwrite a global `c`, and made two calls to the same function share one
8529 // binding.
8530 if let Some(cell) = self.declare_eval_local(name) {
8531 cell.set(Value::Undefined);
8532 return;
8533 }
8534 let global = self.realm.global.clone();
8535 if global.own_property(name).is_some() {
8536 return;
8537 }
8538 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
8539 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
8540 // whole point of that trick and what lets `Object.defineProperty` reshape it
8541 // afterwards. `eval_scope` is `Some` while an eval is running.
8542 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
8543 global.define(
8544 name,
8545 Property {
8546 value: Some(Value::Undefined),
8547 writable: true,
8548 enumerable: true,
8549 configurable: from_eval,
8550 ..Property::default()
8551 },
8552 );
8553 }
8554
8555 /// Declare a *lexical* global binding, which starts in its dead zone.
8556 ///
8557 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
8558 /// global object and is created when its initialiser runs.
8559 pub fn declare_global(&mut self, name: &str, is_const: bool) {
8560 if is_const {
8561 self.realm.lexical_consts.insert(name.to_string());
8562 }
8563 if !self.realm.globals.contains_key(name) {
8564 // `Uninitialized` rather than `Undefined`: the binding exists but is not
8565 // readable until its initialiser runs, and that is what `let x` before
8566 // `x = 1` has to observe.
8567 let cell = self.new_cell(Value::Uninitialized);
8568 self.realm.globals.insert(name.to_string(), cell);
8569 self.realm.declared.push(name.to_string());
8570 }
8571 }
8572}
8573
8574/// The bytecode and environment of a function object, if it is a bytecode function.
8575///
8576/// Extracted before a call so no borrow of the object is held across it.
8577fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
8578 function.with(|data| match &data.kind {
8579 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
8580 _ => None,
8581 })
8582}
8583
8584/// A native call target, extracted before the call so no borrow is held.
8585enum NativeCall {
8586 Native(NativeFn),
8587 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
8588 Bound {
8589 target: Value,
8590 this: Value,
8591 leading: Vec<Value>,
8592 },
8593 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
8594 Revoker(crate::object::ProxyRef),
8595 /// A promise's `resolve`.
8596 PromiseResolve(Gc<JsObject>),
8597 /// A promise's `reject`.
8598 PromiseReject(Gc<JsObject>),
8599 /// One continuation of an `await`.
8600 AwaitResume {
8601 coroutine: Gc<JsObject>,
8602 promise: Gc<JsObject>,
8603 kind: ResumeKind,
8604 },
8605 /// One element of a `Promise` combinator settling.
8606 CombinatorSettle {
8607 state: Gc<JsObject>,
8608 index: usize,
8609 fulfilled: bool,
8610 },
8611 /// One of `Promise.prototype.finally`'s two shims.
8612 FinallyShim {
8613 callback: Option<Value>,
8614 fulfilled: bool,
8615 },
8616 /// Settle a promise with a fixed outcome.
8617 SettlePromise {
8618 promise: Gc<JsObject>,
8619 value: Value,
8620 rejected: bool,
8621 },
8622 /// Continue an async generator after its `await` settled.
8623 GeneratorResume {
8624 generator: Gc<JsObject>,
8625 promise: Gc<JsObject>,
8626 kind: ResumeKind,
8627 },
8628 /// Read a module namespace's binding out of its cell.
8629 ModuleBinding(Gc<Cell>),
8630 /// Answer a pending async-generator method with `{value, done}`.
8631 YieldResult {
8632 promise: Gc<JsObject>,
8633 done: bool,
8634 },
8635 /// One step of `AsyncDisposableStack.disposeAsync`.
8636 DisposeStep {
8637 remaining: Gc<JsObject>,
8638 promise: Gc<JsObject>,
8639 error: Value,
8640 rejected: bool,
8641 },
8642}
8643
8644/// What a store does when the object refuses the write.
8645#[derive(Clone, Copy, PartialEq, Eq)]
8646pub enum DeleteFailure {
8647 /// Raise a `TypeError`, which is what strict mode and every built-in does.
8648 Throw,
8649 /// Ignore the write, which is what a sloppy-mode assignment does.
8650 Ignore,
8651}
8652
8653/// Whether `object` is a `Date` instance, by the class tag it carries.
8654///
8655/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
8656/// builtins module depending on the interpreter's conversion order.
8657fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
8658 interp
8659 .internal_get(object, "_class")
8660 .is_some_and(|value| value.to_js_string() == "Date")
8661}
8662
8663/// Which type `ToPrimitive` prefers when it converts an object.
8664#[derive(Clone, Copy, PartialEq, Eq)]
8665pub enum Hint {
8666 /// The default hint, which behaves like [`Hint::Number`].
8667 Default,
8668 /// `Number(obj)` and the arithmetic operators.
8669 Number,
8670 /// `String(obj)` and `ToPropertyKey`.
8671 String,
8672}
8673
8674/// Which table a binding slot indexes, for the messages that name it.
8675#[derive(Clone, Copy)]
8676enum VarSlot {
8677 Loc,
8678 Closure,
8679}
8680
8681/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
8682fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
8683 Ok(this)
8684}
8685
8686/// An internal iterator: the sequence plus a cursor.
8687pub(crate) struct Iterator {
8688 pub(crate) object: Value,
8689 pub(crate) next: Value,
8690}
8691
8692/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
8693/// and plain `a` for a method.
8694///
8695/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
8696/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
8697/// reads `at get a (file:1:2)`.
8698fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
8699 match flags & 3 {
8700 1 => format!("get {key}"),
8701 2 => format!("set {key}"),
8702 _ => key.to_string(),
8703 }
8704}
8705
8706/// Define a method or accessor property, per the `define_method` flag byte.
8707///
8708/// The low two bits pick value/getter/setter and bit 2 marks the property
8709/// enumerable.
8710///
8711/// A getter and a setter arrive as two separate `define_method` instructions, and the
8712/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
8713/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
8714/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
8715/// `JS_DefineProperty`, which leaves the other half alone.
8716fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
8717 let enumerable = flags & 4 != 0;
8718 let kind = flags & 3;
8719 let existing = object.own_property_key(key);
8720 let property = match kind {
8721 1 => Property {
8722 getter: Some(function),
8723 // The setter half, if this literal already defined one.
8724 setter: existing
8725 .filter(Property::is_accessor)
8726 .and_then(|p| p.setter),
8727 enumerable,
8728 configurable: true,
8729 ..Property::default()
8730 },
8731 2 => Property {
8732 getter: existing
8733 .filter(Property::is_accessor)
8734 .and_then(|p| p.getter),
8735 setter: Some(function),
8736 enumerable,
8737 configurable: true,
8738 ..Property::default()
8739 },
8740 _ => Property {
8741 value: Some(function),
8742 writable: true,
8743 enumerable,
8744 configurable: true,
8745 ..Property::default()
8746 },
8747 };
8748 object.define_key(key, property);
8749}
8750
8751// ---------------------------------------------------------------------------
8752// Operand decoding
8753// ---------------------------------------------------------------------------
8754
8755/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
8756///
8757/// Jump operands are resolved to absolute byte offsets here, because the encoding
8758/// stores them relative to the byte after the opcode and every use site would
8759/// otherwise repeat that arithmetic.
8760fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
8761 let op = Opcode::from_u8(*code.get(pc)?)?;
8762 let info = op.info();
8763 let base = pc + 1;
8764 let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
8765 let read_u16 = |offset: usize| -> u32 {
8766 let mut value = 0u32;
8767 for index in 0..2 {
8768 value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
8769 }
8770 value
8771 };
8772 let read_u32 = |offset: usize| -> u32 {
8773 let mut value = 0u32;
8774 for index in 0..4 {
8775 value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
8776 }
8777 value
8778 };
8779 let jump = |offset: usize, width: usize| -> u32 {
8780 let raw = match width {
8781 1 => read_u8(offset) as u8 as i8 as i64,
8782 2 => read_u16(offset) as u16 as i16 as i64,
8783 _ => read_u32(offset) as i32 as i64,
8784 };
8785 (base as i64 + raw) as u32
8786 };
8787 let (a, b) = match info.format {
8788 OpFormat::None
8789 | OpFormat::NoneInt
8790 | OpFormat::NoneLoc
8791 | OpFormat::NoneArg
8792 | OpFormat::NoneVarRef
8793 | OpFormat::Npopx => (0, 0),
8794 OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
8795 OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
8796 OpFormat::Label8 => (jump(0, 1), 0),
8797 OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
8798 (read_u16(0), 0)
8799 }
8800 OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
8801 OpFormat::Label16 => (jump(0, 2), 0),
8802 OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
8803 OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
8804 OpFormat::I32 | OpFormat::Label => (
8805 if info.format == OpFormat::Label {
8806 jump(0, 4)
8807 } else {
8808 read_u32(0) as i32 as u32
8809 },
8810 0,
8811 ),
8812 OpFormat::AtomU8 | OpFormat::AtomLabelU8 => (read_u32(0), read_u8(4)),
8813 OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
8814 (read_u32(0), read_u16(4))
8815 }
8816 };
8817 Some((op, a, b, pc + info.size as usize))
8818}
8819
8820/// How `print` renders a value: the reference's `JS_PrintValue`.
8821///
8822/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
8823/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
8824/// The format is reproduced closely because the test suite compares output text:
8825///
8826/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
8827/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
8828/// * a cycle prints `[circular N]` with `N` the stack index of the object;
8829/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
8830/// end print as `<N empty item(s)>`;
8831/// * a string is quoted inside a container but raw at the top level, which is why
8832/// `print("x")` and `print(["x"])` differ.
8833pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
8834 // A string argument is printed raw: `js_print` converts it with `ToString`
8835 // instead of dumping it, and the quoting only appears inside a container.
8836 if let Value::String(text) = value {
8837 return text.to_string_lossy().into_owned();
8838 }
8839 let mut printer = Printer {
8840 interp,
8841 out: String::new(),
8842 stack: Vec::new(),
8843 };
8844 printer.value(value, 0);
8845 printer.out
8846}
8847
8848/// The internal class name an object carries, when it has one.
8849fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
8850 interp
8851 .internal_get(object, "_class")
8852 .map(|value| value.to_js_string())
8853}
8854
8855/// A string property, looked up the way `GetProperty` does: own first, then the
8856/// prototype chain. Needed because the print formatter holds the interpreter
8857/// immutably and so cannot run getters.
8858fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
8859 let mut current = Some(object.clone());
8860 // Bounded, because a prototype cycle would otherwise loop forever.
8861 for _ in 0..100 {
8862 let node = current?;
8863 if let Some(property) = node.own_property(name)
8864 && let Some(value) = property.value
8865 {
8866 return Some(value.to_js_string());
8867 }
8868 current = node.with(|data| data.proto.clone());
8869 }
8870 None
8871}
8872
8873/// The `JS_PrintValue` state: output, and the objects currently being printed.
8874struct Printer<'a, 'rt> {
8875 /// Kept for the class-name lookups that typed arrays and `Date` will need.
8876 #[allow(dead_code)]
8877 interp: &'a Interp<'rt>,
8878 out: String,
8879 stack: Vec<Gc<JsObject>>,
8880}
8881
8882impl Printer<'_, '_> {
8883 /// Depth past which a container is summarised by its class name.
8884 const MAX_DEPTH: usize = 2;
8885
8886 fn value(&mut self, value: &Value, level: usize) {
8887 match value {
8888 Value::Undefined
8889 | Value::Uninitialized
8890 | Value::Hole
8891 | Value::CatchOffset(_)
8892 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
8893 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
8894 // The printer writes a bigint the way the language spells one, so a dump is
8895 // unambiguous about which kind of number it is showing.
8896 Value::BigInt(big) => {
8897 self.out.push_str(&big.to_decimal_string());
8898 self.out.push('n');
8899 }
8900 Value::Null => self.out.push_str("null"),
8901 Value::Bool(true) => self.out.push_str("true"),
8902 Value::Bool(false) => self.out.push_str("false"),
8903 Value::Int(number) => self.out.push_str(&number.to_string()),
8904 Value::Float(number) => {
8905 self.out
8906 .push_str(&crate::value::number_to_string_for_print(*number));
8907 }
8908 Value::String(text) => self.print_string(&text.to_string_lossy()),
8909 Value::Object(object) => self.object(object, level),
8910 }
8911 }
8912
8913 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
8914 // A cycle is reported rather than followed; the index is where the object
8915 // already sits in the print stack, which is what the reference shows.
8916 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
8917 self.out.push_str(&format!("[circular {index}]"));
8918 return;
8919 }
8920 if object.is_callable() {
8921 let name = object
8922 .own_property("name")
8923 .and_then(|property| property.value)
8924 .map(|value| value.to_js_string())
8925 .unwrap_or_default();
8926 if name.is_empty() {
8927 self.out.push_str("[Function (anonymous)]");
8928 } else {
8929 self.out.push_str(&format!("[Function {name}]"));
8930 }
8931 return;
8932 }
8933 if level >= Self::MAX_DEPTH {
8934 let class = if object.is_array() { "Array" } else { "Object" };
8935 self.out.push_str(&format!("[{class}]"));
8936 return;
8937 }
8938 // `Date` and `Error` print as themselves rather than as bags of properties:
8939 // the ISO string, and `Name: message` followed by the trace.
8940 if let Some(class) = class_of(self.interp, object) {
8941 if class == "Date" {
8942 self.date(object);
8943 return;
8944 }
8945 if class == "Error" {
8946 self.error(object);
8947 return;
8948 }
8949 }
8950 self.stack.push(object.clone());
8951 if object.is_array() {
8952 self.array(object, level);
8953 } else {
8954 self.plain_object(object, level);
8955 }
8956 self.stack.pop();
8957 }
8958
8959 /// A Date prints as its ISO string; an invalid one falls through to the plain
8960 /// object form, the way the reference falls back when `toISOString` throws.
8961 fn date(&mut self, object: &Gc<JsObject>) {
8962 let value = self
8963 .interp
8964 .internal_get(object, "_date_value")
8965 .map(|value| value.to_number());
8966 match value.and_then(crate::builtins::date::iso_string) {
8967 Some(text) => self.out.push_str(&text),
8968 None => self.plain_object(object, 0),
8969 }
8970 }
8971
8972 /// `Name: message`, then the trace with its trailing newline removed.
8973 fn error(&mut self, object: &Gc<JsObject>) {
8974 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
8975 self.out.push_str(&name);
8976 if let Some(message) = inherited(object, "message")
8977 && !message.is_empty()
8978 {
8979 self.out.push_str(": ");
8980 self.out.push_str(&message);
8981 }
8982 if let Some(stack) = inherited(object, "stack") {
8983 self.out.push('\n');
8984 self.out.push_str(stack.trim_end_matches('\n'));
8985 }
8986 }
8987
8988 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
8989 let elements = object.array_elements().unwrap_or_default();
8990 self.out.push_str("[ ");
8991 // An interior hole means the array is "sparse": the reference prints those
8992 // as `index: value` pairs and says nothing about the holes themselves, while
8993 // a hole run at the end becomes a single `<N empty items>` note.
8994 let last_present = elements
8995 .iter()
8996 .rposition(|value| !matches!(value, Value::Hole));
8997 let has_interior_hole = match last_present {
8998 Some(last) => elements[..last]
8999 .iter()
9000 .any(|value| matches!(value, Value::Hole)),
9001 None => false,
9002 };
9003 let mut first = true;
9004 if has_interior_hole {
9005 let mut index = 0;
9006 while index < elements.len() {
9007 let value = &elements[index];
9008 if matches!(value, Value::Hole) {
9009 index += 1;
9010 continue;
9011 }
9012 if !first {
9013 self.out.push_str(", ");
9014 }
9015 first = false;
9016 self.out.push_str(&format!("{index}: "));
9017 self.value(value, level + 1);
9018 index += 1;
9019 }
9020 } else {
9021 for (index, value) in elements.iter().enumerate() {
9022 if matches!(value, Value::Hole) {
9023 continue;
9024 }
9025 if !first {
9026 self.out.push_str(", ");
9027 }
9028 first = false;
9029 let _ = index;
9030 self.value(value, level + 1);
9031 }
9032 if let Some(last) = last_present {
9033 let trailing = elements.len() - last - 1;
9034 if trailing > 0 {
9035 if !first {
9036 self.out.push_str(", ");
9037 }
9038 self.out.push_str(&format!(
9039 "<{trailing} empty item{}>",
9040 if trailing > 1 { "s" } else { "" }
9041 ));
9042 }
9043 } else if !elements.is_empty() {
9044 let count = elements.len();
9045 self.out.push_str(&format!(
9046 "<{count} empty item{}>",
9047 if count > 1 { "s" } else { "" }
9048 ));
9049 }
9050 }
9051 self.out.push_str(" ]");
9052 }
9053
9054 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
9055 self.out.push_str("{ ");
9056 let mut first = true;
9057 for key in object.own_keys() {
9058 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
9059 continue;
9060 };
9061 if !property.enumerable {
9062 continue;
9063 }
9064 if !first {
9065 self.out.push_str(", ");
9066 }
9067 first = false;
9068 self.out
9069 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
9070 &key.to_string_lossy(),
9071 )));
9072 self.out.push_str(": ");
9073 // An accessor has no value to dump; the reference names the half that
9074 // exists instead of calling it.
9075 if property.is_accessor() {
9076 let text = match (property.getter.is_some(), property.setter.is_some()) {
9077 (true, true) => "[Getter/Setter]",
9078 (false, true) => "[Setter]",
9079 _ => "[Getter]",
9080 };
9081 self.out.push_str(text);
9082 } else {
9083 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
9084 }
9085 }
9086 self.out.push_str(" }");
9087 }
9088
9089 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
9090 fn print_string(&mut self, text: &str) {
9091 self.out.push('"');
9092 for character in text.chars() {
9093 match character {
9094 '"' => self.out.push_str("\\\""),
9095 '\\' => self.out.push_str("\\\\"),
9096 '\n' => self.out.push_str("\\n"),
9097 '\r' => self.out.push_str("\\r"),
9098 '\t' => self.out.push_str("\\t"),
9099 c if (c as u32) < 0x20 => {
9100 self.out.push_str(&format!("\\u{:04x}", c as u32));
9101 }
9102 c => self.out.push(c),
9103 }
9104 }
9105 self.out.push('"');
9106 }
9107}
9108
9109/// How `print` renders a value.
9110///
9111/// `ToString`, except that negative zero keeps its sign — the reference's host
9112/// printer does that while `String(-0)` is `"0"`.
9113pub fn display(value: &Value) -> String {
9114 match value {
9115 Value::Float(number) => crate::value::number_to_string_for_print(*number),
9116 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
9117 "undefined".to_string()
9118 }
9119 other => other.to_js_string(),
9120 }
9121}
9122
9123// ---------------------------------------------------------------------------
9124// Numeric operators
9125// ---------------------------------------------------------------------------
9126
9127/// `a + b` keeping the `Int` representation when it fits.
9128fn add_numbers(left: Value, right: Value) -> Value {
9129 match (&left, &right) {
9130 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9131 Some(sum) => Value::Int(sum),
9132 None => Value::Float(*a as f64 + *b as f64),
9133 },
9134 _ => Value::Float(left.to_number() + right.to_number()),
9135 }
9136}
9137
9138/// The arithmetic operators other than `+`, which needs string concatenation.
9139fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
9140 use Opcode::*;
9141 let (a, b) = (left.to_number(), right.to_number());
9142 Ok(match op {
9143 Sub => match (&left, &right) {
9144 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
9145 Some(value) => Value::Int(value),
9146 None => Value::Float(a - b),
9147 },
9148 _ => Value::Float(a - b),
9149 },
9150 Mul => Value::Float(a * b),
9151 Div => Value::Float(a / b),
9152 Mod => Value::Float(js_mod(a, b)),
9153 Pow => Value::Float(a.powf(b)),
9154 And => Value::Int(left.to_int32() & right.to_int32()),
9155 Or => Value::Int(left.to_int32() | right.to_int32()),
9156 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
9157 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
9158 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
9159 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
9160 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
9161 // fits the small-integer representation stays an `Int`; the rest become a
9162 // float, which is how the reference keeps `n >>> 0` non-negative.
9163 Shr => {
9164 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
9165 match i32::try_from(shifted) {
9166 Ok(value) => Value::Int(value),
9167 Err(_) => Value::Float(shifted as f64),
9168 }
9169 }
9170 _ => Value::Float(a),
9171 })
9172}
9173
9174/// `%`, which follows the sign of the dividend rather than Rust's.
9175fn js_mod(left: f64, right: f64) -> f64 {
9176 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
9177 return f64::NAN;
9178 }
9179 if right.is_infinite() {
9180 return left;
9181 }
9182 let remainder = left % right;
9183 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
9184 // the spec makes the sign match the dividend.
9185 if remainder == 0.0 {
9186 0.0f64.copysign(left)
9187 } else {
9188 remainder
9189 }
9190}
9191
9192fn negate(value: Value) -> Value {
9193 match value {
9194 Value::Int(0) => Value::Float(-0.0),
9195 Value::Int(i) => Value::Int(-i),
9196 other => Value::Float(-other.to_number()),
9197 }
9198}
9199
9200fn increment(value: Value) -> Value {
9201 match value {
9202 Value::Int(i) => match i.checked_add(1) {
9203 Some(next) => Value::Int(next),
9204 None => Value::Float(i as f64 + 1.0),
9205 },
9206 other => Value::Float(other.to_number() + 1.0),
9207 }
9208}
9209
9210fn decrement(value: Value) -> Value {
9211 match value {
9212 Value::Int(i) => match i.checked_sub(1) {
9213 Some(next) => Value::Int(next),
9214 None => Value::Float(i as f64 - 1.0),
9215 },
9216 other => Value::Float(other.to_number() - 1.0),
9217 }
9218}
9219
9220/// Compare a `BigInt` with an `f64` on their mathematical values.
9221///
9222/// Neither side is rounded to the other's precision: the number is split into its integer
9223/// part (compared as an exact bigint) and its fraction, which is what decides the answer
9224/// when the integer parts are equal. An infinite value is larger than every bigint.
9225fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
9226 use std::cmp::Ordering;
9227 if number.is_nan() {
9228 return None;
9229 }
9230 if number.is_infinite() {
9231 return Some(if number > 0.0 {
9232 Ordering::Less
9233 } else {
9234 Ordering::Greater
9235 });
9236 }
9237 let truncated = number.trunc();
9238 // A number wider than `i128` still has an exact integer part, but no bigint form we can
9239 // build cheaply; the sign of the difference is all that is needed, so compare against
9240 // the bigint's own magnitude instead.
9241 if truncated.abs() >= 1.7e38 {
9242 let big_as_f64 = big.to_f64();
9243 return big_as_f64.partial_cmp(&number);
9244 }
9245 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
9246 match big.cmp(&integer) {
9247 Ordering::Equal => {
9248 // Same integer part: the fraction decides, and a negative number's fraction is
9249 // below the integer (`-1.5` truncates to `-1`).
9250 if number > truncated {
9251 Some(Ordering::Less)
9252 } else if number < truncated {
9253 Some(Ordering::Greater)
9254 } else {
9255 Some(Ordering::Equal)
9256 }
9257 }
9258 other => Some(other),
9259 }
9260}