quickjs/interp.rs
1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::{OpFormat, Opcode};
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25 Callable, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars, NativeFn, ObjectKind,
26 Property, PropertyKey, array_index, has_own, lookup_key, same_proto,
27};
28use crate::value::{Cell, Value, number_to_string};
29
30/// Why execution stopped.
31#[derive(Debug, Clone)]
32pub enum Signal {
33 /// A JavaScript exception carrying the thrown value.
34 Throw(Value),
35 /// The runtime ran out of memory.
36 OutOfMemory,
37}
38
39/// What an execution step produced.
40pub type JsResult<T> = std::result::Result<T, Signal>;
41
42/// The result of one instruction.
43enum Step {
44 /// Keep executing the current frame.
45 Continue,
46 /// The current frame returned this value.
47 Return(Value),
48 /// The frame parked at a suspension point, with the yielded value on its stack.
49 ///
50 /// Only a generator or an async function can produce this, and only its own frame —
51 /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
52 /// detached and handed to the generator object, which is what lets it resume later
53 /// with its locals and operand stack intact.
54 Suspend(SuspendKind),
55}
56
57/// Why a frame parked, which decides how the resumption is delivered.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum SuspendKind {
60 /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
61 /// without passing a value, because there is no `yield` expression to receive one.
62 Initial,
63 /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
64 Yield,
65 /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
66 /// `{value, done}` object from the inner iterator and is handed straight back.
67 YieldStar,
68 /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
69 /// what was yielded is the plain value and still has to be awaited and wrapped —
70 /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
71 /// made it pass a bare value through as if it were an iterator result, so
72 /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
73 AsyncYieldStar,
74 /// `await expr`: the value is a promise the async machinery has to settle first.
75 Await,
76}
77
78/// Everything one JavaScript realm owns.
79///
80/// A realm is the set of objects a script can reach without naming them: the global
81/// object, the prototype chain roots, and the global binding cells.
82pub struct Realm {
83 /// The global object.
84 pub global: Gc<JsObject>,
85 /// `Object.prototype`.
86 pub object_proto: Gc<JsObject>,
87 /// `Function.prototype`, which is itself callable.
88 pub function_proto: Gc<JsObject>,
89 /// `Array.prototype`.
90 pub array_proto: Gc<JsObject>,
91 /// Reference cells for globals declared by the script.
92 ///
93 /// A declared global is read with `get_var` (by name) but written with
94 /// `put_var_ref` (through the cell), so the cell is what makes a function
95 /// declaration and its uses agree on one binding.
96 pub globals: BTreeMap<String, Gc<Cell>>,
97 /// Names of the globals that came from a *declaration*, which are
98 /// non-configurable properties of the global object.
99 pub declared: Vec<String>,
100 /// Names among the lexical globals that are `const`.
101 ///
102 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
103 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
104 /// path does not carry, so a store through it would look like a plain `let`. The
105 /// realm records it once, at declaration, and answers for every reader.
106 pub lexical_consts: BTreeSet<String>,
107 /// The error constructors by class name, so a runtime error can throw a real
108 /// `TypeError` instance rather than a look-alike object.
109 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
110 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
111 pub string_proto: Option<Gc<JsObject>>,
112 /// `Number.prototype`.
113 pub number_proto: Option<Gc<JsObject>>,
114 /// `Boolean.prototype`.
115 pub boolean_proto: Option<Gc<JsObject>>,
116 /// `BigInt.prototype`.
117 pub bigint_proto: Option<Gc<JsObject>>,
118 /// `Error.prototype`, the prototype of every error instance.
119 pub error_proto: Gc<JsObject>,
120 /// `Date.prototype`, so the constructor can build an instance in the
121 /// function-call form (`Date()` returns a string) without going through `new`.
122 pub date_proto: Gc<JsObject>,
123 /// `%GeneratorPrototype%`, the prototype of every generator object.
124 pub generator_proto: Gc<JsObject>,
125 /// `Promise.prototype`, the prototype of every promise.
126 pub promise_proto: Option<Gc<JsObject>>,
127 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
128 pub async_generator_proto: Option<Gc<JsObject>>,
129 /// `Symbol.prototype`.
130 pub symbol_proto: Option<Gc<JsObject>>,
131 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
132 /// `_date_value`.
133 ///
134 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
135 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
136 /// language does not have and `new Error()` listed `_class` beside `message` and
137 /// `stack` — and a caller that copies every own property (which
138 /// `Object.create(null, props)` effectively does) tried to write an internal name and
139 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
140 /// and `JSON.stringify`, while remaining an ordinary traced property.
141 ///
142 /// `RefCell` because interning is memoisation rather than observable state: filling the
143 /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
144 /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
145 /// built while reporting a failure must not require an exclusive borrow.
146 pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
147
148 /// The `Symbol.for` registry: `key -> symbol`.
149 ///
150 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
151 /// symbol every time within one script while a fresh realm starts empty.
152 pub symbol_registry: BTreeMap<String, Value>,
153 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
154 pub regexp_proto: Option<Gc<JsObject>>,
155 /// The `RegExp` constructor.
156 pub regexp_ctor: Option<Gc<JsObject>>,
157 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
158 ///
159 /// The prototype rather than the constructor on purpose: a script that replaces
160 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
161 /// error wrapping, which the `using` test suite checks explicitly.
162 pub suppressed_error_proto: Option<Gc<JsObject>>,
163 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
164 pub disposable_stack_proto: Option<Gc<JsObject>>,
165 /// `Map.prototype`.
166 pub map_proto: Option<Gc<JsObject>>,
167 /// `Set.prototype`.
168 pub set_proto: Option<Gc<JsObject>>,
169 /// Every live `FinalizationRegistry`, held weakly.
170 ///
171 /// The cleanup callback has to run from a *safe point* — a place where script is not
172 /// already executing and no engine borrow is held — and the collector cannot enumerate
173 /// heap objects by type. Registering each registry here gives the drain a list to walk.
174 ///
175 /// The handles are weak on purpose: a registry the script dropped must be collectable,
176 /// and it must not be resurrected merely because the drain knew about it. Entries whose
177 /// target has expired are swept out as the drain walks, so the vector does not grow
178 /// without bound in a program that creates many short-lived registries.
179 pub finalization_registries: Vec<WeakGc<JsObject>>,
180 /// `ArrayBuffer.prototype`.
181 pub array_buffer_proto: Option<Gc<JsObject>>,
182 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
183 pub typed_array_proto: Option<Gc<JsObject>>,
184 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
185 ///
186 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
187 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
188 /// `"Object"` and `r instanceof Int32Array` is false.
189 pub typed_array_protos: Vec<Gc<JsObject>>,
190 /// `DataView.prototype`.
191 pub data_view_proto: Option<Gc<JsObject>>,
192 /// The `AsyncDisposableStack` prototype.
193 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
194 /// `Iterator.prototype`.
195 pub iterator_proto: Option<Gc<JsObject>>,
196 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
197 ///
198 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
199 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
200 /// `[object Iterator Helper]`).
201 pub iterator_helper_proto: Option<Gc<JsObject>>,
202 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
203 /// that was not already an `Iterator`.
204 ///
205 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
206 /// untouched and does *not* override `@@toStringTag`, so
207 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
208 pub iterator_wrap_proto: Option<Gc<JsObject>>,
209 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
210 pub generator_function_proto: Option<Gc<JsObject>>,
211 /// `%AsyncFunction.prototype%`.
212 pub async_function_proto: Option<Gc<JsObject>>,
213 /// `%AsyncGeneratorFunction.prototype%`.
214 pub async_generator_function_proto: Option<Gc<JsObject>>,
215 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
216 ///
217 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
218 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
219 /// prototype per iterator made every array iterator's prototype distinct.
220 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
221 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
222 ///
223 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
224 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
225 /// both faster and impossible to break from a script.
226 well_known_symbols: WellKnownSymbols,
227}
228
229/// One binding of the frame that called `eval`, so the eval'd code can read and
230/// write it by name.
231struct EvalBinding {
232 /// The name it was declared with.
233 name: String,
234 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
235 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
236 /// a function that declares `a` must find that `a`.
237 frame: usize,
238 /// Which table of that frame it lives in.
239 slot: EvalSlot,
240 /// The slot index within that table.
241 index: usize,
242}
243
244/// Which table of a frame an [`EvalBinding`] indexes.
245#[derive(Clone, Copy)]
246enum EvalSlot {
247 Arg,
248 Local,
249}
250
251/// One activation record.
252struct Frame {
253 /// The bytecode being run.
254 code: Gc<CompiledCode>,
255 /// The cells this closure captured.
256 env: Gc<ClosureEnv>,
257 /// The `this` binding.
258 this: Value,
259 /// Argument slots, sized to the declared parameter count.
260 args: Vec<Value>,
261 /// The values the caller actually passed, which is what `arguments` exposes.
262 passed: Vec<Value>,
263 /// Local slots.
264 locals: Vec<Value>,
265 /// Reference cells for this frame's own captured bindings.
266 cells: Vec<Gc<Cell>>,
267 /// The operand stack.
268 stack: Vec<Value>,
269 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
270 local_vars: Option<Gc<LocalVars>>,
271
272 /// Byte offset of the next instruction.
273 pc: usize,
274 /// Byte offset of the instruction being executed, which is what a stack trace
275 /// reports. `pc` has already moved past it by the time an instruction runs.
276 at: usize,
277 /// The callee, so a native builtin can tell which constructor it is.
278 callee: Value,
279 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
280 new_target: Value,
281 /// Whether this frame's body ended in a `tail_call`.
282 ///
283 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
284 /// with its own frame just like `call` does and only skips storing the result
285 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
286 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
287 /// pushed as usual, and this marker makes its return value the *caller's* return
288 /// value without running the instructions after the call.
289 tail: bool,
290}
291
292impl js_gc::Trace for Frame {
293 fn trace(&self, tracer: &mut js_gc::Tracer) {
294 self.code.trace(tracer);
295 self.env.trace(tracer);
296 self.this.trace(tracer);
297 for value in &self.args {
298 value.trace(tracer);
299 }
300 for value in &self.passed {
301 value.trace(tracer);
302 }
303 for value in &self.locals {
304 value.trace(tracer);
305 }
306 for cell in &self.cells {
307 cell.trace(tracer);
308 }
309 if let Some(local_vars) = &self.local_vars {
310 tracer.visit(local_vars);
311 }
312 for value in &self.stack {
313 value.trace(tracer);
314 }
315 self.callee.trace(tracer);
316 self.new_target.trace(tracer);
317 }
318}
319
320/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
321/// emitted `if_false` treats as "keep going".
322const RESUME_NEXT: i32 = 0;
323/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
324/// generator fall into its `return_async`.
325const RESUME_RETURN: i32 = 1;
326/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
327/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
328/// must forward the exception into the inner iterator rather than finish.
329const RESUME_THROW: i32 = 2;
330
331/// One microtask.
332///
333/// The queue holds *data* rather than closures because its contents are GC values: a
334/// closure would be invisible to the collector, and a pending reaction is exactly the
335/// kind of thing that must keep its handlers and its promise alive.
336pub enum Job {
337 /// A `then` reaction about to run.
338 Reaction {
339 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
340 handler: Option<Value>,
341 /// The value or reason to call it with.
342 argument: Value,
343 /// Whether the source promise rejected, which decides the pass-through kind.
344 rejected: bool,
345 /// The promise the answer settles.
346 promise: Gc<JsObject>,
347 },
348 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
349 Thenable {
350 /// The `then` that was found on the value.
351 then: Value,
352 /// The thenable itself, which becomes `then`'s `this`.
353 value: Value,
354 /// The promise being resolved.
355 promise: Gc<JsObject>,
356 },
357 /// A pending `import(specifier)`.
358 Import {
359 /// The specifier, already converted to a string.
360 specifier: String,
361 /// The module that asked, which the specifier resolves against.
362 referrer: String,
363 /// The promise `import()` handed back.
364 promise: Gc<JsObject>,
365 },
366 /// An async generator resuming after the value it awaited settled.
367 GeneratorResume {
368 /// The async generator to continue.
369 generator: Gc<JsObject>,
370 /// The promise the pending method returned.
371 promise: Gc<JsObject>,
372 /// Whether this delivers the value or raises the reason.
373 kind: ResumeKind,
374 /// The settled value, or the rejection reason.
375 value: Value,
376 },
377 /// An async function resuming after the value it awaited settled.
378 Resume {
379 /// The body, parked in a coroutine.
380 coroutine: Gc<JsObject>,
381 /// The promise the async function handed its caller.
382 promise: Gc<JsObject>,
383 /// Whether this resumption delivers a value or raises one.
384 kind: ResumeKind,
385 /// The settled value, or the rejection reason.
386 value: Value,
387 },
388}
389
390/// One macro-task: work the event loop owes the script but has not run yet.
391///
392/// The microtask queue ([`Job`]) is different: those run before the host regains control.
393/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
394/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
395/// logic: the engine decides *what* is due, the host decides *how to wait*.
396///
397/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
398/// reference counting even though nothing else references it — the same rule the `HostFn`
399/// documentation states from the other side (a host closure must not hold a `Gc`, so the
400/// `Gc` lives here instead).
401pub enum Task {
402 /// A `setTimeout` that is due at `due_at`.
403 ///
404 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
405 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
406 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
407 /// would give this engine a timer the reference cannot produce, with nothing to
408 /// compare it against.
409 Timer {
410 /// The id `setTimeout` returned, for `clearTimeout`.
411 id: i32,
412 /// What to call when it fires.
413 callback: Value,
414 /// When it becomes runnable, as a monotonic instant.
415 due_at: std::time::Instant,
416 },
417}
418
419/// A descriptor the host has to poll, and which directions have a handler.
420///
421/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
422/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
423/// blocks on it, and the host reports back through [`Interp::fire_fd`].
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
425pub struct FdInterest {
426 /// The descriptor to watch.
427 pub fd: i32,
428 /// Whether `os.setReadHandler` registered a callback.
429 pub read: bool,
430 /// Whether `os.setWriteHandler` registered a callback.
431 pub write: bool,
432}
433
434/// The callbacks registered for one descriptor, per direction.
435#[derive(Default)]
436pub(crate) struct FdHandlers {
437 /// `os.setReadHandler`'s callback.
438 pub read: Option<Value>,
439 /// `os.setWriteHandler`'s callback.
440 pub write: Option<Value>,
441}
442
443/// The file name `eval` reports, which the reference does not inherit from the caller.
444///
445/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
446/// reference and the names show up in stack traces.
447/// The description of the private symbol a class brand is made from.
448///
449/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
450/// place no script can reach, since no expression can name a private symbol.
451const BRAND_DESCRIPTION: &str = "brand";
452
453const EVAL_FILE: &str = "<input>";
454
455/// The file name `std.evalScript` reports.
456const EVAL_SCRIPT_FILE: &str = "<evalScript>";
457
458/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
459///
460/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
461/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
462fn clamp_delay(delay_ms: f64) -> std::time::Duration {
463 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
464 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
465 // non-positive delay mean "due now".
466 if delay_ms.is_nan() || delay_ms <= 0.0 {
467 return std::time::Duration::ZERO;
468 }
469 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
470}
471
472impl js_gc::Trace for Task {
473 fn trace(&self, tracer: &mut js_gc::Tracer) {
474 let Task::Timer { callback, .. } = self;
475 callback.trace(tracer);
476 }
477}
478
479/// What one turn of the event loop did, so the caller cannot spin by accident.
480///
481/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
482/// core until the timer is due. Naming the three cases makes the wait explicit.
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub enum Turn {
485 /// Something ran. Call again immediately — there may be more ready work.
486 Ran,
487 /// Nothing is runnable, but descriptors are registered: the host must poll
488 /// [`Interp::pending_fds`] for at most this long, then report readiness with
489 /// [`Interp::fire_fd`].
490 ///
491 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
492 /// the failure this project treats as worst — a handler that silently never fires —
493 /// so the two cannot be confused by accident.
494 Poll(std::time::Duration),
495 /// Nothing is runnable yet, but something is pending. Block at most this long, then
496 /// call again.
497 Wait(std::time::Duration),
498 /// Nothing is pending at all: the loop is done.
499 Done,
500}
501
502impl js_gc::Trace for Job {
503 fn trace(&self, tracer: &mut js_gc::Tracer) {
504 match self {
505 Job::Reaction {
506 handler,
507 argument,
508 promise,
509 ..
510 } => {
511 if let Some(handler) = handler {
512 handler.trace(tracer);
513 }
514 argument.trace(tracer);
515 tracer.visit(promise);
516 }
517 Job::Thenable {
518 then,
519 value,
520 promise,
521 } => {
522 then.trace(tracer);
523 value.trace(tracer);
524 tracer.visit(promise);
525 }
526 Job::Resume {
527 coroutine,
528 promise,
529 value,
530 ..
531 } => {
532 tracer.visit(coroutine);
533 tracer.visit(promise);
534 value.trace(tracer);
535 }
536 Job::Import { promise, .. } => tracer.visit(promise),
537 Job::GeneratorResume {
538 generator,
539 promise,
540 value,
541 ..
542 } => {
543 tracer.visit(generator);
544 tracer.visit(promise);
545 value.trace(tracer);
546 }
547 }
548 }
549}
550
551/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
552#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553pub enum ResumeKind {
554 /// The generator was just created and is being run to its first suspension.
555 Start,
556 /// `next(v)`.
557 Next,
558 /// `return(v)`.
559 Return,
560 /// `throw(e)`.
561 Throw,
562}
563
564/// A generator object's saved execution.
565///
566/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
567/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
568/// separately allocated buffers.
569pub struct GeneratorState {
570 /// The detached frame, or `None` once the generator has finished or while it runs.
571 frame: Option<Frame>,
572 /// How far it got.
573 phase: GeneratorPhase,
574 /// Whether the last suspension was an `await` rather than a `yield`.
575 ///
576 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
577 /// value and a magic number, because the emitted code branches on which method
578 /// resumed it, while an `await` simply continues with its value. Getting this wrong
579 /// leaves an extra value on the operand stack that the next instruction then
580 /// consumes — a wrong answer rather than a crash.
581 parked_on_await: bool,
582 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
583 ///
584 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
585 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
586 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
587 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
588 /// delegating. Tracking it as part of the phase, the way the reference splits
589 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
590 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
591 /// exception and never reached `xs.throw`.
592 parked_on_yield_star: bool,
593 /// Pending `next`/`return`/`throw` calls, oldest first.
594 ///
595 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
596 /// called back to back must answer in that order, with the second call's value
597 /// arriving at the *second* `yield`. Running each call straight into the body — which
598 /// is what this engine did before — delivered the last queued value to whichever
599 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
600 /// `a === b ===` the final argument.
601 ///
602 /// The front entry is the one being served; it stays there (with `async_busy` set)
603 /// until its promise settles, because an `await` inside the body is a suspension of
604 /// the *driver*, not the end of the request.
605 requests: std::collections::VecDeque<AsyncRequest>,
606 /// Whether the front request is in flight.
607 async_busy: bool,
608}
609
610/// How one async-generator request ended.
611enum AsyncOutcome {
612 /// The method answered this `{value, done}`.
613 Value(Value),
614 /// The body threw.
615 Error(Value),
616}
617
618/// One queued `next`/`return`/`throw` on an async generator: the reference's
619/// `JSAsyncGeneratorRequest`.
620pub struct AsyncRequest {
621 /// Which method was called.
622 kind: ResumeKind,
623 /// Its argument.
624 value: Value,
625 /// The promise the method answered.
626 promise: Gc<JsObject>,
627}
628
629/// Which of §27.5.3.3's states a generator is in.
630#[derive(Debug, Clone, Copy, PartialEq, Eq)]
631enum GeneratorPhase {
632 /// Created, `initial_yield` reached, body not entered.
633 SuspendedStart,
634 /// Parked at a `yield`.
635 SuspendedYield,
636 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
637 Executing,
638 /// Finished; the frame is gone.
639 Completed,
640}
641
642impl js_gc::Trace for GeneratorState {
643 fn trace(&self, tracer: &mut js_gc::Tracer) {
644 if let Some(frame) = &self.frame {
645 frame.trace(tracer);
646 }
647 for request in &self.requests {
648 request.value.trace(tracer);
649 tracer.visit(&request.promise);
650 }
651 }
652}
653
654/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
655/// them in.
656///
657/// Each is a field rather than a map entry because the runtime reads them on hot paths
658/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
659/// failure — reaching a default here means the builtin did not install, and every
660/// accessor panics rather than silently answering `undefined`.
661///
662/// [`builtins::symbol`]: crate::builtins::symbol
663#[derive(Default)]
664pub struct WellKnownSymbols {
665 /// The symbol values, positionally. Empty until `Symbol` installs.
666 symbols: Vec<Value>,
667}
668
669/// Which well-known symbol a caller wants.
670///
671/// A typed accessor beats passing a name around: a typo is a compile error rather than
672/// an `undefined` key that quietly matches nothing.
673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
674pub enum WellKnown {
675 /// `Symbol.toPrimitive`.
676 ToPrimitive,
677 /// `Symbol.iterator`.
678 Iterator,
679 /// `Symbol.match`.
680 Match,
681 /// `Symbol.matchAll`.
682 MatchAll,
683 /// `Symbol.replace`.
684 Replace,
685 /// `Symbol.search`.
686 Search,
687 /// `Symbol.split`.
688 Split,
689 /// `Symbol.toStringTag`.
690 ToStringTag,
691 /// `Symbol.isConcatSpreadable`.
692 IsConcatSpreadable,
693 /// `Symbol.hasInstance`.
694 HasInstance,
695 /// `Symbol.species`.
696 Species,
697 /// `Symbol.unscopables`.
698 Unscopables,
699 /// `Symbol.asyncIterator`.
700 AsyncIterator,
701 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
702 Disposable,
703 /// `Symbol.asyncDispose` — the awaited form.
704 AsyncDisposable,
705}
706
707impl WellKnown {
708 /// The index `Symbol`'s installer creates this symbol at.
709 fn index(self) -> usize {
710 match self {
711 WellKnown::ToPrimitive => 0,
712 WellKnown::Iterator => 1,
713 WellKnown::Match => 2,
714 WellKnown::MatchAll => 3,
715 WellKnown::Replace => 4,
716 WellKnown::Search => 5,
717 WellKnown::Split => 6,
718 WellKnown::ToStringTag => 7,
719 WellKnown::IsConcatSpreadable => 8,
720 WellKnown::HasInstance => 9,
721 WellKnown::Species => 10,
722 WellKnown::Unscopables => 11,
723 WellKnown::AsyncIterator => 12,
724 WellKnown::Disposable => 13,
725 WellKnown::AsyncDisposable => 14,
726 }
727 }
728}
729
730impl Realm {
731 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
732 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
733 self.well_known_symbols.symbols = symbols;
734 }
735
736 /// A well-known symbol.
737 pub fn well_known(&self, which: WellKnown) -> Value {
738 self.well_known_symbols
739 .symbols
740 .get(which.index())
741 .cloned()
742 .unwrap_or(Value::Undefined)
743 }
744
745 /// The well-known symbol as a property key.
746 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
747 match self.well_known(which) {
748 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
749 // Unreachable once `Symbol` has installed; an empty string key matches
750 // nothing, which degrades to "the object has no such method".
751 _ => PropertyKey::from(String::new()),
752 }
753 }
754}
755
756/// The interpreter: a realm plus a frame stack.
757pub struct Interp<'a> {
758 /// The heap everything is allocated on.
759 pub heap: &'a Heap,
760 /// The realm.
761 pub realm: Realm,
762 /// Active frames, outermost first.
763 frames: Vec<Frame>,
764 /// A strict-mode `eval`'s own variable scope, while its script runs.
765 ///
766 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
767 /// become a global. Name lookups still fall through to the realm, which is why
768 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
769 eval_scope: Option<BTreeMap<String, Value>>,
770 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
771 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
772 eval_depth: usize,
773 /// The calling frame's own bindings, which the running `eval` can read and write.
774 ///
775 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
776 /// come from the frame, and a write is applied back to the frame (or to the cell
777 /// the frame captured) when the eval finishes. That is what makes
778 /// `f("a = 3")` visible to the caller as `a === 3`.
779 eval_bindings: Vec<EvalBinding>,
780 /// The calling frame's `arguments`, while an `eval` runs.
781 ///
782 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
783 /// own yet still has to see the caller's `arguments`.
784 eval_arguments: Option<Value>,
785 /// The `with` objects live at the moment the running `eval` started, innermost first.
786 ///
787 /// `None` outside an eval, which is what keeps a finished block's object from
788 /// shadowing ordinary bytecode reads.
789 eval_with: Option<Vec<Gc<JsObject>>>,
790 /// The bindings the running direct `eval` makes visible, as name → cell.
791 ///
792 /// Set for the duration of an eval and then restored, but every closure created
793 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
794 /// `eval("f = () => i")` work after the eval has returned.
795 active_eval_scope: Option<Gc<EvalScope>>,
796 /// The frame that called the direct `eval` currently running, if any.
797 ///
798 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
799 /// on the global object, which is what keeps
800 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
801 /// gives each call its own `x`.
802 eval_caller: Option<Option<usize>>,
803 /// The caller's `new.target`, while an `eval` runs.
804 ///
805 /// The eval'd code is a script with no constructor of its own, so it inherits the
806 /// one the enclosing function was called with.
807 eval_new_target: Option<Value>,
808 /// `new.target` for the frame about to be pushed.
809 ///
810 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
811 /// value reaches the frame without threading a parameter through every call site.
812 pending_new_target: Option<Value>,
813 /// Names of the native functions currently executing, outermost first.
814 ///
815 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
816 /// trace still names it with `(native)` instead of a position, so the names are
817 /// tracked separately and stitched into [`Interp::stack_trace`].
818 ///
819 /// The third field is how many bytecode frames were live when the native was entered,
820 /// which is what places it *among* them rather than before all of them. Native
821 /// functions used to be emitted up front on the grounds that they never re-enter
822 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
823 native_frames: Vec<(String, Gc<JsObject>, usize)>,
824 /// The native function currently executing, for the ones that have to know *which*
825 /// function they are — a typed-array constructor reads its element type off itself.
826 ///
827 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
828 /// reports whatever the enclosing bytecode frame was called with.
829 current_native: Option<Gc<JsObject>>,
830 /// Text written by `print` and friends, in order.
831 ///
832 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
833 /// once at the end, which is also when upstream's line buffering becomes
834 /// visible for the cases compared here.
835 pub output: String,
836 /// Where `print` also writes, as it goes. `output` keeps the full log for
837 /// [`crate::Context::output`]; this is the live copy, flushed per line.
838 ///
839 /// Both exist on purpose. A host that gives a script a sink sees output *when it
840 /// happens* — which is what a timer callback's `console.log` has to do, and what the
841 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
842 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
843 /// would show a script's output all at once when it finished.
844 pub output_sink: Option<Box<dyn std::io::Write>>,
845 /// The most frames that may be live at once.
846 pub max_frames: usize,
847 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
848 ///
849 /// Script execution does not return until this has drained, which is what makes
850 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
851 /// than never. Reactions append to it while it drains, so the loop is a `while` and
852 /// not a `for`.
853 pub(crate) jobs: std::collections::VecDeque<Job>,
854 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
855 ///
856 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
857 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
858 pub(crate) tasks: Vec<Task>,
859 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
860 /// barrier'd evaluation started.
861 ///
862 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
863 /// lets a REPL report an error from the line it just evaluated without also reporting
864 /// its own readline loop.
865 trace_barriers: Vec<usize>,
866 /// `os.signal` handlers, keyed by signal number.
867 ///
868 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
869 /// a handler cannot be freed while it is still registered.
870 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
871 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
872 ///
873 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
874 /// that is only reachable from a host closure could be freed while still registered.
875 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
876 /// The next timer id.
877 ///
878 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
879 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
880 next_timer_id: i32,
881 /// Errors thrown by timer callbacks, already rendered.
882 ///
883 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
884 /// that throws has no promise behind it. Both are reported by the host at the end of
885 /// the loop, but only one is fixed up by a later `.catch`.
886 timer_errors: Vec<String>,
887 /// The module registry, keyed by canonical name.
888 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
889 /// How the host turns a specifier into bytes.
890 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
891 /// The module the host was asked to run, for `import.meta.main`.
892 pub main_module_name: Option<String>,
893 /// Module bodies currently running, innermost last.
894 ///
895 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
896 /// this is the only place that knows which module that is.
897 pub module_stack: Vec<String>,
898 /// Rejections that no handler has claimed, with the promise they belong to.
899 ///
900 /// A `then` registered later prunes its entry, which is why the promise is kept: the
901 /// reason alone cannot say whether somebody eventually listened.
902 unhandled: Vec<(Gc<JsObject>, Value)>,
903}
904
905impl<'a> Interp<'a> {
906 /// Build an interpreter over `heap`, with a fresh realm.
907 pub fn new(heap: &'a Heap) -> Interp<'a> {
908 let object_proto = JsObject::ordinary(heap, None);
909 let function_proto = JsObject::function(
910 heap,
911 Some(object_proto.clone()),
912 Callable::Native {
913 func: |_, _, _| Ok(Value::Undefined),
914 own_instance: false,
915 },
916 );
917 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
918 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
919 let mut interp = Interp {
920 heap,
921 realm: Realm {
922 global,
923 object_proto,
924 function_proto,
925 array_proto,
926 globals: BTreeMap::new(),
927 declared: Vec::new(),
928 lexical_consts: BTreeSet::new(),
929 errors: BTreeMap::new(),
930 string_proto: None,
931 number_proto: None,
932 boolean_proto: None,
933 bigint_proto: None,
934 error_proto: JsObject::ordinary(heap, None),
935 date_proto: JsObject::ordinary(heap, None),
936 generator_proto: JsObject::ordinary(heap, None),
937 promise_proto: None,
938 async_generator_proto: None,
939 symbol_proto: None,
940 symbol_registry: BTreeMap::new(),
941 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
942 regexp_proto: None,
943 regexp_ctor: None,
944 suppressed_error_proto: None,
945 disposable_stack_proto: None,
946 map_proto: None,
947 set_proto: None,
948 finalization_registries: Vec::new(),
949 array_buffer_proto: None,
950 typed_array_proto: None,
951 typed_array_protos: Vec::new(),
952 data_view_proto: None,
953 async_disposable_stack_proto: None,
954 iterator_proto: None,
955 iterator_helper_proto: None,
956 iterator_wrap_proto: None,
957 generator_function_proto: None,
958 async_function_proto: None,
959 async_generator_function_proto: None,
960 iterator_protos: std::collections::BTreeMap::new(),
961 well_known_symbols: WellKnownSymbols::default(),
962 },
963 frames: Vec::new(),
964 eval_scope: None,
965 eval_depth: 0,
966 eval_bindings: Vec::new(),
967 eval_arguments: None,
968 eval_with: None,
969 active_eval_scope: None,
970 eval_caller: None,
971 pending_new_target: None,
972 eval_new_target: None,
973 native_frames: Vec::new(),
974 current_native: None,
975 output: String::new(),
976 output_sink: None,
977 max_frames: 4096,
978 jobs: std::collections::VecDeque::new(),
979 tasks: Vec::new(),
980 trace_barriers: Vec::new(),
981 signal_handlers: std::collections::BTreeMap::new(),
982 fd_handlers: std::collections::BTreeMap::new(),
983 next_timer_id: 1,
984 timer_errors: Vec::new(),
985 modules: std::collections::BTreeMap::new(),
986 module_loader: None,
987 main_module_name: None,
988 module_stack: Vec::new(),
989 unhandled: Vec::new(),
990 };
991 crate::builtins::install(&mut interp);
992 interp
993 }
994
995 // -- allocation helpers -------------------------------------------------
996
997 /// A new string value.
998 /// A `BigInt` value from a computed big integer.
999 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1000 Value::BigInt(Gc::new(self.heap, value))
1001 }
1002
1003 /// A string value from bytes that are already WTF-8, which is how a string with an
1004 /// unpaired surrogate reaches a `Value`.
1005 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1006 Value::string_wtf8(self.heap, text)
1007 }
1008
1009 /// A new string value, from text that is valid UTF-8.
1010 pub fn string(&self, text: impl Into<String>) -> Value {
1011 Value::string(self.heap, text)
1012 }
1013
1014 /// A new ordinary object with the given prototype.
1015 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1016 JsObject::ordinary(self.heap, proto)
1017 }
1018
1019 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1020 ///
1021 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1022 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1023 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1024 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1025 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1026 /// said `[object Object]` instead of `[object Array Iterator]`.
1027 ///
1028 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1029 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1030 /// its own.
1031 pub fn new_iterator_prototype(
1032 &mut self,
1033 tag: &str,
1034 next: crate::object::NativeFn,
1035 ) -> Gc<JsObject> {
1036 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1037 return existing.clone();
1038 }
1039 let parent = self.realm.iterator_proto.clone();
1040 let proto = self.new_object(parent);
1041 let next = self.new_native("next", 0, next);
1042 proto.define(
1043 "next",
1044 Property::with_attributes(Value::Object(next), true, false),
1045 );
1046 let key = self.realm.well_known_key(WellKnown::Iterator);
1047 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1048 proto.define_key(
1049 &key,
1050 Property::with_attributes(Value::Object(identity), true, false),
1051 );
1052 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1053 let tag_value = self.string(tag);
1054 proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
1055 self.realm
1056 .iterator_protos
1057 .insert(tag.to_string(), proto.clone());
1058 proto
1059 }
1060
1061 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1062 ///
1063 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1064 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1065 /// produced. That is why the two branches are not merged.
1066 pub fn object_own_property_keys(
1067 &mut self,
1068 object: &Gc<JsObject>,
1069 ) -> JsResult<Vec<PropertyKey>> {
1070 if let Some(keys) = self.proxy_own_keys(object)? {
1071 return Ok(keys);
1072 }
1073 // Integer-like keys ascending, then the string keys in insertion order, then the
1074 // symbols — the order every schema that walks an object expects.
1075 let entries = object.property_entries();
1076 let mut numeric: Vec<u32> = Vec::new();
1077 let mut strings: Vec<PropertyKey> = Vec::new();
1078 let mut symbols: Vec<PropertyKey> = Vec::new();
1079 for (key, _) in entries {
1080 match &key {
1081 // A class-private name is never reported by any enumeration: that is the
1082 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1083 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1084 // symbol skip, `Object.assign`) therefore cannot see it.
1085 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1086 PropertyKey::Symbol(_) => symbols.push(key),
1087 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1088 Some(index) => {
1089 if !numeric.contains(&index) {
1090 numeric.push(index);
1091 }
1092 }
1093 None => strings.push(key),
1094 },
1095 }
1096 }
1097 numeric.sort_unstable();
1098 let mut keys: Vec<PropertyKey> = numeric
1099 .into_iter()
1100 .map(|index| PropertyKey::from(index.to_string()))
1101 .collect();
1102 keys.extend(strings);
1103 keys.extend(symbols);
1104 Ok(keys)
1105 }
1106
1107 /// The state behind a promise object, or `None` when `object` is not one.
1108 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1109 object.with(|data| match &data.kind {
1110 ObjectKind::Promise(state) => Some(state.clone()),
1111 _ => None,
1112 })
1113 }
1114
1115 /// A new pending promise.
1116 pub fn new_promise(&mut self) -> Gc<JsObject> {
1117 let proto = self.realm.promise_proto.clone();
1118 let promise = JsObject::ordinary(self.heap, proto);
1119 promise.with_mut(|data| {
1120 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1121 crate::object::PromiseState::default(),
1122 )));
1123 });
1124 promise
1125 }
1126
1127 /// Fulfil `promise`, unless it has already settled.
1128 ///
1129 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1130 /// after `reject`, changes nothing.
1131 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1132 let Some(state) = self.promise_state(promise) else {
1133 return;
1134 };
1135 let reactions = {
1136 let mut state = state.borrow_mut();
1137 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1138 return;
1139 }
1140 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1141 std::mem::take(&mut state.reactions)
1142 };
1143 self.queue_reactions(reactions, value, false);
1144 }
1145
1146 /// Reject `promise`, unless it has already settled.
1147 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1148 let Some(state) = self.promise_state(promise) else {
1149 return;
1150 };
1151 let reactions = {
1152 let mut state = state.borrow_mut();
1153 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1154 return;
1155 }
1156 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1157 std::mem::take(&mut state.reactions)
1158 };
1159 // Remember it only when nothing is listening *now*; a `then` registered later
1160 // prunes the entry in `perform_then`.
1161 if reactions.is_empty() {
1162 self.unhandled.push((promise.clone(), reason.clone()));
1163 }
1164 self.queue_reactions(reactions, reason, true);
1165 }
1166
1167 /// Queue one job per reaction.
1168 ///
1169 /// This is what makes `then` asynchronous even on an already-settled promise:
1170 /// `p.then(f); g()` calls `g` first.
1171 fn queue_reactions(
1172 &mut self,
1173 reactions: Vec<crate::object::PromiseReaction>,
1174 argument: Value,
1175 rejected: bool,
1176 ) {
1177 for reaction in reactions {
1178 let handler = if rejected {
1179 reaction.on_rejected.clone()
1180 } else {
1181 reaction.on_fulfilled.clone()
1182 };
1183 self.jobs.push_back(Job::Reaction {
1184 handler,
1185 argument: argument.clone(),
1186 rejected,
1187 promise: reaction.promise,
1188 });
1189 }
1190 }
1191
1192 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1193 /// resolve/reject pair.
1194 ///
1195 /// The pair are callable objects rather than Rust closures, because the script gets
1196 /// them and may stash them for later.
1197 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1198 let promise = self.new_promise();
1199 let resolve = JsObject::function(
1200 self.heap,
1201 Some(self.realm.function_proto.clone()),
1202 Callable::PromiseResolve(promise.clone()),
1203 );
1204 let reject = JsObject::function(
1205 self.heap,
1206 Some(self.realm.function_proto.clone()),
1207 Callable::PromiseReject(promise.clone()),
1208 );
1209 (promise, Value::Object(resolve), Value::Object(reject))
1210 }
1211
1212 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1213 /// promise, as `{ value: completion }`.
1214 ///
1215 /// The three cases are the reference's, and they differ on purpose:
1216 ///
1217 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1218 /// exception before any promise exists;
1219 /// * a **runtime** error rejects the returned promise;
1220 /// * success resolves it with `{ value }`, where the value is the script's completion
1221 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1222 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1223 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1224 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1225 ///
1226 /// # What this does not do
1227 ///
1228 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1229 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1230 /// the parser and the suspension machinery to accept a suspended top-level script, and
1231 /// is not implemented — such source is a syntax error here. Everything else about the
1232 /// flag is reproduced.
1233 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1234 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1235 // too, and the reference truncates that one at the same place as a runtime failure.
1236 if barrier {
1237 let depth = self.frames.len();
1238 self.trace_barriers.push(depth);
1239 }
1240 // Compiled before the promise exists, so a parse failure propagates as a throw
1241 // instead of being folded into a rejection.
1242 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1243 Ok(compiled) => compiled,
1244 Err(error) => {
1245 if barrier {
1246 self.trace_barriers.pop();
1247 }
1248 return Err(error);
1249 }
1250 };
1251 // An async body answers its own promise, and that promise is what the reference
1252 // hands back — the same object, not a wrapper around it. Its resolution value is
1253 // the `{value}` object the compiled epilogue built.
1254 if compiled.kind.is_async() {
1255 let strict = compiled.strict;
1256 let promise = self.run_eval_script(compiled, strict)?;
1257 if barrier {
1258 self.trace_barriers.pop();
1259 }
1260 return Ok(promise);
1261 }
1262 let (promise, resolve, reject) = self.new_promise_capability();
1263 let strict = compiled.strict;
1264 match self.run_eval_script(compiled, strict) {
1265 Ok(value) => {
1266 // `{ value }` is a plain object, so resolving with it adopts nothing even
1267 // when the completion value is itself a promise.
1268 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1269 self.set_property(&wrapped, "value", value)?;
1270 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1271 }
1272 Err(Signal::Throw(error)) => {
1273 self.call_value(reject, Value::Undefined, vec![error])?;
1274 }
1275 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1276 }
1277 if barrier {
1278 self.trace_barriers.pop();
1279 }
1280 Ok(Value::Object(promise))
1281 }
1282
1283 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1284 ///
1285 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1286 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1287 /// timer table, where the collector already scans it.
1288 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1289 let (promise, resolve, _reject) = self.new_promise_capability();
1290 let resolve = self.new_host_function(
1291 "resolve",
1292 1,
1293 Box::new(
1294 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1295 let value = args.first().cloned().unwrap_or(Value::Undefined);
1296 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1297 },
1298 ),
1299 );
1300 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1301 // timer table is part of what the collector walks.
1302 self.schedule_timer(Value::Object(resolve), delay_ms);
1303 Ok(Value::Object(promise))
1304 }
1305
1306 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1307 /// new promise resolved with it.
1308 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1309 if let Value::Object(object) = &value
1310 && self.promise_state(object).is_some()
1311 {
1312 return Ok(value);
1313 }
1314 let promise = self.new_promise();
1315 self.resolve_promise_with(&promise, value)?;
1316 Ok(Value::Object(promise))
1317 }
1318
1319 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1320 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1321 // Resolving a promise with itself is a `TypeError`. The check exists because the
1322 // alternative is a chain of self-reactions that never settles.
1323 if let Value::Object(object) = &value
1324 && object.ptr_eq(promise)
1325 {
1326 // The spec rejects *and* throws, so both the promise and the caller see it.
1327 let thrown = self.type_error("cannot resolve a promise with itself");
1328 let Signal::Throw(error) = thrown.clone() else {
1329 unreachable!("type_error always throws")
1330 };
1331 self.reject_promise(promise, error);
1332 return Err(thrown);
1333 }
1334 let then = match &value {
1335 Value::Object(object) => self.get_property(object, "then")?,
1336 _ => None,
1337 };
1338 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1339 if !callable_then {
1340 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1341 self.fulfill_promise(promise, value);
1342 return Ok(());
1343 }
1344 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1345 // inside `resolve`, so a script cannot make a promise settle synchronously.
1346 self.jobs.push_back(Job::Thenable {
1347 then: then.expect("checked callable"),
1348 value,
1349 promise: promise.clone(),
1350 });
1351 Ok(())
1352 }
1353
1354 /// `Promise.prototype.then`: register a reaction and answer the derived promise.
1355 pub fn perform_then(
1356 &mut self,
1357 promise: &Gc<JsObject>,
1358 on_fulfilled: Option<Value>,
1359 on_rejected: Option<Value>,
1360 ) -> JsResult<Value> {
1361 let Some(state) = self.promise_state(promise) else {
1362 return Err(self.type_error("not a promise"));
1363 };
1364 // Whether a rejection handler is being attached decides whether a recorded
1365 // rejection stops being unhandled, so it is read before the values are moved.
1366 let has_rejection_handler = on_rejected.is_some();
1367 let derived = self.new_promise();
1368 let reaction = crate::object::PromiseReaction {
1369 on_fulfilled,
1370 on_rejected,
1371 promise: derived.clone(),
1372 };
1373 let settled = {
1374 let mut state = state.borrow_mut();
1375 // A rejection somebody reacts to is no longer unhandled.
1376 state.handled = true;
1377 match &state.status {
1378 crate::object::PromiseStatus::Pending => {
1379 state.reactions.push(reaction.clone());
1380 None
1381 }
1382 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1383 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1384 }
1385 };
1386 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1387 // later, means somebody is listening after all.
1388 if has_rejection_handler {
1389 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1390 }
1391 if let Some((argument, rejected)) = settled {
1392 let handler = if rejected {
1393 reaction.on_rejected
1394 } else {
1395 reaction.on_fulfilled
1396 };
1397 self.jobs.push_back(Job::Reaction {
1398 handler,
1399 argument,
1400 rejected,
1401 promise: reaction.promise,
1402 });
1403 }
1404 Ok(Value::Object(derived))
1405 }
1406
1407 /// The rejections nobody listened to, formatted the way the reference reports them.
1408 ///
1409 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
1410 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
1411 /// unhandled at the point the queue drains, because a `then` may still be attached
1412 /// before the host acts on it.
1413 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
1414 let entries = std::mem::take(&mut self.unhandled);
1415 // Somebody may have attached a handler after the rejection was recorded, so the
1416 // promise is the authority rather than the list.
1417 let still_unhandled: Vec<Value> = entries
1418 .into_iter()
1419 .filter_map(|(promise, reason)| {
1420 let handled = self
1421 .promise_state(&promise)
1422 .map(|state| state.borrow().handled)
1423 .unwrap_or(true);
1424 (!handled).then_some(reason)
1425 })
1426 .collect();
1427 still_unhandled
1428 .into_iter()
1429 .map(|reason| {
1430 let text = self.describe_exception(&reason);
1431 let stack = match &reason {
1432 Value::Object(object) => self
1433 .get_property(object, "stack")
1434 .ok()
1435 .flatten()
1436 .map(|value| value.to_js_string())
1437 // `stack` carries a trailing newline of its own, which would leave
1438 // a blank line between two reported rejections.
1439 .map(|text| text.trim_end().to_string())
1440 .unwrap_or_default(),
1441 _ => String::new(),
1442 };
1443 if stack.is_empty() {
1444 format!("Possibly unhandled promise rejection: {text}")
1445 } else {
1446 format!("Possibly unhandled promise rejection: {text}\n{stack}")
1447 }
1448 })
1449 .collect()
1450 }
1451
1452 /// Run the microtask queue to exhaustion.
1453 ///
1454 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
1455 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
1456 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
1457 ///
1458 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
1459 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
1460 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
1461 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
1462 crate::builtins::json::parse_text(self, text, true)
1463 }
1464
1465 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
1466 ///
1467 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
1468 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
1469 /// immediately, and `setTimeout(f, -1)` is ordinary code.
1470 ///
1471 /// The callback is called with **no arguments**. The reference stores only the function
1472 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
1473 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
1474 /// extra arguments arrive as `undefined`.
1475 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
1476 let id = self.next_timer_id;
1477 // Wrap rather than grow: the id reaches the script as an `Int32`.
1478 self.next_timer_id = if self.next_timer_id == i32::MAX {
1479 1
1480 } else {
1481 self.next_timer_id + 1
1482 };
1483 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
1484 self.tasks.push(Task::Timer {
1485 id,
1486 callback,
1487 due_at,
1488 });
1489 id
1490 }
1491
1492 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
1493 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
1494 pub fn cancel_timer(&mut self, id: i32) -> bool {
1495 let before = self.tasks.len();
1496 self.tasks.retain(|task| match task {
1497 Task::Timer { id: task_id, .. } => *task_id != id,
1498 });
1499 self.tasks.len() != before
1500 }
1501
1502 /// How long until the earliest pending timer, or `None` when none is pending.
1503 pub fn next_timeout(&self) -> Option<std::time::Duration> {
1504 let now = std::time::Instant::now();
1505 self.tasks
1506 .iter()
1507 .map(|task| match task {
1508 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
1509 })
1510 .min()
1511 }
1512
1513 /// Run one turn of the event loop.
1514 ///
1515 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
1516 /// run at most one due timer, then drain again. The blocking belongs to the caller
1517 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
1518 /// is how it asks.
1519 ///
1520 /// One timer per turn rather than all of them: a timer callback may schedule another
1521 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
1522 /// starve the microtask queue.
1523 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
1524 self.drain_jobs()?;
1525 let now = std::time::Instant::now();
1526 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
1527 // followed by `setTimeout(g, 1)` must run `g` first.
1528 let due = self
1529 .tasks
1530 .iter()
1531 .enumerate()
1532 .filter(|(_, task)| match task {
1533 Task::Timer { due_at, .. } => *due_at <= now,
1534 })
1535 .min_by_key(|(_, task)| match task {
1536 Task::Timer { due_at, .. } => *due_at,
1537 })
1538 .map(|(index, _)| index);
1539 let Some(index) = due else {
1540 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
1541 // descriptor is registered but no timer is closer, so a script that never
1542 // touches the descriptor still gets control back. Without a cap a handler on a
1543 // descriptor that is never ready would block for as long as the host allows.
1544 let timeout = self
1545 .next_timeout()
1546 .unwrap_or(std::time::Duration::from_secs(10))
1547 .min(std::time::Duration::from_secs(10));
1548 if !self.fd_handlers.is_empty() {
1549 // Blocking on a timer while descriptors are registered would starve them,
1550 // and blocking on the descriptors while a timer is due would delay it; the
1551 // host polls with the earlier of the two deadlines, which this timeout is.
1552 return Ok(Turn::Poll(timeout));
1553 }
1554 return Ok(match self.next_timeout() {
1555 Some(wait) => Turn::Wait(wait),
1556 None => Turn::Done,
1557 });
1558 };
1559 let Task::Timer { callback, .. } = self.tasks.remove(index);
1560 let this = Value::Undefined;
1561 // A throwing timer callback must not stop the loop: the reference reports it and
1562 // keeps going, because the alternative is that one bad timer silently stops every
1563 // later one.
1564 // No arguments: see `schedule_timer` — the reference calls the callback bare.
1565 match self.call_value(callback, this, Vec::new()) {
1566 Ok(_) => {}
1567 Err(Signal::Throw(value)) => {
1568 let text = self.describe_exception(&value);
1569 self.timer_errors.push(text);
1570 }
1571 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1572 }
1573 self.drain_jobs()?;
1574 Ok(Turn::Ran)
1575 }
1576
1577 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
1578 ///
1579 /// `callback` of `None` unregisters that direction, and an entry with neither direction
1580 /// left is removed — the reference does the same, so a script can rely on
1581 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
1582 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
1583 let entry = self.fd_handlers.entry(fd).or_default();
1584 if readable {
1585 entry.read = callback;
1586 } else {
1587 entry.write = callback;
1588 }
1589 if entry.read.is_none() && entry.write.is_none() {
1590 self.fd_handlers.remove(&fd);
1591 }
1592 }
1593
1594 /// Register or clear an `os.signal` handler.
1595 ///
1596 /// `None` removes it; the host separately restores the default disposition or sets
1597 /// ignore, because which of those happened is the script's choice (`null` versus
1598 /// `undefined`) and not something this table can express.
1599 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
1600 match handler {
1601 Some(handler) => {
1602 self.signal_handlers.insert(signal, handler);
1603 }
1604 None => {
1605 self.signal_handlers.remove(&signal);
1606 }
1607 }
1608 }
1609
1610 /// Run the handler for `signal`, reporting whether one ran.
1611 ///
1612 /// A throwing handler is reported and the loop continues, like a timer's.
1613 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
1614 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
1615 return Ok(false);
1616 };
1617 match self.call_value(handler, Value::Undefined, Vec::new()) {
1618 Ok(_) => {}
1619 Err(Signal::Throw(value)) => {
1620 let text = self.describe_exception(&value);
1621 self.timer_errors.push(text);
1622 }
1623 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1624 }
1625 self.drain_jobs()?;
1626 Ok(true)
1627 }
1628
1629 /// The descriptors the host has to poll, and in which direction.
1630 ///
1631 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
1632 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
1633 /// `os_poll` asks for.
1634 pub fn pending_fds(&self) -> Vec<FdInterest> {
1635 self.fd_handlers
1636 .iter()
1637 .map(|(fd, entry)| FdInterest {
1638 fd: *fd,
1639 read: entry.read.is_some(),
1640 write: entry.write.is_some(),
1641 })
1642 .collect()
1643 }
1644
1645 /// Call the handler registered for `fd`, reporting whether one ran.
1646 ///
1647 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
1648 /// poll iteration and then restarts the loop, because the handler may have changed the
1649 /// registration list underneath it; doing the same here keeps a handler that
1650 /// unregisters itself from being called with stale state.
1651 ///
1652 /// A throwing handler is reported and the loop continues — a bad handler must not stop
1653 /// every later one, exactly as with timers.
1654 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
1655 let Some(entry) = self.fd_handlers.get(&fd) else {
1656 return Ok(false);
1657 };
1658 let callback = if readable {
1659 entry.read.clone()
1660 } else if writable {
1661 entry.write.clone()
1662 } else {
1663 None
1664 };
1665 let Some(callback) = callback else {
1666 return Ok(false);
1667 };
1668 self.drain_jobs()?;
1669 match self.call_value(callback, Value::Undefined, Vec::new()) {
1670 Ok(_) => {}
1671 Err(Signal::Throw(value)) => {
1672 let text = self.describe_exception(&value);
1673 self.timer_errors.push(text);
1674 }
1675 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1676 }
1677 self.drain_jobs()?;
1678 Ok(true)
1679 }
1680
1681 /// Take the errors timer callbacks threw, leaving the list empty.
1682 pub fn take_timer_errors(&mut self) -> Vec<String> {
1683 std::mem::take(&mut self.timer_errors)
1684 }
1685
1686 /// Whether anything is still pending: a microtask or a timer.
1687 pub fn has_pending_work(&self) -> bool {
1688 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
1689 }
1690
1691 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
1692 pub fn has_pending_timers_or_jobs(&self) -> bool {
1693 !self.jobs.is_empty() || !self.tasks.is_empty()
1694 }
1695
1696 /// Run every queued microtask, including ones queued while draining.
1697 pub fn drain_jobs(&mut self) -> JsResult<()> {
1698 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
1699 // would spin forever, so the drain is bounded the way the call stack is.
1700 let mut budget = 1_000_000usize;
1701 while let Some(job) = self.jobs.pop_front() {
1702 if budget == 0 {
1703 return Err(Signal::Throw(
1704 self.make_error("InternalError", "promise job queue did not drain"),
1705 ));
1706 }
1707 budget -= 1;
1708 self.run_job(job)?;
1709 // `FinalizationRegistry` at the job boundary: this is the safe point where the
1710 // engine may run script that the script itself did not ask for. Doing it here
1711 // rather than from a drop hook is what keeps the callback out of arbitrary
1712 // engine bookkeeping — see `builtins::weak`'s header.
1713 crate::builtins::weak::drain_finalizers(self)?;
1714 }
1715 // A script that queued no jobs may still have dropped targets, so the checkpoint
1716 // runs once more after the queue empties.
1717 crate::builtins::weak::drain_finalizers(self)?;
1718 Ok(())
1719 }
1720
1721 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
1722 ///
1723 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
1724 /// `None` and is swept out here. This is also where the realm learns that a registry
1725 /// died, which is why it is a mutation rather than a read.
1726 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
1727 let handles = std::mem::take(&mut self.realm.finalization_registries);
1728 let mut live = Vec::with_capacity(handles.len());
1729 for handle in handles {
1730 let Some(object) = handle.upgrade() else {
1731 continue;
1732 };
1733 let Some(state) = object.finalization_state() else {
1734 continue;
1735 };
1736 live.push((object.clone(), *state));
1737 self.realm.finalization_registries.push(object.downgrade());
1738 }
1739 live
1740 }
1741
1742 /// Run one microtask.
1743 fn run_job(&mut self, job: Job) -> JsResult<()> {
1744 match job {
1745 Job::Reaction {
1746 handler: None,
1747 argument,
1748 rejected,
1749 promise,
1750 } => {
1751 // No handler: the settlement passes straight through to the derived
1752 // promise, which is why `p.catch(f)` ignores fulfilments.
1753 if rejected {
1754 self.reject_promise(&promise, argument);
1755 } else {
1756 self.fulfill_promise(&promise, argument);
1757 }
1758 Ok(())
1759 }
1760 Job::Reaction {
1761 handler: Some(handler),
1762 argument,
1763 promise,
1764 ..
1765 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
1766 Ok(answer) => {
1767 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
1768 self.reject_promise(&promise, error);
1769 }
1770 Ok(())
1771 }
1772 Err(Signal::Throw(reason)) => {
1773 self.reject_promise(&promise, reason);
1774 Ok(())
1775 }
1776 Err(other) => Err(other),
1777 },
1778 Job::Thenable {
1779 then,
1780 value,
1781 promise,
1782 } => {
1783 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
1784 // the value it produces settles `promise`.
1785 // The thenable's `then` gets this promise's own pair, so whatever it
1786 // produces settles `promise`.
1787 let resolve = JsObject::function(
1788 self.heap,
1789 Some(self.realm.function_proto.clone()),
1790 Callable::PromiseResolve(promise.clone()),
1791 );
1792 let reject = JsObject::function(
1793 self.heap,
1794 Some(self.realm.function_proto.clone()),
1795 Callable::PromiseReject(promise.clone()),
1796 );
1797 match self.call_value(
1798 then,
1799 value,
1800 vec![Value::Object(resolve), Value::Object(reject)],
1801 ) {
1802 Ok(_) => Ok(()),
1803 Err(Signal::Throw(reason)) => {
1804 self.reject_promise(&promise, reason);
1805 Ok(())
1806 }
1807 Err(other) => Err(other),
1808 }
1809 }
1810 Job::Resume {
1811 coroutine,
1812 promise,
1813 kind,
1814 value,
1815 } => self.drive_async(&coroutine, &promise, kind, value),
1816 Job::GeneratorResume {
1817 generator,
1818 promise,
1819 kind,
1820 value,
1821 } => self.step_async_generator(&generator, &promise, kind, value),
1822 Job::Import {
1823 specifier,
1824 referrer,
1825 promise,
1826 } => {
1827 self.run_dynamic_import(&specifier, &referrer, &promise);
1828 Ok(())
1829 }
1830 }
1831 }
1832
1833 /// One element of a `Promise` combinator settled.
1834 ///
1835 /// The shared state object holds the results array, the number still outstanding, and
1836 /// the combinator's own resolve/reject pair. `all` fills by index so the answer keeps
1837 /// the input order; `race` settles on the first element and ignores the rest, which a
1838 /// one-shot settle gives for free.
1839 fn settle_combinator(
1840 &mut self,
1841 state: &Gc<JsObject>,
1842 index: usize,
1843 fulfilled: bool,
1844 value: Value,
1845 ) -> JsResult<()> {
1846 let kind = state
1847 .own_property("kind")
1848 .and_then(|property| property.value)
1849 .map(|value| value.to_int32())
1850 .unwrap_or(0);
1851 let outcome = state
1852 .own_property("outcome")
1853 .and_then(|property| property.value);
1854 let Some(Value::Object(outcome)) = outcome else {
1855 return Ok(());
1856 };
1857 if kind == 3 {
1858 // `race`: the first settlement wins; the rest are ignored by the one-shot rule.
1859 if fulfilled {
1860 self.resolve_promise_with(&outcome, value)?;
1861 } else {
1862 self.reject_promise(&outcome, value);
1863 }
1864 return Ok(());
1865 }
1866 let results = state
1867 .own_property("results")
1868 .and_then(|property| property.value)
1869 .and_then(|value| value.as_object().cloned());
1870 let remaining = state
1871 .own_property("remaining")
1872 .and_then(|property| property.value)
1873 .map(|value| value.to_int32())
1874 .unwrap_or(0);
1875 match kind {
1876 0 => {
1877 // `all`: the first rejection wins outright.
1878 if !fulfilled {
1879 self.reject_promise(&outcome, value);
1880 return Ok(());
1881 }
1882 let Some(results) = &results else {
1883 return Ok(());
1884 };
1885 results.array_set(index, value);
1886 }
1887 1 => {
1888 // `allSettled`: never rejects; each slot records what happened.
1889 let Some(results) = &results else {
1890 return Ok(());
1891 };
1892 let record = self.new_object(Some(self.realm.object_proto.clone()));
1893 if fulfilled {
1894 record.define_data("status", self.string("fulfilled"));
1895 record.define_data("value", value);
1896 } else {
1897 record.define_data("status", self.string("rejected"));
1898 record.define_data("reason", value);
1899 }
1900 results.array_set(index, Value::Object(record));
1901 }
1902 // `any`: the first fulfilment wins; a full sweep of rejections does not settle
1903 // here — it is handled by the count below.
1904 2 if fulfilled => {
1905 self.resolve_promise_with(&outcome, value)?;
1906 return Ok(());
1907 }
1908 _ => {}
1909 }
1910 let left = remaining - 1;
1911 state.define_data("remaining", Value::Int(left));
1912 if left != 0 {
1913 return Ok(());
1914 }
1915 match kind {
1916 0 | 1 => {
1917 let Some(results) = results else {
1918 return Ok(());
1919 };
1920 self.resolve_promise_with(&outcome, Value::Object(results))?;
1921 }
1922 2 => {
1923 let error = self.make_error("AggregateError", "all promises were rejected");
1924 self.reject_promise(&outcome, error);
1925 }
1926 _ => {}
1927 }
1928 Ok(())
1929 }
1930
1931 /// Build an async function's result: a promise whose body runs as a coroutine.
1932 pub fn new_async_function(
1933 &mut self,
1934 function: Value,
1935 this: Value,
1936 args: Vec<Value>,
1937 ) -> JsResult<Value> {
1938 let promise = self.new_promise();
1939 let coroutine = self.new_coroutine(function, this, args)?;
1940 if let Err(Signal::Throw(reason)) =
1941 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1942 {
1943 self.reject_promise(&promise, reason);
1944 }
1945 Ok(Value::Object(promise))
1946 }
1947
1948 /// The coroutine an async body runs in.
1949 ///
1950 /// Generator-shaped and never exposed to the script: what makes `await` work is the
1951 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
1952 /// than growing a second state machine. The difference is only in the ending — a
1953 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
1954 /// Run `code` as an async function body, answering the promise it settles.
1955 ///
1956 /// Used for a module with top-level `await`: its body is an async function whose
1957 /// caller is the host, so there is no function object to pass through
1958 /// [`Interp::new_async_function`].
1959 pub fn run_async_body(
1960 &mut self,
1961 code: Gc<CompiledCode>,
1962 env: Gc<ClosureEnv>,
1963 this: Value,
1964 ) -> JsResult<Value> {
1965 let promise = self.new_promise();
1966 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
1967 if let Err(Signal::Throw(reason)) =
1968 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1969 {
1970 self.reject_promise(&promise, reason);
1971 }
1972 Ok(Value::Object(promise))
1973 }
1974
1975 fn new_coroutine(
1976 &mut self,
1977 function: Value,
1978 this: Value,
1979 args: Vec<Value>,
1980 ) -> JsResult<Gc<JsObject>> {
1981 let Some(object) = function.as_object().cloned() else {
1982 return Err(self.type_error("not a function"));
1983 };
1984 let Some((code, env)) = bytecode_of(&object) else {
1985 return Err(self.type_error("not a function"));
1986 };
1987 self.new_coroutine_from(code, env, this, args)
1988 }
1989
1990 /// Build a coroutine over an already-resolved body.
1991 fn new_coroutine_from(
1992 &mut self,
1993 code: Gc<CompiledCode>,
1994 env: Gc<ClosureEnv>,
1995 this: Value,
1996 args: Vec<Value>,
1997 ) -> JsResult<Gc<JsObject>> {
1998 let function = Value::Undefined;
1999 self.push_frame(code, env, this, args, function)?;
2000 let frame = self.frames.pop().expect("push_frame just pushed it");
2001 let state = GeneratorState {
2002 frame: Some(frame),
2003 phase: GeneratorPhase::SuspendedStart,
2004 parked_on_await: false,
2005 parked_on_yield_star: false,
2006 requests: std::collections::VecDeque::new(),
2007 async_busy: false,
2008 };
2009 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2010 coroutine.with_mut(|data| {
2011 data.kind = ObjectKind::Generator(Box::new(state));
2012 });
2013 Ok(coroutine)
2014 }
2015
2016 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2017 /// `await` and `value` is what it awaited.
2018 fn resume_coroutine(
2019 &mut self,
2020 coroutine: &Gc<JsObject>,
2021 kind: ResumeKind,
2022 value: Value,
2023 ) -> JsResult<(Value, bool)> {
2024 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2025 ObjectKind::Generator(state) => Some(std::mem::replace(
2026 state.as_mut(),
2027 GeneratorState {
2028 frame: None,
2029 phase: GeneratorPhase::Executing,
2030 parked_on_await: false,
2031 parked_on_yield_star: false,
2032 requests: std::collections::VecDeque::new(),
2033 async_busy: false,
2034 },
2035 )),
2036 _ => None,
2037 }) else {
2038 return Err(self.type_error("not a coroutine"));
2039 };
2040 let result = self.step_generator(&mut state, kind, value);
2041 coroutine.with_mut(|data| {
2042 data.kind = ObjectKind::Generator(Box::new(state));
2043 });
2044 let (value, done, _ready, _reason) = result?;
2045 Ok((value, done))
2046 }
2047
2048 /// Advance an async body and settle its promise with the outcome.
2049 fn drive_async(
2050 &mut self,
2051 coroutine: &Gc<JsObject>,
2052 promise: &Gc<JsObject>,
2053 kind: ResumeKind,
2054 value: Value,
2055 ) -> JsResult<()> {
2056 match self.resume_coroutine(coroutine, kind, value) {
2057 Ok((value, true)) => {
2058 // `Ok` with `done` means the body finished *normally*, even when it was
2059 // resumed by a `throw` — `try { await p } catch {}` completes by
2060 // returning. Only the `Err` arm below is a rejection.
2061 //
2062 // Resolving rather than fulfilling matters: `return promise` in an async
2063 // body adopts the inner promise, so `async function f(){ return
2064 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2065 // promise.
2066 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2067 self.reject_promise(promise, reason);
2068 }
2069 Ok(())
2070 }
2071 Ok((value, false)) => {
2072 // Parked on `await`: follow what it awaited and resume with the outcome.
2073 let awaited = match self.promise_resolve_value(value) {
2074 Ok(awaited) => awaited,
2075 Err(Signal::Throw(error)) => {
2076 self.reject_promise(promise, error);
2077 return Ok(());
2078 }
2079 Err(other) => return Err(other),
2080 };
2081 self.hook_await(awaited, coroutine, promise)
2082 }
2083 Err(Signal::Throw(reason)) => {
2084 self.reject_promise(promise, reason);
2085 Ok(())
2086 }
2087 Err(other) => Err(other),
2088 }
2089 }
2090
2091 /// Arrange for `coroutine` to resume when `awaited` settles.
2092 fn hook_await(
2093 &mut self,
2094 awaited: Value,
2095 coroutine: &Gc<JsObject>,
2096 promise: &Gc<JsObject>,
2097 ) -> JsResult<()> {
2098 let resumed = JsObject::function(
2099 self.heap,
2100 Some(self.realm.function_proto.clone()),
2101 Callable::AwaitResume {
2102 coroutine: coroutine.clone(),
2103 promise: promise.clone(),
2104 kind: ResumeKind::Next,
2105 },
2106 );
2107 let raised = JsObject::function(
2108 self.heap,
2109 Some(self.realm.function_proto.clone()),
2110 Callable::AwaitResume {
2111 coroutine: coroutine.clone(),
2112 promise: promise.clone(),
2113 kind: ResumeKind::Throw,
2114 },
2115 );
2116 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2117 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2118 let Value::Object(awaited) = &awaited else {
2119 self.jobs.push_back(Job::Resume {
2120 coroutine: coroutine.clone(),
2121 promise: promise.clone(),
2122 kind: ResumeKind::Next,
2123 value: awaited,
2124 });
2125 return Ok(());
2126 };
2127 self.perform_then(
2128 awaited,
2129 Some(Value::Object(resumed)),
2130 Some(Value::Object(raised)),
2131 )?;
2132 Ok(())
2133 }
2134
2135 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2136 /// things an engine keeps outside it — array elements and an array's `length`.
2137 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2138 if let Some(property) = object.own_property_key(key) {
2139 return Some(property);
2140 }
2141 // An array's elements live in their own vector rather than the property table, so
2142 // a descriptor for one has to be synthesized — with the attributes an element has.
2143 if let Some(index) = key.as_str().and_then(array_index)
2144 && let Some(value) = object.array_get(index as usize)
2145 && !matches!(value, Value::Hole)
2146 {
2147 return Some(Property::data(value));
2148 }
2149 // `length` is an own property of an array that is not in its property table
2150 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2151 // and non-enumerable.
2152 if key.as_str() == Some("length")
2153 && let Some(length) = object.array_length()
2154 {
2155 return Some(Property {
2156 value: Some(crate::object::length_value(length)),
2157 writable: object.length_writable(),
2158 enumerable: false,
2159 configurable: false,
2160 getter: None,
2161 setter: None,
2162 });
2163 }
2164 None
2165 }
2166
2167 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2168 pub fn object_get_own_property(
2169 &mut self,
2170 object: &Gc<JsObject>,
2171 key: &PropertyKey,
2172 ) -> JsResult<Option<Property>> {
2173 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2174 return Ok(answer);
2175 }
2176 Ok(Self::ordinary_own_property(object, key))
2177 }
2178
2179 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2180 pub fn object_define_own_property(
2181 &mut self,
2182 object: &Gc<JsObject>,
2183 key: &PropertyKey,
2184 property: Property,
2185 ) -> JsResult<bool> {
2186 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2187 return Ok(accepted);
2188 }
2189 // An array index is stored in the element vector, which can hold a plain value and
2190 // nothing else. An accessor — or a data property with non-default attributes —
2191 // therefore has to live in the property table, and the element slot is blanked so
2192 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2193 // {get})` stored the accessor where no read ever looked, and the array kept
2194 // answering its old value.
2195 // An array's `length` is not stored in the property table, so defining it has to
2196 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2197 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2198 // {value: 1})` reported success and changed nothing.
2199 if key.as_str() == Some("length") && object.is_array() {
2200 // `{writable: false}` on `length` does not change the length, but it does make
2201 // it read-only — after which neither a later `{writable: true}` nor a store
2202 // past the end may succeed.
2203 if property.value.is_none() {
2204 if !object.length_writable() && property.writable {
2205 return Ok(false);
2206 }
2207 object.set_length_writable(property.writable);
2208 return Ok(true);
2209 }
2210 if !object.length_writable() {
2211 return Ok(false);
2212 }
2213 }
2214 if key.as_str() == Some("length")
2215 && object.is_array()
2216 && let Some(value) = property.value.clone()
2217 {
2218 let requested = value.to_number();
2219 let valid = requested.is_finite()
2220 && requested >= 0.0
2221 && requested.fract() == 0.0
2222 && requested <= u32::MAX as f64;
2223 if !valid {
2224 return Err(self.range_error("invalid array length"));
2225 }
2226 // Truncating deletes the elements above the new length, and a non-configurable
2227 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2228 // makes `a.length = 2` fail rather than quietly drop it.
2229 let current = object.array_length().unwrap_or(0);
2230 let requested = requested as usize;
2231 if requested < current
2232 && (requested..current).any(|index| object.element_is_undeletable(index as u32))
2233 {
2234 return Ok(false);
2235 }
2236 object.array_set_length(requested);
2237 return Ok(true);
2238 }
2239 let plain = property.writable
2240 && property.enumerable
2241 && property.configurable
2242 && !property.is_accessor();
2243 if let Some(index) = key.as_str().and_then(array_index)
2244 && object.is_array()
2245 {
2246 // Growing the array needs a writable `length`: after
2247 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2248 // be added.
2249 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2250 return Ok(false);
2251 }
2252 if plain && let Some(value) = property.value {
2253 // An ordinary element: the vector is where a read looks first, so it has
2254 // to be the vector that changes.
2255 object.delete_key(key);
2256 object.array_set(index as usize, value);
2257 return Ok(true);
2258 }
2259 object.define_key(key, property);
2260 // The slot stays, so `length` does not shrink; a hole is not an element, so
2261 // the table entry is now what a read finds.
2262 object.array_set(index as usize, Value::Hole);
2263 return Ok(true);
2264 }
2265 object.define_key(key, property);
2266 Ok(true)
2267 }
2268
2269 /// Build a proxy object over `target`, with its traps read from `handler`.
2270 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2271 JsObject::proxy(self.heap, target, handler)
2272 }
2273
2274 /// The `revoke` function for a proxy's slots.
2275 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2276 JsObject::function(
2277 self.heap,
2278 Some(self.realm.function_proto.clone()),
2279 Callable::Revoker(slots),
2280 )
2281 }
2282
2283 /// A new array.
2284 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2285 let array = JsObject::array(
2286 self.heap,
2287 Some(self.realm.array_proto.clone()),
2288 elements.len(),
2289 );
2290 for (index, element) in elements.into_iter().enumerate() {
2291 array.array_set(index, element);
2292 }
2293 array
2294 }
2295
2296 /// A new native function object.
2297 ///
2298 /// The observable `name` and `length` are installed as properties here, which is
2299 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2300 /// so `f.name = "x"` behaves like the writable property it is.
2301 /// A native constructor that builds its own instance after validating its arguments.
2302 ///
2303 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2304 /// check runs before `new.target.prototype` is read.
2305 pub fn new_native_ctor(
2306 &self,
2307 name: impl Into<String>,
2308 length: u32,
2309 func: NativeFn,
2310 ) -> Gc<JsObject> {
2311 let function = JsObject::function(
2312 self.heap,
2313 Some(self.realm.function_proto.clone()),
2314 Callable::Native {
2315 func,
2316 own_instance: true,
2317 },
2318 );
2319 function.set_constructible(true);
2320 function.define(
2321 "length",
2322 Property::name_or_length(Value::Int(length as i32)),
2323 );
2324 function.define("name", Property::name_or_length(self.string(name)));
2325 function
2326 }
2327
2328 /// A native constructor that lets `new` build the instance first.
2329 ///
2330 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
2331 /// validation that must precede reading `new.target.prototype`, so the object can be
2332 /// created before the implementation runs. Distinct from [`Interp::new_native`],
2333 /// which makes a *method* and therefore not a constructor at all.
2334 pub fn new_native_constructor(
2335 &self,
2336 name: impl Into<String>,
2337 length: u32,
2338 func: NativeFn,
2339 ) -> Gc<JsObject> {
2340 let function = self.new_native(name, length, func);
2341 function.set_constructible(true);
2342 function
2343 }
2344
2345 /// A new host function object: a native closure that carries its own state.
2346 ///
2347 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
2348 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
2349 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
2350 /// this safe: the closure must not capture a `Gc`.
2351 pub fn new_host_function(
2352 &self,
2353 name: impl Into<String>,
2354 length: u32,
2355 func: crate::object::HostFn,
2356 ) -> Gc<JsObject> {
2357 self.new_host_inner(name.into(), length, func, false)
2358 }
2359
2360 /// A host constructor: `new` hands it `this = undefined`, so it validates its
2361 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
2362 pub fn new_host_ctor(
2363 &self,
2364 name: impl Into<String>,
2365 length: u32,
2366 func: crate::object::HostFn,
2367 ) -> Gc<JsObject> {
2368 let function = self.new_host_inner(name.into(), length, func, true);
2369 function.set_constructible(true);
2370 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
2371 // installs its own methods on it, so it starts as a plain object.
2372 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
2373 function.define(
2374 "prototype",
2375 Property {
2376 value: Some(Value::Object(proto)),
2377 writable: true,
2378 enumerable: false,
2379 configurable: false,
2380 ..Property::default()
2381 },
2382 );
2383 function
2384 }
2385
2386 fn new_host_inner(
2387 &self,
2388 name: String,
2389 length: u32,
2390 func: crate::object::HostFn,
2391 own_instance: bool,
2392 ) -> Gc<JsObject> {
2393 let function = JsObject::function(
2394 self.heap,
2395 Some(self.realm.function_proto.clone()),
2396 Callable::Host {
2397 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
2398 own_instance,
2399 },
2400 );
2401 function.define(
2402 "length",
2403 Property::name_or_length(Value::Int(length as i32)),
2404 );
2405 function.define("name", Property::name_or_length(self.string(name)));
2406 function
2407 }
2408
2409 /// A new native function object.
2410 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
2411 let function = JsObject::function(
2412 self.heap,
2413 Some(self.realm.function_proto.clone()),
2414 Callable::Native {
2415 func,
2416 own_instance: false,
2417 },
2418 );
2419 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
2420 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
2421 // `length,name` and this listed `name,length`. A bytecode function already gets it
2422 // the right way round; only native ones were built backwards.
2423 function.define(
2424 "length",
2425 Property::name_or_length(Value::Int(length as i32)),
2426 );
2427 function.define("name", Property::name_or_length(self.string(name)));
2428 function
2429 }
2430
2431 /// A new bound function.
2432 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
2433 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
2434 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
2435 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
2436 let constructible = target
2437 .as_object()
2438 .is_some_and(|target| target.is_constructor());
2439 let bound = JsObject::function(
2440 self.heap,
2441 Some(self.realm.function_proto.clone()),
2442 Callable::Bound { target, this, args },
2443 );
2444 bound.set_constructible(constructible);
2445 bound
2446 }
2447
2448 /// A new reference cell.
2449 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
2450 Gc::new(self.heap, Cell::new(value))
2451 }
2452
2453 // -- running ------------------------------------------------------------
2454
2455 /// Evaluate `code` as a script body and return its completion value.
2456 /// Compile and run `source` for the engine's own use, returning its completion value.
2457 ///
2458 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
2459 /// needs to be a real async function, and the engine already runs those as coroutines,
2460 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
2461 ///
2462 /// Differences from [`Self::eval_in_global`], both deliberate:
2463 ///
2464 /// * It does **not** drain the microtask queue. Install runs while the realm is still
2465 /// being built, and the source is an IIFE that only constructs a closure, so there
2466 /// is nothing to drain — and draining here would run script-queued jobs in the
2467 /// middle of `install`.
2468 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
2469 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
2470 /// and it should not look like the user wrote something wrong.
2471 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
2472 let program = match js_parse::parse_script(source) {
2473 Ok(program) => program,
2474 Err(error) => {
2475 let message = format!("builtin source does not parse: {error}");
2476 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2477 }
2478 };
2479 let mut code = match js_compile::compile_script(&program) {
2480 Ok(code) => code,
2481 Err(error) => {
2482 let message = format!("builtin source does not compile: {}", error.message);
2483 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2484 }
2485 };
2486 // The frame has to name something, and `<builtin>` is what a stack trace through
2487 // this code should say.
2488 code.set_filename("<builtin>");
2489 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2490 let closure_vars = compiled.code.closure_vars.clone();
2491 let env = self.global_env(&closure_vars);
2492 let this = Value::Object(self.realm.global.clone());
2493 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
2494 }
2495
2496 /// Run an already-parsed script and drain the microtasks it queued.
2497 ///
2498 /// The drain is what lets an `async` function's body advance past its first `await`
2499 /// before the host sees the result: nothing else pumps the job queue.
2500 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
2501 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2502 let closure_vars = compiled.code.closure_vars.clone();
2503 let env = self.global_env(&closure_vars);
2504 let this = Value::Object(self.realm.global.clone());
2505 let callee = Value::Undefined;
2506 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
2507 // The script is done, so the microtasks it queued run before the host sees the
2508 // result. Without this an `async` function's body would never advance past its
2509 // first `await`, because nothing else drains the queue.
2510 self.drain_jobs()?;
2511 Ok(result)
2512 }
2513
2514 /// Compile and run `source` in global scope, returning its completion value.
2515 ///
2516 /// This is what `eval` and `new Function` use. Running it as a script means it
2517 /// sees the global object and nothing else, which is right for `eval("1+1")` and
2518 /// for a `Function` body; a *direct* eval that reads a local variable would need
2519 /// the compiler to hand its variable environment over, which is not implemented.
2520 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
2521 self.eval_in_global_named(source, EVAL_FILE, false)
2522 }
2523
2524 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
2525 ///
2526 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
2527 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
2528 /// through the code, so they cannot share one constant.
2529 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
2530 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
2531 }
2532
2533 fn eval_in_global_named(&mut self, source: &str, file: &str, barrier: bool) -> JsResult<Value> {
2534 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
2535 // eval-created global binding — configurable, unlike a script's own `var`.
2536 self.eval_depth += 1;
2537 if barrier {
2538 let depth = self.frames.len();
2539 self.trace_barriers.push(depth);
2540 }
2541 let result = self.eval_in_global_inner(source, file);
2542 if barrier {
2543 self.trace_barriers.pop();
2544 }
2545 self.eval_depth -= 1;
2546 result
2547 }
2548
2549 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
2550 let compiled = self.compile_global_script(source, file, false)?;
2551 let strict = compiled.strict;
2552 self.run_eval_script(compiled, strict)
2553 }
2554
2555 /// Parse and compile `source` as a global script, without running it.
2556 ///
2557 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
2558 /// before a promise exists to reject — while still evaluating in the same eval context
2559 /// (direct-eval strictness, `new.target`, `super`).
2560 fn compile_global_script(
2561 &mut self,
2562 source: &str,
2563 file: &str,
2564 async_body: bool,
2565 ) -> JsResult<CompiledFunction> {
2566 // A *direct* eval inherits the strictness of the code that called it, which is
2567 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
2568 // implicit global. The caller's frame is the innermost one here, because a
2569 // native function does not push a frame of its own.
2570 let strict = self.current_strict();
2571 // `eval` runs in the caller's function context, so `new.target` is legal here
2572 // even though the source is a bare script — and so is `super.x` when the caller
2573 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
2574 // caller's, which is what `special_object 4` already does.
2575 let context = js_parse::EvalContext {
2576 in_method: self.enclosing_home_object().is_some(),
2577 // `super()` belongs to a derived constructor, and an eval'd body is not a
2578 // constructor at all: the caller frame's `this` is already built.
2579 in_derived_constructor: false,
2580 };
2581 // A *global* eval is not a function body: `new.target` and `super` are out of
2582 // reach there. Its `{async: true}` form differs in the other direction — the body
2583 // may `await` — so the two flags are independent and the reference sets both from
2584 // the eval type rather than from the caller.
2585 let parsed = if async_body {
2586 js_parse::parse_suspensible_global_eval(source, strict)
2587 } else {
2588 js_parse::parse_eval_script_in(source, strict, context)
2589 };
2590 let program = match parsed {
2591 Ok(program) => program,
2592 Err(error) => {
2593 // The message is bare: the position lives in `fileName`,
2594 // `lineNumber`, `columnNumber` and the stack frame above, which is where
2595 // the reference puts it. An `invalid source: L:C: ` prefix made
2596 // `e.message` differ from the reference while the stack already agreed.
2597 return Err(Signal::Throw(self.syntax_error_at(
2598 file,
2599 error.span.start.line,
2600 error.span.start.column,
2601 &error.message,
2602 )));
2603 }
2604 };
2605 let mut compiled = match if async_body {
2606 js_compile::compile_script_suspensible(&program)
2607 } else {
2608 js_compile::compile_script(&program)
2609 } {
2610 Ok(compiled) => compiled,
2611 // A construct the compiler does not handle yet is reported the same way a
2612 // parse error is: it happens before anything runs, so the trace is the
2613 // position in the source followed by the caller.
2614 Err(error) => {
2615 return Err(Signal::Throw(self.syntax_error_at(
2616 file,
2617 error.span.start.line,
2618 error.span.start.column,
2619 &error.message,
2620 )));
2621 }
2622 };
2623 compiled.set_filename(file);
2624 Ok(compiled)
2625 }
2626
2627 /// Run an `eval`'d script in the caller's scope.
2628 ///
2629 /// Three things have to come from the calling frame, because the eval'd code is a
2630 /// script and would otherwise see only the global object:
2631 ///
2632 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
2633 /// * `arguments`, exposed as a binding of the eval's own scope, so
2634 /// `f("arguments.length", 1)` sees the caller's arguments;
2635 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
2636 /// `eval("var v = 1")` into the global object.
2637 ///
2638 /// Locals of the calling function are *not* reachable: that needs the compiler to
2639 /// hand its variable environment over, which this milestone does not do.
2640 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
2641 // `this` and `arguments` come from the innermost frame only — those are not
2642 // lexical — while the name bindings come from the whole chain of frames, part
2643 // of it being ordinary scope resolution.
2644 // An arrow has no `this` of its own, so an `eval` inside one inherits the
2645 // enclosing function's receiver — the lexical `this` the arrow was compiled to
2646 // read from its closure.
2647 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
2648 // variable environment is the innermost frame of all: an arrow's own body is where
2649 // `var`s declared by an `eval` inside it belong.
2650 let caller_index = self
2651 .frames
2652 .iter()
2653 .rposition(|frame| !frame.code.code.is_arrow)
2654 .or_else(|| self.frames.len().checked_sub(1));
2655 let env_index = self.frames.len().checked_sub(1);
2656 let caller = caller_index.and_then(|index| self.frames.get(index));
2657 let (this, passed) = match caller {
2658 Some(frame) => (frame.this.clone(), frame.passed.clone()),
2659 // No frame at all: the eval is running at the top level, so there is
2660 // nothing to inherit and the global receiver is right.
2661 None => (Value::Object(self.realm.global.clone()), Vec::new()),
2662 };
2663 // Innermost frame first, so the first binding found for a name is the one that
2664 // shadows the rest. A script frame (`<eval>`) contributes nothing.
2665 let mut bindings: Vec<EvalBinding> = Vec::new();
2666 // The calling function's own bindings, resolved by the compiler at the call
2667 // site. That table is the only reliable answer when a name is declared twice in
2668 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
2669 // body means, and guessing by declaration order picks the wrong one as soon as
2670 // two loops in a row use the same name.
2671 // Only a *direct* eval sees the caller's scope. The compiler records a site for
2672 // every direct call — a bare `eval(...)` callee — so finding one at the current
2673 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
2674 // callee to a value first and leave no site behind.
2675 let mut direct = false;
2676 let mut resolved_here = false;
2677 if let Some(frame) = self.frames.last() {
2678 let (line, column) = frame
2679 .code
2680 .code
2681 .position_at(frame.at as u32)
2682 .unwrap_or_default();
2683 // The nearest site at or before the current position, not an exact match:
2684 // the recorded position of the `call` instruction is the callee's, which
2685 // sits a few columns inside the call expression the compiler recorded. A
2686 // site is unique per call, so "the closest one behind us" identifies it.
2687 if let Some(site) = frame
2688 .code
2689 .code
2690 .eval_sites
2691 .iter()
2692 .filter(|site| (site.line, site.column) <= (line, column))
2693 .max_by_key(|site| (site.line, site.column))
2694 {
2695 direct = true;
2696 resolved_here = true;
2697 for binding in &site.bindings {
2698 // An enclosing function's frame sits `owner` levels below the one
2699 // running the call.
2700 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
2701 else {
2702 continue;
2703 };
2704 bindings.push(EvalBinding {
2705 name: binding.name.clone(),
2706 frame,
2707 slot: if binding.is_arg {
2708 EvalSlot::Arg
2709 } else {
2710 EvalSlot::Local
2711 },
2712 index: binding.index as usize,
2713 });
2714 }
2715 }
2716 }
2717 for frame_index in (0..self.frames.len()).rev() {
2718 // Skip the innermost frame's flat scan when the compiler already answered
2719 // for it; an enclosing frame still needs one, because the eval resolves
2720 // those names dynamically.
2721 if resolved_here && frame_index == self.frames.len() - 1 {
2722 continue;
2723 }
2724 let frame = &self.frames[frame_index];
2725 for (index, arg) in frame.code.code.args.iter().enumerate() {
2726 bindings.push(EvalBinding {
2727 name: arg.name.clone(),
2728 frame: frame_index,
2729 slot: EvalSlot::Arg,
2730 index,
2731 });
2732 }
2733 for (index, local) in frame.code.code.vars.iter().enumerate() {
2734 bindings.push(EvalBinding {
2735 name: local.name.clone(),
2736 frame: frame_index,
2737 slot: EvalSlot::Local,
2738 index,
2739 });
2740 }
2741 }
2742 let mut seen = BTreeSet::new();
2743 bindings.retain(|binding| seen.insert(binding.name.clone()));
2744
2745 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
2746 // elements is all the spec's ordinary uses need.
2747 //
2748 // Known divergence: this is bound for a *global* eval too, where there is no
2749 // caller and the reference throws `'arguments' is not defined`. Deciding properly
2750 // needs "does the calling frame have an `arguments` of its own", which is not
2751 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
2752 // script or eval body does not, and `eval(b)` passes the callee as a value so even
2753 // the call-site detection does not answer it. Modelled as a binding in the caller's
2754 // variable environment, this would fall out; that is a larger change than the one
2755 // this comment is attached to.
2756 let arguments = Value::Object(self.new_array(passed));
2757
2758 // Only a *strict* eval gets a variable environment of its own. A sloppy one
2759 // declares its `var`s in the caller's — which for a top-level eval is the global
2760 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
2761 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
2762 // vanish into a scope nobody reads back from.
2763 let previous_scope = if code_strict {
2764 self.eval_scope.replace(BTreeMap::new())
2765 } else {
2766 None
2767 };
2768 let previous_arguments = self.eval_arguments.replace(arguments);
2769 let previous_with = self.eval_with.replace(self.with_objects());
2770 let inherited_new_target = self
2771 .frames
2772 .iter()
2773 .rev()
2774 .find(|frame| !frame.code.code.is_arrow)
2775 .map(|frame| frame.new_target.clone());
2776 let previous_new_target = self
2777 .eval_new_target
2778 .replace(inherited_new_target.unwrap_or(Value::Undefined));
2779 let eval_cells = self.eval_cells_for(&bindings);
2780 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
2781 // A sloppy direct eval declares its `var`s in the caller's variable environment;
2782 // `declare_eval_local` needs to know which frame that is.
2783 // An indirect eval gets the global environment, so nothing of the caller's is
2784 // recorded as the place its `var`s belong.
2785 let previous_caller = self
2786 .eval_caller
2787 .replace(if direct { env_index } else { None });
2788 // The cell-based view of the same bindings, which is what a closure created
2789 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
2790 // whose compiler did not put a binding in a cell simply does not appear here —
2791 // reads and writes still work through `eval_bindings`, they just cannot outlive
2792 // the eval.
2793 let previous_eval_scope = self
2794 .active_eval_scope
2795 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
2796 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2797 let closure_vars = compiled.code.closure_vars.clone();
2798 let env = self.global_env(&closure_vars);
2799 let callee = Value::Undefined;
2800 // An async body does not run here: it becomes a coroutine and answers a promise,
2801 // which is what makes `await` legal in it. `this` still has to be the caller's
2802 // (for a global eval, the global object), because `this` is not part of `await`.
2803 let result = if compiled.code.kind.is_async() {
2804 self.run_async_body(compiled, env, this)
2805 } else {
2806 self.execute(compiled, env, this, Vec::new(), callee)
2807 };
2808 self.eval_scope = previous_scope;
2809 self.eval_arguments = previous_arguments;
2810 self.eval_with = previous_with;
2811 self.eval_new_target = previous_new_target;
2812 self.eval_bindings = previous_bindings;
2813 self.eval_caller = previous_caller;
2814 self.active_eval_scope = previous_eval_scope;
2815 result
2816 }
2817
2818 /// The cell-backed subset of `bindings`, in the same priority order.
2819 ///
2820 /// Both lookup routes have to agree — the eval's own reads go through
2821 /// [`Interp::eval_binding_value`] and the closures it builds go through
2822 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
2823 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
2824 /// is not in a cell simply does not appear: reads and writes still work, they just
2825 /// cannot be handed to a closure that outlives the eval.
2826 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
2827 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
2828 for binding in bindings {
2829 let Some(frame) = self.frames.get(binding.frame) else {
2830 continue;
2831 };
2832 let cell = match binding.slot {
2833 EvalSlot::Arg => frame
2834 .code
2835 .arg_cell
2836 .get(binding.index)
2837 .copied()
2838 .unwrap_or(-1),
2839 EvalSlot::Local => frame
2840 .code
2841 .loc_cell
2842 .get(binding.index)
2843 .copied()
2844 .unwrap_or(-1),
2845 };
2846 if cell < 0 {
2847 continue;
2848 }
2849 if let Some(cell) = frame.cells.get(cell as usize) {
2850 names.push((binding.name.clone(), cell.clone()));
2851 }
2852 }
2853 names
2854 }
2855
2856 /// A `SyntaxError` that reports where in the source it happened.
2857 ///
2858 /// Compile-time failures never run, so they have no frame of their own; the
2859 /// reference still puts the position first in the trace, with no function name and
2860 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
2861 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
2862 /// reference borrows), which is how a script reads the position without parsing
2863 /// the trace.
2864 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
2865 ///
2866 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
2867 /// `columnNumber`, which is how the reference prints one. A positionless error
2868 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
2869 /// the reference raises it from `js_resolve_module`, where there is no position.
2870 pub(crate) fn syntax_error_plain(
2871 &mut self,
2872 error: &js_parse::SyntaxError,
2873 file: &str,
2874 ) -> Value {
2875 if error.positionless {
2876 return self.make_error("SyntaxError", &error.message);
2877 }
2878 self.syntax_error_at(
2879 file,
2880 error.span.start.line,
2881 error.span.start.column,
2882 &error.message,
2883 )
2884 }
2885
2886 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
2887 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
2888 let value = self.make_error("SyntaxError", message);
2889 if let Value::Object(object) = &value {
2890 let text = self.string(blamed);
2891 object.define("stack", Property::with_attributes(text, true, true));
2892 let name = self.string(file);
2893 object.define("fileName", Property::with_attributes(name, true, true));
2894 object.define(
2895 "lineNumber",
2896 Property::with_attributes(Value::Int(line as i32), true, true),
2897 );
2898 object.define(
2899 "columnNumber",
2900 Property::with_attributes(Value::Int(column as i32), true, true),
2901 );
2902 }
2903 value
2904 }
2905
2906 /// Run a compiled script whose completion value is a function, returning it.
2907 ///
2908 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
2909 /// get the closure out, which keeps the constant-pool plumbing in one place.
2910 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
2911 self.run_script(code)
2912 }
2913
2914 /// The environment of a script or of any function compiled at global scope:
2915 /// every entry is a global binding, so each one resolves to the realm's cell.
2916 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
2917 let mut cells = Vec::with_capacity(closure_vars.len());
2918 for closure_var in closure_vars {
2919 let cell = match closure_var.closure_type {
2920 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
2921 if closure_var.is_lexical =>
2922 {
2923 // A lexical declaration: the cell is created here holding the
2924 // dead-zone marker, which is what makes the binding exist and
2925 // unreadable before its initialiser runs.
2926 self.declare_global(&closure_var.name, closure_var.is_const);
2927 self.realm.globals[&closure_var.name].clone()
2928 }
2929 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
2930 // A `var` or function declaration becomes a property of the global
2931 // object, and it exists from here on — which is why
2932 // `print(v); var v = 1` prints `undefined` instead of raising.
2933 // Declaring it at instantiation time (rather than at the
2934 // initialiser) is also what makes it non-configurable: the store
2935 // then lands on an existing property instead of creating one.
2936 self.declare_var_global(&closure_var.name);
2937 // The cell is a placeholder that nothing indexes; it cannot be
2938 // omitted because the slot has to hold something.
2939 self.new_cell(Value::Undefined)
2940 }
2941 _ => {
2942 // An undeclared global is read by name; the cell is a
2943 // placeholder that nothing indexes.
2944 self.new_cell(Value::Undefined)
2945 }
2946 };
2947 cells.push(cell);
2948 }
2949 Gc::new(
2950 self.heap,
2951 ClosureEnv {
2952 cells,
2953 eval_scope: None,
2954 local_vars: None,
2955 local_phase: 1,
2956 },
2957 )
2958 }
2959
2960 /// Push a frame and run until it returns.
2961 pub(crate) fn execute(
2962 &mut self,
2963 code: Gc<CompiledCode>,
2964 env: Gc<ClosureEnv>,
2965 this: Value,
2966 args: Vec<Value>,
2967 callee: Value,
2968 ) -> JsResult<Value> {
2969 let depth = self.frames.len();
2970 self.push_frame(code, env, this, args, callee)?;
2971 loop {
2972 match self.step() {
2973 Ok(Step::Continue) => {}
2974 Ok(Step::Return(value)) => {
2975 self.frames.pop();
2976 // A frame that ended in a `tail_call` hands its value straight to
2977 // its caller: nothing after the call can run, so every frame above
2978 // the callee unwinds with the same value. See [`Frame::tail`] —
2979 // the reference does not reuse frames either, so recursion depth
2980 // and the stack-overflow limit behave the same way.
2981 while self.frames.len() > depth && self.frame().tail {
2982 self.frames.pop();
2983 }
2984 if self.frames.len() == depth {
2985 return Ok(value);
2986 }
2987 // The caller resumes with the value on its stack.
2988 self.frames
2989 .last_mut()
2990 .expect("a caller is live")
2991 .stack
2992 .push(value);
2993 }
2994 Err(Signal::Throw(value)) => {
2995 // A handler lives on the stack of the frame that is throwing —
2996 // `catch` pushed it there — so this frame gets the first chance
2997 // to catch before it is popped.
2998 let value = value;
2999 loop {
3000 if self.frames.len() <= depth {
3001 return Err(Signal::Throw(value));
3002 }
3003 if self.catch_here(value.clone()).is_some() {
3004 break;
3005 }
3006 self.frames.pop();
3007 }
3008 }
3009 // A `yield` in a frame that `execute` is running directly means a
3010 // generator body was entered as an ordinary call, which only happens if
3011 // the generator check in `call_or_push` was bypassed.
3012 Ok(Step::Suspend(_)) => {
3013 return Err(Signal::Throw(self.make_error(
3014 "InternalError",
3015 "a generator body ran as an ordinary call",
3016 )));
3017 }
3018 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3019 }
3020 }
3021 }
3022
3023 /// Install a handler for `value` if this frame has one, resuming at it.
3024 ///
3025 /// The scan is the reference's: walk the frame's stack downwards looking for the
3026 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3027 /// `0` is an enumerator marker rather than a handler — it exists so that a
3028 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3029 /// here and the unwinding continues.
3030 fn catch_here(&mut self, value: Value) -> Option<()> {
3031 let frame = self.frames.last_mut()?;
3032 while let Some(top) = frame.stack.pop() {
3033 if let Value::CatchOffset(offset) = top {
3034 if offset == 0 {
3035 continue;
3036 }
3037 frame.stack.push(value);
3038 frame.pc = offset as usize;
3039 return Some(());
3040 }
3041 }
3042 None
3043 }
3044
3045 fn push_frame(
3046 &mut self,
3047 code: Gc<CompiledCode>,
3048 env: Gc<ClosureEnv>,
3049 this: Value,
3050 mut args: Vec<Value>,
3051 callee: Value,
3052 ) -> JsResult<()> {
3053 if self.frames.len() >= self.max_frames {
3054 return Err(Signal::Throw(
3055 self.string("Maximum call stack size exceeded"),
3056 ));
3057 }
3058 let arg_count = code.code.args.len();
3059 // How many were actually passed, which `arguments.length` reports and
3060 // `assert(x)` depends on: a call with one argument must not look like a call
3061 // with one argument and an explicit `undefined`.
3062 let passed = args.len();
3063 // Missing arguments are `undefined` in their slots; extra ones are dropped
3064 // from the slots but still reachable through `arguments`.
3065 let mut passed_values = args.clone();
3066 args.resize(arg_count, Value::Undefined);
3067 args.truncate(arg_count);
3068 let cell_count = code.code.var_ref_count as usize;
3069 let mut cells = Vec::with_capacity(cell_count);
3070 for _ in 0..cell_count {
3071 cells.push(self.new_cell(Value::Undefined));
3072 }
3073 let locals = vec![Value::Undefined; code.code.vars.len()];
3074 // A captured argument lives in its cell, not in the argument slot, so the
3075 // incoming value has to be moved there before the body runs.
3076 for (slot, cell) in code.arg_cell.iter().enumerate() {
3077 if *cell >= 0
3078 && let Some(value) = args.get(slot).cloned()
3079 {
3080 cells[*cell as usize].set(value);
3081 }
3082 }
3083 // Sloppy mode substitutes the global object for a missing receiver and boxes a
3084 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3085 // reports `object`. Strict mode passes the value through untouched.
3086 let this = if code.code.strict {
3087 this
3088 } else if this.is_nullish() {
3089 Value::Object(self.realm.global.clone())
3090 } else if matches!(this, Value::Object(_)) {
3091 this
3092 } else {
3093 match crate::builtins::this_object(self, &this) {
3094 Ok(boxed) => Value::Object(boxed),
3095 Err(_) => this,
3096 }
3097 };
3098 self.frames.push(Frame {
3099 code,
3100 env,
3101 this,
3102 args,
3103 passed: passed_values.drain(..passed).collect(),
3104 locals,
3105 cells,
3106 local_vars: None,
3107 stack: Vec::with_capacity(16),
3108 pc: 0,
3109 at: 0,
3110 callee,
3111 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3112 tail: false,
3113 });
3114 Ok(())
3115 }
3116
3117 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
3118 ///
3119 /// Only names the eval created are here: a name the frame already declared statically
3120 /// is written through to its own slot instead, so this cannot shadow a real local.
3121 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
3122 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
3123 let (local_vars, phase) = self.visible_local_vars()?;
3124 if !local_vars.contains(name) {
3125 return None;
3126 }
3127 local_vars.get(name, phase)
3128 }
3129
3130 /// The variables a direct `eval` declared, as the code currently running sees them.
3131 ///
3132 /// Inside an eval that is the *caller's* set — the eval's own variable environment
3133 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
3134 /// else it is the current frame's, falling back to the frame the closure was created
3135 /// in.
3136 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
3137 // While an `eval` runs, its own frame is on top but its variable environment is
3138 // the *caller's* — so the caller is what the lookup has to start from.
3139 let (index, phase) = match self.eval_caller.flatten() {
3140 Some(caller) => (
3141 caller,
3142 if self.in_parameter_list_at(caller) {
3143 0
3144 } else {
3145 1
3146 },
3147 ),
3148 None => (
3149 self.frames.len().checked_sub(1)?,
3150 if self.in_parameter_list() { 0 } else { 1 },
3151 ),
3152 };
3153 let frame = self.frames.get(index)?;
3154 // The frame's own variables, or — for an arrow, which has no variable environment
3155 // of its own — the one it was created in, which `ClosureEnv` carries.
3156 if let Some(local_vars) = frame.local_vars.clone() {
3157 return Some((local_vars, phase));
3158 }
3159 frame
3160 .env
3161 .local_vars
3162 .clone()
3163 .map(|local_vars| (local_vars, frame.env.local_phase))
3164 }
3165
3166 /// Whether the innermost frame is still evaluating its parameter list.
3167 ///
3168 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
3169 /// and a closure created there may only see that much of [`LocalVars`].
3170 fn in_parameter_list(&self) -> bool {
3171 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
3172 }
3173
3174 /// [`Interp::in_parameter_list`] for a specific frame.
3175 fn in_parameter_list_at(&self, frame: usize) -> bool {
3176 let Some(frame) = self.frames.get(frame) else {
3177 return false;
3178 };
3179 let code = &frame.code.code;
3180 if !code.has_parameter_expressions {
3181 return false;
3182 }
3183 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
3184 // function as its body and let a direct `eval` act accordingly.
3185 if code.body_start == (0, 0) {
3186 return false;
3187 }
3188 match code.position_at(frame.at as u32) {
3189 Some(position) => position < code.body_start,
3190 None => false,
3191 }
3192 }
3193
3194 fn frame(&self) -> &Frame {
3195 self.frames.last().expect("a frame is live")
3196 }
3197
3198 fn frame_mut(&mut self) -> &mut Frame {
3199 self.frames.last_mut().expect("a frame is live")
3200 }
3201
3202 // -- slot access --------------------------------------------------------
3203
3204 fn read_slot(&self, cell: i32, value: &Value) -> Value {
3205 match cell {
3206 -1 => value.clone(),
3207 index => self
3208 .frame()
3209 .cells
3210 .get(index as usize)
3211 .expect("a cell index in range")
3212 .get(),
3213 }
3214 }
3215
3216 fn get_arg(&self, slot: usize) -> Value {
3217 let frame = self.frame();
3218 let cell = frame.code.arg_cell.get(slot).copied().unwrap_or(-1);
3219 let value = frame.args.get(slot).cloned().unwrap_or(Value::Undefined);
3220 self.read_slot(cell, &value)
3221 }
3222
3223 fn put_arg(&mut self, slot: usize, value: Value) {
3224 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
3225 if cell == -1 {
3226 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
3227 *slot = value;
3228 }
3229 } else {
3230 self.frame().cells[cell as usize].set(value);
3231 }
3232 }
3233
3234 fn get_loc(&self, slot: usize) -> Value {
3235 let frame = self.frame();
3236 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
3237 let value = frame.locals.get(slot).cloned().unwrap_or(Value::Undefined);
3238 self.read_slot(cell, &value)
3239 }
3240
3241 fn put_loc(&mut self, slot: usize, value: Value) {
3242 let cell = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
3243 if cell == -1 {
3244 if let Some(slot) = self.frame_mut().locals.get_mut(slot) {
3245 *slot = value;
3246 }
3247 } else {
3248 self.frame().cells[cell as usize].set(value);
3249 }
3250 }
3251
3252 // -- globals ------------------------------------------------------------
3253
3254 /// The name a global-slot operand refers to.
3255 fn global_name(&self, slot: usize) -> String {
3256 self.frame()
3257 .code
3258 .code
3259 .closure_vars
3260 .get(slot)
3261 .map(|c| c.name.clone())
3262 .unwrap_or_default()
3263 }
3264
3265 /// The facts about a global binding that decide where it lives.
3266 ///
3267 /// A script's globals split in two, and the split is observable: `var` and
3268 /// function declarations become properties of the global object (`globalThis.v`
3269 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
3270 /// declarations live in the global *lexical* environment and are invisible there
3271 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
3272 /// `is_lexical` flag means the answer is already in the bytecode.
3273 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
3274 let name = self.global_name(slot);
3275 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
3276 // while forwarding a reference through a nested function is built with the
3277 // flags cleared, so `const c` would look like an ordinary `var` from inside a
3278 // closure. Presence in the realm's lexical table is the same fact, recorded
3279 // once, and every slot sees it.
3280 let lexical = self.realm.globals.contains_key(&name);
3281 let is_const = self.realm.lexical_consts.contains(&name);
3282 (name, lexical, is_const)
3283 }
3284
3285 /// The value of `name` in the innermost active `with` object, if any.
3286 ///
3287 /// The active objects are the [`VarKind::With`] locals of every frame still running,
3288 /// innermost frame first and innermost block first within one. Walking frames rather
3289 /// than keeping a separate stack is what makes a closure called from inside a `with`
3290 /// see it, and what keeps the object alive only as long as the block is.
3291 /// The innermost active `with` object that has `name`, if any.
3292 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
3293 let objects = self.eval_with.clone().unwrap_or_default();
3294 for object in objects {
3295 let key = self.string(name.to_string());
3296 if self
3297 .has_property(&key, &Value::Object(object.clone()))
3298 .ok()?
3299 {
3300 return Some(object);
3301 }
3302 }
3303 None
3304 }
3305
3306 /// Every active `with` object, innermost first.
3307 fn with_objects(&self) -> Vec<Gc<JsObject>> {
3308 let mut objects = Vec::new();
3309 for frame in self.frames.iter().rev() {
3310 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
3311 if var.kind != js_compile::VarKind::With {
3312 continue;
3313 }
3314 // A captured binding lives in its cell and not in the slot list, so the
3315 // cell is consulted first — a closure created inside the block is exactly
3316 // what makes the object captured. Before the store runs the slot still
3317 // holds `undefined`, and a `with` object is always boxed, so a non-object
3318 // entry is simply not in scope yet.
3319 let value = frame
3320 .code
3321 .loc_cell
3322 .get(index)
3323 .copied()
3324 .filter(|cell| *cell >= 0)
3325 .and_then(|cell| frame.cells.get(cell as usize))
3326 .map(|cell| cell.get())
3327 .or_else(|| frame.locals.get(index).cloned());
3328 if let Some(Value::Object(object)) = value {
3329 objects.push(object);
3330 }
3331 }
3332 }
3333 objects
3334 }
3335
3336 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
3337 for object in self.eval_with.clone().unwrap_or_default() {
3338 let key = self.string(name.to_string());
3339 if self.has_property(&key, &Value::Object(object.clone()))? {
3340 return Ok(Some(self.read_field(&Value::Object(object), name)?));
3341 }
3342 }
3343 Ok(None)
3344 }
3345
3346 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
3347 let (name, lexical, _) = self.global_binding(slot);
3348 if name == "arguments"
3349 && let Some(arguments) = &self.eval_arguments
3350 {
3351 return Ok(arguments.clone());
3352 }
3353 // A `with` block around the *call site* is part of the scope an `eval` sees, so
3354 // the objects live when the eval started are consulted before anything else. The
3355 // snapshot is taken at entry rather than scanning the frames on every read: a
3356 // block that has already finished still leaves its object in the slot, and a
3357 // bytecode read outside the block must not see it.
3358 if let Some(value) = self.with_lookup(&name)? {
3359 return Ok(value);
3360 }
3361 // A variable a direct `eval` declared shadows everything the compiler resolved,
3362 // including an enclosing function's binding: the eval put it in the caller's own
3363 // variable environment, which is nearer than any captured scope.
3364 if let Some((local_vars, phase)) = self.visible_local_vars()
3365 && let Some(cell) = local_vars.get(&name, phase)
3366 {
3367 return Ok(cell.get());
3368 }
3369 // The frame that called `eval` is the innermost scope the eval'd code sees, so
3370 // its local `a` wins over a global `a`.
3371 if let Some(value) = self.eval_binding_value(&name) {
3372 return Ok(value);
3373 }
3374 // A closure created by an `eval` resolves its free names against the bindings
3375 // that eval saw, even after the eval (and its frames) are gone.
3376 if let Some(cell) = self
3377 .frame()
3378 .env
3379 .eval_scope
3380 .as_ref()
3381 .and_then(|scope| scope.get(&name))
3382 {
3383 let value = cell.get();
3384 if matches!(value, Value::Uninitialized) {
3385 return Err(self.throw_reference(&name));
3386 }
3387 return Ok(value);
3388 }
3389 // A binding declared by the strict `eval` currently running shadows anything
3390 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
3391 if let Some(scope) = &self.eval_scope
3392 && let Some(value) = scope.get(&name)
3393 {
3394 return Ok(value.clone());
3395 }
3396 if lexical {
3397 // A lexical global is a binding in a side table, so the dead zone is
3398 // visible and it is nowhere on the global object.
3399 if let Some(cell) = self.realm.globals.get(&name) {
3400 let value = cell.get();
3401 if matches!(value, Value::Uninitialized) {
3402 return Err(self.throw_reference(&name));
3403 }
3404 return Ok(value);
3405 }
3406 return Err(self.throw_reference(&name));
3407 }
3408 // A `var` global is an ordinary property, so the prototype chain and the
3409 // global object's own builtins are all reachable through it.
3410 match self.get_property(&self.realm.global.clone(), &name)? {
3411 Some(value) => Ok(value),
3412 None => Err(self.throw_reference(&name)),
3413 }
3414 }
3415
3416 /// Store to a global binding.
3417 ///
3418 /// Returns a signal when the store is refused: a `const` global may only be
3419 /// written by its initialiser, and a non-configurable `var` global may not be
3420 /// deleted but is always writable.
3421 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
3422 let (name, lexical, is_const) = self.global_binding(slot);
3423
3424 // An assignment inside a `with` writes through to the object that supplies the
3425 // name, which for an `eval` means consulting the same chain `get_global` does.
3426 if let Some(owner) = self.with_owner(&name) {
3427 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
3428 return Ok(());
3429 }
3430 // A variable the running eval *declared* takes the write before any caller
3431 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
3432 // environment even when an enclosing function has a `var c` of its own.
3433 if self.eval_caller.flatten().is_some()
3434 && let Some((local_vars, phase)) = self.visible_local_vars()
3435 && local_vars.contains(&name)
3436 && let Some(cell) = local_vars.get(&name, phase)
3437 {
3438 cell.set(value);
3439 return Ok(());
3440 }
3441 // A binding of the frame that called `eval` takes the write, which is what
3442 // makes `f("a = 3")` change the caller's `a`.
3443 if self.set_eval_binding(&name, &value)? {
3444 return Ok(());
3445 }
3446 // A closure that outlived its `eval` writes through to the same cell it reads.
3447 if let Some(cell) = self
3448 .frame()
3449 .env
3450 .eval_scope
3451 .as_ref()
3452 .and_then(|scope| scope.get(&name))
3453 .cloned()
3454 {
3455 cell.set(value);
3456 return Ok(());
3457 }
3458 // Inside a strict `eval`, a name it declared itself is stored there. An
3459 // *assignment* to a name nobody declared is not a declaration, so it falls
3460 // through: strict mode raises `ReferenceError` for it, which is what
3461 // `eval("1 + (@not_def = 1)")` has to do.
3462 if let Some(scope) = self.eval_scope.as_mut()
3463 && scope.contains_key(&name)
3464 {
3465 scope.insert(name, value);
3466 return Ok(());
3467 }
3468 if lexical {
3469 if let Some(cell) = self.realm.globals.get(&name).cloned() {
3470 if is_const && !matches!(cell.get(), Value::Uninitialized) {
3471 return Err(self.read_only_global(&name));
3472 }
3473 cell.set(value);
3474 return Ok(());
3475 }
3476 // Writing an undeclared lexical global is a `ReferenceError` in strict
3477 // mode and a silent global creation otherwise; creating the cell here
3478 // keeps both paths from losing the value.
3479 let cell = self.new_cell(value);
3480 self.realm.globals.insert(name, cell);
3481 return Ok(());
3482 }
3483 // A variable a direct `eval` declared in this call shadows the global object, even
3484 // when the global already has a property of that name — `var c = "global"` at the
3485 // top level must not capture `eval("var c = 1")` inside a function.
3486 if let Some((local_vars, phase)) = self.visible_local_vars()
3487 && local_vars.contains(&name)
3488 && let Some(cell) = local_vars.get(&name, phase)
3489 {
3490 cell.set(value);
3491 return Ok(());
3492 }
3493 let global = self.realm.global.clone();
3494 match global.own_property(&name) {
3495 // A `var` global is writable, so the store goes straight through — but
3496 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
3497 // store (a non-writable or accessor-without-setter global) is a silent
3498 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
3499 // split every other assignment has.
3500 Some(_) => {
3501 let on_failure = if self.current_strict() {
3502 DeleteFailure::Throw
3503 } else {
3504 DeleteFailure::Ignore
3505 };
3506 self.set_property_with(&global, &name, value, on_failure)
3507 }
3508 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
3509 // declaration creates a *configurable* property, which is what makes it
3510 // deletable and is the one way a global differs from a declared `var`.
3511 // In strict mode the same store is a `ReferenceError` instead: that is the
3512 // whole point of strict mode, and creating the global silently meant
3513 // `"use strict"; x = 1` looked like it worked.
3514 None => {
3515 if self.current_strict() {
3516 return Err(self.throw_reference(&name));
3517 }
3518 // A direct eval declares here rather than on the global object: its
3519 // `var`s belong to the caller's variable environment. `declare_eval_local`
3520 // also covers a plain assignment to a variable an earlier eval made.
3521 if let Some(cell) = self.declare_eval_local(&name) {
3522 cell.set(value);
3523 return Ok(());
3524 }
3525 global.define_data(&name, value);
3526 Ok(())
3527 }
3528 }
3529 }
3530
3531 /// The value of a binding of the frame that called `eval`, if there is one.
3532 fn eval_binding_value(&self, name: &str) -> Option<Value> {
3533 let binding = self
3534 .eval_bindings
3535 .iter()
3536 .find(|binding| binding.name == name)?;
3537 let owner = self.frames.get(binding.frame)?;
3538 let (slot, index) = (binding.slot, binding.index);
3539 Some(match slot {
3540 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
3541 cell if cell >= 0 => owner
3542 .cells
3543 .get(cell as usize)
3544 .map(|cell| cell.get())
3545 .unwrap_or(Value::Undefined),
3546 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
3547 },
3548 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
3549 cell if cell >= 0 => owner
3550 .cells
3551 .get(cell as usize)
3552 .map(|cell| cell.get())
3553 .unwrap_or(Value::Undefined),
3554 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
3555 },
3556 })
3557 }
3558
3559 /// Write to a binding of the frame that called `eval`.
3560 ///
3561 /// `Ok(false)` means no binding matched and the caller should keep looking. A
3562 /// matched binding can still refuse the store, which is why this is fallible: a
3563 /// `const` is read-only everywhere, and a named function expression's own name is
3564 /// read-only in strict mode.
3565 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
3566 let Some(binding) = self
3567 .eval_bindings
3568 .iter()
3569 .find(|binding| binding.name == name)
3570 else {
3571 return Ok(false);
3572 };
3573 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
3574 let strict = self.current_strict();
3575 let Some(owner) = self.frames.get_mut(frame) else {
3576 return Ok(false);
3577 };
3578 match slot {
3579 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
3580 cell if cell >= 0 => {
3581 if let Some(cell) = owner.cells.get(cell as usize) {
3582 cell.set(value.clone());
3583 }
3584 }
3585 _ => {
3586 if let Some(slot) = owner.args.get_mut(index) {
3587 *slot = value.clone();
3588 }
3589 }
3590 },
3591 EvalSlot::Local => {
3592 let declared = owner.code.code.vars.get(index);
3593 // A `const` is read-only even through `eval`. The realm records this for
3594 // globals (see `lexical_consts`), but a local's `const`-ness is only in
3595 // the bytecode, so this is where it has to be enforced.
3596 if declared.is_some_and(|var| var.is_const) {
3597 return Err(self.read_only_local(name));
3598 }
3599 // The name of a named function expression is read-only too, but only
3600 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
3601 // such a name is ignored, the same as a direct store would be.
3602 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
3603 return if strict {
3604 Err(self.read_only_local(name))
3605 } else {
3606 Ok(true)
3607 };
3608 }
3609 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
3610 cell if cell >= 0 => {
3611 if let Some(cell) = owner.cells.get(cell as usize) {
3612 cell.set(value.clone());
3613 }
3614 }
3615 _ => {
3616 if let Some(slot) = owner.locals.get_mut(index) {
3617 *slot = value.clone();
3618 }
3619 }
3620 }
3621 }
3622 }
3623 Ok(true)
3624 }
3625
3626 /// The `TypeError` an assignment to a read-only binding raises.
3627 fn read_only_local(&self, name: &str) -> Signal {
3628 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
3629 }
3630
3631 /// Declare `name` as a variable of the frame that called the running `eval`.
3632 ///
3633 /// `None` when there is no direct eval in progress, or it was called from the top
3634 /// level — then the caller's variable environment *is* the global one and the
3635 /// existing path is right.
3636 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
3637 let caller = self.eval_caller.flatten()?;
3638 // The bottom frame is the top-level script, whose variable environment *is* the
3639 // global one — so `eval("var x = 1")` at the top level still creates a global.
3640 if caller == 0 {
3641 return None;
3642 }
3643 // A name the eval's *own* variable environment already binds is not a new
3644 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
3645 // `arguments`, and creating a second binding would leave the first — the one
3646 // closures read — untouched. A binding of an *outer* frame does not count: a
3647 // declaration shadows it rather than writing through.
3648 if self
3649 .eval_bindings
3650 .iter()
3651 .any(|binding| binding.name == name && binding.frame == caller)
3652 {
3653 return None;
3654 }
3655 let phase = if self.in_parameter_list_at(caller) {
3656 0
3657 } else {
3658 1
3659 };
3660 self.frame_local_vars(caller)?;
3661 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
3662 if let Some(cell) = local_vars.get(name, 1) {
3663 return Some(cell);
3664 }
3665 let cell = self.new_cell(Value::Undefined);
3666 Some(local_vars.declare(name, phase, cell))
3667 }
3668
3669 /// Make sure `frame` has a `LocalVars`, creating it on demand.
3670 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
3671 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
3672 return Some(local_vars.clone());
3673 }
3674 let local_vars = Gc::new(self.heap, LocalVars::new());
3675 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
3676 Some(local_vars)
3677 }
3678
3679 /// Whether the realm already has a binding for `name`, lexically or as an *own*
3680 /// property of the global object. Used to decide whether a store inside an
3681 /// `eval` writes through to the realm or declares a binding of its own.
3682 ///
3683 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
3684 /// write to `Object.prototype.toString`, and must not shadow it either.
3685 fn global_knows(&mut self, name: &str) -> bool {
3686 if self.realm.globals.contains_key(name) {
3687 return true;
3688 }
3689 self.realm.global.own_property(name).is_some()
3690 }
3691
3692 /// Whether the code currently running is strict.
3693 ///
3694 /// Read off the frame's function, which is where the parser's answer ended up; a
3695 /// native function never runs strict-only checks, and there is no frame at all
3696 /// before the first script.
3697 pub fn current_strict(&self) -> bool {
3698 self.frames
3699 .last()
3700 .is_some_and(|frame| frame.code.code.strict)
3701 }
3702
3703 /// Initialise a declared global, which is what ends its dead zone.
3704 ///
3705 /// A `var` global becomes a property of the global object: writable, so a later
3706 /// assignment goes through, and non-configurable, so `delete` refuses.
3707 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
3708 let (name, lexical, _) = self.global_binding(slot);
3709 // A `var` declared by the strict `eval` currently running belongs to the
3710 // eval's scope, not to the global object: `eval("var v = 1")` must not make
3711 // `typeof v` answer `"number"` afterwards. A name the realm already has is
3712 // initialised in place, which is what a re-declaration inside eval does.
3713 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
3714 self.eval_scope
3715 .as_mut()
3716 .expect("checked above")
3717 .insert(name, value);
3718 return Ok(());
3719 }
3720 if let Some(scope) = self.eval_scope.as_mut()
3721 && scope.contains_key(&name)
3722 {
3723 scope.insert(name, value);
3724 return Ok(());
3725 }
3726 if lexical {
3727 // The cell exists (created at declaration time) holding the dead-zone
3728 // marker; storing the value is what makes the binding readable.
3729 if let Some(cell) = self.realm.globals.get(&name).cloned() {
3730 cell.set(value);
3731 return Ok(());
3732 }
3733 let cell = self.new_cell(value);
3734 self.realm.globals.insert(name, cell);
3735 return Ok(());
3736 }
3737 let global = self.realm.global.clone();
3738 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
3739 // to answer `false` and leave the binding in place. `with_attributes` ties
3740 // `configurable` to `writable`, so the property is built field by field.
3741 global.define(
3742 &name,
3743 Property {
3744 value: Some(value),
3745 writable: true,
3746 enumerable: true,
3747 configurable: false,
3748 ..Property::default()
3749 },
3750 );
3751 Ok(())
3752 }
3753
3754 /// The `TypeError` a store to a `const` global raises.
3755 fn read_only_global(&self, name: &str) -> Signal {
3756 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
3757 }
3758
3759 // -- properties ---------------------------------------------------------
3760
3761 /// Read `object[key]`, following the prototype chain.
3762 ///
3763 /// An inherited accessor runs with the *receiver* as `this`, which is why the
3764 /// lookup returns the owner rather than just the value.
3765 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
3766 self.get_property_key(object, &PropertyKey::from(key))
3767 }
3768
3769 /// [`Interp::get_property`] with a key that may be a symbol.
3770 pub fn get_property_key(
3771 &mut self,
3772 object: &Gc<JsObject>,
3773 key: &PropertyKey,
3774 ) -> JsResult<Option<Value>> {
3775 self.get_property_key_for(object, None, key)
3776 }
3777
3778 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
3779 ///
3780 /// The receiver matters when the property is found on a *prototype*: a getter has to
3781 /// see the object the read started from. For a primitive that is the primitive
3782 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
3783 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
3784 /// the owner.
3785 pub fn get_property_key_for(
3786 &mut self,
3787 object: &Gc<JsObject>,
3788 receiver: Option<&Value>,
3789 key: &PropertyKey,
3790 ) -> JsResult<Option<Value>> {
3791 // A proxy answers for itself, before any of the shortcuts below: `new
3792 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
3793 // have.
3794 if object.proxy_state().is_some() {
3795 let receiver = receiver
3796 .cloned()
3797 .unwrap_or_else(|| Value::Object(object.clone()));
3798 return self.proxy_get(object, &receiver, key);
3799 }
3800 // The element-vector and `length` shortcuts are string-only: an array index
3801 // has no symbol spelling.
3802 if let Some(text) = key.as_str() {
3803 if let Some(value) = self.own_element(object, text) {
3804 return Ok(Some(value));
3805 }
3806 // `length` is not stored as a property: an array's length is its element
3807 // count, and keeping one copy of it is what makes `push`/`pop` and
3808 // `a.length = n` agree.
3809 if let Some(length) = object.array_length()
3810 && text == "length"
3811 {
3812 // Not `Value::Int(length as i32)`: see [`length_value`].
3813 return Ok(Some(crate::object::length_value(length)));
3814 }
3815 }
3816 match lookup_key(object, key) {
3817 Some((_, property)) => {
3818 if property.is_accessor() {
3819 match &property.getter {
3820 Some(getter) if !matches!(getter, Value::Undefined) => {
3821 let receiver = receiver
3822 .cloned()
3823 .unwrap_or_else(|| Value::Object(object.clone()));
3824 self.call_value(getter.clone(), receiver, Vec::new())
3825 .map(Some)
3826 }
3827 // An accessor with no getter reads as `undefined`.
3828 _ => Ok(Some(Value::Undefined)),
3829 }
3830 } else {
3831 Ok(property.value)
3832 }
3833 }
3834 None => Ok(None),
3835 }
3836 }
3837
3838 /// `super.key` — start the search at `proto`, but report to `receiver`.
3839 ///
3840 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
3841 /// found on the prototype of a class has to see the *instance* as `this`, and a
3842 /// plain property read off `proto` would lose that.
3843 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
3844 let start = self.require_object(proto)?;
3845 let key = self.propkey(key)?;
3846 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
3847 if matches!(proto, Value::Null) {
3848 return Ok(Value::Undefined);
3849 }
3850 match lookup_key(&start, &key) {
3851 Some((_, property)) if property.is_accessor() => match &property.getter {
3852 Some(getter) if !matches!(getter, Value::Undefined) => {
3853 self.call_value(getter.clone(), receiver.clone(), Vec::new())
3854 }
3855 _ => Ok(Value::Undefined),
3856 },
3857 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
3858 None => Ok(Value::Undefined),
3859 }
3860 }
3861
3862 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
3863 ///
3864 /// A setter found on the prototype runs with `receiver` as `this`; a data property
3865 /// is shadowed by a new own property on the receiver, the same rule an ordinary
3866 /// assignment follows.
3867 fn super_write(
3868 &mut self,
3869 receiver: &Value,
3870 proto: &Value,
3871 key: &Value,
3872 value: Value,
3873 ) -> JsResult<()> {
3874 let target = self.require_object(receiver)?;
3875 let key = self.propkey(key)?;
3876 if !matches!(proto, Value::Null)
3877 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
3878 {
3879 if property.is_accessor() {
3880 if let Some(setter) = &property.setter
3881 && !matches!(setter, Value::Undefined)
3882 {
3883 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
3884 }
3885 return Ok(());
3886 }
3887 // A data property on the prototype is writable or not; reading `owner` at
3888 // all is only for the attribute check.
3889 if !property.writable {
3890 return Err(self.type_error(format!("'{key}' is read-only")));
3891 }
3892 let _ = owner;
3893 }
3894 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
3895 }
3896
3897 /// The object a `super` operation needs, or the `TypeError` the spec raises.
3898 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
3899 match value.as_object() {
3900 Some(object) => Ok(object.clone()),
3901 None => Err(Signal::Throw(
3902 self.make_error("TypeError", "value is not an object"),
3903 )),
3904 }
3905 }
3906
3907 /// Build the class object `define_class` produces.
3908 ///
3909 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
3910 /// whose prototype property is a fresh object inheriting from the parent's
3911 /// prototype, and whose own prototype is the parent constructor — which is what makes
3912 /// a static method inherited too.
3913 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
3914 let ctor = self.pop();
3915 let parent = self.pop();
3916 let Value::Object(function) = &ctor else {
3917 return Err(Signal::Throw(
3918 self.make_error("TypeError", "class constructor must be a function"),
3919 ));
3920 };
3921 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
3922 // but gives the instances no prototype at all.
3923 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
3924 match &parent {
3925 Value::Null => (Some(self.realm.function_proto.clone()), None),
3926 Value::Object(parent_class) => {
3927 if !parent_class.is_callable() {
3928 return Err(Signal::Throw(
3929 self.make_error("TypeError", "parent class must be constructor"),
3930 ));
3931 }
3932 let proto = self.get_property(parent_class, "prototype")?;
3933 match proto {
3934 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
3935 Some(Value::Null) => (Some(parent_class.clone()), None),
3936 _ => {
3937 return Err(Signal::Throw(self.make_error(
3938 "TypeError",
3939 "parent prototype must be an object or null",
3940 )));
3941 }
3942 }
3943 }
3944 _ => {
3945 return Err(Signal::Throw(
3946 self.make_error("TypeError", "parent class must be constructor"),
3947 ));
3948 }
3949 }
3950 } else {
3951 (
3952 Some(self.realm.function_proto.clone()),
3953 Some(self.realm.object_proto.clone()),
3954 )
3955 };
3956 let proto = self.new_object(parent_proto);
3957 function.set_proto(parent_ctor);
3958 // A class is not callable without `new`, and its `prototype` is not writable —
3959 // both follow from being a class and are what `class A {}; A()` throws on.
3960 function.set_class_constructor(true);
3961 function.set_home_object(None);
3962 self.set_function_name(&ctor, name);
3963 self.define_class_properties(function, &ctor, &proto)?;
3964 Ok((ctor, proto))
3965 }
3966
3967 /// Give the constructor its `prototype` and `length`, and the prototype its
3968 /// `constructor` back-pointer.
3969 fn define_class_properties(
3970 &mut self,
3971 function: &Gc<JsObject>,
3972 ctor: &Value,
3973 proto: &Gc<JsObject>,
3974 ) -> JsResult<()> {
3975 proto.define(
3976 "constructor",
3977 Property::with_attributes(ctor.clone(), true, false),
3978 );
3979 function.define(
3980 "prototype",
3981 Property::prototype_of(Value::Object(proto.clone()), false),
3982 );
3983 if let Some((code, _)) = bytecode_of(function) {
3984 let length = code.code.defined_args;
3985 function.define(
3986 "length",
3987 Property::name_or_length(Value::Int(length as i32)),
3988 );
3989 }
3990 Ok(())
3991 }
3992
3993 /// The own array element `key` names, if this object has one.
3994 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
3995 let index = array_index(key)?;
3996 // A typed array's elements live in its buffer, not in a property list: reading one
3997 // goes through the view's element type so a bounds check and a detached buffer are
3998 // both handled there.
3999 if object.typed_array_parts().is_some() {
4000 return object.typed_array_element(index as usize);
4001 }
4002 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
4003 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
4004 // search early, which is why `Array.prototype[1] = 9` could not be seen through
4005 // `[1,,3][1]`.
4006 match object.array_get(index as usize) {
4007 Some(Value::Hole) | None => None,
4008 other => other,
4009 }
4010 }
4011
4012 /// Store `object[key] = value`, honouring setters and inherited properties.
4013 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
4014 self.set_property_with(object, key, value, DeleteFailure::Throw)
4015 }
4016
4017 /// Store a property, choosing what to do when the object refuses.
4018 ///
4019 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
4020 /// mode, which is the one place assignment differs by mode. Native code (the array
4021 /// methods, `JSON`) always asks for the throw.
4022 pub fn set_property_with(
4023 &mut self,
4024 object: &Gc<JsObject>,
4025 key: &str,
4026 value: Value,
4027 on_failure: DeleteFailure,
4028 ) -> JsResult<()> {
4029 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
4030 }
4031
4032 /// [`Interp::set_property_with`] with a key that may be a symbol.
4033 pub fn set_property_with_key(
4034 &mut self,
4035 object: &Gc<JsObject>,
4036 key: &PropertyKey,
4037 value: Value,
4038 on_failure: DeleteFailure,
4039 ) -> JsResult<()> {
4040 // A proxy's `set` trap decides, and its `false` means the same thing an
4041 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
4042 if object.proxy_state().is_some() {
4043 let receiver = Value::Object(object.clone());
4044 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
4045 return match (accepted, on_failure) {
4046 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
4047 (false, DeleteFailure::Throw) => {
4048 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
4049 }
4050 };
4051 }
4052 }
4053 // The element and `length` shortcuts only exist for string keys: an array
4054 // index has no symbol spelling, and a symbol named `length` is an ordinary
4055 // property.
4056 let text = key.as_str();
4057 // A typed array's elements are a window onto its buffer: the store has to go
4058 // through the view's element type so the value is wrapped (or clamped) and so an
4059 // out-of-range or detached write is a silent no-op, as the spec says.
4060 if let Some(text) = text
4061 && let Some(index) = array_index(text)
4062 && let Some(element) = object.typed_array_element_type()
4063 {
4064 // §10.4.5.5: an out-of-bounds index answers `true` *before* `V` is converted,
4065 // so a `valueOf` with a side effect must not run. Checking the length first is
4066 // what keeps `valueOfCalled` at 0 in `key-is-out-of-bounds-receiver-is-…`.
4067 let length = object.typed_array_length().unwrap_or(0);
4068 if index as usize >= length {
4069 return Ok(());
4070 }
4071 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
4072 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
4073 // in `Interp`, because it is script-observable and the storage borrow inside
4074 // `typed_array_set` must not be held across it.
4075 let stored = self.element_value(element, value)?;
4076 if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
4077 return Err(self.type_error(reason));
4078 }
4079 return Ok(());
4080 }
4081 if let Some(text) = text
4082 && let Some(index) = array_index(text)
4083 && object.is_array()
4084 {
4085 // An accessor defined on an index lives in the property table while the
4086 // element slot is a hole, so the store has to go through the property first.
4087 // Writing the vector directly skipped the setter entirely.
4088 if let Some(existing) = object.own_property_key(key) {
4089 if existing.is_accessor() {
4090 return match existing.setter.clone() {
4091 Some(setter) if !matches!(setter, Value::Undefined) => {
4092 let receiver = Value::Object(object.clone());
4093 self.call_value(setter, receiver, vec![value]).map(|_| ())
4094 }
4095 _ => match on_failure {
4096 DeleteFailure::Throw => Err(self.type_error(format!(
4097 "cannot set property '{text}', it has only a getter"
4098 ))),
4099 DeleteFailure::Ignore => Ok(()),
4100 },
4101 };
4102 }
4103 if !existing.writable {
4104 return match on_failure {
4105 DeleteFailure::Throw => {
4106 Err(self.type_error(format!("'{text}' is read-only")))
4107 }
4108 DeleteFailure::Ignore => Ok(()),
4109 };
4110 }
4111 }
4112 {
4113 // Growing the array needs a writable `length`.
4114 if (index as usize) >= object.array_length().unwrap_or(0)
4115 && !object.length_writable()
4116 {
4117 return match on_failure {
4118 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4119 DeleteFailure::Ignore => Ok(()),
4120 };
4121 }
4122 // Adding an index past the end makes the array longer, which a
4123 // non-extensible array refuses.
4124 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
4125 return match on_failure {
4126 DeleteFailure::Throw => Err(self.type_error(format!(
4127 "cannot add property '{key}', object is not extensible"
4128 ))),
4129 DeleteFailure::Ignore => Ok(()),
4130 };
4131 }
4132 if object.element_is_locked(index) {
4133 return match on_failure {
4134 DeleteFailure::Throw => {
4135 Err(self.type_error(format!("'{key}' is read-only")))
4136 }
4137 DeleteFailure::Ignore => Ok(()),
4138 };
4139 }
4140 object.array_set(index as usize, value);
4141 return Ok(());
4142 }
4143 }
4144 if text == Some("length") && object.is_array() {
4145 if !object.length_writable() {
4146 return match on_failure {
4147 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4148 DeleteFailure::Ignore => Ok(()),
4149 };
4150 }
4151 let length = value.to_number();
4152 if length.is_finite() && length >= 0.0 {
4153 let length = length as usize;
4154 // `a.length = n` with `n` below a non-configurable element cannot
4155 // drop that element, so the whole assignment fails. The spec makes
4156 // this a `TypeError` rather than a silent no-op, in any mode.
4157 if let Some(blocked) = (length..object.array_length().unwrap_or(0))
4158 .find(|index| object.element_is_undeletable(*index as u32))
4159 {
4160 // Sloppy mode stops the truncation at the blocking element
4161 // instead of failing; strict mode raises.
4162 // Both modes stop at the blocking element; they differ in
4163 // whether that is reported. The reference truncates *then*
4164 // throws, so the array is left in the shortened state.
4165 object.array_truncate(blocked + 1);
4166 return match on_failure {
4167 DeleteFailure::Throw => {
4168 Err(self.type_error(format!("cannot delete property '{blocked}'")))
4169 }
4170 DeleteFailure::Ignore => Ok(()),
4171 };
4172 }
4173 object.array_set_length(length);
4174 return Ok(());
4175 }
4176 }
4177 if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
4178 {
4179 return match on_failure {
4180 DeleteFailure::Throw => Err(self.type_error(format!(
4181 "cannot add property {}, object is not extensible",
4182 key
4183 ))),
4184 DeleteFailure::Ignore => Ok(()),
4185 };
4186 }
4187 if let Some((owner, property)) = lookup_key(object, key) {
4188 if property.is_accessor() {
4189 if let Some(setter) = &property.setter
4190 && !matches!(setter, Value::Undefined)
4191 {
4192 let receiver = Value::Object(object.clone());
4193 self.call_value(setter.clone(), receiver, vec![value])?;
4194 }
4195 return Ok(());
4196 }
4197 // An inherited *data* property is shadowed by an own property on the
4198 // receiver; a non-writable one is not.
4199 if owner.ptr_eq(object) && !property.writable {
4200 return match on_failure {
4201 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
4202 DeleteFailure::Ignore => Ok(()),
4203 };
4204 }
4205 // An existing writable own property keeps its attributes: only the value
4206 // moves. Redefining instead would reset them, which is how a
4207 // non-configurable global `var` used to become deletable.
4208 if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
4209 return Ok(());
4210 }
4211 }
4212 // No own data property: create one, shadowing whatever the prototype holds.
4213 object.define_data_key(key, value);
4214 Ok(())
4215 }
4216
4217 /// Delete `object[key]`.
4218 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
4219 self.delete_property_key(object, &PropertyKey::from(key))
4220 }
4221
4222 /// [`Interp::delete_property`] with a key that may be a symbol.
4223 pub fn delete_property_key(
4224 &mut self,
4225 object: &Gc<JsObject>,
4226 key: &PropertyKey,
4227 ) -> JsResult<bool> {
4228 // A proxy decides for itself, and may even throw; the invariant checks live in
4229 // `proxy_delete`.
4230 if let Some(answer) = self.proxy_delete(object, key)? {
4231 return Ok(answer);
4232 }
4233 if let Some(index) = key.as_str().and_then(array_index)
4234 && let Some(length) = object.array_length()
4235 && (index as usize) < length
4236 {
4237 // An accessor defined on an index lives in the property table rather than the
4238 // element vector, so both have to be cleared: `delete` after
4239 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
4240 object.delete_key(key);
4241 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
4242 // index stops answering `in`.
4243 if object.element_is_undeletable(index) {
4244 return Ok(false);
4245 }
4246 object.array_set(index as usize, Value::Hole);
4247 return Ok(true);
4248 }
4249 Ok(object.delete_key(key))
4250 }
4251
4252 // -- proxy traps --------------------------------------------------------
4253 //
4254 // A proxy's internal methods all look the same: ask the handler for the trap, call it
4255 // with the target and the operation's own arguments, then check the answer against
4256 // the target. The checks are not decoration — they are what stops a proxy from
4257 // reporting a `non-configurable` property as missing, which would let a frozen object
4258 // be rewritten by standing in front of it.
4259
4260 /// The target and handler of `object`, or `None` when it is not a proxy.
4261 ///
4262 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
4263 /// one has to fail: the slots the traps would have been read from are gone.
4264 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
4265 let Some(state) = object.proxy_state() else {
4266 return Ok(None);
4267 };
4268 let state = state.borrow();
4269 match (&state.target, &state.handler) {
4270 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
4271 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
4272 }
4273 }
4274
4275 /// Call `handler[name]`, or answer `None` when the trap is absent.
4276 ///
4277 /// A trap that is present but not callable is a `TypeError` rather than "no trap":
4278 /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
4279 /// back to the target.
4280 fn proxy_trap(
4281 &mut self,
4282 handler: &Value,
4283 name: &str,
4284 args: Vec<Value>,
4285 ) -> JsResult<Option<Value>> {
4286 let Value::Object(table) = handler else {
4287 return Err(self.type_error("proxy handler is not an object"));
4288 };
4289 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
4290 match trap {
4291 Value::Undefined => Ok(None),
4292 Value::Object(function) if function.is_callable() => {
4293 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
4294 Ok(Some(answer))
4295 }
4296 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
4297 }
4298 }
4299
4300 /// Whether `object`'s own property `key` is one the target refuses to lose.
4301 ///
4302 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
4303 /// its value behind the target's back. This goes through
4304 /// [`Self::ordinary_own_property`] rather than the property table so that an array's
4305 /// elements and its `length` — both fixed, both outside the table — are covered.
4306 fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
4307 Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
4308 }
4309
4310 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
4311 fn proxy_get(
4312 &mut self,
4313 object: &Gc<JsObject>,
4314 receiver: &Value,
4315 key: &PropertyKey,
4316 ) -> JsResult<Option<Value>> {
4317 let Some((target, handler)) = self.proxy_parts(object)? else {
4318 return Ok(None);
4319 };
4320 let key_value = self.key_value(key);
4321 let Some(result) = self.proxy_trap(
4322 &handler,
4323 "get",
4324 vec![Value::Object(target.clone()), key_value, receiver.clone()],
4325 )?
4326 else {
4327 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
4328 // inherited getter still sees the proxy.
4329 return Ok(Some(
4330 self.get_property_key_for(&target, Some(receiver), key)?
4331 .unwrap_or(Value::Undefined),
4332 ));
4333 };
4334 if let Some(fixed) = Self::is_fixed_property(&target, key) {
4335 if fixed.is_accessor() {
4336 // A fixed accessor with no getter must read as `undefined`.
4337 let has_getter = fixed
4338 .getter
4339 .as_ref()
4340 .is_some_and(|getter| !matches!(getter, Value::Undefined));
4341 if !has_getter && !matches!(result, Value::Undefined) {
4342 return Err(self.type_error(format!(
4343 "proxy 'get' must report undefined for the non-configurable property '{key}'"
4344 )));
4345 }
4346 } else if !fixed.writable {
4347 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
4348 if !fixed_value.same_value(&result) {
4349 return Err(self.type_error(format!(
4350 "proxy 'get' disagrees with the non-configurable property '{key}'"
4351 )));
4352 }
4353 }
4354 }
4355 Ok(Some(result))
4356 }
4357
4358 /// `[[Set]]` on a proxy.
4359 ///
4360 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
4361 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
4362 /// read-only store has.
4363 fn proxy_set(
4364 &mut self,
4365 object: &Gc<JsObject>,
4366 key: &PropertyKey,
4367 value: Value,
4368 receiver: &Value,
4369 ) -> JsResult<Option<bool>> {
4370 let Some((target, handler)) = self.proxy_parts(object)? else {
4371 return Ok(None);
4372 };
4373 let key_value = self.key_value(key);
4374 let Some(result) = self.proxy_trap(
4375 &handler,
4376 "set",
4377 vec![
4378 Value::Object(target.clone()),
4379 key_value,
4380 value.clone(),
4381 receiver.clone(),
4382 ],
4383 )?
4384 else {
4385 // No trap: store on the target, which is where an ordinary proxy write lands.
4386 self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
4387 return Ok(Some(true));
4388 };
4389 if !result.to_boolean() {
4390 return Ok(Some(false));
4391 }
4392 if let Some(fixed) = Self::is_fixed_property(&target, key) {
4393 if fixed.is_accessor() {
4394 let has_setter = fixed
4395 .setter
4396 .as_ref()
4397 .is_some_and(|setter| !matches!(setter, Value::Undefined));
4398 if !has_setter {
4399 return Err(self.type_error(format!(
4400 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
4401 )));
4402 }
4403 } else if !fixed.writable {
4404 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
4405 if !fixed_value.same_value(&value) {
4406 return Err(self.type_error(format!(
4407 "proxy 'set' changed the non-configurable property '{key}'"
4408 )));
4409 }
4410 }
4411 }
4412 // A new property cannot appear on a target that refuses new properties.
4413 if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
4414 return Err(self.type_error(format!(
4415 "proxy 'set' added '{key}' to a non-extensible target"
4416 )));
4417 }
4418 Ok(Some(true))
4419 }
4420
4421 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
4422 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
4423 let Some((target, handler)) = self.proxy_parts(object)? else {
4424 return Ok(None);
4425 };
4426 let key_value = self.key_value(key);
4427 let Some(result) = self.proxy_trap(
4428 &handler,
4429 "has",
4430 vec![Value::Object(target.clone()), key_value],
4431 )?
4432 else {
4433 return Ok(Some(self.has_own_or_inherited(&target, key)?));
4434 };
4435 if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
4436 return Err(self.type_error(format!(
4437 "proxy 'has' denied the non-configurable property '{key}'"
4438 )));
4439 }
4440 // A non-extensible target cannot grow, so every own property it *has* is fixed.
4441 if !result.to_boolean()
4442 && !target.is_extensible()
4443 && Self::ordinary_own_property(&target, key).is_some()
4444 {
4445 return Err(self.type_error(format!(
4446 "proxy 'has' denied the own property '{key}' of a non-extensible target"
4447 )));
4448 }
4449 Ok(Some(result.to_boolean()))
4450 }
4451
4452 /// `[[Delete]]` on a proxy.
4453 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
4454 let Some((target, handler)) = self.proxy_parts(object)? else {
4455 return Ok(None);
4456 };
4457 let key_value = self.key_value(key);
4458 let Some(result) = self.proxy_trap(
4459 &handler,
4460 "deleteProperty",
4461 vec![Value::Object(target.clone()), key_value],
4462 )?
4463 else {
4464 return Ok(Some(self.delete_property_key(&target, key)?));
4465 };
4466 if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
4467 return Err(self.type_error(format!(
4468 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
4469 )));
4470 }
4471 if result.to_boolean()
4472 && !target.is_extensible()
4473 && Self::ordinary_own_property(&target, key).is_some()
4474 {
4475 return Err(self.type_error(format!(
4476 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
4477 )));
4478 }
4479 Ok(Some(result.to_boolean()))
4480 }
4481
4482 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
4483 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
4484 let Some((target, handler)) = self.proxy_parts(object)? else {
4485 return Ok(None);
4486 };
4487 let Some(result) =
4488 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
4489 else {
4490 // No trap: the target's own keys, already in the order an object reports.
4491 return Ok(Some(self.object_own_property_keys(&target)?));
4492 };
4493 // `CreateListFromArrayLike` with the string-or-symbol restriction.
4494 let list = self.list_from_array_like(&result, true)?;
4495 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
4496 for value in list {
4497 let key = self.propkey(&value)?;
4498 if keys.contains(&key) {
4499 return Err(self.type_error(format!(
4500 "proxy 'ownKeys' returned the duplicate key '{key}'"
4501 )));
4502 }
4503 keys.push(key);
4504 }
4505 for (key, property) in target.property_entries() {
4506 if !property.configurable && !keys.contains(&key) {
4507 return Err(self.type_error(format!(
4508 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
4509 )));
4510 }
4511 if !target.is_extensible() && !keys.contains(&key) {
4512 return Err(self.type_error(format!(
4513 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
4514 )));
4515 }
4516 }
4517 if !target.is_extensible() {
4518 let own = target.property_entries().len();
4519 if keys.len() != own {
4520 return Err(
4521 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
4522 );
4523 }
4524 }
4525 Ok(Some(keys))
4526 }
4527
4528 /// `[[GetOwnProperty]]` on a proxy.
4529 fn proxy_get_own_property(
4530 &mut self,
4531 object: &Gc<JsObject>,
4532 key: &PropertyKey,
4533 ) -> JsResult<Option<Option<Property>>> {
4534 let Some((target, handler)) = self.proxy_parts(object)? else {
4535 return Ok(None);
4536 };
4537 let key_value = self.key_value(key);
4538 let Some(result) = self.proxy_trap(
4539 &handler,
4540 "getOwnPropertyDescriptor",
4541 vec![Value::Object(target.clone()), key_value],
4542 )?
4543 else {
4544 // No trap: the target's own descriptor is the answer. This has to go through
4545 // the same synthesis an ordinary object gets, because a proxy's own property
4546 // table is empty by design — reading it directly reported `undefined` for
4547 // every key, including an array's indices and `length`.
4548 return Ok(Some(Self::ordinary_own_property(&target, key)));
4549 };
4550 let answer = if matches!(result, Value::Undefined) {
4551 None
4552 } else {
4553 Some(self.property_from_descriptor(&result)?)
4554 };
4555 let fixed = Self::is_fixed_property(&target, key);
4556 match (&answer, &fixed) {
4557 // A non-configurable property cannot be reported as absent.
4558 (None, Some(_)) => {
4559 return Err(self.type_error(format!(
4560 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
4561 )));
4562 }
4563 (Some(descriptor), Some(fixed)) => {
4564 if descriptor.configurable {
4565 return Err(self.type_error(format!(
4566 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
4567 )));
4568 }
4569 if fixed.is_accessor() != descriptor.is_accessor() {
4570 return Err(self.type_error(format!(
4571 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
4572 )));
4573 }
4574 if !fixed.is_accessor() && !fixed.writable {
4575 let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
4576 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
4577 if !fixed_value.same_value(&reported) {
4578 return Err(self.type_error(format!(
4579 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
4580 )));
4581 }
4582 }
4583 }
4584 _ => {}
4585 }
4586 Ok(Some(answer))
4587 }
4588
4589 /// `[[DefineOwnProperty]]` on a proxy.
4590 fn proxy_define_property(
4591 &mut self,
4592 object: &Gc<JsObject>,
4593 key: &PropertyKey,
4594 property: Property,
4595 ) -> JsResult<Option<bool>> {
4596 let Some((target, handler)) = self.proxy_parts(object)? else {
4597 return Ok(None);
4598 };
4599 let key_value = self.key_value(key);
4600 let descriptor = self.descriptor_from_property(&property);
4601 let Some(result) = self.proxy_trap(
4602 &handler,
4603 "defineProperty",
4604 vec![Value::Object(target.clone()), key_value, descriptor],
4605 )?
4606 else {
4607 return Ok(None);
4608 };
4609 if !result.to_boolean() {
4610 return Ok(Some(false));
4611 }
4612 let fixed = Self::is_fixed_property(&target, key);
4613 let creating = Self::ordinary_own_property(&target, key).is_none();
4614 if creating && !target.is_extensible() {
4615 return Err(self.type_error(format!(
4616 "proxy 'defineProperty' added '{key}' to a non-extensible target"
4617 )));
4618 }
4619 if let Some(fixed) = fixed {
4620 if property.configurable {
4621 return Err(self.type_error(format!(
4622 "proxy 'defineProperty' made the non-configurable '{key}' configurable"
4623 )));
4624 }
4625 if !fixed.writable && property.writable && !fixed.is_accessor() {
4626 return Err(self.type_error(format!(
4627 "proxy 'defineProperty' made the read-only '{key}' writable"
4628 )));
4629 }
4630 }
4631 Ok(Some(true))
4632 }
4633
4634 /// `[[GetPrototypeOf]]` on a proxy.
4635 fn proxy_get_prototype_of(
4636 &mut self,
4637 object: &Gc<JsObject>,
4638 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
4639 let Some((target, handler)) = self.proxy_parts(object)? else {
4640 return Ok(None);
4641 };
4642 let Some(result) = self.proxy_trap(
4643 &handler,
4644 "getPrototypeOf",
4645 vec![Value::Object(target.clone())],
4646 )?
4647 else {
4648 return Ok(Some(target.proto()));
4649 };
4650 let proto = match &result {
4651 Value::Null => None,
4652 Value::Object(proto) => Some(proto.clone()),
4653 _ => {
4654 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
4655 }
4656 };
4657 if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
4658 return Err(self.type_error(
4659 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
4660 ));
4661 }
4662 Ok(Some(proto))
4663 }
4664
4665 /// `[[SetPrototypeOf]]` on a proxy.
4666 fn proxy_set_prototype_of(
4667 &mut self,
4668 object: &Gc<JsObject>,
4669 proto: Option<Gc<JsObject>>,
4670 ) -> JsResult<Option<bool>> {
4671 let Some((target, handler)) = self.proxy_parts(object)? else {
4672 return Ok(None);
4673 };
4674 let proto_value = match &proto {
4675 Some(proto) => Value::Object(proto.clone()),
4676 None => Value::Null,
4677 };
4678 let Some(result) = self.proxy_trap(
4679 &handler,
4680 "setPrototypeOf",
4681 vec![Value::Object(target.clone()), proto_value],
4682 )?
4683 else {
4684 target.set_proto(proto);
4685 return Ok(Some(true));
4686 };
4687 if result.to_boolean()
4688 && !target.is_extensible()
4689 && !same_proto(proto.as_ref(), target.proto().as_ref())
4690 {
4691 return Err(self.type_error(
4692 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
4693 ));
4694 }
4695 Ok(Some(result.to_boolean()))
4696 }
4697
4698 /// `[[IsExtensible]]` on a proxy.
4699 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
4700 let Some((target, handler)) = self.proxy_parts(object)? else {
4701 return Ok(None);
4702 };
4703 let Some(result) = self.proxy_trap(
4704 &handler,
4705 "isExtensible",
4706 vec![Value::Object(target.clone())],
4707 )?
4708 else {
4709 return Ok(Some(target.is_extensible()));
4710 };
4711 // The answer is not the proxy's to invent: it must agree with the target, or a
4712 // script could learn `false` while the target keeps accepting new properties.
4713 if result.to_boolean() != target.is_extensible() {
4714 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
4715 }
4716 Ok(Some(result.to_boolean()))
4717 }
4718
4719 /// `[[PreventExtensions]]` on a proxy.
4720 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
4721 let Some((target, handler)) = self.proxy_parts(object)? else {
4722 return Ok(None);
4723 };
4724 let Some(result) = self.proxy_trap(
4725 &handler,
4726 "preventExtensions",
4727 vec![Value::Object(target.clone())],
4728 )?
4729 else {
4730 target.set_extensible(false);
4731 return Ok(Some(true));
4732 };
4733 if result.to_boolean() && target.is_extensible() {
4734 return Err(self.type_error(
4735 "proxy 'preventExtensions' reported success but the target is still extensible",
4736 ));
4737 }
4738 Ok(Some(result.to_boolean()))
4739 }
4740
4741 /// `[[Call]]` on a proxy, through the `apply` trap.
4742 fn proxy_apply(
4743 &mut self,
4744 object: &Gc<JsObject>,
4745 this: Value,
4746 args: Vec<Value>,
4747 ) -> JsResult<Option<Value>> {
4748 let Some((target, handler)) = self.proxy_parts(object)? else {
4749 return Ok(None);
4750 };
4751 // The trap gets the arguments as one array, which is the shape the spec passes
4752 // and the shape `apply` traps are written against (`args[0]` is the first one).
4753 let arguments = self.new_array(args.clone());
4754 let this_for_trap = this.clone();
4755 let Some(result) = self.proxy_trap(
4756 &handler,
4757 "apply",
4758 vec![
4759 Value::Object(target.clone()),
4760 this_for_trap,
4761 Value::Object(arguments),
4762 ],
4763 )?
4764 else {
4765 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
4766 };
4767 Ok(Some(result))
4768 }
4769
4770 /// `[[Construct]]` on a proxy, through the `construct` trap.
4771 fn proxy_construct(
4772 &mut self,
4773 object: &Gc<JsObject>,
4774 args: Vec<Value>,
4775 new_target: &Value,
4776 ) -> JsResult<Option<Value>> {
4777 let Some((target, handler)) = self.proxy_parts(object)? else {
4778 return Ok(None);
4779 };
4780 if !target.is_callable() {
4781 return Err(self.type_error("proxy target is not a constructor"));
4782 }
4783 let arguments = self.new_array(args.clone());
4784 let Some(result) = self.proxy_trap(
4785 &handler,
4786 "construct",
4787 vec![
4788 Value::Object(target.clone()),
4789 Value::Object(arguments),
4790 new_target.clone(),
4791 ],
4792 )?
4793 else {
4794 return Ok(Some(self.construct(
4795 Value::Object(target),
4796 new_target.clone(),
4797 args,
4798 )?));
4799 };
4800 if !matches!(result, Value::Object(_)) {
4801 return Err(self.type_error("proxy 'construct' must return an object"));
4802 }
4803 Ok(Some(result))
4804 }
4805
4806 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
4807 pub(crate) fn has_own_or_inherited(
4808 &mut self,
4809 object: &Gc<JsObject>,
4810 key: &PropertyKey,
4811 ) -> JsResult<bool> {
4812 // The object itself first: it may be a proxy, and then the answer is its trap's.
4813 if let Some(answer) = self.proxy_has(object, key)? {
4814 return Ok(answer);
4815 }
4816 // `has_own` rather than `own_property_key`: an array's elements and its derived
4817 // `length` are invisible to the property table, and `Array.prototype` is an array.
4818 if has_own(object, key) {
4819 return Ok(true);
4820 }
4821 // A hole is *not* the end of the search: the chain may still have the key, which
4822 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
4823 for ancestor in object.chain() {
4824 // A proxy further up the chain answers for itself.
4825 if let Some(answer) = self.proxy_has(&ancestor, key)? {
4826 return Ok(answer);
4827 }
4828 if has_own(&ancestor, key) {
4829 return Ok(true);
4830 }
4831 }
4832 Ok(false)
4833 }
4834
4835 /// `CreateListFromArrayLike`, optionally restricted to property keys.
4836 ///
4837 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
4838 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
4839 /// `TypeError` instead of a property named `"1.5"`.
4840 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
4841 let object = self.object_from(value)?;
4842 let length = self
4843 .get_property(&object, "length")?
4844 .map(|value| value.to_number())
4845 .unwrap_or(0.0);
4846 if !length.is_finite() || length < 0.0 {
4847 return Err(self.type_error("invalid array-like length"));
4848 }
4849 let length = length as usize;
4850 let mut items = Vec::with_capacity(length.min(1024));
4851 for index in 0..length {
4852 let item = self
4853 .get_property(&object, &index.to_string())?
4854 .unwrap_or(Value::Undefined);
4855 if keys_only && matches!(&item, Value::Symbol(_)) {
4856 items.push(item);
4857 continue;
4858 }
4859 if keys_only && !matches!(&item, Value::String(_)) {
4860 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
4861 }
4862 items.push(item);
4863 }
4864 Ok(items)
4865 }
4866
4867 /// A `Property` from the descriptor object a trap returned.
4868 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
4869 let object = self.object_from(value)?;
4870 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
4871 interp.get_property(&object, name)
4872 };
4873 let getter = field(self, "get")?;
4874 let setter = field(self, "set")?;
4875 let accessor = getter.is_some() || setter.is_some();
4876 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
4877 Ok(interp
4878 .get_property(&object, name)?
4879 .is_some_and(|value| value.to_boolean()))
4880 };
4881 let enumerable = boolean(self, "enumerable")?;
4882 let configurable = boolean(self, "configurable")?;
4883 if accessor {
4884 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
4885 return Err(
4886 self.type_error("a descriptor cannot be both a data property and an accessor")
4887 );
4888 }
4889 Ok(Property {
4890 getter: getter.or(Some(Value::Undefined)),
4891 setter: setter.or(Some(Value::Undefined)),
4892 enumerable,
4893 configurable,
4894 writable: false,
4895 value: None,
4896 })
4897 } else {
4898 Ok(Property {
4899 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
4900 writable: boolean(self, "writable")?,
4901 enumerable,
4902 configurable,
4903 getter: None,
4904 setter: None,
4905 })
4906 }
4907 }
4908
4909 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
4910 fn descriptor_from_property(&mut self, property: &Property) -> Value {
4911 let object = self.new_object(None);
4912 if property.is_accessor() {
4913 let getter = property.getter.clone().unwrap_or(Value::Undefined);
4914 let setter = property.setter.clone().unwrap_or(Value::Undefined);
4915 object.define_data("get", getter);
4916 object.define_data("set", setter);
4917 } else {
4918 let value = property.value.clone().unwrap_or(Value::Undefined);
4919 object.define_data("value", value);
4920 object.define_data("writable", Value::Bool(property.writable));
4921 }
4922 object.define_data("enumerable", Value::Bool(property.enumerable));
4923 object.define_data("configurable", Value::Bool(property.configurable));
4924 Value::Object(object)
4925 }
4926
4927 // -- calling ------------------------------------------------------------
4928
4929 /// Call `callee` with `this` and `args`.
4930 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
4931 let Value::Object(function) = &callee else {
4932 // `typeof x === "function"` is not enough to make `x()` legal: only a
4933 // callable object is. `null` and `undefined` need no special wording
4934 // here — their `ToString` already reads the way the reference's does.
4935 let what = format!("{} is not a function", callee.to_js_string());
4936 return Err(Signal::Throw(self.make_error("TypeError", &what)));
4937 };
4938 // A proxy of a function is called through its `apply` trap. It has no
4939 // `ObjectKind::Function` of its own, so this has to come before the dispatch
4940 // below, and a proxy of a non-function has nothing to forward to.
4941 if function.proxy_state().is_some() {
4942 return match self.proxy_apply(function, this, args)? {
4943 Some(result) => Ok(result),
4944 None => Err(Signal::Throw(
4945 self.make_error("TypeError", "proxy target is not callable"),
4946 )),
4947 };
4948 }
4949 let callable = function.with(|data| match &data.kind {
4950 ObjectKind::Function(callable) => match callable {
4951 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
4952 // The `Rc` is cloned out so the borrow of this object's data is released
4953 // before the closure runs: the closure may touch the same object.
4954 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
4955 Callable::Bound {
4956 target,
4957 this,
4958 args: leading,
4959 } => Some(NativeCall::Bound {
4960 target: target.clone(),
4961 this: this.clone(),
4962 leading: leading.clone(),
4963 }),
4964 Callable::Bytecode { code, env } => {
4965 Some(NativeCall::Bytecode(code.clone(), env.clone()))
4966 }
4967 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
4968 Callable::PromiseResolve(promise) => {
4969 Some(NativeCall::PromiseResolve(promise.clone()))
4970 }
4971 Callable::PromiseReject(promise) => {
4972 Some(NativeCall::PromiseReject(promise.clone()))
4973 }
4974 Callable::AwaitResume {
4975 coroutine,
4976 promise,
4977 kind,
4978 } => Some(NativeCall::AwaitResume {
4979 coroutine: coroutine.clone(),
4980 promise: promise.clone(),
4981 kind: *kind,
4982 }),
4983 Callable::CombinatorSettle {
4984 state,
4985 index,
4986 fulfilled,
4987 } => Some(NativeCall::CombinatorSettle {
4988 state: state.clone(),
4989 index: *index,
4990 fulfilled: *fulfilled,
4991 }),
4992 Callable::FinallyShim {
4993 callback,
4994 fulfilled,
4995 } => Some(NativeCall::FinallyShim {
4996 callback: callback.clone(),
4997 fulfilled: *fulfilled,
4998 }),
4999 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
5000 Callable::CompletedReturn {
5001 generator,
5002 promise,
5003 rejected,
5004 } => Some(NativeCall::CompletedReturn {
5005 generator: generator.clone(),
5006 promise: promise.clone(),
5007 rejected: *rejected,
5008 }),
5009 Callable::YieldResult {
5010 generator,
5011 promise,
5012 done,
5013 } => Some(NativeCall::YieldResult {
5014 generator: generator.clone(),
5015 promise: promise.clone(),
5016 done: *done,
5017 }),
5018 Callable::DisposeStep {
5019 remaining,
5020 promise,
5021 error,
5022 rejected,
5023 } => Some(NativeCall::DisposeStep {
5024 remaining: remaining.clone(),
5025 promise: promise.clone(),
5026 error: error.clone(),
5027 rejected: *rejected,
5028 }),
5029 Callable::GeneratorResume {
5030 generator,
5031 promise,
5032 kind,
5033 } => Some(NativeCall::GeneratorResume {
5034 generator: generator.clone(),
5035 promise: promise.clone(),
5036 kind: *kind,
5037 }),
5038 Callable::SettlePromise {
5039 promise,
5040 value,
5041 rejected,
5042 } => Some(NativeCall::SettlePromise {
5043 promise: promise.clone(),
5044 value: value.clone(),
5045 rejected: *rejected,
5046 }),
5047 },
5048 _ => None,
5049 });
5050 match callable {
5051 Some(NativeCall::Host(func)) => {
5052 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
5053 // function by name rather than stopping at the caller.
5054 let frame_less = function
5055 .own_property("_frame_less")
5056 .and_then(|property| property.value)
5057 .is_some_and(|value| value.to_boolean());
5058 let name = function
5059 .own_property("name")
5060 .and_then(|property| property.value)
5061 .map(|value| value.to_js_string())
5062 .unwrap_or_default();
5063 let outer = if frame_less {
5064 None
5065 } else {
5066 self.native_frames
5067 .push((name, function.clone(), self.frames.len()));
5068 Some(self.current_native.replace(function.clone()))
5069 };
5070 let result = {
5071 let mut body = func.borrow_mut();
5072 body(self, this, &args)
5073 };
5074 if !frame_less {
5075 self.native_frames.pop();
5076 self.current_native = outer.flatten();
5077 }
5078 result
5079 }
5080 Some(NativeCall::Native(func)) => {
5081 // A function marked `_frame_less` is one the reference implements
5082 // without a call frame — `eval` is the only one so far.
5083 let frame_less = function
5084 .own_property("_frame_less")
5085 .and_then(|property| property.value)
5086 .is_some_and(|value| value.to_boolean());
5087 let name = function
5088 .own_property("name")
5089 .and_then(|property| property.value)
5090 .map(|value| value.to_js_string())
5091 .unwrap_or_default();
5092 let outer = if frame_less {
5093 None
5094 } else {
5095 self.native_frames
5096 .push((name, function.clone(), self.frames.len()));
5097 Some(self.current_native.replace(function.clone()))
5098 };
5099 let result = func(self, this, &args);
5100 if !frame_less {
5101 self.native_frames.pop();
5102 self.current_native = outer.flatten();
5103 }
5104 result
5105 }
5106 Some(NativeCall::Revoker(slots)) => {
5107 // Idempotent: revoking twice answers `undefined` again rather than
5108 // complaining, which is what the spec says and what a `finally` block
5109 // relies on.
5110 let mut state = slots.borrow_mut();
5111 state.target = None;
5112 state.handler = None;
5113 Ok(Value::Undefined)
5114 }
5115 Some(NativeCall::PromiseResolve(promise)) => {
5116 // One-shot: a second call is silently ignored, which
5117 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
5118 let value = args.first().cloned().unwrap_or(Value::Undefined);
5119 self.resolve_promise_with(&promise, value)?;
5120 Ok(Value::Undefined)
5121 }
5122 Some(NativeCall::PromiseReject(promise)) => {
5123 let reason = args.first().cloned().unwrap_or(Value::Undefined);
5124 self.reject_promise(&promise, reason);
5125 Ok(Value::Undefined)
5126 }
5127 Some(NativeCall::CombinatorSettle {
5128 state,
5129 index,
5130 fulfilled,
5131 }) => {
5132 let value = args.first().cloned().unwrap_or(Value::Undefined);
5133 self.settle_combinator(&state, index, fulfilled, value)?;
5134 Ok(Value::Undefined)
5135 }
5136 Some(NativeCall::AwaitResume {
5137 coroutine,
5138 promise,
5139 kind,
5140 }) => {
5141 // Resume *inline*, in the reaction that delivered the value. Deferring it
5142 // by another job inserts a tick between every `await` and its
5143 // continuation, which reorders `await` against unrelated `then` chains —
5144 // `f().then(g)` then runs before `f`'s own next statement.
5145 self.drive_async(
5146 &coroutine,
5147 &promise,
5148 kind,
5149 args.first().cloned().unwrap_or(Value::Undefined),
5150 )
5151 .map(|()| Value::Undefined)
5152 }
5153 Some(NativeCall::FinallyShim {
5154 callback,
5155 fulfilled,
5156 }) => {
5157 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
5158 // that settles with the *original* outcome once the callback's result has
5159 // settled. The callback's own value is discarded — that is the whole
5160 // difference between `finally` and `then`.
5161 let original = args.first().cloned().unwrap_or(Value::Undefined);
5162 let result = match &callback {
5163 Some(callback) => {
5164 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
5165 }
5166 None => Value::Undefined,
5167 };
5168 let resolved = self.promise_resolve_value(result)?;
5169 let Value::Object(resolved) = resolved else {
5170 return Ok(original);
5171 };
5172 // The wait is a chained promise rather than a bare return, so a callback
5173 // that returns a slow promise really does delay the continuation.
5174 let waiting = self.new_promise();
5175 let pass = JsObject::function(
5176 self.heap,
5177 Some(self.realm.function_proto.clone()),
5178 Callable::SettlePromise {
5179 promise: waiting.clone(),
5180 value: original,
5181 rejected: !fulfilled,
5182 },
5183 );
5184 let pass = Value::Object(pass);
5185 // Whichever way the callback's promise settles, the original outcome wins.
5186 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
5187 Ok(Value::Object(waiting))
5188 }
5189 Some(NativeCall::DisposeStep {
5190 remaining,
5191 promise,
5192 error,
5193 rejected,
5194 }) => {
5195 let error = if rejected {
5196 let reason = args.first().cloned().unwrap_or(Value::Undefined);
5197 self.merge_dispose_error(reason, error)
5198 } else {
5199 error
5200 };
5201 self.dispose_step(&remaining, &promise, error)?;
5202 Ok(Value::Undefined)
5203 }
5204 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
5205 Some(NativeCall::CompletedReturn {
5206 generator,
5207 promise,
5208 rejected,
5209 }) => {
5210 let value = args.first().cloned().unwrap_or(Value::Undefined);
5211 let outcome = if rejected {
5212 AsyncOutcome::Error(value)
5213 } else {
5214 AsyncOutcome::Value(self.iterator_result(value, true)?)
5215 };
5216 self.settle_async_request(&generator, &promise, outcome)?;
5217 Ok(Value::Undefined)
5218 }
5219 Some(NativeCall::YieldResult {
5220 generator,
5221 promise,
5222 done,
5223 }) => {
5224 let value = args.first().cloned().unwrap_or(Value::Undefined);
5225 let result = self.iterator_result(value, done)?;
5226 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
5227 Ok(Value::Undefined)
5228 }
5229 Some(NativeCall::GeneratorResume {
5230 generator,
5231 promise,
5232 kind,
5233 }) => {
5234 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
5235 // tick and reorders the generator against other chains.
5236 self.step_async_generator(
5237 &generator,
5238 &promise,
5239 kind,
5240 args.first().cloned().unwrap_or(Value::Undefined),
5241 )
5242 .map(|()| Value::Undefined)
5243 }
5244 Some(NativeCall::SettlePromise {
5245 promise,
5246 value,
5247 rejected,
5248 }) => {
5249 if rejected {
5250 self.reject_promise(&promise, value);
5251 } else {
5252 self.fulfill_promise(&promise, value);
5253 }
5254 Ok(Value::Undefined)
5255 }
5256 Some(NativeCall::Bound {
5257 target,
5258 this: bound_this,
5259 leading,
5260 }) => {
5261 let mut all = leading;
5262 all.extend(args);
5263 self.call_value(target, bound_this, all)
5264 }
5265 Some(NativeCall::Bytecode(code, env)) => {
5266 if code.code.kind.is_generator() {
5267 return self.new_generator(callee, this, args);
5268 }
5269 if code.code.kind.is_async() {
5270 // Same coroutine machinery as a generator; the difference is only in
5271 // what the completion does — see `new_async_function`.
5272 return self.new_async_function(callee, this, args);
5273 }
5274 self.execute(code, env, this, args, callee)
5275 }
5276 None => Err(Signal::Throw(
5277 self.make_error("TypeError", "not a function"),
5278 )),
5279 }
5280 }
5281
5282 /// Give a freshly built function its own `prototype` object.
5283 ///
5284 /// Every function that can be used with `new` carries one, and its
5285 /// `constructor` points back at the function — a reference cycle, which is
5286 /// exactly what the collector's cycle pass exists to reclaim.
5287 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
5288 let prototype = self.new_object(Some(self.realm.object_proto.clone()));
5289 let constructor = Value::Object(function.clone());
5290 prototype.define(
5291 "constructor",
5292 Property::with_attributes(constructor, true, false),
5293 );
5294 let value = Value::Object(prototype);
5295 function.define("prototype", Property::prototype_of(value, true));
5296 }
5297
5298 /// The object `special_object` builds.
5299 ///
5300 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
5301 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
5302 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
5303 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
5304 /// write through `arguments` does not reach the parameter.
5305 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
5306 match magic {
5307 0 | 1 => {
5308 let args = self.frame().passed.clone();
5309 let proto = self.realm.object_proto.clone();
5310 let object = self.new_object(Some(proto));
5311 // The marker `Object.prototype.toString` needs: an arguments object is an
5312 // ordinary object apart from reporting `[object Arguments]`, and that has
5313 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
5314 // show up ahead of them in a key listing anyway — it is non-enumerable.
5315 self.internal_set(&object, "_class", self.string("Arguments"));
5316 // `length` is writable and configurable but neither enumerable nor a
5317 // plain data property: `Object.keys(arguments)` lists the indices only,
5318 // which is how `{...arguments}` copies them without the length.
5319 object.define(
5320 "length",
5321 Property::with_attributes(Value::Int(args.len() as i32), true, false),
5322 );
5323 for (index, value) in args.into_iter().enumerate() {
5324 object.define_data(&index.to_string(), value);
5325 }
5326 // An arguments object is iterable: `[...arguments]` and
5327 // `for (const a of arguments)` both work, through the *array* iterator
5328 // because the object is array-like. Without this the whole spread form
5329 // reported "not iterable".
5330 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
5331 let values = self
5332 .realm
5333 .array_proto
5334 .own_property("values")
5335 .and_then(|property| property.value);
5336 if let Some(values) = values {
5337 object.define_key(
5338 &iterator_key,
5339 Property::with_attributes(values, true, false),
5340 );
5341 }
5342 Ok(Value::Object(object))
5343 }
5344 // `this.active_func`: the constructor `super()` resolves against.
5345 //
5346 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
5347 // own, so it inherits this from the function it was written in along with `this`
5348 // — and that is a lexical relationship, not a stack one: an arrow that escaped
5349 // the constructor and is called back later (`iter.return = () => super()`) has
5350 // the constructor nowhere on the stack. The compiler therefore reads it out of
5351 // a closure variable of the enclosing function, exactly as the reference does
5352 // with its `this_active_func` local.
5353 2 => Ok(self
5354 .current_callee()
5355 .map_or(Value::Undefined, Value::Object)),
5356 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
5357 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
5358 // its own either, so the lookup walks out to the nearest non-arrow frame for
5359 // the same reason as `this.active_func` above — without that, `super()` inside
5360 // an arrow passed `undefined` as the new target and the parent constructor was
5361 // then rejected for being invoked without `new`.
5362 3 => Ok(self
5363 .eval_new_target
5364 .clone()
5365 .unwrap_or_else(|| self.frame().new_target.clone())),
5366 // `[[HomeObject]]` of the function being run: what `super` is relative to.
5367 // An arrow has none of its own, so the lookup walks out to the enclosing
5368 // method — which is why `super` works inside an arrow inside a method.
5369 4 => Ok(self
5370 .frames
5371 .iter()
5372 .rev()
5373 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
5374 .map_or(Value::Undefined, Value::Object)),
5375 // `import.meta`: the innermost module body's meta object. Outside a module
5376 // the compiler never emits this, so an empty fallback is unreachable rather
5377 // than permissive.
5378 6 => {
5379 let name = self.module_stack.last().cloned();
5380 let meta = name
5381 .and_then(|name| self.modules.get(&name).cloned())
5382 .and_then(|module| module.with(|r| r.import_meta.clone()));
5383 Ok(meta.map_or(Value::Undefined, Value::Object))
5384 }
5385 other => Err(Signal::Throw(self.make_error(
5386 "InternalError",
5387 &format!("special_object {other} is not implemented yet"),
5388 ))),
5389 }
5390 }
5391
5392 /// `[[HomeObject]]` of the innermost function that has one, if any.
5393 ///
5394 /// An arrow has none, so the search walks out to the enclosing method — the same
5395 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
5396 /// inside a method.
5397 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
5398 self.frames
5399 .iter()
5400 .rev()
5401 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
5402 }
5403
5404 /// The dispose method a `using` declaration should snapshot, or an error.
5405 ///
5406 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
5407 /// is what makes a resource that only knows the synchronous protocol usable in both
5408 /// forms.
5409 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
5410 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
5411 if value.is_nullish() {
5412 return Ok(Value::Undefined);
5413 }
5414 let Some(object) = value.as_object() else {
5415 return Err(self.type_error("not an object"));
5416 };
5417 let mut method = if await_form {
5418 let found = self.get_property_key(
5419 object,
5420 &self.realm.well_known_key(WellKnown::AsyncDisposable),
5421 )?;
5422 match found {
5423 Some(found) if !found.is_nullish() => Some(found),
5424 _ => self
5425 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
5426 }
5427 } else {
5428 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
5429 };
5430 let Some(found) = method.take() else {
5431 return Err(self.type_error("value is not disposable"));
5432 };
5433 if found.is_nullish() {
5434 return Err(self.type_error("value is not disposable"));
5435 }
5436 let callable = found.as_object().is_some_and(|object| object.is_callable());
5437 if !callable {
5438 return Err(self.type_error("dispose method is not a function"));
5439 }
5440 Ok(found)
5441 }
5442
5443 /// Call one resource's disposer, folding a failure into `error_state`.
5444 ///
5445 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
5446 /// because a captured `using` binding lives in its reference cell and the local slot is
5447 /// stale — a closure over the resource is legal and must not change what is disposed.
5448 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
5449 let value = self.get_loc(slot);
5450 let method = self.get_loc(slot + 1);
5451 // A resource that was never initialised — its declaration threw — or that is
5452 // `null`/`undefined` has nothing to dispose.
5453 if value.is_nullish() || matches!(value, Value::Uninitialized) {
5454 return Ok(error_state);
5455 }
5456 if matches!(method, Value::Undefined | Value::Uninitialized) {
5457 return Ok(error_state);
5458 }
5459 match self.call_value(method, value, Vec::new()) {
5460 Ok(_) => Ok(error_state),
5461 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
5462 Err(other) => Err(other),
5463 }
5464 }
5465
5466 /// Combine a disposal failure with whatever was already going wrong.
5467 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
5468 if matches!(error_state, Value::Uninitialized) {
5469 return new_error;
5470 }
5471 self.new_suppressed_error(new_error, error_state)
5472 }
5473
5474 /// A `SuppressedError` instance built straight from its prototype.
5475 ///
5476 /// Not through the constructor: a script that rewrites
5477 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
5478 /// error wrapping.
5479 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
5480 let proto = self
5481 .realm
5482 .suppressed_error_proto
5483 .clone()
5484 .unwrap_or_else(|| self.realm.error_proto.clone());
5485 let object = self.new_object(Some(proto));
5486 object.define("error", Property::with_attributes(error, true, true));
5487 object.define(
5488 "suppressed",
5489 Property::with_attributes(suppressed, true, true),
5490 );
5491 object.define(
5492 "message",
5493 Property::with_attributes(self.string("SuppressedError"), true, true),
5494 );
5495 self.internal_set(&object, "_class", self.string("Error"));
5496 self.add_stack(&object);
5497 Value::Object(object)
5498 }
5499
5500 /// Call `callee`, or push its frame and let the main loop run it.
5501 ///
5502 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
5503 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
5504 /// continues, so `function f(){ return f() }` costs heap and stops at
5505 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
5506 /// is entered directly, and natives do not re-enter JavaScript in this
5507 /// milestone.
5508 ///
5509 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
5510 /// because the returning frame will.
5511 /// The elements of an array-like value, as a call argument list.
5512 ///
5513 /// `apply` accepts any array-like, not only a real array: the reference reads
5514 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
5515 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
5516 let Some(object) = value.as_object().cloned() else {
5517 if value.is_nullish() {
5518 // `f.apply(this, null)` passes no arguments at all.
5519 return Ok(Vec::new());
5520 }
5521 return Err(self.type_error("createListFromArrayLike called on non-object"));
5522 };
5523 let length = match self.get_property(&object, "length")? {
5524 Some(length) => length.to_number(),
5525 None => 0.0,
5526 };
5527 if !length.is_finite() || length <= 0.0 {
5528 return Ok(Vec::new());
5529 }
5530 let length = (length as usize).min(1_000_000);
5531 let mut args = Vec::with_capacity(length);
5532 for index in 0..length {
5533 let element = self.get_property(&object, &index.to_string())?;
5534 args.push(element.unwrap_or(Value::Undefined));
5535 }
5536 Ok(args)
5537 }
5538
5539 /// Turn a call to a generator function into a generator object.
5540 ///
5541 /// The frame is built exactly as an ordinary call would build it, then detached and
5542 /// stored in the generator before any body instruction runs — which is what makes
5543 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
5544 /// is `initial_yield`, the first instruction of every suspending body.
5545 pub fn new_generator(
5546 &mut self,
5547 function: Value,
5548 this: Value,
5549 args: Vec<Value>,
5550 ) -> JsResult<Value> {
5551 let Some(object) = function.as_object().cloned() else {
5552 return Err(self.type_error("not a generator function"));
5553 };
5554 let Some((code, env)) = bytecode_of(&object) else {
5555 return Err(self.type_error("not a generator function"));
5556 };
5557 let is_async = code.code.kind.is_async();
5558 self.push_frame(code, env, this, args, function)?;
5559 let frame = self.frames.pop().expect("push_frame just pushed it");
5560 // A fresh generator is *suspended at start*: the body has not run, so a
5561 // `return`/`throw` on it finishes without executing anything.
5562 let mut state = GeneratorState {
5563 frame: Some(frame),
5564 phase: GeneratorPhase::SuspendedStart,
5565 parked_on_await: false,
5566 parked_on_yield_star: false,
5567 requests: std::collections::VecDeque::new(),
5568 async_busy: false,
5569 };
5570 // Run to the first suspension. For a generator that is `initial_yield`, so no
5571 // body code runs; for a malformed body it would be the first `yield`.
5572 // An `async function*` answers an async generator: same coroutine, but its
5573 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
5574 let proto = if is_async {
5575 self.realm
5576 .async_generator_proto
5577 .clone()
5578 .unwrap_or_else(|| self.realm.generator_proto.clone())
5579 } else {
5580 self.realm.generator_proto.clone()
5581 };
5582 let generator = self.new_object(Some(proto));
5583 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
5584 Ok(_) => {}
5585 Err(error) => return Err(error),
5586 }
5587 generator.with_mut(|data| {
5588 data.kind = ObjectKind::Generator(Box::new(state));
5589 });
5590 Ok(Value::Object(generator))
5591 }
5592
5593 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
5594 ///
5595 /// Returns the `{value, done}` object itself rather than the pair, because a
5596 /// `yield*` suspension already has one — the inner iterator's own result — and the
5597 /// protocol says to hand that straight through rather than nest it.
5598 /// Advance a generator and report *why* it parked.
5599 ///
5600 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
5601 /// "hand this value to the caller" — but an async generator does: an `await` has to
5602 /// settle before it can answer, while a `yield` is the answer.
5603 fn resume_generator_detailed(
5604 &mut self,
5605 generator: &Gc<JsObject>,
5606 kind: ResumeKind,
5607 value: Value,
5608 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
5609 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
5610 ObjectKind::Generator(state) => Some(std::mem::replace(
5611 state.as_mut(),
5612 GeneratorState {
5613 frame: None,
5614 phase: GeneratorPhase::Executing,
5615 parked_on_await: false,
5616 parked_on_yield_star: false,
5617 requests: std::collections::VecDeque::new(),
5618 async_busy: false,
5619 },
5620 )),
5621 _ => None,
5622 }) else {
5623 return Err(self.type_error("not a generator"));
5624 };
5625 let result = self.step_generator(&mut state, kind, value);
5626 generator.with_mut(|data| {
5627 data.kind = ObjectKind::Generator(Box::new(state));
5628 });
5629 result
5630 }
5631
5632 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
5633 ///
5634 /// Returns the `{value, done}` object itself rather than the pair, because a
5635 /// `yield*` suspension already has one — the inner iterator's own result — and the
5636 /// protocol says to hand that straight through rather than nest it.
5637 pub fn resume_generator(
5638 &mut self,
5639 generator: &Gc<JsObject>,
5640 kind: ResumeKind,
5641 value: Value,
5642 ) -> JsResult<Value> {
5643 let (value, done, ready, _reason) =
5644 self.resume_generator_detailed(generator, kind, value)?;
5645 if ready {
5646 return Ok(value);
5647 }
5648 self.iterator_result(value, done)
5649 }
5650
5651 /// `next`/`return`/`throw` on an async generator, which answer a promise.
5652 ///
5653 /// The body is the same coroutine a sync generator runs; what changes is that an
5654 /// `await` inside it has to settle before the method can answer, so the step is
5655 /// driven off the job queue rather than returning inline.
5656 pub fn resume_async_generator(
5657 &mut self,
5658 generator: &Gc<JsObject>,
5659 kind: ResumeKind,
5660 value: Value,
5661 ) -> JsResult<Value> {
5662 let promise = self.new_promise();
5663 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
5664 // that order, and the second value must reach the *second* `yield`.
5665 let idle = generator.with_mut(|data| match &mut data.kind {
5666 ObjectKind::Generator(state) => {
5667 state.requests.push_back(AsyncRequest {
5668 kind,
5669 value,
5670 promise: promise.clone(),
5671 });
5672 !state.async_busy
5673 }
5674 _ => false,
5675 });
5676 if idle {
5677 self.next_async_request(generator)?;
5678 }
5679 Ok(Value::Object(promise))
5680 }
5681
5682 /// Serve the front queued request, if the generator is free to run one.
5683 ///
5684 /// A finished generator answers from the queue without running anything:
5685 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
5686 /// first, and `throw(e)` rejects.
5687 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
5688 enum Front {
5689 Idle,
5690 Run(ResumeKind, Value, Gc<JsObject>),
5691 Finished(ResumeKind, Value, Gc<JsObject>),
5692 }
5693 let front = generator.with_mut(|data| match &mut data.kind {
5694 ObjectKind::Generator(state) => {
5695 let Some(request) = state.requests.front() else {
5696 return Front::Idle;
5697 };
5698 // Busy means a request is still in flight — awaiting inside the body, not
5699 // finished. Serving another now would interleave two requests.
5700 if state.async_busy && state.phase != GeneratorPhase::Completed {
5701 return Front::Idle;
5702 }
5703 let kind = request.kind;
5704 let value = request.value.clone();
5705 let promise = request.promise.clone();
5706 state.async_busy = true;
5707 if state.phase == GeneratorPhase::Completed {
5708 Front::Finished(kind, value, promise)
5709 } else {
5710 Front::Run(kind, value, promise)
5711 }
5712 }
5713 _ => Front::Idle,
5714 });
5715 match front {
5716 Front::Idle => Ok(()),
5717 Front::Run(kind, value, promise) => {
5718 self.step_async_generator(generator, &promise, kind, value)
5719 }
5720 Front::Finished(kind, value, promise) => match kind {
5721 ResumeKind::Throw => {
5722 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
5723 }
5724 ResumeKind::Next | ResumeKind::Start => {
5725 let result = self.iterator_result(Value::Undefined, true)?;
5726 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
5727 }
5728 ResumeKind::Return => {
5729 // `js_async_generator_completed_return`: the value is awaited before it
5730 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
5731 // finished generator answers `1`, not a promise.
5732 let resolved = match self.promise_resolve_value(value) {
5733 Ok(resolved) => resolved,
5734 Err(Signal::Throw(reason)) => {
5735 return self.settle_async_request(
5736 generator,
5737 &promise,
5738 AsyncOutcome::Error(reason),
5739 );
5740 }
5741 Err(other) => return Err(other),
5742 };
5743 let done = JsObject::function(
5744 self.heap,
5745 Some(self.realm.function_proto.clone()),
5746 Callable::CompletedReturn {
5747 generator: generator.clone(),
5748 promise: promise.clone(),
5749 rejected: false,
5750 },
5751 );
5752 let failed = JsObject::function(
5753 self.heap,
5754 Some(self.realm.function_proto.clone()),
5755 Callable::CompletedReturn {
5756 generator: generator.clone(),
5757 promise: promise.clone(),
5758 rejected: true,
5759 },
5760 );
5761 let Value::Object(resolved) = resolved else {
5762 return self.settle_async_request(
5763 generator,
5764 &promise,
5765 AsyncOutcome::Error(Value::Undefined),
5766 );
5767 };
5768 self.perform_then(
5769 &resolved,
5770 Some(Value::Object(done)),
5771 Some(Value::Object(failed)),
5772 )?;
5773 Ok(())
5774 }
5775 },
5776 }
5777 }
5778
5779 /// Settle the front request and start the next one.
5780 ///
5781 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
5782 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
5783 /// generator would strand every later request.
5784 fn settle_async_request(
5785 &mut self,
5786 generator: &Gc<JsObject>,
5787 promise: &Gc<JsObject>,
5788 outcome: AsyncOutcome,
5789 ) -> JsResult<()> {
5790 let settled = generator.with_mut(|data| match &mut data.kind {
5791 ObjectKind::Generator(state) => {
5792 let front = state.requests.front();
5793 debug_assert!(
5794 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
5795 "a request settled outside its turn"
5796 );
5797 state.requests.pop_front();
5798 state.async_busy = false;
5799 true
5800 }
5801 _ => false,
5802 });
5803 if settled {
5804 match outcome {
5805 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
5806 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
5807 }
5808 }
5809 self.next_async_request(generator)
5810 }
5811
5812 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
5813 ///
5814 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
5815 /// disposer runs **synchronously** — the reference starts it before returning, which
5816 /// a test can observe by logging after the call — and the rest follow once their
5817 /// predecessor settles.
5818 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
5819 let promise = self.new_promise();
5820 let mut pairs = Vec::with_capacity(resources.len());
5821 for (value, method) in resources {
5822 let pair = self.new_array(vec![value, method]);
5823 pairs.push(Value::Object(pair));
5824 }
5825 let remaining = self.new_array(pairs);
5826 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
5827 Ok(Value::Object(promise))
5828 }
5829
5830 /// One link of the `disposeAsync` chain.
5831 ///
5832 /// Loops while the disposers finish synchronously, and parks on the first thenable it
5833 /// meets — pushing itself back in as the continuation, with the accumulated error
5834 /// carried along so a later failure can still be folded into the `SuppressedError`.
5835 fn dispose_step(
5836 &mut self,
5837 remaining: &Gc<JsObject>,
5838 promise: &Gc<JsObject>,
5839 mut error: Value,
5840 ) -> JsResult<()> {
5841 loop {
5842 let length = remaining.array_length().unwrap_or(0);
5843 if length == 0 {
5844 if matches!(error, Value::Uninitialized) {
5845 self.fulfill_promise(promise, Value::Undefined);
5846 } else {
5847 self.reject_promise(promise, error);
5848 }
5849 return Ok(());
5850 }
5851 let Some(Value::Object(pair)) = remaining
5852 .array_get(length - 1)
5853 .filter(|v| !matches!(v, Value::Hole))
5854 else {
5855 remaining.array_truncate(length - 1);
5856 continue;
5857 };
5858 remaining.array_truncate(length - 1);
5859 let value = pair.array_get(0).unwrap_or(Value::Undefined);
5860 let Some(Value::Object(method)) = pair.array_get(1) else {
5861 continue;
5862 };
5863 if !method.is_callable() {
5864 continue;
5865 }
5866 match self.call_value(Value::Object(method), value, Vec::new()) {
5867 Ok(result) => {
5868 if !self.is_thenable(&result)? {
5869 // Finished synchronously; the next disposer is the next iteration.
5870 continue;
5871 }
5872 let awaited = match self.promise_resolve_value(result) {
5873 Ok(awaited) => awaited,
5874 Err(Signal::Throw(reason)) => {
5875 self.reject_promise(promise, reason);
5876 return Ok(());
5877 }
5878 Err(other) => return Err(other),
5879 };
5880 let Value::Object(awaited) = awaited else {
5881 continue;
5882 };
5883 let ok = JsObject::function(
5884 self.heap,
5885 Some(self.realm.function_proto.clone()),
5886 Callable::DisposeStep {
5887 remaining: remaining.clone(),
5888 promise: promise.clone(),
5889 error: error.clone(),
5890 rejected: false,
5891 },
5892 );
5893 let failed = JsObject::function(
5894 self.heap,
5895 Some(self.realm.function_proto.clone()),
5896 Callable::DisposeStep {
5897 remaining: remaining.clone(),
5898 promise: promise.clone(),
5899 error,
5900 rejected: true,
5901 },
5902 );
5903 self.perform_then(
5904 &awaited,
5905 Some(Value::Object(ok)),
5906 Some(Value::Object(failed)),
5907 )?;
5908 return Ok(());
5909 }
5910 Err(Signal::Throw(thrown)) => {
5911 error = self.merge_dispose_error(thrown, error);
5912 }
5913 Err(other) => return Err(other),
5914 }
5915 }
5916 }
5917
5918 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
5919 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
5920 let Value::Object(object) = value else {
5921 return Ok(false);
5922 };
5923 Ok(matches!(
5924 self.get_property(object, "then")?,
5925 Some(Value::Object(then)) if then.is_callable()
5926 ))
5927 }
5928
5929 /// One step of an async generator, settling `promise` with an `{value, done}` result.
5930 fn step_async_generator(
5931 &mut self,
5932 generator: &Gc<JsObject>,
5933 promise: &Gc<JsObject>,
5934 kind: ResumeKind,
5935 value: Value,
5936 ) -> JsResult<()> {
5937 let stepped = self.resume_generator_detailed(generator, kind, value);
5938 let (value, done, ready, reason) = match stepped {
5939 Ok(stepped) => stepped,
5940 Err(Signal::Throw(reason)) => {
5941 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
5942 }
5943 Err(other) => return Err(other),
5944 };
5945 // Only an `await` has to wait before the method can answer.
5946 if !done && reason == Some(SuspendKind::Await) {
5947 let awaited = match self.promise_resolve_value(value) {
5948 Ok(awaited) => awaited,
5949 Err(Signal::Throw(reason)) => {
5950 return self.settle_async_request(
5951 generator,
5952 promise,
5953 AsyncOutcome::Error(reason),
5954 );
5955 }
5956 Err(other) => return Err(other),
5957 };
5958 let Value::Object(awaited) = awaited else {
5959 return Ok(());
5960 };
5961 let resumed = JsObject::function(
5962 self.heap,
5963 Some(self.realm.function_proto.clone()),
5964 Callable::GeneratorResume {
5965 generator: generator.clone(),
5966 promise: promise.clone(),
5967 kind: ResumeKind::Next,
5968 },
5969 );
5970 let raised = JsObject::function(
5971 self.heap,
5972 Some(self.realm.function_proto.clone()),
5973 Callable::GeneratorResume {
5974 generator: generator.clone(),
5975 promise: promise.clone(),
5976 kind: ResumeKind::Throw,
5977 },
5978 );
5979 self.perform_then(
5980 &awaited,
5981 Some(Value::Object(resumed)),
5982 Some(Value::Object(raised)),
5983 )?;
5984 return Ok(());
5985 }
5986 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
5987 // completes it — both arrive as the settled value rather than as the promise
5988 // object. A plain value skips the round trip, which is also what keeps `yield 1`
5989 // from costing an extra tick.
5990 let awaits_value = self.is_thenable(&value)?;
5991 if awaits_value {
5992 let awaited = match self.promise_resolve_value(value) {
5993 Ok(awaited) => awaited,
5994 Err(Signal::Throw(reason)) => {
5995 return self.settle_async_request(
5996 generator,
5997 promise,
5998 AsyncOutcome::Error(reason),
5999 );
6000 }
6001 Err(other) => return Err(other),
6002 };
6003 let Value::Object(awaited) = awaited else {
6004 return Ok(());
6005 };
6006 // A rejected yield throws *at the yield* inside the body, so the rejection
6007 // resumes the generator rather than the method's promise.
6008 let answer = JsObject::function(
6009 self.heap,
6010 Some(self.realm.function_proto.clone()),
6011 Callable::YieldResult {
6012 generator: generator.clone(),
6013 promise: promise.clone(),
6014 done,
6015 },
6016 );
6017 let raise = JsObject::function(
6018 self.heap,
6019 Some(self.realm.function_proto.clone()),
6020 Callable::GeneratorResume {
6021 generator: generator.clone(),
6022 promise: promise.clone(),
6023 kind: ResumeKind::Throw,
6024 },
6025 );
6026 self.perform_then(
6027 &awaited,
6028 Some(Value::Object(answer)),
6029 Some(Value::Object(raise)),
6030 )?;
6031 return Ok(());
6032 }
6033 let result = if ready {
6034 // `yield*` handed back the inner iterator's own result object.
6035 value
6036 } else {
6037 self.iterator_result(value, done)?
6038 };
6039 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
6040 }
6041
6042 /// The `{value, done}` object an iterator method answers with.
6043 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
6044 let result = self.new_object(Some(self.realm.object_proto.clone()));
6045 result.define_data("value", value);
6046 result.define_data("done", Value::Bool(done));
6047 Ok(Value::Object(result))
6048 }
6049
6050 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
6051 fn step_generator(
6052 &mut self,
6053 state: &mut GeneratorState,
6054 kind: ResumeKind,
6055 value: Value,
6056 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
6057 match state.phase {
6058 GeneratorPhase::Executing => {
6059 return Err(self.type_error("cannot invoke a running generator"));
6060 }
6061 GeneratorPhase::Completed => {
6062 // A finished generator answers every resumption without running.
6063 return Ok(match kind {
6064 ResumeKind::Throw => return Err(Signal::Throw(value)),
6065 ResumeKind::Return => (value, true, false, None),
6066 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
6067 });
6068 }
6069 GeneratorPhase::SuspendedStart => {
6070 if kind != ResumeKind::Next && kind != ResumeKind::Start {
6071 // The body never started, so there is nothing to unwind or return
6072 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
6073 state.frame = None;
6074 state.phase = GeneratorPhase::Completed;
6075 return Ok(match kind {
6076 ResumeKind::Throw => return Err(Signal::Throw(value)),
6077 _ => (value, true, false, None),
6078 });
6079 }
6080 }
6081 GeneratorPhase::SuspendedYield => {}
6082 }
6083
6084 let Some(mut frame) = state.frame.take() else {
6085 return Ok((Value::Undefined, true, false, None));
6086 };
6087 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
6088 // number that says which method resumed it; the emitted `if_false` branches on
6089 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
6090 let mut raised = None;
6091 match kind {
6092 ResumeKind::Next | ResumeKind::Start => {
6093 if state.phase == GeneratorPhase::SuspendedYield {
6094 frame.stack.push(value);
6095 // An `await` resumes with its value alone; only a `yield` gets the
6096 // magic number that says which of `next`/`return` resumed it.
6097 if !state.parked_on_await {
6098 frame.stack.push(Value::Int(RESUME_NEXT));
6099 }
6100 }
6101 }
6102 ResumeKind::Return => {
6103 // A `return` on a not-yet-started generator is handled above, so this is
6104 // always a real resumption.
6105 frame.stack.push(value);
6106 frame.stack.push(Value::Int(RESUME_RETURN));
6107 }
6108 ResumeKind::Throw => {
6109 // At a `yield*` the exception is *data* for the delegation: the compiled
6110 // code resumes with the value and magic `2` and calls the inner iterator's
6111 // `throw`. Everywhere else it is raised at the suspension point, so the
6112 // body's own handler sees it.
6113 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
6114 frame.stack.push(value);
6115 frame.stack.push(Value::Int(RESUME_THROW));
6116 } else {
6117 raised = Some(value);
6118 }
6119 }
6120 }
6121 state.phase = GeneratorPhase::Executing;
6122
6123 let depth = self.frames.len();
6124 self.frames.push(frame);
6125 // A `throw` unwinds from where the frame parked, exactly as if the exception had
6126 // happened at the `yield`.
6127 if let Some(exception) = raised {
6128 if self.catch_here(exception.clone()).is_none() {
6129 self.frames.pop();
6130 state.phase = GeneratorPhase::Completed;
6131 return Err(Signal::Throw(exception));
6132 }
6133 }
6134
6135 // Only the generator's *own* frame ends the generator. The body may call ordinary
6136 // functions, and those push frames of their own: a `Step::Return` from one of them
6137 // is a nested call finishing, not the generator completing. Miscounting that is
6138 // silent — the generator reports the callee's value as its own result and marks
6139 // itself done — so the depth comparison is load-bearing, not defensive.
6140 let own_frame = depth + 1;
6141 loop {
6142 match self.step() {
6143 Ok(Step::Continue) => {}
6144 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
6145 let mut frame = self.frames.pop().expect("a frame is live");
6146 // `yield` left the value on the stack; `initial_yield` left nothing.
6147 let yielded = if reason == SuspendKind::Initial {
6148 Value::Undefined
6149 } else {
6150 frame.stack.pop().unwrap_or(Value::Undefined)
6151 };
6152 state.frame = Some(frame);
6153 state.parked_on_await = reason == SuspendKind::Await;
6154 state.parked_on_yield_star =
6155 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
6156 state.phase = if reason == SuspendKind::Initial {
6157 GeneratorPhase::SuspendedStart
6158 } else {
6159 GeneratorPhase::SuspendedYield
6160 };
6161 // `yield*` hands the inner iterator's own result object straight
6162 // back, so the caller sees one `{value, done}` rather than a nested
6163 // one — which is why the third field says "already a result".
6164 return Ok((
6165 yielded,
6166 false,
6167 reason == SuspendKind::YieldStar,
6168 Some(reason),
6169 ));
6170 }
6171 Ok(Step::Suspend(_)) => {
6172 // A `yield` in a frame other than the generator's would mean a
6173 // generator body entered as an ordinary call, which
6174 // `call_or_push` prevents.
6175 self.unwind_to(depth);
6176 state.phase = GeneratorPhase::Completed;
6177 return Err(Signal::Throw(self.make_error(
6178 "InternalError",
6179 "a generator body ran as an ordinary call",
6180 )));
6181 }
6182 Ok(Step::Return(value)) => {
6183 self.frames.pop();
6184 if self.frames.len() > depth {
6185 // A nested call finished: hand the value back to its caller and
6186 // keep running the generator body.
6187 self.frames
6188 .last_mut()
6189 .expect("a caller is live")
6190 .stack
6191 .push(value);
6192 continue;
6193 }
6194 state.phase = GeneratorPhase::Completed;
6195 // The reference closes the generator's closure variables here; ours
6196 // live in cells the frame owned, which the drop below releases.
6197 return Ok((value, true, false, None));
6198 }
6199 Err(Signal::Throw(exception)) => {
6200 // The frame that threw gets the first chance to catch, exactly as in
6201 // the ordinary call loop; a frame above the generator's is popped and
6202 // the exception carries on down.
6203 let exception = exception;
6204 loop {
6205 if self.frames.len() <= depth {
6206 // The generator's own frame is gone, so nothing here caught it.
6207 state.phase = GeneratorPhase::Completed;
6208 return Err(Signal::Throw(exception));
6209 }
6210 if self.catch_here(exception.clone()).is_some() {
6211 break;
6212 }
6213 self.frames.pop();
6214 }
6215 }
6216 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
6217 }
6218 }
6219 }
6220
6221 /// Pop frames until `depth` are left.
6222 fn unwind_to(&mut self, depth: usize) {
6223 self.frames.truncate(depth);
6224 }
6225 fn call_or_push(
6226 &mut self,
6227 callee: Value,
6228 this: Value,
6229 args: Vec<Value>,
6230 ) -> JsResult<Option<Value>> {
6231 if let Value::Object(function) = &callee
6232 && let Some((code, env)) = bytecode_of(function)
6233 {
6234 // Calling a generator function does not run anything: it captures the
6235 // arguments in a frame and hands back the generator object.
6236 if code.code.kind.is_generator() {
6237 return self.new_generator(callee, this, args).map(Some);
6238 }
6239 // An async function answers a promise and runs its body as a coroutine, so it
6240 // takes the same path as a plain call into it.
6241 if code.code.kind.is_async() {
6242 return self.new_async_function(callee, this, args).map(Some);
6243 }
6244 self.push_frame(code, env, this, args, callee)?;
6245 return Ok(None);
6246 }
6247 self.call_value(callee, this, args).map(Some)
6248 }
6249
6250 /// `new callee(args)`.
6251 ///
6252 /// A constructor differs from a plain call in three ways: it gets a fresh object
6253 /// as `this` whose prototype is the constructor's `prototype` property, its
6254 /// return value is *replaced* by that object unless it returns an object itself,
6255 /// and a native constructor is expected to initialise the object it is given
6256 /// rather than build one.
6257 pub fn construct(
6258 &mut self,
6259 callee: Value,
6260 new_target: Value,
6261 args: Vec<Value>,
6262 ) -> JsResult<Value> {
6263 // `new` on a bound function constructs its *target*, prepending the arguments
6264 // the bind fixed and ignoring the bound `this` — a bound function is a
6265 // constructor only when its target is one, and `new` always makes a fresh
6266 // object of the target's prototype rather than reusing the bound receiver.
6267 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
6268 // ran the body with `this === null` and threw on `this.x = a`.
6269 let mut callee = callee;
6270 let mut new_target = new_target;
6271 let mut args = args;
6272 loop {
6273 let Some(object) = callee.as_object().cloned() else {
6274 return Err(Signal::Throw(
6275 self.make_error("TypeError", "not a constructor"),
6276 ));
6277 };
6278 // A proxy of a function constructs through its `construct` trap, and the
6279 // trap's answer is the result directly — no fresh object is made here.
6280 if object.proxy_state().is_some() {
6281 return match self.proxy_construct(&object, args, &new_target)? {
6282 Some(result) => Ok(result),
6283 None => Err(Signal::Throw(
6284 self.make_error("TypeError", "proxy target is not a constructor"),
6285 )),
6286 };
6287 }
6288 // A generator function has no `[[Construct]]`, and the reference names it in
6289 // the message: `new (function* G(){})()` reports "G is not a constructor".
6290 if object.with(|data| match &data.kind {
6291 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
6292 code.code.kind.is_generator()
6293 }
6294 _ => false,
6295 }) {
6296 let name = object
6297 .own_property("name")
6298 .and_then(|property| property.value)
6299 .map(|value| value.to_js_string())
6300 .unwrap_or_default();
6301 return Err(Signal::Throw(
6302 self.make_error("TypeError", &format!("{name} is not a constructor")),
6303 ));
6304 }
6305 let bound = object.with(|data| match &data.kind {
6306 ObjectKind::Function(Callable::Bound {
6307 target,
6308 args: leading,
6309 ..
6310 }) => Some((target.clone(), leading.clone())),
6311 _ => None,
6312 });
6313 let Some((target, leading)) = bound else {
6314 // Not a bound function, so this object is the callee. §7.2.4
6315 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
6316 // refusals above cover only the built-ins the reference also refuses by
6317 // name. Everything else — a method, an arrow, an async function — has no
6318 // `[[Construct]]` either, and answering "yes" here made
6319 // `new (Array.prototype.map)` build an object instead of throwing.
6320 if !object.is_constructor() {
6321 let name = object
6322 .own_property("name")
6323 .and_then(|property| property.value)
6324 .map(|value| value.to_js_string())
6325 .unwrap_or_default();
6326 return Err(Signal::Throw(
6327 self.make_error("TypeError", &format!("{name} is not a constructor")),
6328 ));
6329 }
6330 break;
6331 };
6332 let mut all = leading;
6333 all.extend(args);
6334 args = all;
6335 // A bound function that is its own `new.target` stands in for its target:
6336 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
6337 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
6338 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
6339 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
6340 _ => false,
6341 };
6342 if same_wrapper {
6343 new_target = target.clone();
6344 }
6345 callee = target;
6346 }
6347 let Value::Object(function) = &callee else {
6348 unreachable!("the loop above only breaks on an object");
6349 };
6350 // The fresh object's prototype comes from `new.target`, not from the callee: a
6351 // derived constructor reaches here through `super()`, and the instance must be a
6352 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
6353 // an object inheriting `D.prototype` rather than `C.prototype`.
6354 let prototype_source = match new_target.as_object() {
6355 Some(target) => target.clone(),
6356 None => function.clone(),
6357 };
6358 // A native constructor builds its own instance, through `new_ctor_instance`, once it
6359 // has validated its arguments. Pre-building one here would read
6360 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
6361 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
6362 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
6363 let is_native = function.native_creates_own_instance();
6364 let this = if is_native {
6365 Value::Undefined
6366 } else {
6367 let prototype = self.get_property(&prototype_source, "prototype")?;
6368 let prototype = match prototype {
6369 Some(Value::Object(proto)) => Some(proto),
6370 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
6371 // object, the answer is the realm's *intrinsic* prototype for this
6372 // constructor, not `%Object.prototype%`.
6373 _ => {
6374 let fallback = self.get_property(function, "prototype")?;
6375 match fallback {
6376 Some(Value::Object(proto)) => Some(proto),
6377 _ => Some(self.realm.object_proto.clone()),
6378 }
6379 }
6380 };
6381 Value::Object(self.new_object(prototype))
6382 };
6383 // `new.target` inside the body is the constructor that was written, so a bound
6384 // function's target sees itself rather than the bound wrapper.
6385 //
6386 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
6387 // `?`, so assigning `None` after the call would be skipped and the failed
6388 // `new.target` would stay visible to every later native call. The symptom was a
6389 // native constructor refusing a plain call — `var s = Symbol(); new
6390 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
6391 // "FinalizationRegistry is not a constructor".
6392 let outer_new_target = self.pending_new_target.replace(new_target);
6393 let result = self.call_value(callee, this.clone(), args);
6394 self.pending_new_target = outer_new_target;
6395 let result = result?;
6396 // A constructor that returns an object overrides `this`; any other return
6397 // value (including `undefined`) is ignored.
6398 Ok(match result {
6399 Value::Object(_) => result,
6400 _ => this,
6401 })
6402 }
6403
6404 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
6405 ///
6406 /// The error classes themselves arrive with the builtins milestone; what
6407 /// matters here is that the thrown value stringifies the way a script printing
6408 /// the caught value expects.
6409 pub fn make_error(&self, name: &str, message: &str) -> Value {
6410 let proto = self
6411 .realm
6412 .errors
6413 .get(name)
6414 .map(|constructor| self.prototype_of(constructor))
6415 .unwrap_or_else(|| self.realm.error_proto.clone());
6416 let error = self.new_object(Some(proto));
6417 // `name` and `message` are own properties of the instance, which is what
6418 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
6419 // `Error`.
6420 error.define(
6421 "name",
6422 Property::with_attributes(self.string(name), true, false),
6423 );
6424 error.define(
6425 "message",
6426 Property::with_attributes(self.string(message), true, false),
6427 );
6428 // The internal class, which is what tells a printer this is an error rather than a
6429 // plain object with `name` and `message` properties. The constructor path sets it
6430 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
6431 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
6432 // literally `"Error"` in both places — the *name* is read from `name`, which is why
6433 // a `RangeError` still prints as `RangeError`.
6434 self.internal_set(&error, "_class", self.string("Error"));
6435 // The trace is captured where the error is *made*, which is where the reference
6436 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
6437 // way out, so a caught engine error already has its stack even if the handler
6438 // never rethrows it.
6439 self.add_stack(&error);
6440 Value::Object(error)
6441 }
6442
6443 /// Give an error object its `stack` property, from the current frame stack.
6444 ///
6445 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
6446 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
6447 /// `stack` a script set, is not rewritten.
6448 pub fn add_stack(&self, object: &Gc<JsObject>) {
6449 self.add_stack_skipping(object, 0);
6450 }
6451
6452 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
6453 ///
6454 /// An `Error` constructor passes 1: the reference builds those traces with
6455 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
6456 /// constructor itself, while a `RangeError` raised inside `toISOString` does
6457 /// report `at toISOString (native)`.
6458 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
6459 if object.has_own("stack") {
6460 return;
6461 }
6462 let trace = self.stack_trace_skipping(skip);
6463 let text = self.string(trace);
6464 object.define("stack", Property::with_attributes(text, true, true));
6465 }
6466
6467 /// The function object currently being called, if any.
6468 ///
6469 /// A native function is a bare `fn` pointer, so it cannot capture which class
6470 /// it belongs to; it reads that from the callee instead. This is also what a
6471 /// stack trace would use.
6472 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
6473 match &self.frames.last()?.callee {
6474 Value::Object(object) => Some(object.clone()),
6475 _ => None,
6476 }
6477 }
6478
6479 /// The `prototype` property of a constructor, falling back to
6480 /// `Object.prototype` for anything that is not shaped like one.
6481 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
6482 constructor
6483 .own_property("prototype")
6484 .and_then(|property| property.value)
6485 .and_then(|value| value.as_object().cloned())
6486 .unwrap_or_else(|| self.realm.object_proto.clone())
6487 }
6488
6489 /// Throw a `TypeError` carrying `message`.
6490 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
6491 Signal::Throw(self.make_error("TypeError", message.as_ref()))
6492 }
6493
6494 /// Throw a `RangeError` carrying `message`.
6495 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
6496 Signal::Throw(self.make_error("RangeError", message.as_ref()))
6497 }
6498
6499 /// The `ReferenceError` a read of an uninitialised binding raises.
6500 /// The name of the binding `slot` refers to, for an error message.
6501 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
6502 match kind {
6503 VarSlot::Loc => self
6504 .frame()
6505 .code
6506 .code
6507 .vars
6508 .get(slot)
6509 .map(|v| v.name.clone()),
6510 VarSlot::Closure => self
6511 .frame()
6512 .code
6513 .code
6514 .closure_vars
6515 .get(slot)
6516 .map(|c| c.name.clone()),
6517 }
6518 .unwrap_or_default()
6519 }
6520
6521 /// Whether `slot` names a `const` binding, which rejects every store after its
6522 /// initialiser.
6523 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
6524 match kind {
6525 VarSlot::Loc => self
6526 .frame()
6527 .code
6528 .code
6529 .vars
6530 .get(slot)
6531 .is_some_and(|v| v.is_const),
6532 VarSlot::Closure => self
6533 .frame()
6534 .code
6535 .code
6536 .closure_vars
6537 .get(slot)
6538 .is_some_and(|c| c.is_const),
6539 }
6540 }
6541
6542 /// The `TypeError` a store to a `const` binding raises.
6543 ///
6544 /// `const` is enforced here rather than at compile time because the binding can be
6545 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
6546 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
6547 /// both halves of what "checked store" means: the dead zone is over, and the
6548 /// binding is writable.
6549 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
6550 let name = self.binding_name(slot, kind);
6551 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6552 }
6553
6554 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
6555 let name = match kind {
6556 VarSlot::Loc => self
6557 .frame()
6558 .code
6559 .code
6560 .vars
6561 .get(slot)
6562 .map(|v| v.name.clone()),
6563 VarSlot::Closure => self
6564 .frame()
6565 .code
6566 .code
6567 .closure_vars
6568 .get(slot)
6569 .map(|c| c.name.clone()),
6570 }
6571 .unwrap_or_default();
6572 Signal::Throw(self.make_error(
6573 "ReferenceError",
6574 &format!("cannot access '{name}' before initialization"),
6575 ))
6576 }
6577
6578 fn throw_reference(&self, name: &str) -> Signal {
6579 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
6580 }
6581
6582 // -- the instruction loop -----------------------------------------------
6583
6584 fn step(&mut self) -> JsResult<Step> {
6585 let pc = self.frame().pc;
6586 let code = self.frame().code.clone();
6587 let bytes = &code.code.code;
6588 if pc >= bytes.len() {
6589 return Ok(Step::Return(Value::Undefined));
6590 }
6591 let Some(decoded) = decode(bytes, pc) else {
6592 return Err(Signal::Throw(
6593 self.make_error("InternalError", "undecodable bytecode"),
6594 ));
6595 };
6596 let (op, a, b, next) = decoded;
6597 self.frame_mut().at = pc;
6598 self.frame_mut().pc = next;
6599 self.execute_instruction(op, a, b, next)
6600 }
6601
6602 fn push(&mut self, value: Value) {
6603 self.frame_mut().stack.push(value);
6604 }
6605
6606 fn pop(&mut self) -> Value {
6607 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
6608 }
6609
6610 fn pop_n(&mut self, count: usize) -> Vec<Value> {
6611 let frame = self.frame_mut();
6612 let start = frame.stack.len().saturating_sub(count);
6613 frame.stack.split_off(start)
6614 }
6615
6616 fn peek(&self, back: usize) -> Value {
6617 let frame = self.frame();
6618 frame
6619 .stack
6620 .get(frame.stack.len().wrapping_sub(1 + back))
6621 .cloned()
6622 .unwrap_or(Value::Undefined)
6623 }
6624
6625 #[allow(clippy::too_many_lines)]
6626 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
6627 use Opcode::*;
6628 match op {
6629 // -- constants and stack shuffling -----------------------------
6630 Nop => {}
6631 PushMinus1 => self.push(Value::Int(-1)),
6632 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
6633 let value = match op {
6634 Push0 => 0,
6635 Push1 => 1,
6636 Push2 => 2,
6637 Push3 => 3,
6638 Push4 => 4,
6639 Push5 => 5,
6640 Push6 => 6,
6641 _ => 7,
6642 };
6643 self.push(Value::Int(value));
6644 }
6645 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
6646 PushBigintI32 => {
6647 // The immediate form of a `BigInt` literal; the reference has the same
6648 // split between this and a constant-pool entry.
6649 let value = crate::bigint::BigInt::from_i64(a as i64);
6650 self.push(self.bigint(value));
6651 }
6652 PushTrue => self.push(Value::Bool(true)),
6653 PushFalse => self.push(Value::Bool(false)),
6654 PushEmptyString => self.push(self.string("")),
6655 Undefined => self.push(Value::Undefined),
6656 Null => self.push(Value::Null),
6657 Object => {
6658 let proto = self.realm.object_proto.clone();
6659 self.push(Value::Object(self.new_object(Some(proto))));
6660 }
6661 PushThis => {
6662 let this = self.frame().this.clone();
6663 self.push(this);
6664 }
6665 PushConst | PushConst8 => {
6666 let value = self.constant(a as usize)?;
6667 self.push(value);
6668 }
6669 PushAtomValue => {
6670 let text = self.atom_text(a as usize);
6671 self.push(self.string(text));
6672 }
6673 Dup => {
6674 let value = self.peek(0);
6675 self.push(value);
6676 }
6677 Dup2 => {
6678 // `a b -> a b a b`
6679 let b = self.peek(0);
6680 let a = self.peek(1);
6681 self.push(a);
6682 self.push(b);
6683 }
6684 Dup3 => {
6685 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
6686 // prototype and key while reading the current value through them.
6687 let c = self.peek(0);
6688 let b = self.peek(1);
6689 let a = self.peek(2);
6690 self.push(a);
6691 self.push(b);
6692 self.push(c);
6693 }
6694 Swap => {
6695 // `a b -> b a`
6696 let bottom = self.pop();
6697 let top = self.pop();
6698 self.push(bottom);
6699 self.push(top);
6700 }
6701 Perm3 => {
6702 // `a b c -> b a c`, the reference's reordering for a spread method
6703 // call: `obj func array` becomes the `func this array` that `apply`
6704 // takes.
6705 let c = self.pop();
6706 let b = self.pop();
6707 let a = self.pop();
6708 self.push(b);
6709 self.push(a);
6710 self.push(c);
6711 }
6712 Dup1 => {
6713 let value = self.peek(1);
6714 self.push(value);
6715 }
6716 Drop => {
6717 self.pop();
6718 }
6719 Nip => {
6720 // `a b -> b`
6721 let top = self.pop();
6722 self.pop();
6723 self.push(top);
6724 }
6725 Perm4 => {
6726 // `obj prop a b -> a obj prop b`, the reference's reordering for a
6727 // postfix update of a computed element: it puts the *old* value
6728 // underneath the receiver and key so `put_array_el` can consume them
6729 // and leave the old value as the expression's result.
6730 let d = self.pop();
6731 let c = self.pop();
6732 let b = self.pop();
6733 let a = self.pop();
6734 self.push(c);
6735 self.push(a);
6736 self.push(b);
6737 self.push(d);
6738 }
6739 Insert2 => {
6740 // `obj a -> a obj a`
6741 let value = self.pop();
6742 let object = self.pop();
6743 self.push(value.clone());
6744 self.push(object);
6745 self.push(value);
6746 }
6747 Insert3 => {
6748 // `obj prop a -> a obj prop a`
6749 let value = self.pop();
6750 let key = self.pop();
6751 let object = self.pop();
6752 self.push(value.clone());
6753 self.push(object);
6754 self.push(key);
6755 self.push(value);
6756 }
6757 Insert4 => {
6758 // `this obj prop a -> a this obj prop a`
6759 //
6760 // `put_super_value` consumes all four and yields nothing, so the copy
6761 // underneath is what leaves the assignment an expression value.
6762 let value = self.pop();
6763 let key = self.pop();
6764 let object = self.pop();
6765 let receiver = self.pop();
6766 self.push(value.clone());
6767 self.push(receiver);
6768 self.push(object);
6769 self.push(key);
6770 self.push(value);
6771 }
6772 Swap2 => {
6773 // `a b c d -> c d a b`
6774 let d = self.pop();
6775 let c = self.pop();
6776 let b = self.pop();
6777 let a = self.pop();
6778 self.push(c);
6779 self.push(d);
6780 self.push(a);
6781 self.push(b);
6782 }
6783 Rot3l => {
6784 // `x a b -> a b x`
6785 let b = self.pop();
6786 let a = self.pop();
6787 let x = self.pop();
6788 self.push(a);
6789 self.push(b);
6790 self.push(x);
6791 }
6792 Rot3r => {
6793 // `a b c -> c a b`
6794 let c = self.pop();
6795 let b = self.pop();
6796 let a_value = self.pop();
6797 self.push(c);
6798 self.push(a_value);
6799 self.push(b);
6800 }
6801
6802 Rest => {
6803 // `...rest` in a parameter list: the arguments from index `a` on, as a
6804 // real array. It takes nothing off the stack — the arguments are in the
6805 // frame, not on it.
6806 let frame = self.frame();
6807 let from = a as usize;
6808 let collected: Vec<Value> = frame.passed.iter().skip(from).cloned().collect();
6809 let array = self.new_array(collected);
6810 self.push(Value::Object(array));
6811 }
6812
6813 // -- slots ------------------------------------------------------
6814 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
6815 let slot = self.slot_operand(op, a);
6816 let value = self.get_loc(slot);
6817 self.push(value);
6818 }
6819 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
6820 let slot = self.slot_operand(op, a);
6821 let value = self.pop();
6822 self.put_loc(slot, value);
6823 }
6824 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
6825 let slot = self.slot_operand(op, a);
6826 let value = self.pop();
6827 self.put_loc(slot, value.clone());
6828 self.push(value);
6829 }
6830 // The `_check` forms are the temporal dead zone: they throw when the
6831 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
6832 // *reads*, so only the two writes may pop — mishandling that quietly
6833 // consumes the value the caller pushed just before.
6834 GetLocCheck => {
6835 let slot = self.slot_operand(op, a);
6836 let value = self.get_loc(slot);
6837 if matches!(value, Value::Uninitialized) {
6838 return Err(self.dead_zone(slot, VarSlot::Loc));
6839 }
6840 self.push(value);
6841 }
6842 PutLocCheck | SetLocCheck => {
6843 let slot = self.slot_operand(op, a);
6844 let value = self.pop();
6845 if matches!(value, Value::Uninitialized) {
6846 return Err(self.dead_zone(slot, VarSlot::Loc));
6847 }
6848 // The initialiser goes through `put_loc`, not this, so any store that
6849 // reaches here is a later assignment — which a `const` refuses.
6850 if self.is_read_only(slot, VarSlot::Loc) {
6851 return Err(self.read_only(slot, VarSlot::Loc));
6852 }
6853 if op == SetLocCheck {
6854 self.put_loc(slot, value.clone());
6855 self.push(value);
6856 } else {
6857 self.put_loc(slot, value);
6858 }
6859 }
6860 PutLocCheckInit => {
6861 // The one store that *initialises* a lexical slot: `this` in a derived
6862 // constructor, which only exists after `super()` has run. A second
6863 // initialisation is the error the reference reports as
6864 // "'this' can be initialized only once".
6865 let slot = self.slot_operand(op, a);
6866 let value = self.pop();
6867 if !matches!(self.get_loc(slot), Value::Uninitialized) {
6868 return Err(Signal::Throw(self.make_error(
6869 "ReferenceError",
6870 "'this' can be initialized only once",
6871 )));
6872 }
6873 self.put_loc(slot, value);
6874 }
6875 CheckCtor => {
6876 // A class constructor may only run under `new`, which is what makes
6877 // `class A {}; A()` a TypeError.
6878 if matches!(self.frame().new_target, Value::Undefined) {
6879 return Err(Signal::Throw(self.make_error(
6880 "TypeError",
6881 "class constructors must be invoked with 'new'",
6882 )));
6883 }
6884 }
6885 InitCtor => {
6886 // The body a derived class gets when it declares no constructor:
6887 // forward every argument to the parent constructor, keeping `new.target`.
6888 if matches!(self.frame().new_target, Value::Undefined) {
6889 return Err(Signal::Throw(self.make_error(
6890 "TypeError",
6891 "class constructors must be invoked with 'new'",
6892 )));
6893 }
6894 let Some(callee) = self.current_callee() else {
6895 return Err(Signal::Throw(
6896 self.make_error("TypeError", "no constructor to inherit from"),
6897 ));
6898 };
6899 let parent = callee.proto().map_or(Value::Null, Value::Object);
6900 let new_target = self.frame().new_target.clone();
6901 let args = self.frame().passed.clone();
6902 let result = self.construct(parent, new_target, args)?;
6903 self.push(result);
6904 }
6905 SetLocUninitialized => {
6906 let slot = self.slot_operand(op, a);
6907 self.put_loc(slot, Value::Uninitialized);
6908 }
6909 CloseLoc => {
6910 // "Close" a binding: give it a *fresh* cell holding the current
6911 // value. Closures created before this point keep the old cell and the
6912 // ones created after see the new one, which is what makes every
6913 // iteration of `for (let i ...)` capture its own `i`, and what freezes
6914 // a block-scoped binding when the block ends.
6915 //
6916 // Clearing the slot instead (which this used to do) broke both: a
6917 // closure over a captured block variable read `undefined`, and a loop
6918 // terminated after one iteration.
6919 let slot = self.slot_operand(op, a);
6920 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
6921 if index >= 0 {
6922 let current = self.frame().cells[index as usize].get();
6923 let fresh = self.new_cell(current);
6924 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
6925 *cell = fresh;
6926 }
6927 }
6928 }
6929 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
6930 let slot = self.slot_operand(op, a);
6931 let value = self.get_arg(slot);
6932 self.push(value);
6933 }
6934 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
6935 let slot = self.slot_operand(op, a);
6936 let value = self.pop();
6937 self.put_arg(slot, value);
6938 }
6939 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
6940 let slot = self.slot_operand(op, a);
6941 let value = self.pop();
6942 self.put_arg(slot, value.clone());
6943 self.push(value);
6944 }
6945
6946 // -- closure variables ------------------------------------------
6947 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
6948 let slot = self.slot_operand(op, a);
6949 // A name a direct `eval` created shadows the binding the compiler chose.
6950 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
6951 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
6952 // and only a runtime lookup can know that.
6953 if let Some(cell) = self.eval_created_local(slot) {
6954 self.push(cell.get());
6955 return self.step();
6956 }
6957 let value = self.cell_value(slot)?;
6958 self.push(value);
6959 }
6960 GetVarRefCheck => {
6961 let slot = self.slot_operand(op, a);
6962 let value = self.cell_value(slot)?;
6963 if matches!(value, Value::Uninitialized) {
6964 return Err(self.dead_zone(slot, VarSlot::Closure));
6965 }
6966 self.push(value);
6967 }
6968 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
6969 let slot = self.slot_operand(op, a);
6970 let value = self.pop();
6971 if let Some(cell) = self.eval_created_local(slot) {
6972 cell.set(value);
6973 return self.step();
6974 }
6975 // Same rule as `PutLocCheck`: a checked store to a captured binding
6976 // refuses a `const` once its initialiser has run.
6977 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
6978 return Err(self.read_only(slot, VarSlot::Closure));
6979 }
6980 self.set_cell(slot, value)?;
6981 }
6982 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
6983 let slot = self.slot_operand(op, a);
6984 let value = self.pop();
6985 if let Some(cell) = self.eval_created_local(slot) {
6986 cell.set(value.clone());
6987 self.push(value);
6988 return self.step();
6989 }
6990 self.set_cell(slot, value.clone())?;
6991 self.push(value);
6992 }
6993
6994 // -- globals ----------------------------------------------------
6995 GetVar => {
6996 let value = self.get_global(a as usize)?;
6997 self.push(value);
6998 }
6999 GetVarUndef => {
7000 let value = self
7001 .get_global(a as usize)
7002 .or_else(|_| Ok(Value::Undefined))?;
7003 self.push(value);
7004 }
7005 DeleteVar => {
7006 // `delete name` for a name that is not a declared binding. A lexical
7007 // global lives in the reference table and cannot be deleted; anything
7008 // reachable only as a property of the global object is *implicit* —
7009 // `x = 1` with no declaration — and goes away if it is configurable,
7010 // which is what `delete` on an implicit global answers.
7011 let name = self.atom_text(a as usize);
7012 let global = self.realm.global.clone();
7013 let deleted = if self.realm.globals.contains_key(&name) {
7014 false
7015 } else if global.own_property(&name).is_some() {
7016 self.delete_property(&global, &name)?
7017 } else {
7018 true
7019 };
7020 self.push(Value::Bool(deleted));
7021 }
7022 PutVar => {
7023 let value = self.pop();
7024 self.put_global(a as usize, value)?;
7025 }
7026 PutVarInit => {
7027 let slot = a as usize;
7028 let value = self.pop();
7029 self.init_global(slot, value)?;
7030 }
7031
7032 // -- arithmetic -------------------------------------------------
7033 Add => self.binary_add()?,
7034 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
7035 let raw_right = self.pop();
7036 let raw_left = self.pop();
7037 // BigInt arithmetic is a separate path, and not only for the type of the
7038 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
7039 // rather than a silent conversion.
7040 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
7041 let left = self.primitive_of(raw_left)?;
7042 let right = self.primitive_of(raw_right)?;
7043 let value = self.bigint_arithmetic(op, left, right)?;
7044 self.push(value);
7045 } else {
7046 let right = self.numeric(raw_right)?;
7047 let left = self.numeric(raw_left)?;
7048 self.push(arithmetic(op, left, right)?);
7049 }
7050 }
7051 Neg => {
7052 let raw = self.pop();
7053 match raw {
7054 // A bigint negates exactly, however wide it is.
7055 Value::BigInt(big) => {
7056 let negated = big.negate();
7057 self.push(self.bigint(negated));
7058 }
7059 other => {
7060 let value = self.numeric(other)?;
7061 self.push(negate(value));
7062 }
7063 }
7064 }
7065 Plus => {
7066 let value = self.pop();
7067 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
7068 // unary plus is defined to produce a *number*, which a bigint cannot
7069 // become without loss. It used to fall through to `NaN`.
7070 if matches!(value, Value::BigInt(_)) {
7071 return Err(self.type_error("cannot convert bigint to number"));
7072 }
7073 let numeric = self.numeric_of(value)?;
7074 self.push(numeric);
7075 }
7076 Inc => {
7077 let raw = self.pop();
7078 let (_, updated) = self.advance_numeric(raw, true)?;
7079 self.push(updated);
7080 }
7081 Dec => {
7082 let raw = self.pop();
7083 let (_, updated) = self.advance_numeric(raw, false)?;
7084 self.push(updated);
7085 }
7086 PostInc | PostDec => {
7087 // `x -> x x+1`: the *new* value ends up on top, so the store the
7088 // compiler emits right after (`put_var`) writes the incremented
7089 // one, while the old value stays underneath for the expression's
7090 // own result. Getting this backwards makes `i++` a no-op, which
7091 // turns `while (i < 3)` into an infinite loop.
7092 let raw = self.pop();
7093 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
7094 self.push(old);
7095 self.push(updated);
7096 }
7097 Not => {
7098 let raw = self.pop();
7099 match raw {
7100 // `~x` on a bigint is `-x - 1`, exact at any width.
7101 Value::BigInt(big) => {
7102 let inverted = big.bitnot();
7103 self.push(self.bigint(inverted));
7104 }
7105 other => {
7106 let value = self.numeric(other)?;
7107 self.push(Value::Int(!value.to_int32()));
7108 }
7109 }
7110 }
7111 Lnot => {
7112 let value = self.pop();
7113 self.push(Value::Bool(!value.to_boolean()));
7114 }
7115
7116 // -- comparison -------------------------------------------------
7117 Lt | Lte | Gt | Gte => {
7118 let right = self.pop();
7119 let left = self.pop();
7120 let answer = self.relational(op, left, right);
7121 self.push(answer);
7122 }
7123 Eq | Neq => {
7124 let right = self.pop();
7125 let left = self.pop();
7126 let equal = self.abstract_equals(left, right)?;
7127 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
7128 }
7129 StrictEq => {
7130 let right = self.pop();
7131 let left = self.pop();
7132 self.push(Value::Bool(left.strict_equals(&right)));
7133 }
7134 StrictNeq => {
7135 let right = self.pop();
7136 let left = self.pop();
7137 self.push(Value::Bool(!left.strict_equals(&right)));
7138 }
7139 IsUndefined => {
7140 // `=== undefined`, which is what a destructuring default tests. It is
7141 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
7142 let value = self.pop();
7143 self.push(Value::Bool(matches!(value, Value::Undefined)));
7144 }
7145 IsUndefinedOrNull => {
7146 let value = self.pop();
7147 self.push(Value::Bool(value.is_nullish()));
7148 }
7149 Typeof => {
7150 let value = self.pop();
7151 self.push(self.string(value.type_of()));
7152 }
7153 ToObject => {
7154 // A destructuring *object* pattern starts here, which is why
7155 // `var {} = null` throws. Only `undefined` and `null` are refused; a
7156 // primitive is boxed.
7157 let value = self.pop();
7158 let object = self.object_from(&value)?;
7159 self.push(Value::Object(object));
7160 }
7161 Instanceof => {
7162 let constructor = self.pop();
7163 let object = self.pop();
7164 let answer = self.instance_of(&object, &constructor)?;
7165 self.push(Value::Bool(answer));
7166 }
7167 In => {
7168 let object = self.pop();
7169 let key = self.pop();
7170 let answer = self.has_property(&key, &object)?;
7171 self.push(Value::Bool(answer));
7172 }
7173
7174 // -- control flow -----------------------------------------------
7175 Goto | Goto8 | Goto16 => {
7176 self.frame_mut().pc = a as usize;
7177 }
7178 IfTrue | IfTrue8 => {
7179 let value = self.pop();
7180 if value.to_boolean() {
7181 self.frame_mut().pc = a as usize;
7182 }
7183 }
7184 IfFalse | IfFalse8 => {
7185 let value = self.pop();
7186 if !value.to_boolean() {
7187 self.frame_mut().pc = a as usize;
7188 }
7189 }
7190 Catch => {
7191 // Pushes the handler target onto the value stack; `unwind` finds it.
7192 self.push(Value::CatchOffset(a));
7193 }
7194 Gosub => {
7195 self.push(Value::ReturnAddress(next as u32));
7196 self.frame_mut().pc = a as usize;
7197 }
7198 Ret => {
7199 let value = self.pop();
7200 match value {
7201 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
7202 _ => {
7203 return Err(Signal::Throw(
7204 self.make_error("InternalError", "invalid return address"),
7205 ));
7206 }
7207 }
7208 }
7209 NipCatch => {
7210 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
7211 // including the marker, keeping the top value.
7212 let top = self.pop();
7213 loop {
7214 match self.pop() {
7215 Value::CatchOffset(_) | Value::Undefined => break,
7216 _ => {}
7217 }
7218 if self.frame().stack.is_empty() {
7219 break;
7220 }
7221 }
7222 self.push(top);
7223 }
7224 Throw => {
7225 let value = self.pop();
7226 return Err(Signal::Throw(value));
7227 }
7228 ThrowError => {
7229 let name = self.atom_text(a as usize);
7230 let (class, message) = match b {
7231 0 => ("TypeError", format!("'{name}' is read-only")),
7232 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
7233 2 => ("ReferenceError", format!("'{name}' is not initialized")),
7234 // `delete super.x` is a syntax-level mistake the reference reports
7235 // with this wording, not a property-access failure.
7236 3 => (
7237 "ReferenceError",
7238 "unsupported reference to 'super'".to_string(),
7239 ),
7240 4 => (
7241 "TypeError",
7242 "iterator does not have a throw method".to_string(),
7243 ),
7244 5 => (
7245 "ReferenceError",
7246 "invalid assignment left-hand side".to_string(),
7247 ),
7248 _ => ("TypeError", format!("invalid operation on '{name}'")),
7249 };
7250 return Err(Signal::Throw(self.make_error(class, &message)));
7251 }
7252 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
7253 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
7254 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
7255 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
7256 Await => return Ok(Step::Suspend(SuspendKind::Await)),
7257 ReturnAsync => {
7258 // The reference's `return_async` returns `undefined` and lets the resume
7259 // machinery pick the real value off `sp[-1]`, which is how it tells a
7260 // completion from a suspension. Carrying the value explicitly says the
7261 // same thing without the implicit stack slot.
7262 let value = self.pop();
7263 return Ok(Step::Return(value));
7264 }
7265 Return => {
7266 let value = self.pop();
7267 return Ok(Step::Return(value));
7268 }
7269 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
7270
7271 // -- calls ------------------------------------------------------
7272 Call | Call0 | Call1 | Call2 | Call3 => {
7273 let argc = self.argc_operand(op, a);
7274 let args = self.pop_n(argc);
7275 let callee = self.pop();
7276 // A plain call has no receiver; the callee decides what to do with
7277 // `undefined` (a sloppy function substitutes the global object).
7278 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
7279 self.push(result);
7280 }
7281 }
7282 CallConstructor => {
7283 // `constructor this_obj args… -> object`. The duplicated
7284 // constructor is `new.target`; this milestone does not expose it,
7285 // so the extra copy is simply consumed here.
7286 let argc = a as usize;
7287 let args = self.pop_n(argc);
7288 let new_target = self.pop();
7289 let callee = self.pop();
7290 let result = self.construct(callee, new_target, args)?;
7291 self.push(result);
7292 }
7293 CallMethod => {
7294 let argc = a as usize;
7295 let args = self.pop_n(argc);
7296 let callee = self.pop();
7297 let this = self.pop();
7298 if let Some(result) = self.call_or_push(callee, this, args)? {
7299 self.push(result);
7300 }
7301 }
7302 Apply => {
7303 // `func this array -> result`, the spread-call form: the compiler
7304 // builds one array of arguments, and all that is left here is to
7305 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
7306 let array = self.pop();
7307 let this = self.pop();
7308 let callee = self.pop();
7309 let args = self.array_like_to_args(&array)?;
7310 if a & 1 != 0 {
7311 let result = self.construct(callee, this, args)?;
7312 self.push(result);
7313 } else if let Some(result) = self.call_or_push(callee, this, args)? {
7314 self.push(result);
7315 }
7316 }
7317 TailCall | TailCallMethod => {
7318 // `tail_call` is `call` whose result is returned immediately — the
7319 // reference jumps straight to `done` instead of storing the value and
7320 // running on. The callee still gets its own frame, so deep tail
7321 // recursion hits the stack limit exactly like plain recursion does;
7322 // marking this frame lets the return path unwind without needing
7323 // instructions after the call.
7324 let argc = if op == TailCallMethod {
7325 a as usize
7326 } else {
7327 self.argc_operand(op, a)
7328 };
7329 let args = self.pop_n(argc);
7330 let callee = self.pop();
7331 let this = if op == TailCallMethod {
7332 self.pop()
7333 } else {
7334 Value::Undefined
7335 };
7336 if let Value::Object(function) = &callee
7337 && let Some((code, env)) = bytecode_of(function)
7338 {
7339 // A generator or async body is not run here at all: calling it only
7340 // *creates* the generator/coroutine, so it must not inherit this
7341 // frame. Doing so made `function f(){ return g() }` push `g`'s body
7342 // onto `f`'s frame, and the first `yield`/`await` then reported
7343 // "a generator body ran as an ordinary call".
7344 if code.code.kind.is_generator() || code.code.kind.is_async() {
7345 let value = self.call_value(callee, this, args)?;
7346 return Ok(Step::Return(value));
7347 }
7348 self.frame_mut().tail = true;
7349 self.push_frame(code, env, this, args, callee)?;
7350 return Ok(Step::Continue);
7351 }
7352 // A native callee has no frame to reuse, so its value is simply
7353 // returned.
7354 let value = self.call_value(callee, this, args)?;
7355 return Ok(Step::Return(value));
7356 }
7357
7358 // -- objects ----------------------------------------------------
7359 SpecialObject => {
7360 let value = self.special_object(a)?;
7361 self.push(value);
7362 }
7363 PrivateSymbol => {
7364 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
7365 // symbol each time it is evaluated, which is why the compiler evaluates it
7366 // once (at class definition) and stores it in a class-scope binding.
7367 let name = self.atom_text(a as usize);
7368 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
7369 self.push(Value::Symbol(symbol));
7370 }
7371 GetPrivateField => {
7372 // `obj symbol -> value`. A missing private field is a TypeError, which is what
7373 // makes `#x` inaccessible on any object not built by this class.
7374 let symbol = self.pop();
7375 let object = self.pop();
7376 let value = self.read_private_field(&object, &symbol)?;
7377 self.push(value);
7378 }
7379 PutPrivateField => {
7380 // `obj value symbol ->`, and the store is a plain assignment to a property the
7381 // class already created, so there is no setter to consult.
7382 let symbol = self.pop();
7383 let value = self.pop();
7384 let object = self.pop();
7385 self.write_private_field(&object, &symbol, value)?;
7386 }
7387 DefinePrivateField => {
7388 // `obj symbol value -> obj`: a field initialiser creates the property, and
7389 // redefining one is a TypeError ("already exists").
7390 let value = self.pop();
7391 let symbol = self.pop();
7392 let object = self.pop();
7393 self.define_private_field(&object, &symbol, value)?;
7394 self.push(object);
7395 }
7396 PrivateIn => {
7397 // `obj key -> bool`: `#x in o`. The second operand decides which question is
7398 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
7399 // is a field, so this is an own-property test; a *function* is a method or
7400 // accessor, so this is a brand check.
7401 let key = self.pop();
7402 let object = self.pop();
7403 let Some(target) = object.as_object() else {
7404 return Err(Signal::Throw(
7405 self.make_error("TypeError", "invalid 'in' operand"),
7406 ));
7407 };
7408 let present = match &key {
7409 Value::Object(_) => self.check_brand(target, &key)?,
7410 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
7411 };
7412 self.push(Value::Bool(present));
7413 }
7414 AddBrand => {
7415 // `obj home ->`: create the class brand on `home` if it has none, then give
7416 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
7417 // class definition: only the prototype's copy of the symbol is wanted.
7418 let home = self.pop();
7419 let object = self.pop();
7420 self.add_brand(&object, &home)?;
7421 }
7422 CheckBrand => {
7423 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
7424 // Both stay, because the caller needs them — `nip` halves a read into its
7425 // value and `call_method` uses the pair as receiver and callee.
7426 let function = self.peek(0);
7427 let object = self.peek(1);
7428 let Some(target) = object.as_object() else {
7429 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
7430 };
7431 if !self.check_brand(target, &function)? {
7432 return Err(Signal::Throw(
7433 self.make_error("TypeError", "invalid brand on object"),
7434 ));
7435 }
7436 }
7437 GetLength => {
7438 // `get_length` is the `.length` read; an array and a string answer
7439 // from their own length, anything else from the property.
7440 let target = self.pop();
7441 let value = match &target {
7442 Value::Object(object) => match object.array_length() {
7443 Some(length) => crate::object::length_value(length),
7444 None => self.read_field(&target, "length")?,
7445 },
7446 Value::String(text) => Value::Int(text.utf16_len() as i32),
7447 _ => self.read_field(&target, "length")?,
7448 };
7449 self.push(value);
7450 }
7451 GetField | GetField2 => {
7452 let object = self.pop();
7453 let key = self.atom_text(a as usize);
7454 let value = self.read_field(&object, &key)?;
7455 if op == GetField2 {
7456 self.push(object);
7457 }
7458 self.push(value);
7459 }
7460 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
7461 let key = self.pop();
7462 let object = self.pop();
7463 let key = self.propkey(&key)?;
7464 let value = self.read_field_key(&object, &key)?;
7465 if matches!(op, GetArrayEl2 | GetArrayEl3) {
7466 self.push(object);
7467 }
7468 if op == GetArrayEl3 {
7469 // The key goes back in its *value* form, which the compiler stores
7470 // into the target of a destructuring assignment.
7471 self.push(match &key {
7472 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
7473 PropertyKey::String(text) => self.string_wtf8(text.clone()),
7474 });
7475 }
7476 self.push(value);
7477 }
7478 PutField => {
7479 let value = self.pop();
7480 let object = self.pop();
7481 let key = self.atom_text(a as usize);
7482 self.write_field(&object, &key, value)?;
7483 }
7484 PutArrayEl => {
7485 let value = self.pop();
7486 let key = self.pop();
7487 let object = self.pop();
7488 let key = self.propkey(&key)?;
7489 self.write_field_key(&object, &key, value)?;
7490 }
7491 DefineField => {
7492 let value = self.pop();
7493 let object = self.pop();
7494 let key = self.atom_text(a as usize);
7495 // No naming here. `{m: function(){}}` is named by the *compiler*, which
7496 // emits `set_name` — and only where `NamedEvaluation` applies, so
7497 // `{m: (0, function(){})}` stays anonymous. Naming every function that
7498 // reaches a property definition got that case wrong, and the compiler is
7499 // the only place that can tell the two apart.
7500 if let Some(target) = object.as_object() {
7501 // Only an *array* stores into the element vector. A numeric key
7502 // on an ordinary object is an ordinary property, which is what
7503 // makes `{1: 'a'}` iterate as a key rather than disappear.
7504 let stored = target.is_array()
7505 && array_index(&key)
7506 .is_some_and(|index| target.array_set(index as usize, value.clone()));
7507 if !stored {
7508 target.define_data(&key, value);
7509 }
7510 }
7511 self.push(object);
7512 }
7513 DefineArrayEl => {
7514 // `obj key value -> obj key`. The *value* form of the key is what goes
7515 // back on the stack — the compiler stores it into the pattern's binding —
7516 // so the symbol is not stringified on the way through.
7517 let value = self.pop();
7518 let key_value = self.pop();
7519 let object = self.peek(0);
7520 let key = self.propkey(&key_value)?;
7521 self.write_field_key(&object, &key, value)?;
7522 self.push(key_value);
7523 }
7524 SetHomeObject => {
7525 // `obj func -> obj func`: records the object a method was defined on so
7526 // `super` inside it resolves against that object's prototype.
7527 let function = self.peek(0);
7528 let home = self.peek(1);
7529 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
7530 function.set_home_object(Some(home.clone()));
7531 }
7532 }
7533 Regexp => {
7534 // `pattern flags -> regexp`. A literal compiles here rather than through the
7535 // constructor, which is both what the reference's dedicated opcode is for
7536 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
7537 let flags = self.pop();
7538 let pattern = self.pop();
7539 let pattern = self.to_js_string(&pattern)?;
7540 let flags = self.to_js_string(&flags)?;
7541 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
7542 self.push(Value::Object(object));
7543 }
7544 UsingDisposeInit => {
7545 // The error state a disposal accumulates into. Uninitialised means "no
7546 // failure yet"; anything else is the exception being propagated.
7547 self.push(Value::Uninitialized);
7548 }
7549 UsingCheck => {
7550 // `value -> value, method`: validate and snapshot the disposer now, so a
7551 // later change to `Symbol.dispose` cannot change what gets called, and so a
7552 // value that is not disposable fails before the body runs.
7553 let value = self.pop();
7554 let method = self.using_method_for(&value, a as u8 == 1)?;
7555 self.push(value);
7556 self.push(method);
7557 }
7558 UsingDispose => {
7559 // `error_state -> error_state'`: dispose the variable at `slot` — its value
7560 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
7561 // the pending error.
7562 let slot = self.slot_operand(op, a);
7563 let error_state = self.pop();
7564 let merged = self.using_dispose_once(slot, error_state)?;
7565 self.push(merged);
7566 }
7567 UsingDisposeMerge => {
7568 let new_error = self.pop();
7569 let error_state = self.pop();
7570 let merged = self.merge_dispose_error(new_error, error_state);
7571 self.push(merged);
7572 }
7573 UsingDisposeEnd => {
7574 // A disposal that failed replaces the block's normal completion, so the
7575 // error state becomes a real throw here rather than at the call site.
7576 let error_state = self.pop();
7577 if !matches!(error_state, Value::Uninitialized) {
7578 return Err(Signal::Throw(error_state));
7579 }
7580 }
7581 UsingDisposeAsync => {
7582 // `await using` needs a promise to await and this runtime has no
7583 // `Promise` builtin, so the disposer is called synchronously and its result
7584 // discarded. That is correct for a disposer that returns nothing and is
7585 // reported as a gap rather than silently skipped.
7586 let slot = self.slot_operand(op, a);
7587 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
7588 self.push(error_state);
7589 }
7590 GetSuper => {
7591 // `obj -> obj's prototype`: the starting point of a `super` lookup.
7592 let object = self.pop();
7593 let proto = match &object {
7594 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
7595 _ => Value::Null,
7596 };
7597 self.push(proto);
7598 }
7599 GetSuperValue => {
7600 // `receiver proto key -> value`, searching from `proto` but reporting to
7601 // `receiver`, which is what `super.g` must do for a getter to see `this`.
7602 //
7603 // Three values in, one out: the receiver is *consumed*, not left under the
7604 // result. Leaving it there was invisible for `super.x` in `return` or
7605 // statement position (the result is what gets popped) and corrupted the
7606 // frame everywhere else — `print(super.x)` left the class where the call
7607 // opcode looks for the receiver and called the class itself.
7608 let key = self.pop();
7609 let proto = self.pop();
7610 let receiver = self.pop();
7611 let value = self.super_read(&receiver, &proto, &key)?;
7612 self.push(value);
7613 }
7614 PutSuperValue => {
7615 // `receiver proto key value ->`: a store that starts at `proto` but
7616 // assigns to `receiver`.
7617 let value = self.pop();
7618 let key = self.pop();
7619 let proto = self.pop();
7620 let receiver = self.pop();
7621 self.super_write(&receiver, &proto, &key, value)?;
7622 }
7623 DefineClass => {
7624 // `parent ctor -> ctor proto`: the constructor becomes the class and a
7625 // fresh prototype object lands on top for the methods to go on.
7626 let name = self.atom_text(a as usize);
7627 let (ctor, proto) = self.define_class(&name, b)?;
7628 self.push(ctor);
7629 self.push(Value::Object(proto));
7630 }
7631 DefineClassComputed => {
7632 // `parent ctor key -> ctor proto key`: the computed name stays put so
7633 // `define_field`-style consumers can still read it.
7634 let key = self.pop();
7635 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
7636 let (ctor, proto) = self.define_class(&name, b)?;
7637 self.push(ctor);
7638 self.push(Value::Object(proto));
7639 self.push(key);
7640 }
7641 DefineMethod => {
7642 let function = self.pop();
7643 let object = self.pop();
7644 let key = self.atom_text(a as usize);
7645 // A method's `[[HomeObject]]` is the object it was defined on, which is
7646 // what `super` inside it resolves against.
7647 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
7648 function.set_home_object(Some(object.clone()));
7649 }
7650 self.set_function_name(&function, &key_with_accessor_prefix(&key, b));
7651 if let Some(array) = object.as_object() {
7652 define_function_property(array, &PropertyKey::from(key.as_str()), function, b);
7653 }
7654 self.push(object);
7655 }
7656 DefineMethodComputed => {
7657 let function = self.pop();
7658 let key = self.pop();
7659 let object = self.pop();
7660 let key = self.propkey(&key)?;
7661 self.set_function_name(&function, &key_with_accessor_prefix(&key.to_string(), a));
7662 if let Some(array) = object.as_object() {
7663 define_function_property(array, &key, function, a);
7664 }
7665 self.push(object);
7666 }
7667 SetProto => {
7668 let proto = self.pop();
7669 let object = self.pop();
7670 if let Some(target) = object.as_object() {
7671 target.set_proto(proto.as_object().cloned());
7672 }
7673 self.push(object);
7674 }
7675 CopyDataProperties => {
7676 let exclusion = self.pop();
7677 let source = self.pop();
7678 let target = self.peek(0);
7679 self.copy_properties(&target, &source, &exclusion)?;
7680 self.push(source);
7681 self.push(exclusion);
7682 }
7683 ToPropkey => {
7684 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
7685 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
7686 // ordinary `"Symbol(b)"` property.
7687 let value = self.pop();
7688 let key = match self.propkey(&value)? {
7689 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
7690 PropertyKey::String(text) => self.string_wtf8(text),
7691 };
7692 self.push(key);
7693 }
7694 SetName => {
7695 let function = self.peek(0);
7696 let name = self.atom_text(a as usize);
7697 self.set_function_name(&function, &name);
7698 }
7699 SetNameComputed => {
7700 let key = self.peek(1);
7701 let function = self.peek(0);
7702 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
7703 self.set_function_name(&function, &name);
7704 }
7705
7706 // -- arrays -----------------------------------------------------
7707 ArrayFrom => {
7708 let count = a as usize;
7709 let elements = self.pop_n(count);
7710 let array = self.new_array(elements);
7711 self.push(Value::Object(array));
7712 }
7713 Append => {
7714 // `array index iterable -> array new_index`
7715 let iterable = self.pop();
7716 self.pop();
7717 let array = self.peek(0);
7718 let added = self.append_enumerate(&array, &iterable)?;
7719 self.push(Value::Int(added));
7720 }
7721
7722 // -- iteration --------------------------------------------------
7723 ForInStart => {
7724 let value = self.pop();
7725 let record = self.for_in_record(&value)?;
7726 self.push(Value::Object(record));
7727 }
7728 ForInNext => {
7729 // `record -> record key done`. The flag is *done*, not "found":
7730 // the compiler tests it with `if_false` to jump back into the body,
7731 // so reporting `true` while keys remain would end the loop at once.
7732 let record = self.peek(0);
7733 match self.for_in_advance(&record)? {
7734 Some(key) => {
7735 let text = self.string(key);
7736 self.push(text);
7737 self.push(Value::Bool(false));
7738 }
7739 None => {
7740 self.push(Value::Undefined);
7741 self.push(Value::Bool(true));
7742 }
7743 }
7744 }
7745 ForOfStart => {
7746 let value = self.pop();
7747 let iterator = self.get_iterator(&value)?;
7748 self.push(iterator.object);
7749 self.push(iterator.next);
7750 self.push(Value::CatchOffset(0));
7751 }
7752 ForOfNext => {
7753 // `iter next catch_offset -> iter next catch_offset value done`.
7754 //
7755 // The operand is how many values sit *above* the iterator triple: a
7756 // destructuring rest element keeps its target array and running index
7757 // there while draining the iterator, so the triple is not at the top.
7758 let extra = a as usize;
7759 let iterator_slot = 2 + extra;
7760 // An exhausted iterator is replaced by `undefined` (see below), so a
7761 // second step must not call `next` again — `Array.from` and a
7762 // destructuring pattern both keep stepping past the end.
7763 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
7764 (Value::Undefined, true)
7765 } else {
7766 let iterator = Iterator {
7767 object: self.peek(iterator_slot),
7768 next: self.peek(1 + extra),
7769 };
7770 self.iterator_step(&iterator)?
7771 };
7772 if done {
7773 // The result's `value` is meaningless once the iterator is done:
7774 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
7775 // rather than binding the generator's return value.
7776 let top = self.frame().stack.len() - 1 - iterator_slot;
7777 self.frame_mut().stack[top] = Value::Undefined;
7778 self.push(Value::Undefined);
7779 self.push(Value::Bool(true));
7780 } else {
7781 self.push(value);
7782 self.push(Value::Bool(false));
7783 }
7784 }
7785 IteratorNext => {
7786 // `iter next catch val -> iter next catch val'`: replace the argument with
7787 // the result of `next(val)`. The triple below stays put, which is why the
7788 // three instructions of the `yield*` loop all address the stack the same way.
7789 let value = self.pop();
7790 let object = self.peek(2);
7791 let next = self.peek(1);
7792 let result = self.call_value(next, object, vec![value])?;
7793 self.push(result);
7794 }
7795 IteratorCall => {
7796 // `iter next catch val -> iter next catch val' flag`.
7797 //
7798 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
7799 // The flag is `true` when the method was missing, which is how the
7800 // caller learns that the inner iterator cannot take part in the
7801 // unwinding.
7802 let value = self.pop();
7803 let object = self.peek(2);
7804 let key = if a & 1 != 0 { "throw" } else { "return" };
7805 let method = self.read_field(&object, key)?;
7806 if matches!(method, Value::Undefined | Value::Null) {
7807 self.push(value);
7808 self.push(Value::Bool(true));
7809 } else {
7810 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
7811 let result = self.call_value(method, object, argument)?;
7812 self.push(result);
7813 self.push(Value::Bool(false));
7814 }
7815 }
7816 IteratorCheckObject => {
7817 if !matches!(self.peek(0), Value::Object(_)) {
7818 return Err(Signal::Throw(
7819 self.make_error("TypeError", "iterator must return an object"),
7820 ));
7821 }
7822 }
7823 IteratorClose => {
7824 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
7825 // calling the iterator's `return` so it can release whatever it holds.
7826 //
7827 // The catch offset goes first, so an exception from `return` is not caught
7828 // by the loop being abandoned. This used to pop the three operands and call
7829 // nothing at all, which made `break` out of a `for of` invisible to an
7830 // iterator with a `return` method.
7831 self.pop();
7832 self.pop();
7833 let iterator = self.pop();
7834 if !matches!(iterator, Value::Undefined) {
7835 let method = self.read_field(&iterator, "return")?;
7836 if !matches!(method, Value::Undefined | Value::Null) {
7837 let result = self.call_value(method, iterator.clone(), Vec::new())?;
7838 // §7.4.6: a `return` that answers a non-object is a TypeError.
7839 if !matches!(result, Value::Object(_)) {
7840 return Err(Signal::Throw(
7841 self.make_error("TypeError", "iterator must return an object"),
7842 ));
7843 }
7844 }
7845 }
7846 }
7847 Import => {
7848 // `import(specifier)`: the options slot is on top and is not read yet.
7849 let _options = self.pop();
7850 let specifier = self.pop();
7851 let promise = self.dynamic_import(specifier)?;
7852 self.push(promise);
7853 }
7854 ForAwaitOfStart => {
7855 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
7856 // `Symbol.iterator` fallback.
7857 let value = self.pop();
7858 let iterator = self.get_async_iterator(&value)?;
7859 self.push(iterator.object);
7860 self.push(iterator.next);
7861 self.push(Value::CatchOffset(0));
7862 }
7863 ForAwaitOfNext => {
7864 // `for await` steps the iterator and leaves the *result* wrapped in a
7865 // promise, so the `await` the compiler emits right after this can suspend
7866 // on it. Unwrapping happens in `iterator_get_value_done`.
7867 let extra = a as usize;
7868 let iterator_slot = 2 + extra;
7869 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
7870 Value::Undefined
7871 } else {
7872 let iterator = Iterator {
7873 object: self.peek(iterator_slot),
7874 next: self.peek(1 + extra),
7875 };
7876 let next = iterator.next.clone();
7877 self.call_value(next, iterator.object, Vec::new())?
7878 };
7879 let promise = self.promise_resolve_value(result)?;
7880 self.push(promise);
7881 }
7882 IteratorGetValueDone => {
7883 // `result -> value done`. A missing result object means the iterator was
7884 // already exhausted, which the loop treats as `done`.
7885 let result = self.pop();
7886 let done = match &result {
7887 Value::Object(object) => self
7888 .get_property(object, "done")?
7889 .is_some_and(|value| value.to_boolean()),
7890 _ => true,
7891 };
7892 if done {
7893 // Clear the iterator object so the `iterator_close` the loop emits on
7894 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
7895 // on normal completion, and this is where a normal completion is
7896 // recognised — the same trick `for_of_next` uses, which also replaces
7897 // the slot with `undefined`.
7898 //
7899 // The layout is fixed because only `for await` emits this opcode:
7900 // `iter next catch [result]`, so the iterator is three below the top.
7901 let depth = self.frame().stack.len();
7902 if depth >= 3 {
7903 self.frame_mut().stack[depth - 3] = Value::Undefined;
7904 }
7905 self.push(Value::Undefined);
7906 self.push(Value::Bool(true));
7907 } else {
7908 let Value::Object(object) = &result else {
7909 self.push(Value::Undefined);
7910 self.push(Value::Bool(true));
7911 return Ok(Step::Continue);
7912 };
7913 let value = self
7914 .get_property(object, "value")?
7915 .unwrap_or(Value::Undefined);
7916 self.push(value);
7917 self.push(Value::Bool(false));
7918 }
7919 }
7920
7921 Delete => {
7922 // `delete obj[key]`, where the key was just pushed. Deleting an array
7923 // index leaves a *hole* rather than closing the gap, and a
7924 // non-configurable property answers `false` and stays.
7925 let key = self.pop();
7926 let target = self.pop();
7927 let key = self.propkey(&key)?;
7928 let text_label = key.as_str().unwrap_or("").to_string();
7929 let deleted = match &target {
7930 Value::Object(object) => {
7931 let object = object.clone();
7932 self.delete_property_key(&object, &key)?
7933 }
7934 // A string's `length` and its index properties are
7935 // non-configurable, so deleting one answers `false`.
7936 Value::String(text) => {
7937 !(text_label == "length"
7938 || array_index(&text_label)
7939 .is_some_and(|index| (index as usize) < text.utf16_len()))
7940 }
7941 // "delete null.a" is a TypeError, not a no-op: the operator needs an
7942 // object to delete from, and only a *boxable* primitive has one.
7943 Value::Undefined | Value::Null => {
7944 return Err(Signal::Throw(
7945 self.make_error("TypeError", "cannot convert to object"),
7946 ));
7947 }
7948 // Any other primitive has no own properties; deleting nothing
7949 // succeeds.
7950 _ => true,
7951 };
7952 self.push(Value::Bool(deleted));
7953 }
7954
7955 // -- exceptions and bookkeeping ---------------------------------
7956 Fclosure | Fclosure8 => {
7957 let value = self.closure(a as usize)?;
7958 self.push(value);
7959 }
7960
7961 other => {
7962 let name = other.info().name;
7963 return Err(Signal::Throw(self.make_error(
7964 "InternalError",
7965 &format!("{name} is not implemented yet"),
7966 )));
7967 }
7968 }
7969 Ok(Step::Continue)
7970 }
7971
7972 // -- operand helpers ----------------------------------------------------
7973
7974 /// The slot index an operand names, taking short forms into account.
7975 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
7976 use Opcode::*;
7977 match op {
7978 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
7979 | SetVarRef0 => 0,
7980 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
7981 | SetVarRef1 => 1,
7982 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
7983 | SetVarRef2 => 2,
7984 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
7985 | SetVarRef3 => 3,
7986 _ => a as usize,
7987 }
7988 }
7989
7990 /// The argument count of a call, taking `call0`…`call3` into account.
7991 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
7992 use Opcode::*;
7993 match op {
7994 Call0 => 0,
7995 Call1 => 1,
7996 Call2 => 2,
7997 Call3 => 3,
7998 _ => a as usize,
7999 }
8000 }
8001
8002 fn atom_text(&self, index: usize) -> String {
8003 self.frame()
8004 .code
8005 .code
8006 .atoms
8007 .get(index)
8008 .map(|atom| match atom {
8009 Atom::Str(text) => text.clone(),
8010 Atom::Index(value) => value.to_string(),
8011 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
8012 // `throw_error`, `delete super.x`) never read it.
8013 Atom::Null => String::new(),
8014 })
8015 .unwrap_or_default()
8016 }
8017
8018 fn constant(&mut self, index: usize) -> JsResult<Value> {
8019 let constant = self.frame().code.code.cpool.get(index).cloned();
8020 Ok(match &constant {
8021 Some(Constant::Number(number)) => Value::Float(*number),
8022 Some(Constant::String(text)) => self.string(text.clone()),
8023 Some(Constant::BigInt { digits, radix }) => {
8024 match crate::bigint::BigInt::from_radix(digits, *radix) {
8025 Some(big) => self.bigint(big),
8026 // A literal the parser accepted is always parseable; a failure here
8027 // would be a compiler bug, so it reads as an `InternalError`.
8028 None => {
8029 return Err(Signal::Throw(
8030 self.make_error("InternalError", "unparseable bigint literal"),
8031 ));
8032 }
8033 }
8034 }
8035 Some(Constant::Function(_)) => {
8036 return Err(Signal::Throw(
8037 self.make_error("InternalError", "a bare function constant"),
8038 ));
8039 }
8040 // A tagged template's call site: a frozen array of the cooked chunks with a
8041 // frozen `raw` array beside it, which is what `String.raw` reads back.
8042 Some(Constant::Template { cooked, raw }) => {
8043 let cooked_values: Vec<Value> = cooked
8044 .iter()
8045 .map(|chunk| match chunk {
8046 Some(text) => self.string(text.clone()),
8047 None => Value::Undefined,
8048 })
8049 .collect();
8050 let raw_values: Vec<Value> =
8051 raw.iter().map(|text| self.string(text.clone())).collect();
8052 let raw_array = self.new_array(raw_values);
8053 raw_array.set_extensible(false);
8054 let template = self.new_array(cooked_values);
8055 template.define(
8056 "raw",
8057 Property::with_attributes(Value::Object(raw_array), false, false),
8058 );
8059 template.set_extensible(false);
8060 Value::Object(template)
8061 }
8062 _ => Value::Undefined,
8063 })
8064 }
8065
8066 /// The reference cell a closure-variable slot names.
8067 ///
8068 /// Two kinds of binding share this addressing: a genuine closure variable
8069 /// (captured from an enclosing function) lives in this frame's environment,
8070 /// while a *declared global* lives in the realm so that a script, a function
8071 /// declaration and their uses all see one binding. A plain `Global` — an
8072 /// undeclared name that may be satisfied by the global object — has no cell at
8073 /// all, which is how `typeof x` still works for a name that does not exist.
8074 /// The reference cell a closure-variable slot names.
8075 ///
8076 /// The environment is resolved once, when the closure is built, and this is
8077 /// just the lookup afterwards. A *declared global* is in there too, pointing at
8078 /// the realm's cell, so a script, a hoisted function declaration and their uses
8079 /// all share one binding. A plain `Global` — a name the script never declared —
8080 /// is read and written through `get_var`/`put_var` by name instead, which is
8081 /// what lets the global object satisfy it.
8082 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
8083 self.frame().env.cells.get(slot).cloned()
8084 }
8085
8086 /// Whether `slot` refers to a global binding through the reference table.
8087 ///
8088 /// A global's cell in the closure environment only exists so the slot has
8089 /// something to point at; the binding itself lives on the global object (a `var`)
8090 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
8091 /// be routed, not performed on the placeholder.
8092 fn is_global_slot(&self, slot: usize) -> bool {
8093 self.frame()
8094 .code
8095 .code
8096 .closure_vars
8097 .get(slot)
8098 .is_some_and(|c| {
8099 // A module's declarations and imports are *not* globals: their cells are
8100 // the module environment's, filled by the host, so the placeholder routing
8101 // must not apply to them.
8102 matches!(
8103 c.closure_type,
8104 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
8105 )
8106 })
8107 }
8108
8109 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
8110 if self.is_global_slot(slot) {
8111 return self.get_global(slot);
8112 }
8113 Ok(self
8114 .var_ref_cell(slot)
8115 .map(|cell| cell.get())
8116 .unwrap_or(Value::Undefined))
8117 }
8118
8119 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
8120 // A function declaration is hoisted by storing into a global reference before
8121 // the body runs, so this path is also what puts it on the global object.
8122 if self.is_global_slot(slot) {
8123 return self.put_global(slot, value);
8124 }
8125 if let Some(cell) = self.var_ref_cell(slot) {
8126 cell.set(value);
8127 }
8128 Ok(())
8129 }
8130
8131 // -- closures -----------------------------------------------------------
8132
8133 /// Build the closure for the function constant `index`.
8134 ///
8135 /// Every entry in the child's closure table names where its binding lives in
8136 /// *this* frame: a local or argument slot that was marked captured, or a cell
8137 /// this frame is itself holding. That is how a variable three functions deep
8138 /// stays one binding.
8139 fn closure(&mut self, index: usize) -> JsResult<Value> {
8140 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
8141 else {
8142 return Err(Signal::Throw(
8143 self.make_error("InternalError", "fclosure of a non-function"),
8144 ));
8145 };
8146 let mut cells = Vec::with_capacity(function.closure_vars.len());
8147 for closure_var in &function.closure_vars {
8148 let cell = match closure_var.closure_type {
8149 ClosureType::Arg => {
8150 let slot = closure_var.var_idx as usize;
8151 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
8152 }
8153 ClosureType::Local => {
8154 let slot = closure_var.var_idx as usize;
8155 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
8156 }
8157 ClosureType::Ref | ClosureType::GlobalRef => {
8158 // A `Ref` names a cell in this frame's own closure table; a
8159 // `GlobalRef` also starts there, then resolves by name below.
8160 let slot = closure_var.var_idx as usize;
8161 if let Some(cell) = self.frame().env.cells.get(slot) {
8162 cells.push(cell.clone());
8163 continue;
8164 }
8165 -1
8166 }
8167 _ => -1,
8168 };
8169 if cell >= 0 {
8170 let cell = self.frame().cells[cell as usize].clone();
8171 cells.push(cell);
8172 continue;
8173 }
8174 // A global: the cell is created on demand and shared through the realm,
8175 // so every function sees one binding.
8176 let name = closure_var.name.clone();
8177 let cell = match self.realm.globals.get(&name) {
8178 Some(cell) => cell.clone(),
8179 None => {
8180 let cell = self.new_cell(Value::Undefined);
8181 self.realm.globals.insert(name.clone(), cell.clone());
8182 cell
8183 }
8184 };
8185 cells.push(cell);
8186 }
8187 let name = function.name.clone();
8188 // `.length` is the arity before any default or rest parameter, not the number
8189 // of slots a pattern parameter needs.
8190 let length = function.defined_args;
8191 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
8192 // function and an arrow function do not. A *method* also does not, but that is not
8193 // known here — the method is marked when the `[[HomeObject]]` is attached (see
8194 // `set_home_object`), which is the moment it becomes a method.
8195 let function_kind = function.kind;
8196 let constructible =
8197 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
8198 let code = Gc::new(self.heap, CompiledCode::new(*function));
8199 // A closure built inside an `eval` inherits the eval's view of the enclosing
8200 // bindings, so it can still read them once the eval has returned.
8201 let eval_scope = self
8202 .active_eval_scope
8203 .clone()
8204 .or_else(|| self.frame().env.eval_scope.clone());
8205 // A closure sees the variables a direct `eval` declared in the frame it was
8206 // created in — the ones declared before *and after* it, so the same object is
8207 // shared; only the phase bounds which of them are visible.
8208 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
8209 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
8210 let env = Gc::new(
8211 self.heap,
8212 ClosureEnv {
8213 cells,
8214 eval_scope,
8215 local_vars,
8216 local_phase,
8217 },
8218 );
8219 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
8220 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
8221 // the only thing that carries `Symbol.toStringTag`, so without it
8222 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
8223 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
8224 let proto = match function_kind {
8225 js_compile::bytecode::FunctionKind::AsyncGenerator => self
8226 .realm
8227 .async_generator_function_proto
8228 .clone()
8229 .or_else(|| self.realm.function_proto.clone().into()),
8230 js_compile::bytecode::FunctionKind::Generator => self
8231 .realm
8232 .generator_function_proto
8233 .clone()
8234 .or_else(|| self.realm.function_proto.clone().into()),
8235 js_compile::bytecode::FunctionKind::Async => self
8236 .realm
8237 .async_function_proto
8238 .clone()
8239 .or_else(|| self.realm.function_proto.clone().into()),
8240 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
8241 };
8242 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
8243 object.set_constructible(constructible);
8244 object.define(
8245 "length",
8246 Property::name_or_length(Value::Int(length as i32)),
8247 );
8248 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
8249 // that checks the own-property descriptor fails if the property is missing.
8250 object.define("name", Property::name_or_length(self.string(name)));
8251 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
8252 // when `[[Construct]]` is created, so a generator, an async function and an arrow
8253 // function have none of their own. Installing it unconditionally gave
8254 // `Array.fromAsync` (an async function) an own `prototype` property, which
8255 // `builtin.js` checks for absence.
8256 if constructible {
8257 self.install_function_prototype(&object);
8258 }
8259 Ok(Value::Object(object))
8260 }
8261
8262 // -- conversions used by the operators ----------------------------------
8263
8264 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
8265 // `+x` is `ToNumber`, which for a string parses it and for an object runs
8266 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
8267 // string, which then behaves differently in every later comparison.
8268 match value {
8269 Value::Int(_) | Value::Float(_) => Ok(value),
8270 other => Ok(Value::Float(self.to_js_number(&other)?)),
8271 }
8272 }
8273
8274 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
8275 ///
8276 /// Returns the *converted* old value and the new one, because the two callers need
8277 /// different halves: `++x` yields the new value, while `x++` yields the old one and
8278 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
8279 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
8280 /// boolean.
8281 ///
8282 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
8283 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
8284 /// a bigint algorithm then ran exactly once.
8285 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
8286 if let Value::BigInt(big) = &value {
8287 let one = crate::bigint::BigInt::from_i64(1);
8288 let next = if up { big.add(&one) } else { big.sub(&one) };
8289 return Ok((value, self.bigint(next)));
8290 }
8291 let old = self.numeric(value)?;
8292 let new = if up {
8293 increment(old.clone())
8294 } else {
8295 decrement(old.clone())
8296 };
8297 Ok((old, new))
8298 }
8299
8300 fn numeric(&mut self, value: Value) -> JsResult<Value> {
8301 // `ToNumber` on an object runs `ToPrimitive` first, which is how
8302 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
8303 // heard at all. Reading the object's own tag instead (`other.to_number()`)
8304 // turned the whole operand into `NaN` and swallowed the exception.
8305 match value {
8306 Value::Int(_) | Value::Float(_) => Ok(value),
8307 other => Ok(Value::Float(self.to_js_number(&other)?)),
8308 }
8309 }
8310
8311 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
8312 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
8313 match value {
8314 Value::BigInt(big) => Ok((**big).clone()),
8315 // The reference words this the same way for every operator, so a failing
8316 // script reads identically; the operator itself adds nothing a caller can use.
8317 _ => Err(Signal::Throw(
8318 self.make_error("TypeError", "cannot convert bigint to number"),
8319 )),
8320 }
8321 }
8322
8323 /// Arithmetic where at least one operand is a `BigInt`.
8324 ///
8325 /// The two numeric types never mix, so a bigint paired with anything else is an error
8326 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
8327 /// that the relational operators handle it separately.
8328 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
8329 use Opcode::*;
8330 let a = self.bigint_operand(&left)?;
8331 let b = self.bigint_operand(&right)?;
8332 let result = match op {
8333 Add => a.add(&b),
8334 Sub => a.sub(&b),
8335 Mul => a.mul(&b),
8336 Div | Mod => {
8337 let Some((quotient, remainder)) = a.div_rem(&b) else {
8338 return Err(Signal::Throw(
8339 self.make_error("RangeError", "division by zero"),
8340 ));
8341 };
8342 if op == Div { quotient } else { remainder }
8343 }
8344 Pow => {
8345 let Some(value) = a.pow(&b) else {
8346 return Err(Signal::Throw(self.make_error(
8347 "RangeError",
8348 "BigInt exponent must be non-negative and not absurdly large",
8349 )));
8350 };
8351 value
8352 }
8353 And => a.bitand(&b),
8354 Or => a.bitor(&b),
8355 Xor => a.bitxor(&b),
8356 Shl | Sar => {
8357 // A shift count is a `BigInt` here, and both directions are exact; a
8358 // negative count would be the other direction, which the spec forbids.
8359 let Some(count) = b.to_i64() else {
8360 return Err(Signal::Throw(
8361 self.make_error("RangeError", "BigInt shift count is too large"),
8362 ));
8363 };
8364 if count < 0 {
8365 return Err(Signal::Throw(self.make_error(
8366 "RangeError",
8367 "BigInt shift count must be non-negative",
8368 )));
8369 }
8370 if op == Shl {
8371 a.shl(count as u64)
8372 } else {
8373 a.shr(count as u64)
8374 }
8375 }
8376 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
8377 _ => {
8378 return Err(Signal::Throw(self.make_error(
8379 "TypeError",
8380 "BigInts have no unsigned right shift, use >> instead",
8381 )));
8382 }
8383 };
8384 Ok(self.bigint(result))
8385 }
8386
8387 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
8388 ///
8389 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
8390 /// is on the mathematical values, and nothing is rounded first.
8391 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> Value {
8392 use Opcode::*;
8393 let ordering = match (&left, &right) {
8394 (Value::String(a), Value::String(b)) => {
8395 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
8396 }
8397 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
8398 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
8399 // is true even though `2.5` has no bigint form.
8400 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
8401 let b = other.to_number();
8402 if b.is_nan() {
8403 None
8404 } else {
8405 compare_bigint_and_f64(a, b)
8406 }
8407 }
8408 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
8409 let a = other.to_number();
8410 if a.is_nan() {
8411 None
8412 } else {
8413 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
8414 }
8415 }
8416 _ => left.to_number().partial_cmp(&right.to_number()),
8417 };
8418 let _ = self;
8419 let answer = match (op, ordering) {
8420 (_, None) => false,
8421 (Lt, Some(ordering)) => ordering.is_lt(),
8422 (Lte, Some(ordering)) => ordering.is_le(),
8423 (Gt, Some(ordering)) => ordering.is_gt(),
8424 (Gte, Some(ordering)) => ordering.is_ge(),
8425 _ => false,
8426 };
8427 Value::Bool(answer)
8428 }
8429
8430 fn binary_add(&mut self) -> JsResult<()> {
8431 let right = self.pop();
8432 let left = self.pop();
8433 let left = self.primitive_of(left)?;
8434 let right = self.primitive_of(right)?;
8435 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
8436 // that check comes before the bigint one: `"" + 1n` is a string, not a
8437 // mixed-type error.
8438 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
8439 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
8440 // `TypeError`, the one place a symbol and a string do not mix.
8441 let left = self.checked_to_wtf8(&left)?;
8442 let right = self.checked_to_wtf8(&right)?;
8443 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
8444 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
8445 let text = left.concat(&right);
8446 self.push(self.string_wtf8(text));
8447 return Ok(());
8448 }
8449 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
8450 // not a conversion.
8451 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
8452 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
8453 self.push(value);
8454 return Ok(());
8455 }
8456 let left = self.numeric(left)?;
8457 let right = self.numeric(right)?;
8458 self.push(add_numbers(left, right));
8459 Ok(())
8460 }
8461
8462 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
8463 self.to_primitive(value, Hint::Default)
8464 }
8465
8466 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
8467 ///
8468 /// The order depends on the hint: the "number" order tries `valueOf` first and
8469 /// `toString` second, the "string" order the other way round, and the default
8470 /// hint uses the number order. A result that is still an object is a `TypeError`,
8471 /// because no built-in `valueOf`/`toString` returns one.
8472 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
8473 let Value::Object(object) = &value else {
8474 return Ok(value);
8475 };
8476 // A Date overrides the default hint to mean "string", which is what
8477 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
8478 // this, `"" + new Date()` would print the milliseconds, not the date.
8479 let hint = if hint == Hint::Default && is_date_object(self, object) {
8480 Hint::String
8481 } else {
8482 hint
8483 };
8484 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
8485 // handed the hint as a string. This is the hook a Date uses for its default hint
8486 // and a script uses to take over conversion entirely.
8487 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
8488 if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
8489 if !function.is_callable() {
8490 return Err(self.type_error("Symbol.toPrimitive is not a function"));
8491 }
8492 let hint = match hint {
8493 Hint::String => "string",
8494 Hint::Number => "number",
8495 Hint::Default => "default",
8496 };
8497 let hint = self.string(hint);
8498 let result = self.call_value(
8499 Value::Object(function),
8500 Value::Object(object.clone()),
8501 vec![hint],
8502 )?;
8503 if matches!(result, Value::Object(_)) {
8504 return Err(self.type_error("cannot convert object to primitive value"));
8505 }
8506 return Ok(result);
8507 }
8508 let order: [&str; 2] = match hint {
8509 Hint::String => ["toString", "valueOf"],
8510 Hint::Number | Hint::Default => ["valueOf", "toString"],
8511 };
8512 let receiver = object.clone();
8513 for method in order {
8514 if let Some(function) = self.get_property(&receiver, method)?
8515 && matches!(&function, Value::Object(object) if object.is_callable())
8516 {
8517 let result =
8518 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
8519 if !matches!(result, Value::Object(_)) {
8520 return Ok(result);
8521 }
8522 }
8523 }
8524 Err(self.type_error("cannot convert object to primitive value"))
8525 }
8526
8527 /// `ToString` with the object case going through `ToPrimitive`.
8528 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
8529 if matches!(value, Value::Object(_)) {
8530 let primitive = self.to_primitive(value.clone(), Hint::String)?;
8531 return Ok(primitive.to_js_string());
8532 }
8533 Ok(value.to_js_string())
8534 }
8535
8536 /// `ToString` that keeps the string's code units instead of flattening them.
8537 ///
8538 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
8539 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
8540 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
8541 if matches!(value, Value::Symbol(_)) {
8542 return Err(Signal::Throw(
8543 self.make_error("TypeError", "cannot convert symbol to string"),
8544 ));
8545 }
8546 // An object runs `ToPrimitive` first, which may itself produce a symbol.
8547 let value = self.to_primitive(value.clone(), Hint::String)?;
8548 match value {
8549 Value::Symbol(_) => Err(Signal::Throw(
8550 self.make_error("TypeError", "cannot convert symbol to string"),
8551 )),
8552 Value::String(text) => Ok(text.wtf8().clone()),
8553 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
8554 }
8555 }
8556
8557 /// `ToNumber` with the object case going through `ToPrimitive`.
8558 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
8559 let value = if matches!(value, Value::Object(_)) {
8560 self.to_primitive(value.clone(), Hint::Number)?
8561 } else {
8562 value.clone()
8563 };
8564 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
8565 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
8566 // `NaN` to stay total, and the operators check for the bigint themselves — but
8567 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
8568 // refuse, and answering `NaN` made them silently wrong instead.
8569 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
8570 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
8571 match value {
8572 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
8573 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
8574 other => Ok(other.to_number()),
8575 }
8576 }
8577
8578 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
8579 /// [`ElementType::write`].
8580 ///
8581 /// This is separated from the write because both conversions are observable script —
8582 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
8583 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
8584 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
8585 /// setters, and a plain `a[i] = v`.
8586 pub(crate) fn element_value(
8587 &mut self,
8588 element: crate::builtins::typedarray::ElementType,
8589 value: Value,
8590 ) -> JsResult<Value> {
8591 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
8592 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
8593 let primitive = match &value {
8594 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
8595 _ => value,
8596 };
8597 if element.is_bigint() {
8598 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
8599 Ok(Value::BigInt(Gc::new(self.heap, big)))
8600 } else {
8601 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
8602 Ok(Value::Float(self.to_js_number(&primitive)?))
8603 }
8604 }
8605
8606 /// `ToPropertyKey`: what a computed member access uses as its key.
8607 ///
8608 /// A symbol is returned as itself, never stringified — that is what keeps
8609 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
8610 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
8611 match value {
8612 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
8613 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
8614 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
8615 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
8616 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
8617 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
8618 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
8619 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
8620 other.to_js_string(),
8621 ))),
8622 },
8623 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
8624 }
8625 }
8626
8627 /// `ToPropertyKey` for the callers that can only use a string key.
8628 ///
8629 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
8630 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
8631 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
8632 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
8633 /// program continues with a value nobody asked for.
8634 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
8635 use crate::value::Wtf8;
8636 Ok(match value {
8637 // A string key keeps its code units. Going through a lossy `String` would make
8638 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
8639 Value::String(text) => text.wtf8().clone(),
8640 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
8641 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
8642 // falling back to its `ToString` would print `[object Object]`.
8643 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
8644 Value::String(text) => text.wtf8().clone(),
8645 other => Wtf8::new(other.to_js_string()),
8646 },
8647 other => Wtf8::new(other.to_js_string()),
8648 })
8649 }
8650
8651 // -- object operations used by instructions -----------------------------
8652
8653 /// Read `object[key]`, returning `undefined` when the property is missing.
8654 ///
8655 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
8656 /// primitive (looking through its prototype) as well as an object — which is what
8657 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
8658 /// argument needs too.
8659 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
8660 self.read_field_key(object, &PropertyKey::from(key))
8661 }
8662
8663 /// [`Interp::read_field`] with a key that may be a symbol.
8664 ///
8665 /// A symbol key never reaches the string shortcuts: a string's `length` and its
8666 /// indices are string properties, and a symbol named `length` is a different
8667 /// property that a string primitive cannot have.
8668 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
8669 let text = key.as_str().unwrap_or("");
8670 let Value::Object(object) = object else {
8671 // Reading a property of `undefined`/`null` is the classic TypeError.
8672 if object.is_nullish() {
8673 return Err(Signal::Throw(self.make_error(
8674 "TypeError",
8675 &format!("cannot read property '{key}' of {}", object.to_js_string()),
8676 )));
8677 }
8678 // A string has `length` and index access without being boxed.
8679 if let Value::String(value) = object {
8680 if text == "length" {
8681 return Ok(Value::Int(value.utf16_len() as i32));
8682 }
8683 if let Some(index) = array_index(text) {
8684 return Ok(match value.wtf8().unit_at(index as usize) {
8685 Some(unit) => self.string_wtf8(unit),
8686 None => Value::Undefined,
8687 });
8688 }
8689 }
8690 // A property of a primitive is looked up on its prototype: this is what
8691 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
8692 let prototype = match object {
8693 Value::String(_) => self.realm.string_proto.clone(),
8694 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
8695 Value::Bool(_) => self.realm.boolean_proto.clone(),
8696 // A symbol's methods live on `Symbol.prototype`, reached the same way —
8697 // `sym.description` reads through the prototype, not off the symbol.
8698 Value::Symbol(_) => self.realm.symbol_proto.clone(),
8699 // …and a bigint's on `BigInt.prototype`, which is how
8700 // `(255n).toString(16)` reaches its method.
8701 Value::BigInt(_) => self.realm.bigint_proto.clone(),
8702 _ => None,
8703 };
8704 if let Some(prototype) = prototype
8705 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
8706 {
8707 return Ok(value);
8708 }
8709 return Ok(Value::Undefined);
8710 };
8711 Ok(self
8712 .get_property_key(object, key)?
8713 .unwrap_or(Value::Undefined))
8714 }
8715
8716 fn write_field(&mut self, object: &Value, key: &str, value: Value) -> JsResult<()> {
8717 self.write_field_key(object, &PropertyKey::from(key), value)
8718 }
8719
8720 /// The `#name` a private symbol stands for, for error messages.
8721 ///
8722 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
8723 /// was made from.
8724 fn private_name(symbol: &Value) -> Option<String> {
8725 match symbol {
8726 Value::Symbol(symbol) if symbol.is_private() => Some(
8727 symbol
8728 .description()
8729 .map(|text| text.to_string())
8730 .unwrap_or_default(),
8731 ),
8732 _ => None,
8733 }
8734 }
8735
8736 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
8737 ///
8738 /// Every private-field opcode takes the symbol the class stored in its own scope; a
8739 /// non-symbol here would be a compiler bug, and the reference guards it with
8740 /// `JS_ThrowTypeErrorNotASymbol`.
8741 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
8742 match symbol {
8743 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
8744 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
8745 }
8746 }
8747
8748 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
8749 ///
8750 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
8751 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
8752 /// would hit if the parser did not reject it first.
8753 fn define_private_field(
8754 &mut self,
8755 object: &Value,
8756 symbol: &Value,
8757 value: Value,
8758 ) -> JsResult<()> {
8759 let key = self.private_key(symbol)?;
8760 let Some(target) = object.as_object() else {
8761 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
8762 };
8763 if !target.is_extensible() {
8764 return Err(Signal::Throw(
8765 self.make_error("TypeError", "object is not extensible"),
8766 ));
8767 }
8768 if target.own_property_key(&key).is_some() {
8769 let name = Self::private_name(symbol).unwrap_or_default();
8770 return Err(Signal::Throw(self.make_error(
8771 "TypeError",
8772 &format!("private class field '{name}' already exists"),
8773 )));
8774 }
8775 target.define_data_key(&key, value);
8776 Ok(())
8777 }
8778
8779 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
8780 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
8781 let key = self.private_key(symbol)?;
8782 let Some(target) = object.as_object() else {
8783 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
8784 };
8785 match target.own_property_key(&key) {
8786 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
8787 None => {
8788 let name = Self::private_name(symbol).unwrap_or_default();
8789 Err(Signal::Throw(self.make_error(
8790 "TypeError",
8791 &format!("private class field '{name}' does not exist"),
8792 )))
8793 }
8794 }
8795 }
8796
8797 /// `JS_SetPrivateField`: the store half of the same rule.
8798 fn write_private_field(
8799 &mut self,
8800 object: &Value,
8801 symbol: &Value,
8802 value: Value,
8803 ) -> JsResult<()> {
8804 let key = self.private_key(symbol)?;
8805 let Some(target) = object.as_object() else {
8806 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
8807 };
8808 if target.write_value_key(&key, value) {
8809 return Ok(());
8810 }
8811 let name = Self::private_name(symbol).unwrap_or_default();
8812 Err(Signal::Throw(self.make_error(
8813 "TypeError",
8814 &format!("private class field '{name}' does not exist"),
8815 )))
8816 }
8817
8818 /// The `in` half: does `object` have this private field?
8819 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
8820 ///
8821 /// The symbol is created once per class — the first `add_brand` on a given home object
8822 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
8823 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
8824 /// emit for the *instance* brand passes null because all it wants is the symbol.
8825 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
8826 let Some(home_object) = home.as_object() else {
8827 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
8828 };
8829 let symbol = match home_object.private_brand() {
8830 Some(symbol) => symbol,
8831 None => {
8832 let symbol = Gc::new(
8833 self.heap,
8834 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
8835 );
8836 home_object.set_private_brand(symbol.clone());
8837 symbol
8838 }
8839 };
8840 let Some(target) = object.as_object() else {
8841 // Not an object: nothing to brand. The reference does the same, and `undefined`
8842 // here would otherwise turn a field initialiser into a TypeError.
8843 return Ok(());
8844 };
8845 if !target.is_extensible() {
8846 return Err(Signal::Throw(
8847 self.make_error("TypeError", "object is not extensible"),
8848 ));
8849 }
8850 if target.carries_brand(&symbol) {
8851 return Err(Signal::Throw(
8852 self.make_error("TypeError", "private method is already present"),
8853 ));
8854 }
8855 target.add_brand(symbol);
8856 Ok(())
8857 }
8858
8859 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
8860 ///
8861 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
8862 /// decides whether to throw.
8863 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
8864 let Some(function) = function.as_object() else {
8865 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
8866 };
8867 let Some(home) = function.home_object() else {
8868 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
8869 };
8870 let Some(brand) = home.private_brand() else {
8871 return Err(Signal::Throw(
8872 self.make_error("TypeError", "expecting <brand> private field"),
8873 ));
8874 };
8875 Ok(object.carries_brand(&brand))
8876 }
8877
8878 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
8879 let Value::Object(object) = object else {
8880 return Err(Signal::Throw(self.make_error(
8881 "TypeError",
8882 &format!("cannot set property '{key}' of {}", object.to_js_string()),
8883 )));
8884 };
8885 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
8886 let on_failure = if self.frame().code.code.strict {
8887 DeleteFailure::Throw
8888 } else {
8889 DeleteFailure::Ignore
8890 };
8891 self.set_property_with_key(object, key, value, on_failure)
8892 }
8893
8894 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
8895 ///
8896 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
8897 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
8898 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
8899 /// `Number.parseInt(sym)` — so those callers use this instead.
8900 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
8901 if matches!(value, Value::Symbol(_)) {
8902 return Err(Signal::Throw(
8903 self.make_error("TypeError", "cannot convert symbol to string"),
8904 ));
8905 }
8906 // An object runs `ToPrimitive` first, which may itself produce a symbol —
8907 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
8908 let value = self.to_primitive(value.clone(), Hint::String)?;
8909 if matches!(value, Value::Symbol(_)) {
8910 return Err(Signal::Throw(
8911 self.make_error("TypeError", "cannot convert symbol to string"),
8912 ));
8913 }
8914 Ok(value.to_js_string())
8915 }
8916
8917 /// `ToPropertyKey` for a builtin that takes a key argument.
8918 ///
8919 /// Fallible: a key whose `toString` throws has to propagate that error, both for
8920 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
8921 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
8922 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
8923 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
8924 self.propkey(value)
8925 }
8926
8927 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
8928 ///
8929 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
8930 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
8931 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
8932 /// `RangeError` — and why this cannot be a plain `ToNumber`.
8933 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
8934 let number = match value {
8935 Value::Int(number) => *number as f64,
8936 Value::Float(number) => *number,
8937 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
8938 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
8939 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
8940 // reference answers 0.
8941 Value::Null | Value::Bool(_) => value.to_number(),
8942 _ => {
8943 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
8944 match primitive {
8945 Value::Int(number) => number as f64,
8946 Value::Float(number) => number,
8947 other => {
8948 // `ToString` then `ToNumber`, so a string length goes through the
8949 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
8950 // `Value::to_number` on the string already implements exactly that.
8951 let text = self.to_js_string(&other)?;
8952 crate::value::string_to_number(&text)
8953 }
8954 }
8955 }
8956 };
8957 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
8958 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
8959 // is a `RangeError`, not `0`.
8960 if !number.is_finite()
8961 || number.fract() != 0.0
8962 || !(0.0..=u32::MAX as f64).contains(&number)
8963 {
8964 return Err(self.range_error("invalid array length"));
8965 }
8966 Ok(number as u32)
8967 }
8968
8969 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
8970 /// `Object.getOwnPropertySymbols` put in their result array.
8971 pub fn key_value(&self, key: &PropertyKey) -> Value {
8972 match key {
8973 PropertyKey::String(text) => self.string_wtf8(text.clone()),
8974 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
8975 }
8976 }
8977
8978 /// Fill in a String exotic object: `_value`, `length` and the index properties.
8979 ///
8980 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
8981 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
8982 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
8983 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
8984 /// the two paths had drifted; this is the one both now use.
8985 ///
8986 /// The indices are *code units*, so an astral character occupies two of them — the
8987 /// same rule `s.length` and `s[i]` follow.
8988 /// Give an already-created object the internal slot that makes it a wrapper of
8989 /// `value`, so the primitive's prototype methods work on it.
8990 ///
8991 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
8992 /// which are wrappers of their own type holding the empty value.
8993 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
8994 self.internal_set(object, "_value", value);
8995 }
8996
8997 pub(crate) fn init_string_wrapper(
8998 &mut self,
8999 object: &Gc<JsObject>,
9000 text: &Gc<crate::value::JsString>,
9001 ) {
9002 object.define(
9003 "length",
9004 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
9005 );
9006 for index in 0..text.utf16_len() {
9007 if let Some(unit) = text.wtf8().unit_at(index) {
9008 object.define(
9009 &index.to_string(),
9010 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
9011 Property::with_attributes(self.string_wtf8(unit), false, true),
9012 );
9013 }
9014 }
9015 object.define_key(
9016 &self.internal_slot("_value"),
9017 Property::with_attributes(Value::String(text.clone()), false, false),
9018 );
9019 }
9020
9021 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
9022 ///
9023 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
9024 /// throws. The wrapper carries its primitive in `_value` — the same slot
9025 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
9026 /// on a boxed value no constructor ever built.
9027 pub(crate) fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
9028 let (prototype, primitive) = match value {
9029 Value::Object(object) => return Ok(object.clone()),
9030 Value::String(text) => {
9031 let object = self.new_object(self.realm.string_proto.clone());
9032 self.init_string_wrapper(&object, text);
9033 return Ok(object);
9034 }
9035 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
9036 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
9037 // A symbol and a bigint box into wrappers whose methods live on
9038 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
9039 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
9040 // branch below instead produced an object with *no* prototype, so those
9041 // methods were unreachable on a box.
9042 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
9043 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
9044 Value::Undefined | Value::Null => {
9045 return Err(Signal::Throw(self.make_error(
9046 "TypeError",
9047 &format!("cannot convert {} to object", value.to_js_string()),
9048 )));
9049 }
9050 _ => (None, value.clone()),
9051 };
9052 let object = self.new_object(prototype);
9053 self.internal_set(&object, "_value", primitive);
9054 Ok(object)
9055 }
9056
9057 /// `a == b`, the coercing comparison.
9058 ///
9059 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
9060 /// which is what makes `[] == ""` true: `[]` becomes `""` via
9061 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
9062 /// because the conversion is allowed to call script code, so the two primitive
9063 /// operands are handed back to it.
9064 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
9065 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
9066 return Ok(left.loose_equals(&right));
9067 }
9068 // `null == undefined` holds even though neither is an object.
9069 if matches!(left, Value::Undefined | Value::Null)
9070 && matches!(right, Value::Undefined | Value::Null)
9071 {
9072 return Ok(true);
9073 }
9074 if matches!(left, Value::Undefined | Value::Null)
9075 || matches!(right, Value::Undefined | Value::Null)
9076 {
9077 return Ok(false);
9078 }
9079 // Two objects compare by identity. Only an object *against a primitive* is
9080 // converted, which is why `{} == {}` is false while `[] == ""` is true.
9081 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
9082 return Ok(a.ptr_eq(b));
9083 }
9084 let left = self.to_primitive(left, Hint::Default)?;
9085 let right = self.to_primitive(right, Hint::Default)?;
9086 Ok(left.loose_equals(&right))
9087 }
9088
9089 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
9090 let Value::Object(object) = object else {
9091 return Err(Signal::Throw(
9092 self.make_error("TypeError", "cannot use 'in' on a non-object"),
9093 ));
9094 };
9095 let key = self.propkey(key)?;
9096 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
9097 // trap. One implementation, so an array's derived `length` and its inherited holes
9098 // cannot be right in one caller and wrong in another.
9099 self.has_own_or_inherited(object, &key)
9100 }
9101
9102 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
9103 let Value::Object(target) = object else {
9104 return Ok(false);
9105 };
9106 let Value::Object(function) = constructor else {
9107 return Err(Signal::Throw(self.make_error(
9108 "TypeError",
9109 "right-hand side of 'instanceof' is not callable",
9110 )));
9111 };
9112 let prototype = self.get_property(function, "prototype")?;
9113 let Some(Value::Object(prototype)) = prototype else {
9114 return Ok(false);
9115 };
9116 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
9117 // which is also what makes `proxyOfInstance instanceof C` work.
9118 let mut current = Some(target.clone());
9119 while let Some(object) = current {
9120 if object.ptr_eq(&prototype) {
9121 return Ok(true);
9122 }
9123 current = self.object_prototype_of(&object)?;
9124 }
9125 Ok(false)
9126 }
9127
9128 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
9129 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
9130 if let Some(proto) = self.proxy_get_prototype_of(object)? {
9131 return Ok(proto);
9132 }
9133 Ok(object.proto())
9134 }
9135
9136 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
9137 pub fn object_set_prototype_of(
9138 &mut self,
9139 object: &Gc<JsObject>,
9140 proto: Option<Gc<JsObject>>,
9141 ) -> JsResult<bool> {
9142 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
9143 return Ok(answer);
9144 }
9145 object.set_proto(proto);
9146 Ok(true)
9147 }
9148
9149 /// `[[IsExtensible]]`, with the proxy trap when there is one.
9150 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
9151 if let Some(answer) = self.proxy_is_extensible(object)? {
9152 return Ok(answer);
9153 }
9154 Ok(object.is_extensible())
9155 }
9156
9157 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
9158 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
9159 if let Some(answer) = self.proxy_prevent_extensions(object)? {
9160 return Ok(answer);
9161 }
9162 object.set_extensible(false);
9163 Ok(true)
9164 }
9165
9166 fn copy_properties(
9167 &mut self,
9168 target: &Value,
9169 source: &Value,
9170 exclusion: &Value,
9171 ) -> JsResult<()> {
9172 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
9173 // does contribute: its index properties are own, enumerable and writable, which
9174 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
9175 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
9176 // is a no-op.
9177 let Some(target) = target.as_object() else {
9178 return Ok(());
9179 };
9180 let source_object = match source {
9181 Value::Object(object) => object.clone(),
9182 Value::String(text) => {
9183 // Untaken keys are the string's indices, which are code units.
9184 for index in 0..text.utf16_len() {
9185 if let Some(unit) = text.wtf8().unit_at(index) {
9186 target.define_data(&index.to_string(), self.string_wtf8(unit));
9187 }
9188 }
9189 return Ok(());
9190 }
9191 _ => return Ok(()),
9192 };
9193 // An object *rest* element passes the keys already taken by the literal part as
9194 // an array of strings; a spread passes `null`, which excludes nothing. Only the
9195 // string keys of the exclusion array are meaningful, so an array is read by its
9196 // elements rather than by its own property names.
9197 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
9198 if let Value::Object(list) = exclusion
9199 && let Some(length) = list.array_length()
9200 {
9201 for index in 0..length {
9202 if let Some(value) = list.array_get(index) {
9203 excluded.push(self.propkey_of(&value)?);
9204 }
9205 }
9206 }
9207 let source = &source_object;
9208 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
9209 // Reading the property table directly made every spread of a proxy empty.
9210 let keys = self.object_own_property_keys(source)?;
9211 for as_key in keys {
9212 if as_key.is_symbol() {
9213 // A spread copies string-keyed properties only.
9214 continue;
9215 }
9216 if excluded.contains(&crate::value::Wtf8::new(
9217 as_key.as_str().unwrap_or_default(),
9218 )) {
9219 continue;
9220 }
9221 let enumerable = self
9222 .object_get_own_property(source, &as_key)?
9223 .is_some_and(|property| property.enumerable);
9224 if !enumerable {
9225 continue;
9226 }
9227 let value = self
9228 .get_property_key(source, &as_key)?
9229 .unwrap_or(Value::Undefined);
9230 target.define_data_key(&as_key, value);
9231 }
9232 Ok(())
9233 }
9234
9235 // -- iteration ---------------------------------------------------------
9236
9237 /// One object's own keys in enumeration order: array indices ascending, then the
9238 /// rest in insertion order.
9239 ///
9240 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
9241 /// whether the key is enumerable, which the caller resolves per key because an
9242 /// array's elements are not in the same store as its named properties.
9243 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
9244 // An index can arrive twice, once from the array's element store and once from
9245 // its property map, so the numeric keys go through a map that keeps the
9246 // enumerable answer if either source gave one.
9247 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
9248 for (key, enumerable) in &own {
9249 if let Some(index) = key.as_str().and_then(array_index) {
9250 let entry = numeric.entry(index).or_insert(false);
9251 *entry = *entry || *enumerable;
9252 }
9253 }
9254 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
9255 .into_iter()
9256 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
9257 .collect();
9258 ordered.extend(
9259 own.into_iter()
9260 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
9261 );
9262 ordered
9263 }
9264
9265 /// Build the key list a `for-in` loop walks.
9266 ///
9267 /// The order is the specification's: own properties before inherited ones, and
9268 /// within one object the integer-like keys in ascending numeric order ahead of the
9269 /// string keys in insertion order. A shadowed key only appears once, and a key that
9270 /// is a non-enumerable own property anywhere nearer is skipped entirely.
9271 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
9272 let record = self.new_object(None);
9273 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
9274 // A proxy supplies its own key list, and — the reason this is not just another
9275 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
9276 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
9277 // descriptor there.
9278 if let Value::Object(object) = value
9279 && object.proxy_state().is_some()
9280 {
9281 let own = self
9282 .proxy_own_keys(object)?
9283 .unwrap_or_else(|| object.own_property_keys());
9284 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
9285 let mut numeric: Vec<u32> = Vec::new();
9286 let mut rest: Vec<PropertyKey> = Vec::new();
9287 for key in own {
9288 match key.as_str().and_then(array_index) {
9289 Some(index) => numeric.push(index),
9290 None => rest.push(key),
9291 }
9292 }
9293 numeric.sort_unstable();
9294 ordered.extend(
9295 numeric
9296 .into_iter()
9297 .map(|index| PropertyKey::from(index.to_string())),
9298 );
9299 ordered.extend(rest);
9300 for (index, key) in ordered.into_iter().enumerate() {
9301 record.define_data(&index.to_string(), self.key_value(&key));
9302 }
9303 record.define_data("__index", Value::Int(0));
9304 // The mark that makes `for_in_advance` re-ask the proxy per key.
9305 record.define_data("__proxy", Value::Object(object.clone()));
9306 return Ok(record);
9307 }
9308 if let Value::Object(object) = value {
9309 let mut chain = vec![object.clone()];
9310 chain.extend(object.chain());
9311 // Every own string key the walk has seen, enumerable or not. A
9312 // non-enumerable own property still hides a same-named enumerable one
9313 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
9314 // keeps `x` out of the loop even when the prototype has one.
9315 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
9316 for object in chain {
9317 let mut own: Vec<(crate::value::Wtf8, bool)> = object
9318 .own_property_keys()
9319 .iter()
9320 .filter_map(|key| key.as_wtf8().cloned())
9321 .map(|key| {
9322 let enumerable = object
9323 .own_property(&key.to_string_lossy())
9324 .map(|property| property.enumerable)
9325 .unwrap_or(false);
9326 (key, enumerable)
9327 })
9328 .collect();
9329 if let Some(length) = object.array_length() {
9330 own.retain(|(key, _)| key.as_str() != Some("length"));
9331 for index in 0..length {
9332 if object.array_get(index).is_some() {
9333 own.push((crate::value::Wtf8::new(index.to_string()), true));
9334 }
9335 }
9336 }
9337 // Integer-like keys come first in ascending order, then the rest in
9338 // insertion order — and the ordering is *per object*, not for the chain
9339 // as a whole: one pass over every collected key lifted a prototype's
9340 // `"4"` above the target's own `x`/`y`, which is not the order
9341 // `for…in` reports.
9342 for (key, enumerable) in Self::order_own_keys(own) {
9343 if visited.contains(&key) {
9344 continue;
9345 }
9346 visited.push(key.clone());
9347 if enumerable {
9348 keys.push(key);
9349 }
9350 }
9351 }
9352 }
9353 for (index, key) in keys.into_iter().enumerate() {
9354 record.define_data(&index.to_string(), self.string_wtf8(key));
9355 }
9356 record.define_data("__index", Value::Int(0));
9357 Ok(record)
9358 }
9359
9360 /// The next key of a `for…in` record, `None` when the loop is done.
9361 ///
9362 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
9363 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
9364 /// the loop reaches it, so a handler that stops reporting a key partway through drops
9365 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
9366 /// key the handler had already withdrawn.
9367 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
9368 let Value::Object(record) = record else {
9369 return Ok(None);
9370 };
9371 let proxy = record
9372 .own_property("__proxy")
9373 .and_then(|property| property.value);
9374 loop {
9375 let index = record
9376 .own_property("__index")
9377 .and_then(|property| property.value)
9378 .map(|value| value.to_int32())
9379 .unwrap_or(0);
9380 let Some(candidate) = record
9381 .own_property(&index.to_string())
9382 .and_then(|property| property.value)
9383 else {
9384 return Ok(None);
9385 };
9386 record.define_data("__index", Value::Int(index + 1));
9387 let text = candidate.to_js_string();
9388 let Some(Value::Object(proxy)) = &proxy else {
9389 return Ok(Some(text));
9390 };
9391 // The candidate is already a key string here, so the lookup does not need a
9392 // second `ToPropertyKey` conversion.
9393 let key = PropertyKey::from(text.as_str());
9394 let live = match self.proxy_get_own_property(proxy, &key)? {
9395 Some(descriptor) => descriptor,
9396 // Not a proxy after all, or it lost its state: fall back to the target.
9397 None => proxy.own_property_key(&key),
9398 };
9399 if live.is_some_and(|property| property.enumerable) {
9400 return Ok(Some(text));
9401 }
9402 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
9403 // next one.
9404 }
9405 }
9406
9407 /// The iterator for `for-of`: the object and its `next` method.
9408 ///
9409 /// An object that already carries a `next` method is used as it is — that is what
9410 /// `arr.values()` returns — and only arrays and strings get the built-in
9411 /// sequence iterator.
9412 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
9413 ///
9414 /// Callers that must choose between the iterable and the array-like protocol — the
9415 /// typed-array constructor is the main one — need to ask *before* committing to one.
9416 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
9417 let key = self.realm.well_known_key(WellKnown::Iterator);
9418 let method = self.read_field_key(value, &key)?;
9419 if matches!(method, Value::Undefined | Value::Null) {
9420 return Ok(false);
9421 }
9422 if !matches!(&method, Value::Object(object) if object.is_callable()) {
9423 return Err(Signal::Throw(
9424 self.make_error("TypeError", "Symbol.iterator is not callable"),
9425 ));
9426 }
9427 Ok(true)
9428 }
9429
9430 /// Collect everything an iterable yields, closing it if the walk is abandoned.
9431 ///
9432 /// The cap is a guard against a generator that never ends: an unbounded collect would
9433 /// be an out-of-memory abort rather than a catchable error.
9434 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
9435 const MAX_ITEMS: usize = 1 << 24;
9436 let iterator = self.get_iterator(value)?;
9437 let mut out = Vec::new();
9438 loop {
9439 let (element, done) = self.iterator_step(&iterator)?;
9440 if done {
9441 return Ok(out);
9442 }
9443 out.push(element);
9444 if out.len() > MAX_ITEMS {
9445 return Err(self.range_error("iterable is too long to collect"));
9446 }
9447 }
9448 }
9449
9450 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
9451 ///
9452 /// A native constructor calls this once it has validated its arguments, which is the
9453 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
9454 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
9455 /// never reached. The prototype comes from `new.target` when it is an object, and from
9456 /// `default_proto` otherwise.
9457 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
9458 let Some(target) = self.pending_new_target.clone() else {
9459 return Ok(self.new_object(Some(default_proto)));
9460 };
9461 let Some(target) = target.as_object().cloned() else {
9462 return Ok(self.new_object(Some(default_proto)));
9463 };
9464 let proto = match self.get_property(&target, "prototype")? {
9465 Some(Value::Object(proto)) => proto,
9466 _ => default_proto,
9467 };
9468 Ok(self.new_object(Some(proto)))
9469 }
9470
9471 /// Whether this call is a construction, i.e. `new.target` is defined.
9472 ///
9473 /// A native constructor receives `this = undefined` (it builds its own instance), so it
9474 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
9475 /// The native function currently executing, if any.
9476 pub fn current_native(&self) -> Option<Gc<JsObject>> {
9477 self.current_native.clone()
9478 }
9479
9480 /// Whether this call is a construction, i.e. `new.target` is defined.
9481 pub fn is_constructing(&self) -> bool {
9482 self.pending_new_target.is_some()
9483 }
9484
9485 /// The `TypeError` a constructor too primitive to have a wrapper raises.
9486 ///
9487 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
9488 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
9489 /// happens inside the native function, which is why the trace carries an
9490 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
9491 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
9492 /// constructor`, and an unnamed one reports the leading space of `" is not a
9493 /// constructor"` because the reference formats the empty name as it is.
9494 ///
9495 /// It is also the answer for a `new.target` that cannot be named at all — not a
9496 /// function, or a throwing `name` getter — where the reference falls back to the bare
9497 /// `not a constructor`.
9498 pub fn not_a_constructor_error(&mut self) -> Signal {
9499 let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
9500 self.not_a_constructor_error_for(target)
9501 }
9502
9503 /// The same `TypeError` for an explicit target, for the callers that check
9504 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
9505 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
9506 let target = match target {
9507 Value::Object(target) if target.is_callable() => target,
9508 _ => return self.type_error("not a constructor"),
9509 };
9510 let name = match self.get_property(&target, "name") {
9511 Ok(Some(value)) => value.to_js_string(),
9512 _ => return self.type_error("not a constructor"),
9513 };
9514 self.type_error(format!("{name} is not a constructor"))
9515 }
9516
9517 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
9518 ///
9519 /// True whenever `new.target` is not the callee itself, or when it has no usable
9520 /// `prototype` — the cases where reading the property is observable at all.
9521 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
9522 match &self.pending_new_target {
9523 Some(Value::Object(target)) => !target.ptr_eq(callee),
9524 Some(_) => true,
9525 None => false,
9526 }
9527 }
9528
9529 /// The symbol key for one of the engine's own hidden slots.
9530 ///
9531 /// Cached on the realm, so every object of a kind shares one key and a slot can be
9532 /// read back by name.
9533 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
9534 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
9535 return PropertyKey::Symbol(symbol.clone());
9536 }
9537 let symbol = Gc::new(
9538 self.heap,
9539 crate::value::JsSymbol::new(Some(name.to_string())),
9540 );
9541 self.realm
9542 .internal_slots
9543 .borrow_mut()
9544 .insert(name, Value::Symbol(symbol.clone()));
9545 PropertyKey::Symbol(symbol)
9546 }
9547
9548 /// Read a hidden slot, or `None` when the object has none of that name.
9549 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
9550 let slots = self.realm.internal_slots.borrow();
9551 let Value::Symbol(symbol) = slots.get(name)? else {
9552 return None;
9553 };
9554 object
9555 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
9556 .and_then(|property| property.value)
9557 }
9558
9559 /// Define a hidden slot.
9560 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
9561 let key = self.internal_slot(name);
9562 object.define_key(&key, Property::with_attributes(value, false, false));
9563 }
9564
9565 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
9566 ///
9567 /// The method is looked up on the value (through its prototype), called with no
9568 /// arguments, and its result becomes the iterator. A generator gets here through
9569 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
9570 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
9571 ///
9572 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
9573 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
9574 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
9575 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
9576 /// does, and a user-defined iterable works without a special case.
9577 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
9578 /// `Symbol.iterator`.
9579 ///
9580 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
9581 /// iterable is legal there, and each value it produces is simply already settled by
9582 /// the time the `await` around it runs.
9583 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
9584 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
9585 let method = self.read_field_key(value, &async_key)?;
9586 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
9587 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
9588 // is *present but not callable* is a TypeError — it does not mean "try the other
9589 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
9590 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
9591 // guard is there to catch.
9592 let absent = matches!(method, Value::Undefined | Value::Null);
9593 if !absent {
9594 let Value::Object(object) = &method else {
9595 return Err(Signal::Throw(
9596 self.make_error("TypeError", "value is not iterable"),
9597 ));
9598 };
9599 if !object.is_callable() {
9600 return Err(Signal::Throw(
9601 self.make_error("TypeError", "value is not iterable"),
9602 ));
9603 }
9604 }
9605 if absent {
9606 return self.get_iterator(value);
9607 }
9608 let iterator = self.call_value(method, value.clone(), Vec::new())?;
9609 if !matches!(iterator, Value::Object(_)) {
9610 return Err(Signal::Throw(
9611 self.make_error("TypeError", "iterator is not an object"),
9612 ));
9613 }
9614 let next = self.read_field(&iterator, "next")?;
9615 Ok(Iterator {
9616 object: iterator,
9617 next,
9618 })
9619 }
9620
9621 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
9622 let key = self.realm.well_known_key(WellKnown::Iterator);
9623 let method = self.read_field_key(value, &key)?;
9624 let Value::Object(function) = &method else {
9625 return Err(Signal::Throw(self.make_error(
9626 "TypeError",
9627 &format!("{} is not iterable", value.to_js_string()),
9628 )));
9629 };
9630 if !function.is_callable() {
9631 return Err(Signal::Throw(self.make_error(
9632 "TypeError",
9633 &format!("{} is not iterable", value.to_js_string()),
9634 )));
9635 }
9636 let iterator = self.call_value(method, value.clone(), Vec::new())?;
9637 // The spec requires an object here; a primitive iterator has no `next` to call
9638 // and would fail one step later with a confusing message.
9639 if !matches!(iterator, Value::Object(_)) {
9640 return Err(Signal::Throw(
9641 self.make_error("TypeError", "iterator is not an object"),
9642 ));
9643 }
9644 let next = self.read_field(&iterator, "next")?;
9645 Ok(Iterator {
9646 object: iterator,
9647 next,
9648 })
9649 }
9650
9651 /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
9652 /// not iterable.
9653 ///
9654 /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
9655 /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
9656 /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
9657 /// was `[]`.
9658 pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
9659 let key = self.realm.well_known_key(WellKnown::Iterator);
9660 let method = self.read_field_key(value, &key)?;
9661 if !matches!(&method, Value::Object(object) if object.is_callable()) {
9662 return Ok(None);
9663 }
9664 let iterator = self.get_iterator(value)?;
9665 let mut out = Vec::new();
9666 loop {
9667 let (element, done) = self.iterator_step(&iterator)?;
9668 if done {
9669 return Ok(Some(out));
9670 }
9671 out.push(element);
9672 }
9673 }
9674
9675 /// One step of an internal iterator: the value and whether it is exhausted.
9676 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
9677 // A real iterator (`next` is a function) answers with a result object.
9678 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
9679 let result =
9680 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
9681 let Some(result) = result.as_object().cloned() else {
9682 return Err(self.type_error("iterator result is not an object"));
9683 };
9684 let done = self
9685 .get_property(&result, "done")?
9686 .is_some_and(|value| value.to_boolean());
9687 let value = self
9688 .get_property(&result, "value")?
9689 .unwrap_or(Value::Undefined);
9690 return Ok((value, done));
9691 }
9692 // An iterator whose `next` is not callable is treated as exhausted, which is
9693 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
9694 // that are not iterable at all.
9695 Ok((Value::Undefined, true))
9696 }
9697
9698 /// `[...iterable]`: append everything the iterator yields, and answer the next
9699 /// index.
9700 ///
9701 /// This goes through the same iterator machinery `for-of` uses rather than copying
9702 /// an array's elements, because a spread source is any iterable: a string spreads
9703 /// into its characters and an array iterator spreads into its results. Handling
9704 /// only arrays made `[..."ab"]` come out empty with no error at all.
9705 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
9706 let Some(target) = array.as_object().cloned() else {
9707 return Ok(0);
9708 };
9709 let start = target.array_length().unwrap_or(0);
9710 let mut added = 0;
9711 let iterator = self.get_iterator(iterable)?;
9712 loop {
9713 let (value, done) = self.iterator_step(&iterator)?;
9714 if done {
9715 break;
9716 }
9717 target.array_set(start + added, value);
9718 added += 1;
9719 }
9720 Ok((start + added) as i32)
9721 }
9722
9723 /// How an uncaught exception is reported.
9724 ///
9725 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
9726 /// with `ToString` — `js_std_dump_error` is three lines that end in
9727 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
9728 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
9729 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
9730 ///
9731 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
9732 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
9733 /// `toString`"; it does call it, but only for objects of a class it does not know how
9734 /// to walk, and never for errors, arrays or plain objects.
9735 ///
9736 /// A printer that fails must not take the reporter down with it, so that case falls
9737 /// back to the `ToString` rendering.
9738 pub fn describe_exception(&mut self, value: &Value) -> String {
9739 match crate::print::sprint(self, value) {
9740 Ok(text) => text,
9741 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
9742 }
9743 }
9744
9745 /// The file name of whatever is running, innermost frame first.
9746 ///
9747 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
9748 /// innermost frame's file name, without distinguishing a module body from a plain
9749 /// script. `import()` uses it as the base for a relative specifier, which is why
9750 /// `import('./x.js')` inside a script resolves next to the script and not next to the
9751 /// process's working directory.
9752 pub fn script_or_module_name(&self) -> Option<String> {
9753 self.frames
9754 .iter()
9755 .rev()
9756 .find_map(|frame| frame.code.code.filename.clone())
9757 }
9758
9759 /// The current call stack, formatted the way `qjs` prints `error.stack`.
9760 ///
9761 /// One ` at name (file:line:col)` line per active frame, innermost first. The
9762 /// position is the one recorded for the instruction each frame is stopped on, which
9763 /// is why the compiler builds a pc-to-position table per function: without it a
9764 /// trace could only name the function, not the line inside it.
9765 ///
9766 /// A frame whose code has no positions prints just `(file)`, matching the
9767 /// reference's output for stripped bytecode.
9768 pub fn stack_trace(&self) -> String {
9769 self.stack_trace_skipping(0)
9770 }
9771
9772 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
9773 fn stack_trace_skipping(&self, skip: usize) -> String {
9774 // One ordered list, innermost first, so `skip` counts the same thing whether the
9775 // frames it leaves out are native or bytecode. Indices rather than references: a
9776 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
9777 let depth = self.frames.len();
9778 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
9779 // A native entered while `at` bytecode frames were live was called *from* the
9780 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
9781 // entered at the current depth are therefore innermost of all.
9782 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
9783 for (index, (_, _, at)) in self.native_frames.iter().enumerate().rev() {
9784 if *at == wanted {
9785 order.push((true, index));
9786 }
9787 }
9788 };
9789 push_natives(&mut order, depth);
9790 for index in (0..depth).rev() {
9791 order.push((false, index));
9792 push_natives(&mut order, index);
9793 }
9794 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
9795 // barrier. Natives entered at exactly the barrier depth are the eval entry point
9796 // itself (`evalScript (native)`), and the reference leaves those out too.
9797 if let Some(barrier) = self.trace_barriers.last().copied() {
9798 order.retain(|(is_native, index)| match is_native {
9799 true => *index == usize::MAX || self.native_frames[*index].2 > barrier,
9800 false => *index >= barrier,
9801 });
9802 }
9803
9804 let mut out = String::new();
9805 for (is_native, index) in order.into_iter().skip(skip) {
9806 match is_native {
9807 true => {
9808 out.push_str(" at ");
9809 out.push_str(&self.native_frames[index].0);
9810 out.push_str(" (native)\n");
9811 }
9812 false => {
9813 let frame = &self.frames[index];
9814 let code = &frame.code.code;
9815 let file = code.filename.as_deref().unwrap_or("<input>");
9816 // The name comes from the function *object*, not from the compiled code:
9817 // an anonymous function expression is named by the property it is stored
9818 // in (`{valueOf: function(){}}`), which only the object knows.
9819 let bound_name = match &frame.callee {
9820 Value::Object(object) => {
9821 object
9822 .own_property("name")
9823 .and_then(|property| match property.value {
9824 Some(Value::String(text)) if !text.wtf8().is_empty() => {
9825 Some(text.to_string_lossy().into_owned())
9826 }
9827 _ => None,
9828 })
9829 }
9830 _ => None,
9831 };
9832 // No callee object means the body was entered by the host, so the
9833 // name has to come from the compiled code. Two cases differ:
9834 //
9835 // * an *unnamed* function of any kind — the reference reads the
9836 // `name` property, finds it empty, and prints `<anonymous>`;
9837 // * a *module* body, which has no `name` property at all: the
9838 // reference builds that function object with `js_closure2` and
9839 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
9840 // so a trace reaching it also prints `<anonymous>` — while a
9841 // *script* body prints `<eval>`, its `name`.
9842 let unnamed = code.name.is_empty() || code.module.is_some();
9843 out.push_str(" at ");
9844 match bound_name.as_deref() {
9845 Some(name) => out.push_str(name),
9846 None if unnamed => out.push_str("<anonymous>"),
9847 None => out.push_str(&code.name),
9848 }
9849 match code.position_at(frame.at as u32) {
9850 Some((line, column)) => {
9851 out.push_str(&format!(" ({file}:{line}:{column})\n"));
9852 }
9853 None => out.push_str(&format!(" ({file})\n")),
9854 }
9855 }
9856 }
9857 }
9858 out
9859 }
9860
9861 /// Give an anonymous function the name of the property it is stored in.
9862 ///
9863 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
9864 /// enumerable and not configurable, and a function that already has a real name
9865 /// keeps it.
9866 ///
9867 /// "Already named" means a *non-empty* name: every function object is created with
9868 /// a `name` of `""` so the property exists on all of them, and treating that empty
9869 /// string as a name left every anonymous function nameless — which is how a stack
9870 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
9871 fn set_function_name(&mut self, function: &Value, name: &str) {
9872 let Value::Object(object) = function else {
9873 return;
9874 };
9875 // `SetFunctionName` applies to *functions* and classes only, and only when they are
9876 // anonymous. Without the callability guard, `{value: someObject}` renamed
9877 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
9878 // on the right-hand side of a property. That is how a `zipKeyed` result object
9879 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
9880 // has no `NamedEvaluation` at all.
9881 if !object.is_callable() {
9882 return;
9883 }
9884 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
9885 && !existing.wtf8().is_empty()
9886 {
9887 return;
9888 }
9889 let text = self.string(name);
9890 object.define("name", Property::name_or_length(text));
9891 }
9892
9893 // -- global declarations -----------------------------------------------
9894
9895 /// Declare a global binding, creating its reference cell.
9896 /// Declare a `var` or function global, whose home is the global object.
9897 ///
9898 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
9899 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
9900 /// such as `print`, or a redeclaration — is left alone.
9901 pub fn declare_var_global(&mut self, name: &str) {
9902 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
9903 // global object is exactly the leak `typeof my_var === "undefined"` after
9904 // `eval("var my_var=2")` rules out.
9905 if let Some(scope) = self.eval_scope.as_mut() {
9906 scope.entry(name.to_string()).or_insert(Value::Undefined);
9907 return;
9908 }
9909 // A sloppy direct eval declares into its *caller's* variable environment. Doing
9910 // this on the global object instead made `eval("var c = 1")` inside a parameter
9911 // list overwrite a global `c`, and made two calls to the same function share one
9912 // binding.
9913 if let Some(cell) = self.declare_eval_local(name) {
9914 cell.set(Value::Undefined);
9915 return;
9916 }
9917 let global = self.realm.global.clone();
9918 if global.own_property(name).is_some() {
9919 return;
9920 }
9921 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
9922 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
9923 // whole point of that trick and what lets `Object.defineProperty` reshape it
9924 // afterwards. `eval_scope` is `Some` while an eval is running.
9925 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
9926 global.define(
9927 name,
9928 Property {
9929 value: Some(Value::Undefined),
9930 writable: true,
9931 enumerable: true,
9932 configurable: from_eval,
9933 ..Property::default()
9934 },
9935 );
9936 }
9937
9938 /// Declare a *lexical* global binding, which starts in its dead zone.
9939 ///
9940 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
9941 /// global object and is created when its initialiser runs.
9942 pub fn declare_global(&mut self, name: &str, is_const: bool) {
9943 if is_const {
9944 self.realm.lexical_consts.insert(name.to_string());
9945 }
9946 if !self.realm.globals.contains_key(name) {
9947 // `Uninitialized` rather than `Undefined`: the binding exists but is not
9948 // readable until its initialiser runs, and that is what `let x` before
9949 // `x = 1` has to observe.
9950 let cell = self.new_cell(Value::Uninitialized);
9951 self.realm.globals.insert(name.to_string(), cell);
9952 self.realm.declared.push(name.to_string());
9953 }
9954 }
9955}
9956
9957/// The bytecode and environment of a function object, if it is a bytecode function.
9958///
9959/// Extracted before a call so no borrow of the object is held across it.
9960fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
9961 function.with(|data| match &data.kind {
9962 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
9963 _ => None,
9964 })
9965}
9966
9967/// A native call target, extracted before the call so no borrow is held.
9968enum NativeCall {
9969 Native(NativeFn),
9970 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
9971 /// not hold that object's `RefCell` borrow.
9972 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
9973 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
9974 Bound {
9975 target: Value,
9976 this: Value,
9977 leading: Vec<Value>,
9978 },
9979 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
9980 Revoker(crate::object::ProxyRef),
9981 /// A promise's `resolve`.
9982 PromiseResolve(Gc<JsObject>),
9983 /// A promise's `reject`.
9984 PromiseReject(Gc<JsObject>),
9985 /// One continuation of an `await`.
9986 AwaitResume {
9987 coroutine: Gc<JsObject>,
9988 promise: Gc<JsObject>,
9989 kind: ResumeKind,
9990 },
9991 /// One element of a `Promise` combinator settling.
9992 CombinatorSettle {
9993 state: Gc<JsObject>,
9994 index: usize,
9995 fulfilled: bool,
9996 },
9997 /// One of `Promise.prototype.finally`'s two shims.
9998 FinallyShim {
9999 callback: Option<Value>,
10000 fulfilled: bool,
10001 },
10002 /// Settle a promise with a fixed outcome.
10003 SettlePromise {
10004 promise: Gc<JsObject>,
10005 value: Value,
10006 rejected: bool,
10007 },
10008 /// Continue an async generator after its `await` settled.
10009 GeneratorResume {
10010 generator: Gc<JsObject>,
10011 promise: Gc<JsObject>,
10012 kind: ResumeKind,
10013 },
10014 /// Read a module namespace's binding out of its cell.
10015 ModuleBinding(Gc<Cell>),
10016 /// Finish a completed async generator's `return(v)` once `v` has settled.
10017 CompletedReturn {
10018 generator: Gc<JsObject>,
10019 promise: Gc<JsObject>,
10020 rejected: bool,
10021 },
10022 /// Answer a pending async-generator method with `{value, done}`.
10023 YieldResult {
10024 generator: Gc<JsObject>,
10025 promise: Gc<JsObject>,
10026 done: bool,
10027 },
10028 /// One step of `AsyncDisposableStack.disposeAsync`.
10029 DisposeStep {
10030 remaining: Gc<JsObject>,
10031 promise: Gc<JsObject>,
10032 error: Value,
10033 rejected: bool,
10034 },
10035}
10036
10037/// What a store does when the object refuses the write.
10038#[derive(Clone, Copy, PartialEq, Eq)]
10039pub enum DeleteFailure {
10040 /// Raise a `TypeError`, which is what strict mode and every built-in does.
10041 Throw,
10042 /// Ignore the write, which is what a sloppy-mode assignment does.
10043 Ignore,
10044}
10045
10046/// Whether `object` is a `Date` instance, by the class tag it carries.
10047///
10048/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
10049/// builtins module depending on the interpreter's conversion order.
10050fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
10051 interp
10052 .internal_get(object, "_class")
10053 .is_some_and(|value| value.to_js_string() == "Date")
10054}
10055
10056/// Which type `ToPrimitive` prefers when it converts an object.
10057#[derive(Clone, Copy, PartialEq, Eq)]
10058pub enum Hint {
10059 /// The default hint, which behaves like [`Hint::Number`].
10060 Default,
10061 /// `Number(obj)` and the arithmetic operators.
10062 Number,
10063 /// `String(obj)` and `ToPropertyKey`.
10064 String,
10065}
10066
10067/// Which table a binding slot indexes, for the messages that name it.
10068#[derive(Clone, Copy)]
10069enum VarSlot {
10070 Loc,
10071 Closure,
10072}
10073
10074/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
10075fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
10076 Ok(this)
10077}
10078
10079/// An internal iterator: the sequence plus a cursor.
10080pub(crate) struct Iterator {
10081 pub(crate) object: Value,
10082 pub(crate) next: Value,
10083}
10084
10085/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
10086/// and plain `a` for a method.
10087///
10088/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
10089/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
10090/// reads `at get a (file:1:2)`.
10091fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
10092 match flags & 3 {
10093 1 => format!("get {key}"),
10094 2 => format!("set {key}"),
10095 _ => key.to_string(),
10096 }
10097}
10098
10099/// Define a method or accessor property, per the `define_method` flag byte.
10100///
10101/// The low two bits pick value/getter/setter and bit 2 marks the property
10102/// enumerable.
10103///
10104/// A getter and a setter arrive as two separate `define_method` instructions, and the
10105/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
10106/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
10107/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
10108/// `JS_DefineProperty`, which leaves the other half alone.
10109fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
10110 let enumerable = flags & 4 != 0;
10111 let kind = flags & 3;
10112 let existing = object.own_property_key(key);
10113 let property = match kind {
10114 1 => Property {
10115 getter: Some(function),
10116 // The setter half, if this literal already defined one.
10117 setter: existing
10118 .filter(Property::is_accessor)
10119 .and_then(|p| p.setter),
10120 enumerable,
10121 configurable: true,
10122 ..Property::default()
10123 },
10124 2 => Property {
10125 getter: existing
10126 .filter(Property::is_accessor)
10127 .and_then(|p| p.getter),
10128 setter: Some(function),
10129 enumerable,
10130 configurable: true,
10131 ..Property::default()
10132 },
10133 _ => Property {
10134 value: Some(function),
10135 writable: true,
10136 enumerable,
10137 configurable: true,
10138 ..Property::default()
10139 },
10140 };
10141 object.define_key(key, property);
10142}
10143
10144// ---------------------------------------------------------------------------
10145// Operand decoding
10146// ---------------------------------------------------------------------------
10147
10148/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
10149///
10150/// Jump operands are resolved to absolute byte offsets here, because the encoding
10151/// stores them relative to the byte after the opcode and every use site would
10152/// otherwise repeat that arithmetic.
10153fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
10154 let op = Opcode::from_u8(*code.get(pc)?)?;
10155 let info = op.info();
10156 let base = pc + 1;
10157 let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
10158 let read_u16 = |offset: usize| -> u32 {
10159 let mut value = 0u32;
10160 for index in 0..2 {
10161 value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
10162 }
10163 value
10164 };
10165 let read_u32 = |offset: usize| -> u32 {
10166 let mut value = 0u32;
10167 for index in 0..4 {
10168 value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
10169 }
10170 value
10171 };
10172 let jump = |offset: usize, width: usize| -> u32 {
10173 let raw = match width {
10174 1 => read_u8(offset) as u8 as i8 as i64,
10175 2 => read_u16(offset) as u16 as i16 as i64,
10176 _ => read_u32(offset) as i32 as i64,
10177 };
10178 (base as i64 + raw) as u32
10179 };
10180 let (a, b) = match info.format {
10181 OpFormat::None
10182 | OpFormat::NoneInt
10183 | OpFormat::NoneLoc
10184 | OpFormat::NoneArg
10185 | OpFormat::NoneVarRef
10186 | OpFormat::Npopx => (0, 0),
10187 OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
10188 OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
10189 OpFormat::Label8 => (jump(0, 1), 0),
10190 OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
10191 (read_u16(0), 0)
10192 }
10193 OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
10194 OpFormat::Label16 => (jump(0, 2), 0),
10195 OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
10196 OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
10197 OpFormat::I32 | OpFormat::Label => (
10198 if info.format == OpFormat::Label {
10199 jump(0, 4)
10200 } else {
10201 read_u32(0) as i32 as u32
10202 },
10203 0,
10204 ),
10205 OpFormat::AtomU8 | OpFormat::AtomLabelU8 => (read_u32(0), read_u8(4)),
10206 OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
10207 (read_u32(0), read_u16(4))
10208 }
10209 };
10210 Some((op, a, b, pc + info.size as usize))
10211}
10212
10213/// How `print` renders a value: the reference's `JS_PrintValue`.
10214///
10215/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
10216/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
10217/// The format is reproduced closely because the test suite compares output text:
10218///
10219/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
10220/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
10221/// * a cycle prints `[circular N]` with `N` the stack index of the object;
10222/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
10223/// end print as `<N empty item(s)>`;
10224/// * a string is quoted inside a container but raw at the top level, which is why
10225/// `print("x")` and `print(["x"])` differ.
10226pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
10227 // A string argument is printed raw: `js_print` converts it with `ToString`
10228 // instead of dumping it, and the quoting only appears inside a container.
10229 if let Value::String(text) = value {
10230 return text.to_string_lossy().into_owned();
10231 }
10232 let mut printer = Printer {
10233 interp,
10234 out: String::new(),
10235 stack: Vec::new(),
10236 };
10237 printer.value(value, 0);
10238 printer.out
10239}
10240
10241/// The internal class name an object carries, when it has one.
10242fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
10243 interp
10244 .internal_get(object, "_class")
10245 .map(|value| value.to_js_string())
10246}
10247
10248/// A string property, looked up the way `GetProperty` does: own first, then the
10249/// prototype chain. Needed because the print formatter holds the interpreter
10250/// immutably and so cannot run getters.
10251fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
10252 let mut current = Some(object.clone());
10253 // Bounded, because a prototype cycle would otherwise loop forever.
10254 for _ in 0..100 {
10255 let node = current?;
10256 if let Some(property) = node.own_property(name)
10257 && let Some(value) = property.value
10258 {
10259 return Some(value.to_js_string());
10260 }
10261 current = node.with(|data| data.proto.clone());
10262 }
10263 None
10264}
10265
10266/// The `JS_PrintValue` state: output, and the objects currently being printed.
10267struct Printer<'a, 'rt> {
10268 /// Kept for the class-name lookups that typed arrays and `Date` will need.
10269 #[allow(dead_code)]
10270 interp: &'a Interp<'rt>,
10271 out: String,
10272 stack: Vec<Gc<JsObject>>,
10273}
10274
10275impl Printer<'_, '_> {
10276 /// Depth past which a container is summarised by its class name.
10277 const MAX_DEPTH: usize = 2;
10278
10279 fn value(&mut self, value: &Value, level: usize) {
10280 match value {
10281 Value::Undefined
10282 | Value::Uninitialized
10283 | Value::Hole
10284 | Value::CatchOffset(_)
10285 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
10286 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
10287 // The printer writes a bigint the way the language spells one, so a dump is
10288 // unambiguous about which kind of number it is showing.
10289 Value::BigInt(big) => {
10290 self.out.push_str(&big.to_decimal_string());
10291 self.out.push('n');
10292 }
10293 Value::Null => self.out.push_str("null"),
10294 Value::Bool(true) => self.out.push_str("true"),
10295 Value::Bool(false) => self.out.push_str("false"),
10296 Value::Int(number) => self.out.push_str(&number.to_string()),
10297 Value::Float(number) => {
10298 self.out
10299 .push_str(&crate::value::number_to_string_for_print(*number));
10300 }
10301 Value::String(text) => self.print_string(&text.to_string_lossy()),
10302 Value::Object(object) => self.object(object, level),
10303 }
10304 }
10305
10306 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
10307 // A cycle is reported rather than followed; the index is where the object
10308 // already sits in the print stack, which is what the reference shows.
10309 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
10310 self.out.push_str(&format!("[circular {index}]"));
10311 return;
10312 }
10313 if object.is_callable() {
10314 let name = object
10315 .own_property("name")
10316 .and_then(|property| property.value)
10317 .map(|value| value.to_js_string())
10318 .unwrap_or_default();
10319 if name.is_empty() {
10320 self.out.push_str("[Function (anonymous)]");
10321 } else {
10322 self.out.push_str(&format!("[Function {name}]"));
10323 }
10324 return;
10325 }
10326 if level >= Self::MAX_DEPTH {
10327 let class = if object.is_array() { "Array" } else { "Object" };
10328 self.out.push_str(&format!("[{class}]"));
10329 return;
10330 }
10331 // `Date` and `Error` print as themselves rather than as bags of properties:
10332 // the ISO string, and `Name: message` followed by the trace.
10333 if let Some(class) = class_of(self.interp, object) {
10334 if class == "Date" {
10335 self.date(object);
10336 return;
10337 }
10338 if class == "Error" {
10339 self.error(object);
10340 return;
10341 }
10342 }
10343 self.stack.push(object.clone());
10344 if object.is_array() {
10345 self.array(object, level);
10346 } else {
10347 self.plain_object(object, level);
10348 }
10349 self.stack.pop();
10350 }
10351
10352 /// A Date prints as its ISO string; an invalid one falls through to the plain
10353 /// object form, the way the reference falls back when `toISOString` throws.
10354 fn date(&mut self, object: &Gc<JsObject>) {
10355 let value = self
10356 .interp
10357 .internal_get(object, "_date_value")
10358 .map(|value| value.to_number());
10359 match value.and_then(crate::builtins::date::iso_string) {
10360 Some(text) => self.out.push_str(&text),
10361 None => self.plain_object(object, 0),
10362 }
10363 }
10364
10365 /// `Name: message`, then the trace with its trailing newline removed.
10366 fn error(&mut self, object: &Gc<JsObject>) {
10367 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
10368 self.out.push_str(&name);
10369 if let Some(message) = inherited(object, "message")
10370 && !message.is_empty()
10371 {
10372 self.out.push_str(": ");
10373 self.out.push_str(&message);
10374 }
10375 if let Some(stack) = inherited(object, "stack") {
10376 self.out.push('\n');
10377 self.out.push_str(stack.trim_end_matches('\n'));
10378 }
10379 }
10380
10381 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
10382 let elements = object.array_elements().unwrap_or_default();
10383 self.out.push_str("[ ");
10384 // An interior hole means the array is "sparse": the reference prints those
10385 // as `index: value` pairs and says nothing about the holes themselves, while
10386 // a hole run at the end becomes a single `<N empty items>` note.
10387 let last_present = elements
10388 .iter()
10389 .rposition(|value| !matches!(value, Value::Hole));
10390 let has_interior_hole = match last_present {
10391 Some(last) => elements[..last]
10392 .iter()
10393 .any(|value| matches!(value, Value::Hole)),
10394 None => false,
10395 };
10396 let mut first = true;
10397 if has_interior_hole {
10398 let mut index = 0;
10399 while index < elements.len() {
10400 let value = &elements[index];
10401 if matches!(value, Value::Hole) {
10402 index += 1;
10403 continue;
10404 }
10405 if !first {
10406 self.out.push_str(", ");
10407 }
10408 first = false;
10409 self.out.push_str(&format!("{index}: "));
10410 self.value(value, level + 1);
10411 index += 1;
10412 }
10413 } else {
10414 for (index, value) in elements.iter().enumerate() {
10415 if matches!(value, Value::Hole) {
10416 continue;
10417 }
10418 if !first {
10419 self.out.push_str(", ");
10420 }
10421 first = false;
10422 let _ = index;
10423 self.value(value, level + 1);
10424 }
10425 if let Some(last) = last_present {
10426 let trailing = elements.len() - last - 1;
10427 if trailing > 0 {
10428 if !first {
10429 self.out.push_str(", ");
10430 }
10431 self.out.push_str(&format!(
10432 "<{trailing} empty item{}>",
10433 if trailing > 1 { "s" } else { "" }
10434 ));
10435 }
10436 } else if !elements.is_empty() {
10437 let count = elements.len();
10438 self.out.push_str(&format!(
10439 "<{count} empty item{}>",
10440 if count > 1 { "s" } else { "" }
10441 ));
10442 }
10443 }
10444 self.out.push_str(" ]");
10445 }
10446
10447 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
10448 self.out.push_str("{ ");
10449 let mut first = true;
10450 for key in object.own_keys() {
10451 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
10452 continue;
10453 };
10454 if !property.enumerable {
10455 continue;
10456 }
10457 if !first {
10458 self.out.push_str(", ");
10459 }
10460 first = false;
10461 self.out
10462 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
10463 &key.to_string_lossy(),
10464 )));
10465 self.out.push_str(": ");
10466 // An accessor has no value to dump; the reference names the half that
10467 // exists instead of calling it.
10468 if property.is_accessor() {
10469 let text = match (property.getter.is_some(), property.setter.is_some()) {
10470 (true, true) => "[Getter/Setter]",
10471 (false, true) => "[Setter]",
10472 _ => "[Getter]",
10473 };
10474 self.out.push_str(text);
10475 } else {
10476 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
10477 }
10478 }
10479 self.out.push_str(" }");
10480 }
10481
10482 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
10483 fn print_string(&mut self, text: &str) {
10484 self.out.push('"');
10485 for character in text.chars() {
10486 match character {
10487 '"' => self.out.push_str("\\\""),
10488 '\\' => self.out.push_str("\\\\"),
10489 '\n' => self.out.push_str("\\n"),
10490 '\r' => self.out.push_str("\\r"),
10491 '\t' => self.out.push_str("\\t"),
10492 c if (c as u32) < 0x20 => {
10493 self.out.push_str(&format!("\\u{:04x}", c as u32));
10494 }
10495 c => self.out.push(c),
10496 }
10497 }
10498 self.out.push('"');
10499 }
10500}
10501
10502/// How `print` renders a value.
10503///
10504/// `ToString`, except that negative zero keeps its sign — the reference's host
10505/// printer does that while `String(-0)` is `"0"`.
10506pub fn display(value: &Value) -> String {
10507 match value {
10508 Value::Float(number) => crate::value::number_to_string_for_print(*number),
10509 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
10510 "undefined".to_string()
10511 }
10512 other => other.to_js_string(),
10513 }
10514}
10515
10516// ---------------------------------------------------------------------------
10517// Numeric operators
10518// ---------------------------------------------------------------------------
10519
10520/// `a + b` keeping the `Int` representation when it fits.
10521fn add_numbers(left: Value, right: Value) -> Value {
10522 match (&left, &right) {
10523 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10524 Some(sum) => Value::Int(sum),
10525 None => Value::Float(*a as f64 + *b as f64),
10526 },
10527 _ => Value::Float(left.to_number() + right.to_number()),
10528 }
10529}
10530
10531/// The arithmetic operators other than `+`, which needs string concatenation.
10532fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10533 use Opcode::*;
10534 let (a, b) = (left.to_number(), right.to_number());
10535 Ok(match op {
10536 Sub => match (&left, &right) {
10537 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
10538 Some(value) => Value::Int(value),
10539 None => Value::Float(a - b),
10540 },
10541 _ => Value::Float(a - b),
10542 },
10543 Mul => Value::Float(a * b),
10544 Div => Value::Float(a / b),
10545 Mod => Value::Float(js_mod(a, b)),
10546 Pow => Value::Float(a.powf(b)),
10547 And => Value::Int(left.to_int32() & right.to_int32()),
10548 Or => Value::Int(left.to_int32() | right.to_int32()),
10549 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
10550 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
10551 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
10552 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
10553 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
10554 // fits the small-integer representation stays an `Int`; the rest become a
10555 // float, which is how the reference keeps `n >>> 0` non-negative.
10556 Shr => {
10557 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
10558 match i32::try_from(shifted) {
10559 Ok(value) => Value::Int(value),
10560 Err(_) => Value::Float(shifted as f64),
10561 }
10562 }
10563 _ => Value::Float(a),
10564 })
10565}
10566
10567/// `%`, which follows the sign of the dividend rather than Rust's.
10568fn js_mod(left: f64, right: f64) -> f64 {
10569 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
10570 return f64::NAN;
10571 }
10572 if right.is_infinite() {
10573 return left;
10574 }
10575 let remainder = left % right;
10576 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
10577 // the spec makes the sign match the dividend.
10578 if remainder == 0.0 {
10579 0.0f64.copysign(left)
10580 } else {
10581 remainder
10582 }
10583}
10584
10585fn negate(value: Value) -> Value {
10586 match value {
10587 Value::Int(0) => Value::Float(-0.0),
10588 Value::Int(i) => Value::Int(-i),
10589 other => Value::Float(-other.to_number()),
10590 }
10591}
10592
10593fn increment(value: Value) -> Value {
10594 match value {
10595 Value::Int(i) => match i.checked_add(1) {
10596 Some(next) => Value::Int(next),
10597 None => Value::Float(i as f64 + 1.0),
10598 },
10599 other => Value::Float(other.to_number() + 1.0),
10600 }
10601}
10602
10603fn decrement(value: Value) -> Value {
10604 match value {
10605 Value::Int(i) => match i.checked_sub(1) {
10606 Some(next) => Value::Int(next),
10607 None => Value::Float(i as f64 - 1.0),
10608 },
10609 other => Value::Float(other.to_number() - 1.0),
10610 }
10611}
10612
10613/// Compare a `BigInt` with an `f64` on their mathematical values.
10614///
10615/// Neither side is rounded to the other's precision: the number is split into its integer
10616/// part (compared as an exact bigint) and its fraction, which is what decides the answer
10617/// when the integer parts are equal. An infinite value is larger than every bigint.
10618fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
10619 use std::cmp::Ordering;
10620 if number.is_nan() {
10621 return None;
10622 }
10623 if number.is_infinite() {
10624 return Some(if number > 0.0 {
10625 Ordering::Less
10626 } else {
10627 Ordering::Greater
10628 });
10629 }
10630 let truncated = number.trunc();
10631 // A number wider than `i128` still has an exact integer part, but no bigint form we can
10632 // build cheaply; the sign of the difference is all that is needed, so compare against
10633 // the bigint's own magnitude instead.
10634 if truncated.abs() >= 1.7e38 {
10635 let big_as_f64 = big.to_f64();
10636 return big_as_f64.partial_cmp(&number);
10637 }
10638 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
10639 match big.cmp(&integer) {
10640 Ordering::Equal => {
10641 // Same integer part: the fraction decides, and a negative number's fraction is
10642 // below the integer (`-1.5` truncates to `-1`).
10643 if number > truncated {
10644 Some(Ordering::Less)
10645 } else if number < truncated {
10646 Some(Ordering::Greater)
10647 } else {
10648 Some(Ordering::Equal)
10649 }
10650 }
10651 other => Some(other),
10652 }
10653}