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