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