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 /// What this frame costs against [`Interp::stack_limit`], in bytes.
282 ///
283 /// Cached rather than recomputed because it is charged on every call and a call is the
284 /// hottest thing in the interpreter.
285 cost: usize,
286 /// [`Interp::stack_used`] before this frame was pushed.
287 ///
288 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
289 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
290 /// leave the counter wrong. There are eight places that drop frames; one subtraction
291 /// forgotten in any of them would leak budget until the depth limit moved.
292 stack_base: usize,
293 /// Whether this frame's body ended in a `tail_call`.
294 ///
295 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
296 /// with its own frame just like `call` does and only skips storing the result
297 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
298 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
299 /// pushed as usual, and this marker makes its return value the *caller's* return
300 /// value without running the instructions after the call.
301 tail: bool,
302}
303
304impl js_gc::Trace for Frame {
305 fn trace(&self, tracer: &mut js_gc::Tracer) {
306 self.code.trace(tracer);
307 self.env.trace(tracer);
308 self.this.trace(tracer);
309 for value in &self.args {
310 value.trace(tracer);
311 }
312 for value in &self.passed {
313 value.trace(tracer);
314 }
315 for value in &self.locals {
316 value.trace(tracer);
317 }
318 for cell in &self.cells {
319 cell.trace(tracer);
320 }
321 if let Some(local_vars) = &self.local_vars {
322 tracer.visit(local_vars);
323 }
324 for value in &self.stack {
325 value.trace(tracer);
326 }
327 self.callee.trace(tracer);
328 self.new_target.trace(tracer);
329 }
330}
331
332/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
333/// emitted `if_false` treats as "keep going".
334const RESUME_NEXT: i32 = 0;
335/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
336/// generator fall into its `return_async`.
337const RESUME_RETURN: i32 = 1;
338/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
339/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
340/// must forward the exception into the inner iterator rather than finish.
341const RESUME_THROW: i32 = 2;
342
343/// One microtask.
344///
345/// The queue holds *data* rather than closures because its contents are GC values: a
346/// closure would be invisible to the collector, and a pending reaction is exactly the
347/// kind of thing that must keep its handlers and its promise alive.
348pub enum Job {
349 /// A `then` reaction about to run.
350 Reaction {
351 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
352 handler: Option<Value>,
353 /// The value or reason to call it with.
354 argument: Value,
355 /// Whether the source promise rejected, which decides the pass-through kind.
356 rejected: bool,
357 /// The promise the answer settles.
358 promise: Gc<JsObject>,
359 },
360 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
361 Thenable {
362 /// The `then` that was found on the value.
363 then: Value,
364 /// The thenable itself, which becomes `then`'s `this`.
365 value: Value,
366 /// The promise being resolved.
367 promise: Gc<JsObject>,
368 },
369 /// A pending `import(specifier)`.
370 Import {
371 /// The specifier, already converted to a string.
372 specifier: String,
373 /// The module that asked, which the specifier resolves against.
374 referrer: String,
375 /// The promise `import()` handed back.
376 promise: Gc<JsObject>,
377 },
378 /// An async generator resuming after the value it awaited settled.
379 GeneratorResume {
380 /// The async generator to continue.
381 generator: Gc<JsObject>,
382 /// The promise the pending method returned.
383 promise: Gc<JsObject>,
384 /// Whether this delivers the value or raises the reason.
385 kind: ResumeKind,
386 /// The settled value, or the rejection reason.
387 value: Value,
388 },
389 /// An async function resuming after the value it awaited settled.
390 Resume {
391 /// The body, parked in a coroutine.
392 coroutine: Gc<JsObject>,
393 /// The promise the async function handed its caller.
394 promise: Gc<JsObject>,
395 /// Whether this resumption delivers a value or raises one.
396 kind: ResumeKind,
397 /// The settled value, or the rejection reason.
398 value: Value,
399 },
400}
401
402/// One macro-task: work the event loop owes the script but has not run yet.
403///
404/// The microtask queue ([`Job`]) is different: those run before the host regains control.
405/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
406/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
407/// logic: the engine decides *what* is due, the host decides *how to wait*.
408///
409/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
410/// reference counting even though nothing else references it — the same rule the `HostFn`
411/// documentation states from the other side (a host closure must not hold a `Gc`, so the
412/// `Gc` lives here instead).
413pub enum Task {
414 /// A `setTimeout` that is due at `due_at`.
415 ///
416 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
417 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
418 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
419 /// would give this engine a timer the reference cannot produce, with nothing to
420 /// compare it against.
421 Timer {
422 /// The id `setTimeout` returned, for `clearTimeout`.
423 id: i32,
424 /// What to call when it fires.
425 callback: Value,
426 /// When it becomes runnable, as a monotonic instant.
427 due_at: std::time::Instant,
428 },
429}
430
431/// A descriptor the host has to poll, and which directions have a handler.
432///
433/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
434/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
435/// blocks on it, and the host reports back through [`Interp::fire_fd`].
436#[derive(Debug, Clone, Copy, PartialEq, Eq)]
437pub struct FdInterest {
438 /// The descriptor to watch.
439 pub fd: i32,
440 /// Whether `os.setReadHandler` registered a callback.
441 pub read: bool,
442 /// Whether `os.setWriteHandler` registered a callback.
443 pub write: bool,
444}
445
446/// The callbacks registered for one descriptor, per direction.
447#[derive(Default)]
448pub(crate) struct FdHandlers {
449 /// `os.setReadHandler`'s callback.
450 pub read: Option<Value>,
451 /// `os.setWriteHandler`'s callback.
452 pub write: Option<Value>,
453}
454
455/// The file name `eval` reports, which the reference does not inherit from the caller.
456///
457/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
458/// reference and the names show up in stack traces.
459/// The description of the private symbol a class brand is made from.
460///
461/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
462/// place no script can reach, since no expression can name a private symbol.
463const BRAND_DESCRIPTION: &str = "brand";
464
465/// One validated property lookup.
466pub struct FieldCache {
467 /// The object the lookup was made on, weakly.
468 object: js_gc::WeakGc<JsObject>,
469 /// The name, so two different properties of one object do not collide.
470 key: PropertyKey,
471 /// Where the value was found in that object's property table.
472 index: usize,
473}
474
475/// How many property lookups are remembered.
476///
477/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
478/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
479/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
480/// lookup itself. Making it bigger stops helping: the working set of a real program's
481/// property sites is bounded by its code size.
482const FIELD_CACHE_SLOTS: usize = 4096;
483
484/// How much the heap may grow past the last `out of memory` before saying it again.
485///
486/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
487/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
488/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
489/// because it looks like it works. The reference gets this for free: it fails inside
490/// `js_malloc`, and its printing path happens not to allocate.
491///
492/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
493/// allocating is stopped within a rounding error of the limit) and far above what a
494/// handler needs.
495const OOM_HYSTERESIS: usize = 64 * 1024;
496
497/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
498pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
499
500/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
501///
502/// Chosen so that the byte budget is what actually decides for every ordinary
503/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
504/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
505/// millions of frames.
506pub const MAX_FRAMES: usize = 200_000;
507
508const EVAL_FILE: &str = "<input>";
509
510/// The file name `std.evalScript` reports.
511const EVAL_SCRIPT_FILE: &str = "<evalScript>";
512
513/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
514///
515/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
516/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
517fn clamp_delay(delay_ms: f64) -> std::time::Duration {
518 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
519 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
520 // non-positive delay mean "due now".
521 if delay_ms.is_nan() || delay_ms <= 0.0 {
522 return std::time::Duration::ZERO;
523 }
524 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
525}
526
527impl js_gc::Trace for Task {
528 fn trace(&self, tracer: &mut js_gc::Tracer) {
529 let Task::Timer { callback, .. } = self;
530 callback.trace(tracer);
531 }
532}
533
534/// What one turn of the event loop did, so the caller cannot spin by accident.
535///
536/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
537/// core until the timer is due. Naming the three cases makes the wait explicit.
538#[derive(Debug, Clone, Copy, PartialEq, Eq)]
539pub enum Turn {
540 /// Something ran. Call again immediately — there may be more ready work.
541 Ran,
542 /// Nothing is runnable, but descriptors are registered: the host must poll
543 /// [`Interp::pending_fds`] for at most this long, then report readiness with
544 /// [`Interp::fire_fd`].
545 ///
546 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
547 /// the failure this project treats as worst — a handler that silently never fires —
548 /// so the two cannot be confused by accident.
549 Poll(std::time::Duration),
550 /// Nothing is runnable yet, but something is pending. Block at most this long, then
551 /// call again.
552 Wait(std::time::Duration),
553 /// Nothing is pending at all: the loop is done.
554 Done,
555}
556
557impl js_gc::Trace for Job {
558 fn trace(&self, tracer: &mut js_gc::Tracer) {
559 match self {
560 Job::Reaction {
561 handler,
562 argument,
563 promise,
564 ..
565 } => {
566 if let Some(handler) = handler {
567 handler.trace(tracer);
568 }
569 argument.trace(tracer);
570 tracer.visit(promise);
571 }
572 Job::Thenable {
573 then,
574 value,
575 promise,
576 } => {
577 then.trace(tracer);
578 value.trace(tracer);
579 tracer.visit(promise);
580 }
581 Job::Resume {
582 coroutine,
583 promise,
584 value,
585 ..
586 } => {
587 tracer.visit(coroutine);
588 tracer.visit(promise);
589 value.trace(tracer);
590 }
591 Job::Import { promise, .. } => tracer.visit(promise),
592 Job::GeneratorResume {
593 generator,
594 promise,
595 value,
596 ..
597 } => {
598 tracer.visit(generator);
599 tracer.visit(promise);
600 value.trace(tracer);
601 }
602 }
603 }
604}
605
606/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
608pub enum ResumeKind {
609 /// The generator was just created and is being run to its first suspension.
610 Start,
611 /// `next(v)`.
612 Next,
613 /// `return(v)`.
614 Return,
615 /// `throw(e)`.
616 Throw,
617}
618
619/// A generator object's saved execution.
620///
621/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
622/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
623/// separately allocated buffers.
624pub struct GeneratorState {
625 /// The detached frame, or `None` once the generator has finished or while it runs.
626 frame: Option<Frame>,
627 /// How far it got.
628 phase: GeneratorPhase,
629 /// Whether the last suspension was an `await` rather than a `yield`.
630 ///
631 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
632 /// value and a magic number, because the emitted code branches on which method
633 /// resumed it, while an `await` simply continues with its value. Getting this wrong
634 /// leaves an extra value on the operand stack that the next instruction then
635 /// consumes — a wrong answer rather than a crash.
636 parked_on_await: bool,
637 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
638 ///
639 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
640 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
641 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
642 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
643 /// delegating. Tracking it as part of the phase, the way the reference splits
644 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
645 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
646 /// exception and never reached `xs.throw`.
647 parked_on_yield_star: bool,
648 /// Pending `next`/`return`/`throw` calls, oldest first.
649 ///
650 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
651 /// called back to back must answer in that order, with the second call's value
652 /// arriving at the *second* `yield`. Running each call straight into the body — which
653 /// is what this engine did before — delivered the last queued value to whichever
654 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
655 /// `a === b ===` the final argument.
656 ///
657 /// The front entry is the one being served; it stays there (with `async_busy` set)
658 /// until its promise settles, because an `await` inside the body is a suspension of
659 /// the *driver*, not the end of the request.
660 requests: std::collections::VecDeque<AsyncRequest>,
661 /// Whether the front request is in flight.
662 async_busy: bool,
663}
664
665/// How one async-generator request ended.
666enum AsyncOutcome {
667 /// The method answered this `{value, done}`.
668 Value(Value),
669 /// The body threw.
670 Error(Value),
671}
672
673/// One queued `next`/`return`/`throw` on an async generator: the reference's
674/// `JSAsyncGeneratorRequest`.
675pub struct AsyncRequest {
676 /// Which method was called.
677 kind: ResumeKind,
678 /// Its argument.
679 value: Value,
680 /// The promise the method answered.
681 promise: Gc<JsObject>,
682}
683
684/// Which of §27.5.3.3's states a generator is in.
685#[derive(Debug, Clone, Copy, PartialEq, Eq)]
686enum GeneratorPhase {
687 /// Created, `initial_yield` reached, body not entered.
688 SuspendedStart,
689 /// Parked at a `yield`.
690 SuspendedYield,
691 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
692 Executing,
693 /// Finished; the frame is gone.
694 Completed,
695}
696
697impl js_gc::Trace for GeneratorState {
698 fn trace(&self, tracer: &mut js_gc::Tracer) {
699 if let Some(frame) = &self.frame {
700 frame.trace(tracer);
701 }
702 for request in &self.requests {
703 request.value.trace(tracer);
704 tracer.visit(&request.promise);
705 }
706 }
707}
708
709/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
710/// them in.
711///
712/// Each is a field rather than a map entry because the runtime reads them on hot paths
713/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
714/// failure — reaching a default here means the builtin did not install, and every
715/// accessor panics rather than silently answering `undefined`.
716///
717/// [`builtins::symbol`]: crate::builtins::symbol
718#[derive(Default)]
719pub struct WellKnownSymbols {
720 /// The symbol values, positionally. Empty until `Symbol` installs.
721 symbols: Vec<Value>,
722}
723
724/// Which well-known symbol a caller wants.
725///
726/// A typed accessor beats passing a name around: a typo is a compile error rather than
727/// an `undefined` key that quietly matches nothing.
728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
729pub enum WellKnown {
730 /// `Symbol.toPrimitive`.
731 ToPrimitive,
732 /// `Symbol.iterator`.
733 Iterator,
734 /// `Symbol.match`.
735 Match,
736 /// `Symbol.matchAll`.
737 MatchAll,
738 /// `Symbol.replace`.
739 Replace,
740 /// `Symbol.search`.
741 Search,
742 /// `Symbol.split`.
743 Split,
744 /// `Symbol.toStringTag`.
745 ToStringTag,
746 /// `Symbol.isConcatSpreadable`.
747 IsConcatSpreadable,
748 /// `Symbol.hasInstance`.
749 HasInstance,
750 /// `Symbol.species`.
751 Species,
752 /// `Symbol.unscopables`.
753 Unscopables,
754 /// `Symbol.asyncIterator`.
755 AsyncIterator,
756 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
757 Disposable,
758 /// `Symbol.asyncDispose` — the awaited form.
759 AsyncDisposable,
760}
761
762impl WellKnown {
763 /// The index `Symbol`'s installer creates this symbol at.
764 fn index(self) -> usize {
765 match self {
766 WellKnown::ToPrimitive => 0,
767 WellKnown::Iterator => 1,
768 WellKnown::Match => 2,
769 WellKnown::MatchAll => 3,
770 WellKnown::Replace => 4,
771 WellKnown::Search => 5,
772 WellKnown::Split => 6,
773 WellKnown::ToStringTag => 7,
774 WellKnown::IsConcatSpreadable => 8,
775 WellKnown::HasInstance => 9,
776 WellKnown::Species => 10,
777 WellKnown::Unscopables => 11,
778 WellKnown::AsyncIterator => 12,
779 WellKnown::Disposable => 13,
780 WellKnown::AsyncDisposable => 14,
781 }
782 }
783}
784
785impl Realm {
786 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
787 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
788 self.well_known_symbols.symbols = symbols;
789 }
790
791 /// A well-known symbol.
792 pub fn well_known(&self, which: WellKnown) -> Value {
793 self.well_known_symbols
794 .symbols
795 .get(which.index())
796 .cloned()
797 .unwrap_or(Value::Undefined)
798 }
799
800 /// The well-known symbol as a property key.
801 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
802 match self.well_known(which) {
803 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
804 // Unreachable once `Symbol` has installed; an empty string key matches
805 // nothing, which degrades to "the object has no such method".
806 _ => PropertyKey::from(String::new()),
807 }
808 }
809}
810
811/// The interpreter: a realm plus a frame stack.
812pub struct Interp<'a> {
813 /// The heap everything is allocated on.
814 pub heap: &'a Heap,
815 /// The realm.
816 pub realm: Realm,
817 /// Active frames, outermost first.
818 frames: Vec<Frame>,
819 /// A strict-mode `eval`'s own variable scope, while its script runs.
820 ///
821 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
822 /// become a global. Name lookups still fall through to the realm, which is why
823 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
824 eval_scope: Option<BTreeMap<String, Value>>,
825 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
826 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
827 eval_depth: usize,
828 /// The calling frame's own bindings, which the running `eval` can read and write.
829 ///
830 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
831 /// come from the frame, and a write is applied back to the frame (or to the cell
832 /// the frame captured) when the eval finishes. That is what makes
833 /// `f("a = 3")` visible to the caller as `a === 3`.
834 eval_bindings: Vec<EvalBinding>,
835 /// The calling frame's `arguments`, while an `eval` runs.
836 ///
837 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
838 /// own yet still has to see the caller's `arguments`.
839 eval_arguments: Option<Value>,
840 /// The `with` objects live at the moment the running `eval` started, innermost first.
841 ///
842 /// `None` outside an eval, which is what keeps a finished block's object from
843 /// shadowing ordinary bytecode reads.
844 eval_with: Option<Vec<Gc<JsObject>>>,
845 /// The bindings the running direct `eval` makes visible, as name → cell.
846 ///
847 /// Set for the duration of an eval and then restored, but every closure created
848 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
849 /// `eval("f = () => i")` work after the eval has returned.
850 active_eval_scope: Option<Gc<EvalScope>>,
851 /// The frame that called the direct `eval` currently running, if any.
852 ///
853 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
854 /// on the global object, which is what keeps
855 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
856 /// gives each call its own `x`.
857 eval_caller: Option<Option<usize>>,
858 /// The caller's `new.target`, while an `eval` runs.
859 ///
860 /// The eval'd code is a script with no constructor of its own, so it inherits the
861 /// one the enclosing function was called with.
862 eval_new_target: Option<Value>,
863 /// `new.target` for the frame about to be pushed.
864 ///
865 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
866 /// value reaches the frame without threading a parameter through every call site.
867 pending_new_target: Option<Value>,
868 /// Names of the native functions currently executing, outermost first.
869 ///
870 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
871 /// trace still names it with `(native)` instead of a position, so the names are
872 /// tracked separately and stitched into [`Interp::stack_trace`].
873 ///
874 /// The third field is how many bytecode frames were live when the native was entered,
875 /// which is what places it *among* them rather than before all of them. Native
876 /// functions used to be emitted up front on the grounds that they never re-enter
877 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
878 native_frames: Vec<(String, Gc<JsObject>, usize)>,
879 /// The native function currently executing, for the ones that have to know *which*
880 /// function they are — a typed-array constructor reads its element type off itself.
881 ///
882 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
883 /// reports whatever the enclosing bytecode frame was called with.
884 current_native: Option<Gc<JsObject>>,
885 /// Text written by `print` and friends, in order.
886 ///
887 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
888 /// once at the end, which is also when upstream's line buffering becomes
889 /// visible for the cases compared here.
890 pub output: String,
891 /// Where `print` also writes, as it goes. `output` keeps the full log for
892 /// [`crate::Context::output`]; this is the live copy, flushed per line.
893 ///
894 /// Both exist on purpose. A host that gives a script a sink sees output *when it
895 /// happens* — which is what a timer callback's `console.log` has to do, and what the
896 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
897 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
898 /// would show a script's output all at once when it finished.
899 pub output_sink: Option<Box<dyn std::io::Write>>,
900 /// Where recent property reads found their value.
901 ///
902 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
903 /// table remembering *which object* and *which entry of its property table* answered a
904 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
905 /// can move; the property can become an accessor), which is what makes a stale entry a
906 /// miss rather than a wrong answer.
907 ///
908 /// The object is held weakly: a cache that held it strongly would keep up to
909 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
910 /// program cannot see and cannot work around.
911 pub field_cache: Vec<Option<FieldCache>>,
912 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
913 /// under its limit. See [`Interp::check_memory`].
914 pub oom_reported_at: usize,
915 /// The most stack a JavaScript call chain may use, in bytes of frame state.
916 ///
917 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
918 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
919 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
920 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
921 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
922 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
923 ///
924 /// The numbers come out close for the same reason a C frame and a heap frame of this
925 /// shape cost about the same (both are a few hundred bytes, dominated by the value
926 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
927 /// and this engine lands in the same neighbourhood — measured, not fudged, by
928 /// `crates/quickjs-cli/tests/limits.rs`.
929 pub stack_limit: usize,
930 /// The most frames that may be live at once, whatever the byte budget says.
931 ///
932 /// A second bound for a reason the reference does not have: our frames cost less than
933 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
934 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
935 /// `--stack-size 1G` from being a memory bomb.
936 pub max_frames: usize,
937 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
938 ///
939 /// Script execution does not return until this has drained, which is what makes
940 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
941 /// than never. Reactions append to it while it drains, so the loop is a `while` and
942 /// not a `for`.
943 pub(crate) jobs: std::collections::VecDeque<Job>,
944 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
945 ///
946 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
947 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
948 pub(crate) tasks: Vec<Task>,
949 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
950 /// barrier'd evaluation started.
951 ///
952 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
953 /// lets a REPL report an error from the line it just evaluated without also reporting
954 /// its own readline loop.
955 trace_barriers: Vec<usize>,
956 /// `os.signal` handlers, keyed by signal number.
957 ///
958 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
959 /// a handler cannot be freed while it is still registered.
960 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
961 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
962 ///
963 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
964 /// that is only reachable from a host closure could be freed while still registered.
965 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
966 /// The next timer id.
967 ///
968 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
969 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
970 next_timer_id: i32,
971 /// Errors thrown by timer callbacks, already rendered.
972 ///
973 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
974 /// that throws has no promise behind it. Both are reported by the host at the end of
975 /// the loop, but only one is fixed up by a later `.catch`.
976 timer_errors: Vec<String>,
977 /// The module registry, keyed by canonical name.
978 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
979 /// How the host turns a specifier into bytes.
980 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
981 /// The module the host was asked to run, for `import.meta.main`.
982 pub main_module_name: Option<String>,
983 /// Module bodies currently running, innermost last.
984 ///
985 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
986 /// this is the only place that knows which module that is.
987 pub module_stack: Vec<String>,
988 /// Rejections that no handler has claimed, with the promise they belong to.
989 ///
990 /// A `then` registered later prunes its entry, which is why the promise is kept: the
991 /// reason alone cannot say whether somebody eventually listened.
992 unhandled: Vec<(Gc<JsObject>, Value)>,
993}
994
995impl<'a> Interp<'a> {
996 /// Build an interpreter over `heap`, with a fresh realm.
997 pub fn new(heap: &'a Heap) -> Interp<'a> {
998 let object_proto = JsObject::ordinary(heap, None);
999 let function_proto = JsObject::function(
1000 heap,
1001 Some(object_proto.clone()),
1002 Callable::Native {
1003 func: |_, _, _| Ok(Value::Undefined),
1004 own_instance: false,
1005 },
1006 );
1007 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1008 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1009 let mut interp = Interp {
1010 heap,
1011 realm: Realm {
1012 global,
1013 object_proto,
1014 function_proto,
1015 array_proto,
1016 globals: BTreeMap::new(),
1017 declared: Vec::new(),
1018 lexical_consts: BTreeSet::new(),
1019 errors: BTreeMap::new(),
1020 string_proto: None,
1021 number_proto: None,
1022 boolean_proto: None,
1023 bigint_proto: None,
1024 error_proto: JsObject::ordinary(heap, None),
1025 date_proto: JsObject::ordinary(heap, None),
1026 generator_proto: JsObject::ordinary(heap, None),
1027 promise_proto: None,
1028 async_generator_proto: None,
1029 symbol_proto: None,
1030 symbol_registry: BTreeMap::new(),
1031 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1032 regexp_proto: None,
1033 regexp_ctor: None,
1034 suppressed_error_proto: None,
1035 disposable_stack_proto: None,
1036 map_proto: None,
1037 set_proto: None,
1038 finalization_registries: Vec::new(),
1039 array_buffer_proto: None,
1040 typed_array_proto: None,
1041 typed_array_protos: Vec::new(),
1042 data_view_proto: None,
1043 async_disposable_stack_proto: None,
1044 iterator_proto: None,
1045 iterator_helper_proto: None,
1046 iterator_wrap_proto: None,
1047 generator_function_proto: None,
1048 async_function_proto: None,
1049 async_generator_function_proto: None,
1050 iterator_protos: std::collections::BTreeMap::new(),
1051 well_known_symbols: WellKnownSymbols::default(),
1052 },
1053 frames: Vec::new(),
1054 eval_scope: None,
1055 eval_depth: 0,
1056 eval_bindings: Vec::new(),
1057 eval_arguments: None,
1058 eval_with: None,
1059 active_eval_scope: None,
1060 eval_caller: None,
1061 pending_new_target: None,
1062 eval_new_target: None,
1063 native_frames: Vec::new(),
1064 current_native: None,
1065 output: String::new(),
1066 output_sink: None,
1067 field_cache: {
1068 let mut cache = Vec::new();
1069 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1070 cache
1071 },
1072 oom_reported_at: 0,
1073 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1074 // absent.
1075 stack_limit: DEFAULT_STACK_SIZE,
1076 max_frames: MAX_FRAMES,
1077 jobs: std::collections::VecDeque::new(),
1078 tasks: Vec::new(),
1079 trace_barriers: Vec::new(),
1080 signal_handlers: std::collections::BTreeMap::new(),
1081 fd_handlers: std::collections::BTreeMap::new(),
1082 next_timer_id: 1,
1083 timer_errors: Vec::new(),
1084 modules: std::collections::BTreeMap::new(),
1085 module_loader: None,
1086 main_module_name: None,
1087 module_stack: Vec::new(),
1088 unhandled: Vec::new(),
1089 };
1090 crate::builtins::install(&mut interp);
1091 interp
1092 }
1093
1094 // -- allocation helpers -------------------------------------------------
1095
1096 /// A new string value.
1097 /// A `BigInt` value from a computed big integer.
1098 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1099 Value::BigInt(Gc::new(self.heap, value))
1100 }
1101
1102 /// A string value from bytes that are already WTF-8, which is how a string with an
1103 /// unpaired surrogate reaches a `Value`.
1104 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1105 Value::string_wtf8(self.heap, text)
1106 }
1107
1108 /// A new string value, from text that is valid UTF-8.
1109 pub fn string(&self, text: impl Into<String>) -> Value {
1110 Value::string(self.heap, text)
1111 }
1112
1113 /// A new ordinary object with the given prototype.
1114 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1115 JsObject::ordinary(self.heap, proto)
1116 }
1117
1118 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1119 ///
1120 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1121 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1122 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1123 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1124 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1125 /// said `[object Object]` instead of `[object Array Iterator]`.
1126 ///
1127 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1128 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1129 /// its own.
1130 pub fn new_iterator_prototype(
1131 &mut self,
1132 tag: &str,
1133 next: crate::object::NativeFn,
1134 ) -> Gc<JsObject> {
1135 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1136 return existing.clone();
1137 }
1138 let parent = self.realm.iterator_proto.clone();
1139 let proto = self.new_object(parent);
1140 let next = self.new_native("next", 0, next);
1141 proto.define(
1142 "next",
1143 Property::with_attributes(Value::Object(next), true, false),
1144 );
1145 let key = self.realm.well_known_key(WellKnown::Iterator);
1146 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1147 proto.define_key(
1148 &key,
1149 Property::with_attributes(Value::Object(identity), true, false),
1150 );
1151 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1152 let tag_value = self.string(tag);
1153 proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
1154 self.realm
1155 .iterator_protos
1156 .insert(tag.to_string(), proto.clone());
1157 proto
1158 }
1159
1160 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1161 ///
1162 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1163 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1164 /// produced. That is why the two branches are not merged.
1165 pub fn object_own_property_keys(
1166 &mut self,
1167 object: &Gc<JsObject>,
1168 ) -> JsResult<Vec<PropertyKey>> {
1169 if let Some(keys) = self.proxy_own_keys(object)? {
1170 return Ok(keys);
1171 }
1172 // Integer-like keys ascending, then the string keys in insertion order, then the
1173 // symbols — the order every schema that walks an object expects.
1174 let entries = object.property_entries();
1175 let mut numeric: Vec<u32> = Vec::new();
1176 let mut strings: Vec<PropertyKey> = Vec::new();
1177 let mut symbols: Vec<PropertyKey> = Vec::new();
1178 for (key, _) in entries {
1179 match &key {
1180 // A class-private name is never reported by any enumeration: that is the
1181 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1182 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1183 // symbol skip, `Object.assign`) therefore cannot see it.
1184 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1185 PropertyKey::Symbol(_) => symbols.push(key),
1186 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1187 Some(index) => {
1188 if !numeric.contains(&index) {
1189 numeric.push(index);
1190 }
1191 }
1192 None => strings.push(key),
1193 },
1194 }
1195 }
1196 numeric.sort_unstable();
1197 let mut keys: Vec<PropertyKey> = numeric
1198 .into_iter()
1199 .map(|index| PropertyKey::from(index.to_string()))
1200 .collect();
1201 keys.extend(strings);
1202 keys.extend(symbols);
1203 Ok(keys)
1204 }
1205
1206 /// The state behind a promise object, or `None` when `object` is not one.
1207 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1208 object.with(|data| match &data.kind {
1209 ObjectKind::Promise(state) => Some(state.clone()),
1210 _ => None,
1211 })
1212 }
1213
1214 /// A new pending promise.
1215 pub fn new_promise(&mut self) -> Gc<JsObject> {
1216 let proto = self.realm.promise_proto.clone();
1217 let promise = JsObject::ordinary(self.heap, proto);
1218 promise.with_mut(|data| {
1219 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1220 crate::object::PromiseState::default(),
1221 )));
1222 });
1223 promise
1224 }
1225
1226 /// Fulfil `promise`, unless it has already settled.
1227 ///
1228 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1229 /// after `reject`, changes nothing.
1230 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1231 let Some(state) = self.promise_state(promise) else {
1232 return;
1233 };
1234 let reactions = {
1235 let mut state = state.borrow_mut();
1236 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1237 return;
1238 }
1239 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1240 std::mem::take(&mut state.reactions)
1241 };
1242 self.queue_reactions(reactions, value, false);
1243 }
1244
1245 /// Reject `promise`, unless it has already settled.
1246 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1247 let Some(state) = self.promise_state(promise) else {
1248 return;
1249 };
1250 let reactions = {
1251 let mut state = state.borrow_mut();
1252 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1253 return;
1254 }
1255 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1256 std::mem::take(&mut state.reactions)
1257 };
1258 // Remember it only when nothing is listening *now*; a `then` registered later
1259 // prunes the entry in `perform_then`.
1260 if reactions.is_empty() {
1261 self.unhandled.push((promise.clone(), reason.clone()));
1262 }
1263 self.queue_reactions(reactions, reason, true);
1264 }
1265
1266 /// Queue one job per reaction.
1267 ///
1268 /// This is what makes `then` asynchronous even on an already-settled promise:
1269 /// `p.then(f); g()` calls `g` first.
1270 fn queue_reactions(
1271 &mut self,
1272 reactions: Vec<crate::object::PromiseReaction>,
1273 argument: Value,
1274 rejected: bool,
1275 ) {
1276 for reaction in reactions {
1277 let handler = if rejected {
1278 reaction.on_rejected.clone()
1279 } else {
1280 reaction.on_fulfilled.clone()
1281 };
1282 self.jobs.push_back(Job::Reaction {
1283 handler,
1284 argument: argument.clone(),
1285 rejected,
1286 promise: reaction.promise,
1287 });
1288 }
1289 }
1290
1291 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1292 /// resolve/reject pair.
1293 ///
1294 /// The pair are callable objects rather than Rust closures, because the script gets
1295 /// them and may stash them for later.
1296 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1297 let promise = self.new_promise();
1298 let resolve = JsObject::function(
1299 self.heap,
1300 Some(self.realm.function_proto.clone()),
1301 Callable::PromiseResolve(promise.clone()),
1302 );
1303 let reject = JsObject::function(
1304 self.heap,
1305 Some(self.realm.function_proto.clone()),
1306 Callable::PromiseReject(promise.clone()),
1307 );
1308 (promise, Value::Object(resolve), Value::Object(reject))
1309 }
1310
1311 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1312 /// promise, as `{ value: completion }`.
1313 ///
1314 /// The three cases are the reference's, and they differ on purpose:
1315 ///
1316 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1317 /// exception before any promise exists;
1318 /// * a **runtime** error rejects the returned promise;
1319 /// * success resolves it with `{ value }`, where the value is the script's completion
1320 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1321 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1322 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1323 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1324 ///
1325 /// # What this does not do
1326 ///
1327 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1328 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1329 /// the parser and the suspension machinery to accept a suspended top-level script, and
1330 /// is not implemented — such source is a syntax error here. Everything else about the
1331 /// flag is reproduced.
1332 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1333 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1334 // too, and the reference truncates that one at the same place as a runtime failure.
1335 if barrier {
1336 let depth = self.frames.len();
1337 self.trace_barriers.push(depth);
1338 }
1339 // Compiled before the promise exists, so a parse failure propagates as a throw
1340 // instead of being folded into a rejection.
1341 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1342 Ok(compiled) => compiled,
1343 Err(error) => {
1344 if barrier {
1345 self.trace_barriers.pop();
1346 }
1347 return Err(error);
1348 }
1349 };
1350 // An async body answers its own promise, and that promise is what the reference
1351 // hands back — the same object, not a wrapper around it. Its resolution value is
1352 // the `{value}` object the compiled epilogue built.
1353 if compiled.kind.is_async() {
1354 let strict = compiled.strict;
1355 let promise = self.run_eval_script(compiled, strict)?;
1356 if barrier {
1357 self.trace_barriers.pop();
1358 }
1359 return Ok(promise);
1360 }
1361 let (promise, resolve, reject) = self.new_promise_capability();
1362 let strict = compiled.strict;
1363 match self.run_eval_script(compiled, strict) {
1364 Ok(value) => {
1365 // `{ value }` is a plain object, so resolving with it adopts nothing even
1366 // when the completion value is itself a promise.
1367 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1368 self.set_property(&wrapped, "value", value)?;
1369 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1370 }
1371 Err(Signal::Throw(error)) => {
1372 self.call_value(reject, Value::Undefined, vec![error])?;
1373 }
1374 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1375 }
1376 if barrier {
1377 self.trace_barriers.pop();
1378 }
1379 Ok(Value::Object(promise))
1380 }
1381
1382 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1383 ///
1384 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1385 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1386 /// timer table, where the collector already scans it.
1387 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1388 let (promise, resolve, _reject) = self.new_promise_capability();
1389 let resolve = self.new_host_function(
1390 "resolve",
1391 1,
1392 Box::new(
1393 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1394 let value = args.first().cloned().unwrap_or(Value::Undefined);
1395 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1396 },
1397 ),
1398 );
1399 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1400 // timer table is part of what the collector walks.
1401 self.schedule_timer(Value::Object(resolve), delay_ms);
1402 Ok(Value::Object(promise))
1403 }
1404
1405 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1406 /// new promise resolved with it.
1407 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1408 if let Value::Object(object) = &value
1409 && self.promise_state(object).is_some()
1410 {
1411 return Ok(value);
1412 }
1413 let promise = self.new_promise();
1414 self.resolve_promise_with(&promise, value)?;
1415 Ok(Value::Object(promise))
1416 }
1417
1418 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1419 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1420 // Resolving a promise with itself is a `TypeError`. The check exists because the
1421 // alternative is a chain of self-reactions that never settles.
1422 if let Value::Object(object) = &value
1423 && object.ptr_eq(promise)
1424 {
1425 // The spec rejects *and* throws, so both the promise and the caller see it.
1426 let thrown = self.type_error("cannot resolve a promise with itself");
1427 let Signal::Throw(error) = thrown.clone() else {
1428 unreachable!("type_error always throws")
1429 };
1430 self.reject_promise(promise, error);
1431 return Err(thrown);
1432 }
1433 let then = match &value {
1434 Value::Object(object) => self.get_property(object, "then")?,
1435 _ => None,
1436 };
1437 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1438 if !callable_then {
1439 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1440 self.fulfill_promise(promise, value);
1441 return Ok(());
1442 }
1443 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1444 // inside `resolve`, so a script cannot make a promise settle synchronously.
1445 self.jobs.push_back(Job::Thenable {
1446 then: then.expect("checked callable"),
1447 value,
1448 promise: promise.clone(),
1449 });
1450 Ok(())
1451 }
1452
1453 /// `Promise.prototype.then`: register a reaction and answer the derived promise.
1454 pub fn perform_then(
1455 &mut self,
1456 promise: &Gc<JsObject>,
1457 on_fulfilled: Option<Value>,
1458 on_rejected: Option<Value>,
1459 ) -> JsResult<Value> {
1460 let Some(state) = self.promise_state(promise) else {
1461 return Err(self.type_error("not a promise"));
1462 };
1463 // Whether a rejection handler is being attached decides whether a recorded
1464 // rejection stops being unhandled, so it is read before the values are moved.
1465 let has_rejection_handler = on_rejected.is_some();
1466 let derived = self.new_promise();
1467 let reaction = crate::object::PromiseReaction {
1468 on_fulfilled,
1469 on_rejected,
1470 promise: derived.clone(),
1471 };
1472 let settled = {
1473 let mut state = state.borrow_mut();
1474 // A rejection somebody reacts to is no longer unhandled.
1475 state.handled = true;
1476 match &state.status {
1477 crate::object::PromiseStatus::Pending => {
1478 state.reactions.push(reaction.clone());
1479 None
1480 }
1481 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1482 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1483 }
1484 };
1485 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1486 // later, means somebody is listening after all.
1487 if has_rejection_handler {
1488 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1489 }
1490 if let Some((argument, rejected)) = settled {
1491 let handler = if rejected {
1492 reaction.on_rejected
1493 } else {
1494 reaction.on_fulfilled
1495 };
1496 self.jobs.push_back(Job::Reaction {
1497 handler,
1498 argument,
1499 rejected,
1500 promise: reaction.promise,
1501 });
1502 }
1503 Ok(Value::Object(derived))
1504 }
1505
1506 /// The rejections nobody listened to, formatted the way the reference reports them.
1507 ///
1508 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
1509 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
1510 /// unhandled at the point the queue drains, because a `then` may still be attached
1511 /// before the host acts on it.
1512 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
1513 let entries = std::mem::take(&mut self.unhandled);
1514 // Somebody may have attached a handler after the rejection was recorded, so the
1515 // promise is the authority rather than the list.
1516 let still_unhandled: Vec<Value> = entries
1517 .into_iter()
1518 .filter_map(|(promise, reason)| {
1519 let handled = self
1520 .promise_state(&promise)
1521 .map(|state| state.borrow().handled)
1522 .unwrap_or(true);
1523 (!handled).then_some(reason)
1524 })
1525 .collect();
1526 still_unhandled
1527 .into_iter()
1528 .map(|reason| {
1529 let text = self.describe_exception(&reason);
1530 let stack = match &reason {
1531 Value::Object(object) => self
1532 .get_property(object, "stack")
1533 .ok()
1534 .flatten()
1535 .map(|value| value.to_js_string())
1536 // `stack` carries a trailing newline of its own, which would leave
1537 // a blank line between two reported rejections.
1538 .map(|text| text.trim_end().to_string())
1539 .unwrap_or_default(),
1540 _ => String::new(),
1541 };
1542 if stack.is_empty() {
1543 format!("Possibly unhandled promise rejection: {text}")
1544 } else {
1545 format!("Possibly unhandled promise rejection: {text}\n{stack}")
1546 }
1547 })
1548 .collect()
1549 }
1550
1551 /// Run the microtask queue to exhaustion.
1552 ///
1553 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
1554 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
1555 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
1556 ///
1557 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
1558 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
1559 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
1560 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
1561 crate::builtins::json::parse_text(self, text, true)
1562 }
1563
1564 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
1565 ///
1566 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
1567 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
1568 /// immediately, and `setTimeout(f, -1)` is ordinary code.
1569 ///
1570 /// The callback is called with **no arguments**. The reference stores only the function
1571 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
1572 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
1573 /// extra arguments arrive as `undefined`.
1574 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
1575 let id = self.next_timer_id;
1576 // Wrap rather than grow: the id reaches the script as an `Int32`.
1577 self.next_timer_id = if self.next_timer_id == i32::MAX {
1578 1
1579 } else {
1580 self.next_timer_id + 1
1581 };
1582 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
1583 self.tasks.push(Task::Timer {
1584 id,
1585 callback,
1586 due_at,
1587 });
1588 id
1589 }
1590
1591 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
1592 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
1593 pub fn cancel_timer(&mut self, id: i32) -> bool {
1594 let before = self.tasks.len();
1595 self.tasks.retain(|task| match task {
1596 Task::Timer { id: task_id, .. } => *task_id != id,
1597 });
1598 self.tasks.len() != before
1599 }
1600
1601 /// How long until the earliest pending timer, or `None` when none is pending.
1602 pub fn next_timeout(&self) -> Option<std::time::Duration> {
1603 let now = std::time::Instant::now();
1604 self.tasks
1605 .iter()
1606 .map(|task| match task {
1607 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
1608 })
1609 .min()
1610 }
1611
1612 /// Run one turn of the event loop.
1613 ///
1614 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
1615 /// run at most one due timer, then drain again. The blocking belongs to the caller
1616 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
1617 /// is how it asks.
1618 ///
1619 /// One timer per turn rather than all of them: a timer callback may schedule another
1620 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
1621 /// starve the microtask queue.
1622 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
1623 self.drain_jobs()?;
1624 let now = std::time::Instant::now();
1625 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
1626 // followed by `setTimeout(g, 1)` must run `g` first.
1627 let due = self
1628 .tasks
1629 .iter()
1630 .enumerate()
1631 .filter(|(_, task)| match task {
1632 Task::Timer { due_at, .. } => *due_at <= now,
1633 })
1634 .min_by_key(|(_, task)| match task {
1635 Task::Timer { due_at, .. } => *due_at,
1636 })
1637 .map(|(index, _)| index);
1638 let Some(index) = due else {
1639 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
1640 // descriptor is registered but no timer is closer, so a script that never
1641 // touches the descriptor still gets control back. Without a cap a handler on a
1642 // descriptor that is never ready would block for as long as the host allows.
1643 let timeout = self
1644 .next_timeout()
1645 .unwrap_or(std::time::Duration::from_secs(10))
1646 .min(std::time::Duration::from_secs(10));
1647 if !self.fd_handlers.is_empty() {
1648 // Blocking on a timer while descriptors are registered would starve them,
1649 // and blocking on the descriptors while a timer is due would delay it; the
1650 // host polls with the earlier of the two deadlines, which this timeout is.
1651 return Ok(Turn::Poll(timeout));
1652 }
1653 return Ok(match self.next_timeout() {
1654 Some(wait) => Turn::Wait(wait),
1655 None => Turn::Done,
1656 });
1657 };
1658 let Task::Timer { callback, .. } = self.tasks.remove(index);
1659 let this = Value::Undefined;
1660 // A throwing timer callback must not stop the loop: the reference reports it and
1661 // keeps going, because the alternative is that one bad timer silently stops every
1662 // later one.
1663 // No arguments: see `schedule_timer` — the reference calls the callback bare.
1664 match self.call_value(callback, this, Vec::new()) {
1665 Ok(_) => {}
1666 Err(Signal::Throw(value)) => {
1667 let text = self.describe_exception(&value);
1668 self.timer_errors.push(text);
1669 }
1670 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1671 }
1672 self.drain_jobs()?;
1673 Ok(Turn::Ran)
1674 }
1675
1676 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
1677 ///
1678 /// `callback` of `None` unregisters that direction, and an entry with neither direction
1679 /// left is removed — the reference does the same, so a script can rely on
1680 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
1681 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
1682 let entry = self.fd_handlers.entry(fd).or_default();
1683 if readable {
1684 entry.read = callback;
1685 } else {
1686 entry.write = callback;
1687 }
1688 if entry.read.is_none() && entry.write.is_none() {
1689 self.fd_handlers.remove(&fd);
1690 }
1691 }
1692
1693 /// Register or clear an `os.signal` handler.
1694 ///
1695 /// `None` removes it; the host separately restores the default disposition or sets
1696 /// ignore, because which of those happened is the script's choice (`null` versus
1697 /// `undefined`) and not something this table can express.
1698 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
1699 match handler {
1700 Some(handler) => {
1701 self.signal_handlers.insert(signal, handler);
1702 }
1703 None => {
1704 self.signal_handlers.remove(&signal);
1705 }
1706 }
1707 }
1708
1709 /// Run the handler for `signal`, reporting whether one ran.
1710 ///
1711 /// A throwing handler is reported and the loop continues, like a timer's.
1712 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
1713 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
1714 return Ok(false);
1715 };
1716 match self.call_value(handler, Value::Undefined, Vec::new()) {
1717 Ok(_) => {}
1718 Err(Signal::Throw(value)) => {
1719 let text = self.describe_exception(&value);
1720 self.timer_errors.push(text);
1721 }
1722 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1723 }
1724 self.drain_jobs()?;
1725 Ok(true)
1726 }
1727
1728 /// The descriptors the host has to poll, and in which direction.
1729 ///
1730 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
1731 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
1732 /// `os_poll` asks for.
1733 pub fn pending_fds(&self) -> Vec<FdInterest> {
1734 self.fd_handlers
1735 .iter()
1736 .map(|(fd, entry)| FdInterest {
1737 fd: *fd,
1738 read: entry.read.is_some(),
1739 write: entry.write.is_some(),
1740 })
1741 .collect()
1742 }
1743
1744 /// Call the handler registered for `fd`, reporting whether one ran.
1745 ///
1746 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
1747 /// poll iteration and then restarts the loop, because the handler may have changed the
1748 /// registration list underneath it; doing the same here keeps a handler that
1749 /// unregisters itself from being called with stale state.
1750 ///
1751 /// A throwing handler is reported and the loop continues — a bad handler must not stop
1752 /// every later one, exactly as with timers.
1753 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
1754 let Some(entry) = self.fd_handlers.get(&fd) else {
1755 return Ok(false);
1756 };
1757 let callback = if readable {
1758 entry.read.clone()
1759 } else if writable {
1760 entry.write.clone()
1761 } else {
1762 None
1763 };
1764 let Some(callback) = callback else {
1765 return Ok(false);
1766 };
1767 self.drain_jobs()?;
1768 match self.call_value(callback, Value::Undefined, Vec::new()) {
1769 Ok(_) => {}
1770 Err(Signal::Throw(value)) => {
1771 let text = self.describe_exception(&value);
1772 self.timer_errors.push(text);
1773 }
1774 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1775 }
1776 self.drain_jobs()?;
1777 Ok(true)
1778 }
1779
1780 /// Take the errors timer callbacks threw, leaving the list empty.
1781 pub fn take_timer_errors(&mut self) -> Vec<String> {
1782 std::mem::take(&mut self.timer_errors)
1783 }
1784
1785 /// Whether anything is still pending: a microtask or a timer.
1786 pub fn has_pending_work(&self) -> bool {
1787 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
1788 }
1789
1790 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
1791 pub fn has_pending_timers_or_jobs(&self) -> bool {
1792 !self.jobs.is_empty() || !self.tasks.is_empty()
1793 }
1794
1795 /// Run every queued microtask, including ones queued while draining.
1796 pub fn drain_jobs(&mut self) -> JsResult<()> {
1797 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
1798 // would spin forever, so the drain is bounded the way the call stack is.
1799 let mut budget = 1_000_000usize;
1800 while let Some(job) = self.jobs.pop_front() {
1801 if budget == 0 {
1802 return Err(Signal::Throw(
1803 self.make_error("InternalError", "promise job queue did not drain"),
1804 ));
1805 }
1806 budget -= 1;
1807 self.run_job(job)?;
1808 // `FinalizationRegistry` at the job boundary: this is the safe point where the
1809 // engine may run script that the script itself did not ask for. Doing it here
1810 // rather than from a drop hook is what keeps the callback out of arbitrary
1811 // engine bookkeeping — see `builtins::weak`'s header.
1812 crate::builtins::weak::drain_finalizers(self)?;
1813 }
1814 // A script that queued no jobs may still have dropped targets, so the checkpoint
1815 // runs once more after the queue empties.
1816 crate::builtins::weak::drain_finalizers(self)?;
1817 Ok(())
1818 }
1819
1820 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
1821 ///
1822 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
1823 /// `None` and is swept out here. This is also where the realm learns that a registry
1824 /// died, which is why it is a mutation rather than a read.
1825 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
1826 let handles = std::mem::take(&mut self.realm.finalization_registries);
1827 let mut live = Vec::with_capacity(handles.len());
1828 for handle in handles {
1829 let Some(object) = handle.upgrade() else {
1830 continue;
1831 };
1832 let Some(state) = object.finalization_state() else {
1833 continue;
1834 };
1835 live.push((object.clone(), *state));
1836 self.realm.finalization_registries.push(object.downgrade());
1837 }
1838 live
1839 }
1840
1841 /// Run one microtask.
1842 fn run_job(&mut self, job: Job) -> JsResult<()> {
1843 match job {
1844 Job::Reaction {
1845 handler: None,
1846 argument,
1847 rejected,
1848 promise,
1849 } => {
1850 // No handler: the settlement passes straight through to the derived
1851 // promise, which is why `p.catch(f)` ignores fulfilments.
1852 if rejected {
1853 self.reject_promise(&promise, argument);
1854 } else {
1855 self.fulfill_promise(&promise, argument);
1856 }
1857 Ok(())
1858 }
1859 Job::Reaction {
1860 handler: Some(handler),
1861 argument,
1862 promise,
1863 ..
1864 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
1865 Ok(answer) => {
1866 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
1867 self.reject_promise(&promise, error);
1868 }
1869 Ok(())
1870 }
1871 Err(Signal::Throw(reason)) => {
1872 self.reject_promise(&promise, reason);
1873 Ok(())
1874 }
1875 Err(other) => Err(other),
1876 },
1877 Job::Thenable {
1878 then,
1879 value,
1880 promise,
1881 } => {
1882 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
1883 // the value it produces settles `promise`.
1884 // The thenable's `then` gets this promise's own pair, so whatever it
1885 // produces settles `promise`.
1886 let resolve = JsObject::function(
1887 self.heap,
1888 Some(self.realm.function_proto.clone()),
1889 Callable::PromiseResolve(promise.clone()),
1890 );
1891 let reject = JsObject::function(
1892 self.heap,
1893 Some(self.realm.function_proto.clone()),
1894 Callable::PromiseReject(promise.clone()),
1895 );
1896 match self.call_value(
1897 then,
1898 value,
1899 vec![Value::Object(resolve), Value::Object(reject)],
1900 ) {
1901 Ok(_) => Ok(()),
1902 Err(Signal::Throw(reason)) => {
1903 self.reject_promise(&promise, reason);
1904 Ok(())
1905 }
1906 Err(other) => Err(other),
1907 }
1908 }
1909 Job::Resume {
1910 coroutine,
1911 promise,
1912 kind,
1913 value,
1914 } => self.drive_async(&coroutine, &promise, kind, value),
1915 Job::GeneratorResume {
1916 generator,
1917 promise,
1918 kind,
1919 value,
1920 } => self.step_async_generator(&generator, &promise, kind, value),
1921 Job::Import {
1922 specifier,
1923 referrer,
1924 promise,
1925 } => {
1926 self.run_dynamic_import(&specifier, &referrer, &promise);
1927 Ok(())
1928 }
1929 }
1930 }
1931
1932 /// One element of a `Promise` combinator settled.
1933 ///
1934 /// The shared state object holds the results array, the number still outstanding, and
1935 /// the combinator's own resolve/reject pair. `all` fills by index so the answer keeps
1936 /// the input order; `race` settles on the first element and ignores the rest, which a
1937 /// one-shot settle gives for free.
1938 fn settle_combinator(
1939 &mut self,
1940 state: &Gc<JsObject>,
1941 index: usize,
1942 fulfilled: bool,
1943 value: Value,
1944 ) -> JsResult<()> {
1945 let kind = state
1946 .own_property("kind")
1947 .and_then(|property| property.value)
1948 .map(|value| value.to_int32())
1949 .unwrap_or(0);
1950 let outcome = state
1951 .own_property("outcome")
1952 .and_then(|property| property.value);
1953 let Some(Value::Object(outcome)) = outcome else {
1954 return Ok(());
1955 };
1956 if kind == 3 {
1957 // `race`: the first settlement wins; the rest are ignored by the one-shot rule.
1958 if fulfilled {
1959 self.resolve_promise_with(&outcome, value)?;
1960 } else {
1961 self.reject_promise(&outcome, value);
1962 }
1963 return Ok(());
1964 }
1965 let results = state
1966 .own_property("results")
1967 .and_then(|property| property.value)
1968 .and_then(|value| value.as_object().cloned());
1969 let remaining = state
1970 .own_property("remaining")
1971 .and_then(|property| property.value)
1972 .map(|value| value.to_int32())
1973 .unwrap_or(0);
1974 match kind {
1975 0 => {
1976 // `all`: the first rejection wins outright.
1977 if !fulfilled {
1978 self.reject_promise(&outcome, value);
1979 return Ok(());
1980 }
1981 let Some(results) = &results else {
1982 return Ok(());
1983 };
1984 results.array_set(self.heap, index, value);
1985 }
1986 1 => {
1987 // `allSettled`: never rejects; each slot records what happened.
1988 let Some(results) = &results else {
1989 return Ok(());
1990 };
1991 let record = self.new_object(Some(self.realm.object_proto.clone()));
1992 if fulfilled {
1993 record.define_data("status", self.string("fulfilled"));
1994 record.define_data("value", value);
1995 } else {
1996 record.define_data("status", self.string("rejected"));
1997 record.define_data("reason", value);
1998 }
1999 results.array_set(self.heap, index, Value::Object(record));
2000 }
2001 // `any`: the first fulfilment wins; a full sweep of rejections does not settle
2002 // here — it is handled by the count below.
2003 2 if fulfilled => {
2004 self.resolve_promise_with(&outcome, value)?;
2005 return Ok(());
2006 }
2007 _ => {}
2008 }
2009 let left = remaining - 1;
2010 state.define_data("remaining", Value::Int(left));
2011 if left != 0 {
2012 return Ok(());
2013 }
2014 match kind {
2015 0 | 1 => {
2016 let Some(results) = results else {
2017 return Ok(());
2018 };
2019 self.resolve_promise_with(&outcome, Value::Object(results))?;
2020 }
2021 2 => {
2022 let error = self.make_error("AggregateError", "all promises were rejected");
2023 self.reject_promise(&outcome, error);
2024 }
2025 _ => {}
2026 }
2027 Ok(())
2028 }
2029
2030 /// Build an async function's result: a promise whose body runs as a coroutine.
2031 pub fn new_async_function(
2032 &mut self,
2033 function: Value,
2034 this: Value,
2035 args: Vec<Value>,
2036 ) -> JsResult<Value> {
2037 let promise = self.new_promise();
2038 let coroutine = self.new_coroutine(function, this, args)?;
2039 if let Err(Signal::Throw(reason)) =
2040 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2041 {
2042 self.reject_promise(&promise, reason);
2043 }
2044 Ok(Value::Object(promise))
2045 }
2046
2047 /// The coroutine an async body runs in.
2048 ///
2049 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2050 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2051 /// than growing a second state machine. The difference is only in the ending — a
2052 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2053 /// Run `code` as an async function body, answering the promise it settles.
2054 ///
2055 /// Used for a module with top-level `await`: its body is an async function whose
2056 /// caller is the host, so there is no function object to pass through
2057 /// [`Interp::new_async_function`].
2058 pub fn run_async_body(
2059 &mut self,
2060 code: Gc<CompiledCode>,
2061 env: Gc<ClosureEnv>,
2062 this: Value,
2063 ) -> JsResult<Value> {
2064 let promise = self.new_promise();
2065 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2066 if let Err(Signal::Throw(reason)) =
2067 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2068 {
2069 self.reject_promise(&promise, reason);
2070 }
2071 Ok(Value::Object(promise))
2072 }
2073
2074 fn new_coroutine(
2075 &mut self,
2076 function: Value,
2077 this: Value,
2078 args: Vec<Value>,
2079 ) -> JsResult<Gc<JsObject>> {
2080 let Some(object) = function.as_object().cloned() else {
2081 return Err(self.type_error("not a function"));
2082 };
2083 let Some((code, env)) = bytecode_of(&object) else {
2084 return Err(self.type_error("not a function"));
2085 };
2086 self.new_coroutine_from(code, env, this, args)
2087 }
2088
2089 /// Build a coroutine over an already-resolved body.
2090 fn new_coroutine_from(
2091 &mut self,
2092 code: Gc<CompiledCode>,
2093 env: Gc<ClosureEnv>,
2094 this: Value,
2095 args: Vec<Value>,
2096 ) -> JsResult<Gc<JsObject>> {
2097 let function = Value::Undefined;
2098 self.push_frame(code, env, this, args, function)?;
2099 let frame = self.frames.pop().expect("push_frame just pushed it");
2100 let state = GeneratorState {
2101 frame: Some(frame),
2102 phase: GeneratorPhase::SuspendedStart,
2103 parked_on_await: false,
2104 parked_on_yield_star: false,
2105 requests: std::collections::VecDeque::new(),
2106 async_busy: false,
2107 };
2108 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2109 coroutine.with_mut(|data| {
2110 data.kind = ObjectKind::Generator(Box::new(state));
2111 });
2112 Ok(coroutine)
2113 }
2114
2115 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2116 /// `await` and `value` is what it awaited.
2117 fn resume_coroutine(
2118 &mut self,
2119 coroutine: &Gc<JsObject>,
2120 kind: ResumeKind,
2121 value: Value,
2122 ) -> JsResult<(Value, bool)> {
2123 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2124 ObjectKind::Generator(state) => Some(std::mem::replace(
2125 state.as_mut(),
2126 GeneratorState {
2127 frame: None,
2128 phase: GeneratorPhase::Executing,
2129 parked_on_await: false,
2130 parked_on_yield_star: false,
2131 requests: std::collections::VecDeque::new(),
2132 async_busy: false,
2133 },
2134 )),
2135 _ => None,
2136 }) else {
2137 return Err(self.type_error("not a coroutine"));
2138 };
2139 let result = self.step_generator(&mut state, kind, value);
2140 coroutine.with_mut(|data| {
2141 data.kind = ObjectKind::Generator(Box::new(state));
2142 });
2143 let (value, done, _ready, _reason) = result?;
2144 Ok((value, done))
2145 }
2146
2147 /// Advance an async body and settle its promise with the outcome.
2148 fn drive_async(
2149 &mut self,
2150 coroutine: &Gc<JsObject>,
2151 promise: &Gc<JsObject>,
2152 kind: ResumeKind,
2153 value: Value,
2154 ) -> JsResult<()> {
2155 match self.resume_coroutine(coroutine, kind, value) {
2156 Ok((value, true)) => {
2157 // `Ok` with `done` means the body finished *normally*, even when it was
2158 // resumed by a `throw` — `try { await p } catch {}` completes by
2159 // returning. Only the `Err` arm below is a rejection.
2160 //
2161 // Resolving rather than fulfilling matters: `return promise` in an async
2162 // body adopts the inner promise, so `async function f(){ return
2163 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2164 // promise.
2165 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2166 self.reject_promise(promise, reason);
2167 }
2168 Ok(())
2169 }
2170 Ok((value, false)) => {
2171 // Parked on `await`: follow what it awaited and resume with the outcome.
2172 let awaited = match self.promise_resolve_value(value) {
2173 Ok(awaited) => awaited,
2174 Err(Signal::Throw(error)) => {
2175 self.reject_promise(promise, error);
2176 return Ok(());
2177 }
2178 Err(other) => return Err(other),
2179 };
2180 self.hook_await(awaited, coroutine, promise)
2181 }
2182 Err(Signal::Throw(reason)) => {
2183 self.reject_promise(promise, reason);
2184 Ok(())
2185 }
2186 Err(other) => Err(other),
2187 }
2188 }
2189
2190 /// Arrange for `coroutine` to resume when `awaited` settles.
2191 fn hook_await(
2192 &mut self,
2193 awaited: Value,
2194 coroutine: &Gc<JsObject>,
2195 promise: &Gc<JsObject>,
2196 ) -> JsResult<()> {
2197 let resumed = JsObject::function(
2198 self.heap,
2199 Some(self.realm.function_proto.clone()),
2200 Callable::AwaitResume {
2201 coroutine: coroutine.clone(),
2202 promise: promise.clone(),
2203 kind: ResumeKind::Next,
2204 },
2205 );
2206 let raised = JsObject::function(
2207 self.heap,
2208 Some(self.realm.function_proto.clone()),
2209 Callable::AwaitResume {
2210 coroutine: coroutine.clone(),
2211 promise: promise.clone(),
2212 kind: ResumeKind::Throw,
2213 },
2214 );
2215 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2216 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2217 let Value::Object(awaited) = &awaited else {
2218 self.jobs.push_back(Job::Resume {
2219 coroutine: coroutine.clone(),
2220 promise: promise.clone(),
2221 kind: ResumeKind::Next,
2222 value: awaited,
2223 });
2224 return Ok(());
2225 };
2226 self.perform_then(
2227 awaited,
2228 Some(Value::Object(resumed)),
2229 Some(Value::Object(raised)),
2230 )?;
2231 Ok(())
2232 }
2233
2234 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2235 /// things an engine keeps outside it — array elements and an array's `length`.
2236 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2237 if let Some(property) = object.own_property_key(key) {
2238 return Some(property);
2239 }
2240 // An array's elements live in their own vector rather than the property table, so
2241 // a descriptor for one has to be synthesized — with the attributes an element has.
2242 if let Some(index) = key.as_str().and_then(array_index)
2243 && let Some(value) = object.array_get(index as usize)
2244 && !matches!(value, Value::Hole)
2245 {
2246 return Some(Property::data(value));
2247 }
2248 // `length` is an own property of an array that is not in its property table
2249 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2250 // and non-enumerable.
2251 if key.as_str() == Some("length")
2252 && let Some(length) = object.array_length()
2253 {
2254 return Some(Property {
2255 value: Some(crate::object::length_value(length)),
2256 writable: object.length_writable(),
2257 enumerable: false,
2258 configurable: false,
2259 getter: None,
2260 setter: None,
2261 });
2262 }
2263 None
2264 }
2265
2266 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2267 pub fn object_get_own_property(
2268 &mut self,
2269 object: &Gc<JsObject>,
2270 key: &PropertyKey,
2271 ) -> JsResult<Option<Property>> {
2272 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2273 return Ok(answer);
2274 }
2275 Ok(Self::ordinary_own_property(object, key))
2276 }
2277
2278 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2279 pub fn object_define_own_property(
2280 &mut self,
2281 object: &Gc<JsObject>,
2282 key: &PropertyKey,
2283 property: Property,
2284 ) -> JsResult<bool> {
2285 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2286 return Ok(accepted);
2287 }
2288 // An array index is stored in the element vector, which can hold a plain value and
2289 // nothing else. An accessor — or a data property with non-default attributes —
2290 // therefore has to live in the property table, and the element slot is blanked so
2291 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2292 // {get})` stored the accessor where no read ever looked, and the array kept
2293 // answering its old value.
2294 // An array's `length` is not stored in the property table, so defining it has to
2295 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2296 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2297 // {value: 1})` reported success and changed nothing.
2298 if key.as_str() == Some("length") && object.is_array() {
2299 // `{writable: false}` on `length` does not change the length, but it does make
2300 // it read-only — after which neither a later `{writable: true}` nor a store
2301 // past the end may succeed.
2302 if property.value.is_none() {
2303 if !object.length_writable() && property.writable {
2304 return Ok(false);
2305 }
2306 object.set_length_writable(property.writable);
2307 return Ok(true);
2308 }
2309 if !object.length_writable() {
2310 return Ok(false);
2311 }
2312 }
2313 if key.as_str() == Some("length")
2314 && object.is_array()
2315 && let Some(value) = property.value.clone()
2316 {
2317 let requested = value.to_number();
2318 let valid = requested.is_finite()
2319 && requested >= 0.0
2320 && requested.fract() == 0.0
2321 && requested <= u32::MAX as f64;
2322 if !valid {
2323 return Err(self.range_error("invalid array length"));
2324 }
2325 // Truncating deletes the elements above the new length, and a non-configurable
2326 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2327 // makes `a.length = 2` fail rather than quietly drop it.
2328 let current = object.array_length().unwrap_or(0);
2329 let requested = requested as usize;
2330 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2331 return Ok(false);
2332 }
2333 object.array_set_length(self.heap, requested);
2334 return Ok(true);
2335 }
2336 let plain = property.writable
2337 && property.enumerable
2338 && property.configurable
2339 && !property.is_accessor();
2340 if let Some(index) = key.as_str().and_then(array_index)
2341 && object.is_array()
2342 {
2343 // Growing the array needs a writable `length`: after
2344 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2345 // be added.
2346 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2347 return Ok(false);
2348 }
2349 if plain && property.value.is_some() {
2350 // An ordinary element: the vector is where a read looks first, so it has
2351 // to be the vector that changes — unless the index is too far out to be
2352 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2353 // one property, because past its own limit it stores the index as an
2354 // ordinary key. Falling through to `define_key` below is the same choice,
2355 // and the alternative was worse: the store used to be *dropped* and the
2356 // length left at 0, which is a silent wrong answer.
2357 let value = property.value.clone().unwrap_or(Value::Undefined);
2358 object.delete_key(key);
2359 if object.array_set(self.heap, index as usize, value) {
2360 return Ok(true);
2361 }
2362 object.define_key(key, property);
2363 // A sparse store past the dense limit still extends `length`, which is what
2364 // `a[a.length] = v` relies on — but only extends: shortening would delete
2365 // the sparse properties above the index, including this one.
2366 if index as usize + 1 > object.array_length().unwrap_or(0) {
2367 object.array_set_length(self.heap, index as usize + 1);
2368 }
2369 return Ok(true);
2370 }
2371 object.define_key(key, property);
2372 // The slot stays, so `length` does not shrink; a hole is not an element, so
2373 // the table entry is now what a read finds.
2374 object.array_set(self.heap, index as usize, Value::Hole);
2375 return Ok(true);
2376 }
2377 object.define_key(key, property);
2378 Ok(true)
2379 }
2380
2381 /// Build a proxy object over `target`, with its traps read from `handler`.
2382 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2383 JsObject::proxy(self.heap, target, handler)
2384 }
2385
2386 /// The `revoke` function for a proxy's slots.
2387 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2388 JsObject::function(
2389 self.heap,
2390 Some(self.realm.function_proto.clone()),
2391 Callable::Revoker(slots),
2392 )
2393 }
2394
2395 /// A new array.
2396 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2397 let array = JsObject::array(
2398 self.heap,
2399 Some(self.realm.array_proto.clone()),
2400 elements.len(),
2401 );
2402 for (index, element) in elements.into_iter().enumerate() {
2403 array.array_set(self.heap, index, element);
2404 }
2405 array
2406 }
2407
2408 /// A new native function object.
2409 ///
2410 /// The observable `name` and `length` are installed as properties here, which is
2411 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2412 /// so `f.name = "x"` behaves like the writable property it is.
2413 /// A native constructor that builds its own instance after validating its arguments.
2414 ///
2415 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2416 /// check runs before `new.target.prototype` is read.
2417 pub fn new_native_ctor(
2418 &self,
2419 name: impl Into<String>,
2420 length: u32,
2421 func: NativeFn,
2422 ) -> Gc<JsObject> {
2423 let function = JsObject::function(
2424 self.heap,
2425 Some(self.realm.function_proto.clone()),
2426 Callable::Native {
2427 func,
2428 own_instance: true,
2429 },
2430 );
2431 function.set_constructible(true);
2432 function.define(
2433 "length",
2434 Property::name_or_length(Value::Int(length as i32)),
2435 );
2436 function.define("name", Property::name_or_length(self.string(name)));
2437 function
2438 }
2439
2440 /// A native constructor that lets `new` build the instance first.
2441 ///
2442 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
2443 /// validation that must precede reading `new.target.prototype`, so the object can be
2444 /// created before the implementation runs. Distinct from [`Interp::new_native`],
2445 /// which makes a *method* and therefore not a constructor at all.
2446 pub fn new_native_constructor(
2447 &self,
2448 name: impl Into<String>,
2449 length: u32,
2450 func: NativeFn,
2451 ) -> Gc<JsObject> {
2452 let function = self.new_native(name, length, func);
2453 function.set_constructible(true);
2454 function
2455 }
2456
2457 /// A new host function object: a native closure that carries its own state.
2458 ///
2459 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
2460 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
2461 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
2462 /// this safe: the closure must not capture a `Gc`.
2463 pub fn new_host_function(
2464 &self,
2465 name: impl Into<String>,
2466 length: u32,
2467 func: crate::object::HostFn,
2468 ) -> Gc<JsObject> {
2469 self.new_host_inner(name.into(), length, func, false)
2470 }
2471
2472 /// A host constructor: `new` hands it `this = undefined`, so it validates its
2473 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
2474 pub fn new_host_ctor(
2475 &self,
2476 name: impl Into<String>,
2477 length: u32,
2478 func: crate::object::HostFn,
2479 ) -> Gc<JsObject> {
2480 let function = self.new_host_inner(name.into(), length, func, true);
2481 function.set_constructible(true);
2482 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
2483 // installs its own methods on it, so it starts as a plain object.
2484 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
2485 function.define(
2486 "prototype",
2487 Property {
2488 value: Some(Value::Object(proto)),
2489 writable: true,
2490 enumerable: false,
2491 configurable: false,
2492 ..Property::default()
2493 },
2494 );
2495 function
2496 }
2497
2498 fn new_host_inner(
2499 &self,
2500 name: String,
2501 length: u32,
2502 func: crate::object::HostFn,
2503 own_instance: bool,
2504 ) -> Gc<JsObject> {
2505 let function = JsObject::function(
2506 self.heap,
2507 Some(self.realm.function_proto.clone()),
2508 Callable::Host {
2509 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
2510 own_instance,
2511 },
2512 );
2513 function.define(
2514 "length",
2515 Property::name_or_length(Value::Int(length as i32)),
2516 );
2517 function.define("name", Property::name_or_length(self.string(name)));
2518 function
2519 }
2520
2521 /// A new native function object.
2522 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
2523 let function = JsObject::function(
2524 self.heap,
2525 Some(self.realm.function_proto.clone()),
2526 Callable::Native {
2527 func,
2528 own_instance: false,
2529 },
2530 );
2531 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
2532 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
2533 // `length,name` and this listed `name,length`. A bytecode function already gets it
2534 // the right way round; only native ones were built backwards.
2535 function.define(
2536 "length",
2537 Property::name_or_length(Value::Int(length as i32)),
2538 );
2539 function.define("name", Property::name_or_length(self.string(name)));
2540 function
2541 }
2542
2543 /// A new bound function.
2544 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
2545 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
2546 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
2547 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
2548 let constructible = target
2549 .as_object()
2550 .is_some_and(|target| target.is_constructor());
2551 let bound = JsObject::function(
2552 self.heap,
2553 Some(self.realm.function_proto.clone()),
2554 Callable::Bound { target, this, args },
2555 );
2556 bound.set_constructible(constructible);
2557 bound
2558 }
2559
2560 /// A new reference cell.
2561 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
2562 Gc::new(self.heap, Cell::new(value))
2563 }
2564
2565 // -- running ------------------------------------------------------------
2566
2567 /// Evaluate `code` as a script body and return its completion value.
2568 /// Compile and run `source` for the engine's own use, returning its completion value.
2569 ///
2570 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
2571 /// needs to be a real async function, and the engine already runs those as coroutines,
2572 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
2573 ///
2574 /// Differences from [`Self::eval_in_global`], both deliberate:
2575 ///
2576 /// * It does **not** drain the microtask queue. Install runs while the realm is still
2577 /// being built, and the source is an IIFE that only constructs a closure, so there
2578 /// is nothing to drain — and draining here would run script-queued jobs in the
2579 /// middle of `install`.
2580 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
2581 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
2582 /// and it should not look like the user wrote something wrong.
2583 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
2584 let program = match js_parse::parse_script(source) {
2585 Ok(program) => program,
2586 Err(error) => {
2587 let message = format!("builtin source does not parse: {error}");
2588 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2589 }
2590 };
2591 let mut code = match js_compile::compile_script(&program) {
2592 Ok(code) => code,
2593 Err(error) => {
2594 let message = format!("builtin source does not compile: {}", error.message);
2595 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2596 }
2597 };
2598 // The frame has to name something, and `<builtin>` is what a stack trace through
2599 // this code should say.
2600 code.set_filename("<builtin>");
2601 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2602 let closure_vars = compiled.code.closure_vars.clone();
2603 let env = self.global_env(&closure_vars);
2604 let this = Value::Object(self.realm.global.clone());
2605 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
2606 }
2607
2608 /// Run an already-parsed script and drain the microtasks it queued.
2609 ///
2610 /// The drain is what lets an `async` function's body advance past its first `await`
2611 /// before the host sees the result: nothing else pumps the job queue.
2612 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
2613 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2614 let closure_vars = compiled.code.closure_vars.clone();
2615 let env = self.global_env(&closure_vars);
2616 let this = Value::Object(self.realm.global.clone());
2617 let callee = Value::Undefined;
2618 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
2619 // The script is done, so the microtasks it queued run before the host sees the
2620 // result. Without this an `async` function's body would never advance past its
2621 // first `await`, because nothing else drains the queue.
2622 self.drain_jobs()?;
2623 Ok(result)
2624 }
2625
2626 /// Compile and run `source` in global scope, returning its completion value.
2627 ///
2628 /// This is what `eval` and `new Function` use. Running it as a script means it
2629 /// sees the global object and nothing else, which is right for `eval("1+1")` and
2630 /// for a `Function` body; a *direct* eval that reads a local variable would need
2631 /// the compiler to hand its variable environment over, which is not implemented.
2632 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
2633 self.eval_in_global_named(source, EVAL_FILE, false)
2634 }
2635
2636 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
2637 ///
2638 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
2639 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
2640 /// through the code, so they cannot share one constant.
2641 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
2642 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
2643 }
2644
2645 fn eval_in_global_named(&mut self, source: &str, file: &str, barrier: bool) -> JsResult<Value> {
2646 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
2647 // eval-created global binding — configurable, unlike a script's own `var`.
2648 self.eval_depth += 1;
2649 if barrier {
2650 let depth = self.frames.len();
2651 self.trace_barriers.push(depth);
2652 }
2653 let result = self.eval_in_global_inner(source, file);
2654 if barrier {
2655 self.trace_barriers.pop();
2656 }
2657 self.eval_depth -= 1;
2658 result
2659 }
2660
2661 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
2662 let compiled = self.compile_global_script(source, file, false)?;
2663 let strict = compiled.strict;
2664 self.run_eval_script(compiled, strict)
2665 }
2666
2667 /// Parse and compile `source` as a global script, without running it.
2668 ///
2669 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
2670 /// before a promise exists to reject — while still evaluating in the same eval context
2671 /// (direct-eval strictness, `new.target`, `super`).
2672 fn compile_global_script(
2673 &mut self,
2674 source: &str,
2675 file: &str,
2676 async_body: bool,
2677 ) -> JsResult<CompiledFunction> {
2678 // A *direct* eval inherits the strictness of the code that called it, which is
2679 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
2680 // implicit global. The caller's frame is the innermost one here, because a
2681 // native function does not push a frame of its own.
2682 let strict = self.current_strict();
2683 // `eval` runs in the caller's function context, so `new.target` is legal here
2684 // even though the source is a bare script — and so is `super.x` when the caller
2685 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
2686 // caller's, which is what `special_object 4` already does.
2687 let context = js_parse::EvalContext {
2688 in_method: self.enclosing_home_object().is_some(),
2689 // `super()` belongs to a derived constructor, and an eval'd body is not a
2690 // constructor at all: the caller frame's `this` is already built.
2691 in_derived_constructor: false,
2692 };
2693 // A *global* eval is not a function body: `new.target` and `super` are out of
2694 // reach there. Its `{async: true}` form differs in the other direction — the body
2695 // may `await` — so the two flags are independent and the reference sets both from
2696 // the eval type rather than from the caller.
2697 let parsed = if async_body {
2698 js_parse::parse_suspensible_global_eval(source, strict)
2699 } else {
2700 js_parse::parse_eval_script_in(source, strict, context)
2701 };
2702 let program = match parsed {
2703 Ok(program) => program,
2704 Err(error) => {
2705 // The message is bare: the position lives in `fileName`,
2706 // `lineNumber`, `columnNumber` and the stack frame above, which is where
2707 // the reference puts it. An `invalid source: L:C: ` prefix made
2708 // `e.message` differ from the reference while the stack already agreed.
2709 return Err(Signal::Throw(self.syntax_error_at(
2710 file,
2711 error.span.start.line,
2712 error.span.start.column,
2713 &error.message,
2714 )));
2715 }
2716 };
2717 let mut compiled = match if async_body {
2718 js_compile::compile_script_suspensible(&program)
2719 } else {
2720 js_compile::compile_script(&program)
2721 } {
2722 Ok(compiled) => compiled,
2723 // A construct the compiler does not handle yet is reported the same way a
2724 // parse error is: it happens before anything runs, so the trace is the
2725 // position in the source followed by the caller.
2726 Err(error) => {
2727 return Err(Signal::Throw(self.syntax_error_at(
2728 file,
2729 error.span.start.line,
2730 error.span.start.column,
2731 &error.message,
2732 )));
2733 }
2734 };
2735 compiled.set_filename(file);
2736 Ok(compiled)
2737 }
2738
2739 /// Run an `eval`'d script in the caller's scope.
2740 ///
2741 /// Three things have to come from the calling frame, because the eval'd code is a
2742 /// script and would otherwise see only the global object:
2743 ///
2744 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
2745 /// * `arguments`, exposed as a binding of the eval's own scope, so
2746 /// `f("arguments.length", 1)` sees the caller's arguments;
2747 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
2748 /// `eval("var v = 1")` into the global object.
2749 ///
2750 /// Locals of the calling function are *not* reachable: that needs the compiler to
2751 /// hand its variable environment over, which this milestone does not do.
2752 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
2753 // `this` and `arguments` come from the innermost frame only — those are not
2754 // lexical — while the name bindings come from the whole chain of frames, part
2755 // of it being ordinary scope resolution.
2756 // An arrow has no `this` of its own, so an `eval` inside one inherits the
2757 // enclosing function's receiver — the lexical `this` the arrow was compiled to
2758 // read from its closure.
2759 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
2760 // variable environment is the innermost frame of all: an arrow's own body is where
2761 // `var`s declared by an `eval` inside it belong.
2762 let caller_index = self
2763 .frames
2764 .iter()
2765 .rposition(|frame| !frame.code.code.is_arrow)
2766 .or_else(|| self.frames.len().checked_sub(1));
2767 let env_index = self.frames.len().checked_sub(1);
2768 let caller = caller_index.and_then(|index| self.frames.get(index));
2769 let (this, passed) = match caller {
2770 Some(frame) => (frame.this.clone(), frame.passed.clone()),
2771 // No frame at all: the eval is running at the top level, so there is
2772 // nothing to inherit and the global receiver is right.
2773 None => (Value::Object(self.realm.global.clone()), Vec::new()),
2774 };
2775 // Innermost frame first, so the first binding found for a name is the one that
2776 // shadows the rest. A script frame (`<eval>`) contributes nothing.
2777 let mut bindings: Vec<EvalBinding> = Vec::new();
2778 // The calling function's own bindings, resolved by the compiler at the call
2779 // site. That table is the only reliable answer when a name is declared twice in
2780 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
2781 // body means, and guessing by declaration order picks the wrong one as soon as
2782 // two loops in a row use the same name.
2783 // Only a *direct* eval sees the caller's scope. The compiler records a site for
2784 // every direct call — a bare `eval(...)` callee — so finding one at the current
2785 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
2786 // callee to a value first and leave no site behind.
2787 let mut direct = false;
2788 let mut resolved_here = false;
2789 if let Some(frame) = self.frames.last() {
2790 let (line, column) = frame
2791 .code
2792 .code
2793 .position_at(frame.at as u32)
2794 .unwrap_or_default();
2795 // The nearest site at or before the current position, not an exact match:
2796 // the recorded position of the `call` instruction is the callee's, which
2797 // sits a few columns inside the call expression the compiler recorded. A
2798 // site is unique per call, so "the closest one behind us" identifies it.
2799 if let Some(site) = frame
2800 .code
2801 .code
2802 .eval_sites
2803 .iter()
2804 .filter(|site| (site.line, site.column) <= (line, column))
2805 .max_by_key(|site| (site.line, site.column))
2806 {
2807 direct = true;
2808 resolved_here = true;
2809 for binding in &site.bindings {
2810 // An enclosing function's frame sits `owner` levels below the one
2811 // running the call.
2812 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
2813 else {
2814 continue;
2815 };
2816 bindings.push(EvalBinding {
2817 name: binding.name.clone(),
2818 frame,
2819 slot: if binding.is_arg {
2820 EvalSlot::Arg
2821 } else {
2822 EvalSlot::Local
2823 },
2824 index: binding.index as usize,
2825 });
2826 }
2827 }
2828 }
2829 for frame_index in (0..self.frames.len()).rev() {
2830 // Skip the innermost frame's flat scan when the compiler already answered
2831 // for it; an enclosing frame still needs one, because the eval resolves
2832 // those names dynamically.
2833 if resolved_here && frame_index == self.frames.len() - 1 {
2834 continue;
2835 }
2836 let frame = &self.frames[frame_index];
2837 for (index, arg) in frame.code.code.args.iter().enumerate() {
2838 bindings.push(EvalBinding {
2839 name: arg.name.clone(),
2840 frame: frame_index,
2841 slot: EvalSlot::Arg,
2842 index,
2843 });
2844 }
2845 for (index, local) in frame.code.code.vars.iter().enumerate() {
2846 bindings.push(EvalBinding {
2847 name: local.name.clone(),
2848 frame: frame_index,
2849 slot: EvalSlot::Local,
2850 index,
2851 });
2852 }
2853 }
2854 let mut seen = BTreeSet::new();
2855 bindings.retain(|binding| seen.insert(binding.name.clone()));
2856
2857 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
2858 // elements is all the spec's ordinary uses need.
2859 //
2860 // Known divergence: this is bound for a *global* eval too, where there is no
2861 // caller and the reference throws `'arguments' is not defined`. Deciding properly
2862 // needs "does the calling frame have an `arguments` of its own", which is not
2863 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
2864 // script or eval body does not, and `eval(b)` passes the callee as a value so even
2865 // the call-site detection does not answer it. Modelled as a binding in the caller's
2866 // variable environment, this would fall out; that is a larger change than the one
2867 // this comment is attached to.
2868 let arguments = Value::Object(self.new_array(passed));
2869
2870 // Only a *strict* eval gets a variable environment of its own. A sloppy one
2871 // declares its `var`s in the caller's — which for a top-level eval is the global
2872 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
2873 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
2874 // vanish into a scope nobody reads back from.
2875 let previous_scope = if code_strict {
2876 self.eval_scope.replace(BTreeMap::new())
2877 } else {
2878 None
2879 };
2880 let previous_arguments = self.eval_arguments.replace(arguments);
2881 let previous_with = self.eval_with.replace(self.with_objects());
2882 let inherited_new_target = self
2883 .frames
2884 .iter()
2885 .rev()
2886 .find(|frame| !frame.code.code.is_arrow)
2887 .map(|frame| frame.new_target.clone());
2888 let previous_new_target = self
2889 .eval_new_target
2890 .replace(inherited_new_target.unwrap_or(Value::Undefined));
2891 let eval_cells = self.eval_cells_for(&bindings);
2892 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
2893 // A sloppy direct eval declares its `var`s in the caller's variable environment;
2894 // `declare_eval_local` needs to know which frame that is.
2895 // An indirect eval gets the global environment, so nothing of the caller's is
2896 // recorded as the place its `var`s belong.
2897 let previous_caller = self
2898 .eval_caller
2899 .replace(if direct { env_index } else { None });
2900 // The cell-based view of the same bindings, which is what a closure created
2901 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
2902 // whose compiler did not put a binding in a cell simply does not appear here —
2903 // reads and writes still work through `eval_bindings`, they just cannot outlive
2904 // the eval.
2905 let previous_eval_scope = self
2906 .active_eval_scope
2907 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
2908 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2909 let closure_vars = compiled.code.closure_vars.clone();
2910 let env = self.global_env(&closure_vars);
2911 let callee = Value::Undefined;
2912 // An async body does not run here: it becomes a coroutine and answers a promise,
2913 // which is what makes `await` legal in it. `this` still has to be the caller's
2914 // (for a global eval, the global object), because `this` is not part of `await`.
2915 let result = if compiled.code.kind.is_async() {
2916 self.run_async_body(compiled, env, this)
2917 } else {
2918 self.execute(compiled, env, this, Vec::new(), callee)
2919 };
2920 self.eval_scope = previous_scope;
2921 self.eval_arguments = previous_arguments;
2922 self.eval_with = previous_with;
2923 self.eval_new_target = previous_new_target;
2924 self.eval_bindings = previous_bindings;
2925 self.eval_caller = previous_caller;
2926 self.active_eval_scope = previous_eval_scope;
2927 result
2928 }
2929
2930 /// The cell-backed subset of `bindings`, in the same priority order.
2931 ///
2932 /// Both lookup routes have to agree — the eval's own reads go through
2933 /// [`Interp::eval_binding_value`] and the closures it builds go through
2934 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
2935 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
2936 /// is not in a cell simply does not appear: reads and writes still work, they just
2937 /// cannot be handed to a closure that outlives the eval.
2938 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
2939 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
2940 for binding in bindings {
2941 let Some(frame) = self.frames.get(binding.frame) else {
2942 continue;
2943 };
2944 let cell = match binding.slot {
2945 EvalSlot::Arg => frame
2946 .code
2947 .arg_cell
2948 .get(binding.index)
2949 .copied()
2950 .unwrap_or(-1),
2951 EvalSlot::Local => frame
2952 .code
2953 .loc_cell
2954 .get(binding.index)
2955 .copied()
2956 .unwrap_or(-1),
2957 };
2958 if cell < 0 {
2959 continue;
2960 }
2961 if let Some(cell) = frame.cells.get(cell as usize) {
2962 names.push((binding.name.clone(), cell.clone()));
2963 }
2964 }
2965 names
2966 }
2967
2968 /// A `SyntaxError` that reports where in the source it happened.
2969 ///
2970 /// Compile-time failures never run, so they have no frame of their own; the
2971 /// reference still puts the position first in the trace, with no function name and
2972 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
2973 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
2974 /// reference borrows), which is how a script reads the position without parsing
2975 /// the trace.
2976 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
2977 ///
2978 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
2979 /// `columnNumber`, which is how the reference prints one. A positionless error
2980 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
2981 /// the reference raises it from `js_resolve_module`, where there is no position.
2982 pub(crate) fn syntax_error_plain(
2983 &mut self,
2984 error: &js_parse::SyntaxError,
2985 file: &str,
2986 ) -> Value {
2987 if error.positionless {
2988 return self.make_error("SyntaxError", &error.message);
2989 }
2990 self.syntax_error_at(
2991 file,
2992 error.span.start.line,
2993 error.span.start.column,
2994 &error.message,
2995 )
2996 }
2997
2998 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
2999 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
3000 let value = self.make_error("SyntaxError", message);
3001 if let Value::Object(object) = &value {
3002 let text = self.string(blamed);
3003 object.define("stack", Property::with_attributes(text, true, true));
3004 let name = self.string(file);
3005 object.define("fileName", Property::with_attributes(name, true, true));
3006 object.define(
3007 "lineNumber",
3008 Property::with_attributes(Value::Int(line as i32), true, true),
3009 );
3010 object.define(
3011 "columnNumber",
3012 Property::with_attributes(Value::Int(column as i32), true, true),
3013 );
3014 }
3015 value
3016 }
3017
3018 /// Run a compiled script whose completion value is a function, returning it.
3019 ///
3020 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3021 /// get the closure out, which keeps the constant-pool plumbing in one place.
3022 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3023 self.run_script(code)
3024 }
3025
3026 /// The environment of a script or of any function compiled at global scope:
3027 /// every entry is a global binding, so each one resolves to the realm's cell.
3028 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3029 let mut cells = Vec::with_capacity(closure_vars.len());
3030 for closure_var in closure_vars {
3031 let cell = match closure_var.closure_type {
3032 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3033 if closure_var.is_lexical =>
3034 {
3035 // A lexical declaration: the cell is created here holding the
3036 // dead-zone marker, which is what makes the binding exist and
3037 // unreadable before its initialiser runs.
3038 self.declare_global(&closure_var.name, closure_var.is_const);
3039 self.realm.globals[&closure_var.name].clone()
3040 }
3041 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3042 // A `var` or function declaration becomes a property of the global
3043 // object, and it exists from here on — which is why
3044 // `print(v); var v = 1` prints `undefined` instead of raising.
3045 // Declaring it at instantiation time (rather than at the
3046 // initialiser) is also what makes it non-configurable: the store
3047 // then lands on an existing property instead of creating one.
3048 self.declare_var_global(&closure_var.name);
3049 // The cell is a placeholder that nothing indexes; it cannot be
3050 // omitted because the slot has to hold something.
3051 self.new_cell(Value::Undefined)
3052 }
3053 _ => {
3054 // An undeclared global is read by name; the cell is a
3055 // placeholder that nothing indexes.
3056 self.new_cell(Value::Undefined)
3057 }
3058 };
3059 cells.push(cell);
3060 }
3061 Gc::new(
3062 self.heap,
3063 ClosureEnv {
3064 cells,
3065 eval_scope: None,
3066 local_vars: None,
3067 local_phase: 1,
3068 },
3069 )
3070 }
3071
3072 /// Push a frame and run until it returns.
3073 pub(crate) fn execute(
3074 &mut self,
3075 code: Gc<CompiledCode>,
3076 env: Gc<ClosureEnv>,
3077 this: Value,
3078 args: Vec<Value>,
3079 callee: Value,
3080 ) -> JsResult<Value> {
3081 let depth = self.frames.len();
3082 self.push_frame(code, env, this, args, callee)?;
3083 loop {
3084 match self.step() {
3085 Ok(Step::Continue) => {}
3086 Ok(Step::Return(value)) => {
3087 self.frames.pop();
3088 // A frame that ended in a `tail_call` hands its value straight to
3089 // its caller: nothing after the call can run, so every frame above
3090 // the callee unwinds with the same value. See [`Frame::tail`] —
3091 // the reference does not reuse frames either, so recursion depth
3092 // and the stack-overflow limit behave the same way.
3093 while self.frames.len() > depth && self.frame().tail {
3094 self.frames.pop();
3095 }
3096 if self.frames.len() == depth {
3097 return Ok(value);
3098 }
3099 // The caller resumes with the value on its stack.
3100 self.frames
3101 .last_mut()
3102 .expect("a caller is live")
3103 .stack
3104 .push(value);
3105 }
3106 Err(Signal::Throw(value)) => {
3107 // A handler lives on the stack of the frame that is throwing —
3108 // `catch` pushed it there — so this frame gets the first chance
3109 // to catch before it is popped.
3110 let value = value;
3111 loop {
3112 if self.frames.len() <= depth {
3113 return Err(Signal::Throw(value));
3114 }
3115 if self.catch_here(value.clone()).is_some() {
3116 break;
3117 }
3118 self.frames.pop();
3119 }
3120 }
3121 // A `yield` in a frame that `execute` is running directly means a
3122 // generator body was entered as an ordinary call, which only happens if
3123 // the generator check in `call_or_push` was bypassed.
3124 Ok(Step::Suspend(_)) => {
3125 return Err(Signal::Throw(self.make_error(
3126 "InternalError",
3127 "a generator body ran as an ordinary call",
3128 )));
3129 }
3130 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3131 }
3132 }
3133 }
3134
3135 /// Install a handler for `value` if this frame has one, resuming at it.
3136 ///
3137 /// The scan is the reference's: walk the frame's stack downwards looking for the
3138 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3139 /// `0` is an enumerator marker rather than a handler — it exists so that a
3140 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3141 /// here and the unwinding continues.
3142 fn catch_here(&mut self, value: Value) -> Option<()> {
3143 let frame = self.frames.last_mut()?;
3144 while let Some(top) = frame.stack.pop() {
3145 if let Value::CatchOffset(offset) = top {
3146 if offset == 0 {
3147 continue;
3148 }
3149 frame.stack.push(value);
3150 frame.pc = offset as usize;
3151 return Some(());
3152 }
3153 }
3154 None
3155 }
3156
3157 fn push_frame(
3158 &mut self,
3159 code: Gc<CompiledCode>,
3160 env: Gc<ClosureEnv>,
3161 this: Value,
3162 mut args: Vec<Value>,
3163 callee: Value,
3164 ) -> JsResult<()> {
3165 // Two bounds, and the byte budget is the one that decides in practice. The
3166 // reference's message is `stack overflow` on an `InternalError`, not V8's
3167 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3168 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3169 let frame_cost = Self::frame_cost(&code);
3170 let stack_base = self.stack_used();
3171 if self.frames.len() >= self.max_frames
3172 || stack_base.saturating_add(frame_cost) > self.stack_limit
3173 {
3174 return Err(Signal::Throw(
3175 self.make_error("InternalError", "stack overflow"),
3176 ));
3177 }
3178 let arg_count = code.code.args.len();
3179 // How many were actually passed, which `arguments.length` reports and
3180 // `assert(x)` depends on: a call with one argument must not look like a call
3181 // with one argument and an explicit `undefined`.
3182 let passed = args.len();
3183 // Missing arguments are `undefined` in their slots; extra ones are dropped
3184 // from the slots but still reachable through `arguments`.
3185 // What the caller actually passed, for `arguments`. Built as one exact-size copy
3186 // before the resize, rather than `args.clone()` followed by a `drain().collect()`:
3187 // that was two heap allocations per call, on the path that `call:recursion` spends
3188 // all its time in — and for a function that never mentions `arguments`.
3189 let mut passed_values = Vec::with_capacity(passed);
3190 passed_values.extend_from_slice(&args[..passed]);
3191 args.resize(arg_count, Value::Undefined);
3192 args.truncate(arg_count);
3193 let cell_count = code.code.var_ref_count as usize;
3194 let mut cells = Vec::with_capacity(cell_count);
3195 for _ in 0..cell_count {
3196 cells.push(self.new_cell(Value::Undefined));
3197 }
3198 let locals = vec![Value::Undefined; code.code.vars.len()];
3199 // A captured argument lives in its cell, not in the argument slot, so the
3200 // incoming value has to be moved there before the body runs.
3201 for (slot, cell) in code.arg_cell.iter().enumerate() {
3202 if *cell >= 0
3203 && let Some(value) = args.get(slot).cloned()
3204 {
3205 cells[*cell as usize].set(value);
3206 }
3207 }
3208 // Sloppy mode substitutes the global object for a missing receiver and boxes a
3209 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3210 // reports `object`. Strict mode passes the value through untouched.
3211 let this = if code.code.strict {
3212 this
3213 } else if this.is_nullish() {
3214 Value::Object(self.realm.global.clone())
3215 } else if matches!(this, Value::Object(_)) {
3216 this
3217 } else {
3218 match crate::builtins::this_object(self, &this) {
3219 Ok(boxed) => Value::Object(boxed),
3220 Err(_) => this,
3221 }
3222 };
3223 let stack_depth = code.code.stack_size as usize + 1;
3224 self.frames.push(Frame {
3225 code,
3226 env,
3227 this,
3228 args,
3229 passed: passed_values.drain(..passed).collect(),
3230 locals,
3231 cells,
3232 local_vars: None,
3233 // Exactly the depth the compiler computed, so the operand stack never
3234 // reallocates. `16` was an arbitrary guess, and a loop that pushes more than
3235 // that reallocated on its way in — a malloc per call, on the hottest path in
3236 // the interpreter.
3237 stack: Vec::with_capacity(stack_depth),
3238 pc: 0,
3239 at: 0,
3240 callee,
3241 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3242 cost: frame_cost,
3243 stack_base,
3244 tail: false,
3245 });
3246 Ok(())
3247 }
3248
3249 /// A memory checkpoint: does the heap still fit under its limit?
3250 ///
3251 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
3252 /// a `Cell` read and a predictable branch, and the point of asking that often is that
3253 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
3254 /// only at calls would let it run until the machine died, which is the exact failure
3255 /// `--memory-limit` exists to prevent.
3256 ///
3257 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
3258 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
3259 /// script that catches it, drops the reference and carries on is legitimate: measured
3260 /// on `qjs --memory-limit 1M`, the engine recovers.
3261 fn check_memory(&mut self) -> JsResult<()> {
3262 // One `Cell` read and a predictable branch when no limit is set, and an integer
3263 // compare when one is. Containers report their own growth as it happens
3264 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
3265 // walking it here was the first version and it was O(live) per 256 instructions,
3266 // which turned a 100k-element push loop into a five-minute one.
3267 let Some(limit) = self.heap.memory_limit() else {
3268 return Ok(());
3269 };
3270 let used = self.heap.used_bytes();
3271 if used <= limit {
3272 // Back under the limit — a collection or a dropped reference did it. The next
3273 // time it goes over is a new failure, not a repeat of this one.
3274 self.oom_reported_at = 0;
3275 return Ok(());
3276 }
3277 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
3278 // block runs normally after `out of memory` — it allocates nothing, so nothing
3279 // fails. A check that re-fired on every instruction made the handler itself throw,
3280 // which is a dead end: the error became unobservable from script.
3281 //
3282 // Comparing against the total at the last report gives the same behaviour: the
3283 // handler runs while the total is unchanged, and the very next allocation over the
3284 // limit fails.
3285 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
3286 {
3287 return Ok(());
3288 }
3289 self.oom_reported_at = used;
3290 Err(Signal::Throw(
3291 self.make_error("InternalError", "out of memory"),
3292 ))
3293 }
3294
3295 /// Fail before allocating `payload` bytes, if they would not fit.
3296 ///
3297 /// For the allocations whose size comes from script data — `new Array(n)`,
3298 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
3299 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
3300 /// answering NULL for the one big request.
3301 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
3302 if self.heap.fits(payload) {
3303 return Ok(());
3304 }
3305 Err(Signal::Throw(
3306 self.make_error("InternalError", "out of memory"),
3307 ))
3308 }
3309
3310 /// Bytes of frame state the live call chain accounts for.
3311 pub fn stack_used(&self) -> usize {
3312 match self.frames.last() {
3313 Some(frame) => frame.stack_base + frame.cost,
3314 None => 0,
3315 }
3316 }
3317
3318 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
3319 ///
3320 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
3321 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
3322 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
3323 /// instead. That is the whole difference between the two models: it rations C stack, we
3324 /// ration frame state, and both quantities are dominated by the value slots — which is
3325 /// why the two depths come out comparable rather than merely proportional.
3326 fn frame_cost(code: &CompiledCode) -> usize {
3327 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
3328 std::mem::size_of::<Frame>()
3329 + std::mem::size_of::<Value>() * slots
3330 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
3331 }
3332
3333 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
3334 ///
3335 /// Only names the eval created are here: a name the frame already declared statically
3336 /// is written through to its own slot instead, so this cannot shadow a real local.
3337 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
3338 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
3339 let (local_vars, phase) = self.visible_local_vars()?;
3340 if !local_vars.contains(name) {
3341 return None;
3342 }
3343 local_vars.get(name, phase)
3344 }
3345
3346 /// The variables a direct `eval` declared, as the code currently running sees them.
3347 ///
3348 /// Inside an eval that is the *caller's* set — the eval's own variable environment
3349 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
3350 /// else it is the current frame's, falling back to the frame the closure was created
3351 /// in.
3352 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
3353 // While an `eval` runs, its own frame is on top but its variable environment is
3354 // the *caller's* — so the caller is what the lookup has to start from.
3355 let (index, phase) = match self.eval_caller.flatten() {
3356 Some(caller) => (
3357 caller,
3358 if self.in_parameter_list_at(caller) {
3359 0
3360 } else {
3361 1
3362 },
3363 ),
3364 None => (
3365 self.frames.len().checked_sub(1)?,
3366 if self.in_parameter_list() { 0 } else { 1 },
3367 ),
3368 };
3369 let frame = self.frames.get(index)?;
3370 // The frame's own variables, or — for an arrow, which has no variable environment
3371 // of its own — the one it was created in, which `ClosureEnv` carries.
3372 if let Some(local_vars) = frame.local_vars.clone() {
3373 return Some((local_vars, phase));
3374 }
3375 frame
3376 .env
3377 .local_vars
3378 .clone()
3379 .map(|local_vars| (local_vars, frame.env.local_phase))
3380 }
3381
3382 /// Whether the innermost frame is still evaluating its parameter list.
3383 ///
3384 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
3385 /// and a closure created there may only see that much of [`LocalVars`].
3386 fn in_parameter_list(&self) -> bool {
3387 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
3388 }
3389
3390 /// [`Interp::in_parameter_list`] for a specific frame.
3391 fn in_parameter_list_at(&self, frame: usize) -> bool {
3392 let Some(frame) = self.frames.get(frame) else {
3393 return false;
3394 };
3395 let code = &frame.code.code;
3396 if !code.has_parameter_expressions {
3397 return false;
3398 }
3399 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
3400 // function as its body and let a direct `eval` act accordingly.
3401 if code.body_start == (0, 0) {
3402 return false;
3403 }
3404 match code.position_at(frame.at as u32) {
3405 Some(position) => position < code.body_start,
3406 None => false,
3407 }
3408 }
3409
3410 fn frame(&self) -> &Frame {
3411 self.frames.last().expect("a frame is live")
3412 }
3413
3414 fn frame_mut(&mut self) -> &mut Frame {
3415 self.frames.last_mut().expect("a frame is live")
3416 }
3417
3418 // -- slot access --------------------------------------------------------
3419
3420 fn read_slot(&self, cell: i32, value: &Value) -> Value {
3421 match cell {
3422 -1 => value.clone(),
3423 index => self
3424 .frame()
3425 .cells
3426 .get(index as usize)
3427 .expect("a cell index in range")
3428 .get(),
3429 }
3430 }
3431
3432 fn get_arg(&self, slot: usize) -> Value {
3433 let frame = self.frame();
3434 let cell = frame.code.arg_cell.get(slot).copied().unwrap_or(-1);
3435 let value = frame.args.get(slot).cloned().unwrap_or(Value::Undefined);
3436 self.read_slot(cell, &value)
3437 }
3438
3439 fn put_arg(&mut self, slot: usize, value: Value) {
3440 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
3441 if cell == -1 {
3442 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
3443 *slot = value;
3444 }
3445 } else {
3446 self.frame().cells[cell as usize].set(value);
3447 }
3448 }
3449
3450 fn get_loc(&self, slot: usize) -> Value {
3451 let frame = self.frame();
3452 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
3453 let value = frame.locals.get(slot).cloned().unwrap_or(Value::Undefined);
3454 self.read_slot(cell, &value)
3455 }
3456
3457 fn put_loc(&mut self, slot: usize, value: Value) {
3458 let cell = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
3459 if cell == -1 {
3460 if let Some(slot) = self.frame_mut().locals.get_mut(slot) {
3461 *slot = value;
3462 }
3463 } else {
3464 self.frame().cells[cell as usize].set(value);
3465 }
3466 }
3467
3468 // -- globals ------------------------------------------------------------
3469
3470 /// The name a global-slot operand refers to.
3471 fn global_name(&self, slot: usize) -> String {
3472 self.frame()
3473 .code
3474 .code
3475 .closure_vars
3476 .get(slot)
3477 .map(|c| c.name.clone())
3478 .unwrap_or_default()
3479 }
3480
3481 /// The facts about a global binding that decide where it lives.
3482 ///
3483 /// A script's globals split in two, and the split is observable: `var` and
3484 /// function declarations become properties of the global object (`globalThis.v`
3485 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
3486 /// declarations live in the global *lexical* environment and are invisible there
3487 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
3488 /// `is_lexical` flag means the answer is already in the bytecode.
3489 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
3490 let name = self.global_name(slot);
3491 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
3492 // while forwarding a reference through a nested function is built with the
3493 // flags cleared, so `const c` would look like an ordinary `var` from inside a
3494 // closure. Presence in the realm's lexical table is the same fact, recorded
3495 // once, and every slot sees it.
3496 let lexical = self.realm.globals.contains_key(&name);
3497 let is_const = self.realm.lexical_consts.contains(&name);
3498 (name, lexical, is_const)
3499 }
3500
3501 /// The value of `name` in the innermost active `with` object, if any.
3502 ///
3503 /// The active objects are the [`VarKind::With`] locals of every frame still running,
3504 /// innermost frame first and innermost block first within one. Walking frames rather
3505 /// than keeping a separate stack is what makes a closure called from inside a `with`
3506 /// see it, and what keeps the object alive only as long as the block is.
3507 /// The innermost active `with` object that has `name`, if any.
3508 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
3509 let objects = self.eval_with.clone().unwrap_or_default();
3510 for object in objects {
3511 let key = self.string(name.to_string());
3512 if self
3513 .has_property(&key, &Value::Object(object.clone()))
3514 .ok()?
3515 {
3516 return Some(object);
3517 }
3518 }
3519 None
3520 }
3521
3522 /// Every active `with` object, innermost first.
3523 fn with_objects(&self) -> Vec<Gc<JsObject>> {
3524 let mut objects = Vec::new();
3525 for frame in self.frames.iter().rev() {
3526 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
3527 if var.kind != js_compile::VarKind::With {
3528 continue;
3529 }
3530 // A captured binding lives in its cell and not in the slot list, so the
3531 // cell is consulted first — a closure created inside the block is exactly
3532 // what makes the object captured. Before the store runs the slot still
3533 // holds `undefined`, and a `with` object is always boxed, so a non-object
3534 // entry is simply not in scope yet.
3535 let value = frame
3536 .code
3537 .loc_cell
3538 .get(index)
3539 .copied()
3540 .filter(|cell| *cell >= 0)
3541 .and_then(|cell| frame.cells.get(cell as usize))
3542 .map(|cell| cell.get())
3543 .or_else(|| frame.locals.get(index).cloned());
3544 if let Some(Value::Object(object)) = value {
3545 objects.push(object);
3546 }
3547 }
3548 }
3549 objects
3550 }
3551
3552 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
3553 for object in self.eval_with.clone().unwrap_or_default() {
3554 let key = self.string(name.to_string());
3555 if self.has_property(&key, &Value::Object(object.clone()))? {
3556 return Ok(Some(self.read_field(&Value::Object(object), name)?));
3557 }
3558 }
3559 Ok(None)
3560 }
3561
3562 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
3563 let (name, lexical, _) = self.global_binding(slot);
3564 if name == "arguments"
3565 && let Some(arguments) = &self.eval_arguments
3566 {
3567 return Ok(arguments.clone());
3568 }
3569 // A `with` block around the *call site* is part of the scope an `eval` sees, so
3570 // the objects live when the eval started are consulted before anything else. The
3571 // snapshot is taken at entry rather than scanning the frames on every read: a
3572 // block that has already finished still leaves its object in the slot, and a
3573 // bytecode read outside the block must not see it.
3574 if let Some(value) = self.with_lookup(&name)? {
3575 return Ok(value);
3576 }
3577 // A variable a direct `eval` declared shadows everything the compiler resolved,
3578 // including an enclosing function's binding: the eval put it in the caller's own
3579 // variable environment, which is nearer than any captured scope.
3580 if let Some((local_vars, phase)) = self.visible_local_vars()
3581 && let Some(cell) = local_vars.get(&name, phase)
3582 {
3583 return Ok(cell.get());
3584 }
3585 // The frame that called `eval` is the innermost scope the eval'd code sees, so
3586 // its local `a` wins over a global `a`.
3587 if let Some(value) = self.eval_binding_value(&name) {
3588 return Ok(value);
3589 }
3590 // A closure created by an `eval` resolves its free names against the bindings
3591 // that eval saw, even after the eval (and its frames) are gone.
3592 if let Some(cell) = self
3593 .frame()
3594 .env
3595 .eval_scope
3596 .as_ref()
3597 .and_then(|scope| scope.get(&name))
3598 {
3599 let value = cell.get();
3600 if matches!(value, Value::Uninitialized) {
3601 return Err(self.throw_reference(&name));
3602 }
3603 return Ok(value);
3604 }
3605 // A binding declared by the strict `eval` currently running shadows anything
3606 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
3607 if let Some(scope) = &self.eval_scope
3608 && let Some(value) = scope.get(&name)
3609 {
3610 return Ok(value.clone());
3611 }
3612 if lexical {
3613 // A lexical global is a binding in a side table, so the dead zone is
3614 // visible and it is nowhere on the global object.
3615 if let Some(cell) = self.realm.globals.get(&name) {
3616 let value = cell.get();
3617 if matches!(value, Value::Uninitialized) {
3618 return Err(self.throw_reference(&name));
3619 }
3620 return Ok(value);
3621 }
3622 return Err(self.throw_reference(&name));
3623 }
3624 // A `var` global is an ordinary property, so the prototype chain and the
3625 // global object's own builtins are all reachable through it.
3626 match self.get_property(&self.realm.global.clone(), &name)? {
3627 Some(value) => Ok(value),
3628 None => Err(self.throw_reference(&name)),
3629 }
3630 }
3631
3632 /// Store to a global binding.
3633 ///
3634 /// Returns a signal when the store is refused: a `const` global may only be
3635 /// written by its initialiser, and a non-configurable `var` global may not be
3636 /// deleted but is always writable.
3637 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
3638 let (name, lexical, is_const) = self.global_binding(slot);
3639
3640 // An assignment inside a `with` writes through to the object that supplies the
3641 // name, which for an `eval` means consulting the same chain `get_global` does.
3642 if let Some(owner) = self.with_owner(&name) {
3643 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
3644 return Ok(());
3645 }
3646 // A variable the running eval *declared* takes the write before any caller
3647 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
3648 // environment even when an enclosing function has a `var c` of its own.
3649 if self.eval_caller.flatten().is_some()
3650 && let Some((local_vars, phase)) = self.visible_local_vars()
3651 && local_vars.contains(&name)
3652 && let Some(cell) = local_vars.get(&name, phase)
3653 {
3654 cell.set(value);
3655 return Ok(());
3656 }
3657 // A binding of the frame that called `eval` takes the write, which is what
3658 // makes `f("a = 3")` change the caller's `a`.
3659 if self.set_eval_binding(&name, &value)? {
3660 return Ok(());
3661 }
3662 // A closure that outlived its `eval` writes through to the same cell it reads.
3663 if let Some(cell) = self
3664 .frame()
3665 .env
3666 .eval_scope
3667 .as_ref()
3668 .and_then(|scope| scope.get(&name))
3669 .cloned()
3670 {
3671 cell.set(value);
3672 return Ok(());
3673 }
3674 // Inside a strict `eval`, a name it declared itself is stored there. An
3675 // *assignment* to a name nobody declared is not a declaration, so it falls
3676 // through: strict mode raises `ReferenceError` for it, which is what
3677 // `eval("1 + (@not_def = 1)")` has to do.
3678 if let Some(scope) = self.eval_scope.as_mut()
3679 && scope.contains_key(&name)
3680 {
3681 scope.insert(name, value);
3682 return Ok(());
3683 }
3684 if lexical {
3685 if let Some(cell) = self.realm.globals.get(&name).cloned() {
3686 if is_const && !matches!(cell.get(), Value::Uninitialized) {
3687 return Err(self.read_only_global(&name));
3688 }
3689 cell.set(value);
3690 return Ok(());
3691 }
3692 // Writing an undeclared lexical global is a `ReferenceError` in strict
3693 // mode and a silent global creation otherwise; creating the cell here
3694 // keeps both paths from losing the value.
3695 let cell = self.new_cell(value);
3696 self.realm.globals.insert(name, cell);
3697 return Ok(());
3698 }
3699 // A variable a direct `eval` declared in this call shadows the global object, even
3700 // when the global already has a property of that name — `var c = "global"` at the
3701 // top level must not capture `eval("var c = 1")` inside a function.
3702 if let Some((local_vars, phase)) = self.visible_local_vars()
3703 && local_vars.contains(&name)
3704 && let Some(cell) = local_vars.get(&name, phase)
3705 {
3706 cell.set(value);
3707 return Ok(());
3708 }
3709 let global = self.realm.global.clone();
3710 match global.own_property(&name) {
3711 // A `var` global is writable, so the store goes straight through — but
3712 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
3713 // store (a non-writable or accessor-without-setter global) is a silent
3714 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
3715 // split every other assignment has.
3716 Some(_) => {
3717 let on_failure = if self.current_strict() {
3718 DeleteFailure::Throw
3719 } else {
3720 DeleteFailure::Ignore
3721 };
3722 self.set_property_with(&global, &name, value, on_failure)
3723 }
3724 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
3725 // declaration creates a *configurable* property, which is what makes it
3726 // deletable and is the one way a global differs from a declared `var`.
3727 // In strict mode the same store is a `ReferenceError` instead: that is the
3728 // whole point of strict mode, and creating the global silently meant
3729 // `"use strict"; x = 1` looked like it worked.
3730 None => {
3731 if self.current_strict() {
3732 return Err(self.throw_reference(&name));
3733 }
3734 // A direct eval declares here rather than on the global object: its
3735 // `var`s belong to the caller's variable environment. `declare_eval_local`
3736 // also covers a plain assignment to a variable an earlier eval made.
3737 if let Some(cell) = self.declare_eval_local(&name) {
3738 cell.set(value);
3739 return Ok(());
3740 }
3741 global.define_data(&name, value);
3742 Ok(())
3743 }
3744 }
3745 }
3746
3747 /// The value of a binding of the frame that called `eval`, if there is one.
3748 fn eval_binding_value(&self, name: &str) -> Option<Value> {
3749 let binding = self
3750 .eval_bindings
3751 .iter()
3752 .find(|binding| binding.name == name)?;
3753 let owner = self.frames.get(binding.frame)?;
3754 let (slot, index) = (binding.slot, binding.index);
3755 Some(match slot {
3756 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
3757 cell if cell >= 0 => owner
3758 .cells
3759 .get(cell as usize)
3760 .map(|cell| cell.get())
3761 .unwrap_or(Value::Undefined),
3762 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
3763 },
3764 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
3765 cell if cell >= 0 => owner
3766 .cells
3767 .get(cell as usize)
3768 .map(|cell| cell.get())
3769 .unwrap_or(Value::Undefined),
3770 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
3771 },
3772 })
3773 }
3774
3775 /// Write to a binding of the frame that called `eval`.
3776 ///
3777 /// `Ok(false)` means no binding matched and the caller should keep looking. A
3778 /// matched binding can still refuse the store, which is why this is fallible: a
3779 /// `const` is read-only everywhere, and a named function expression's own name is
3780 /// read-only in strict mode.
3781 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
3782 let Some(binding) = self
3783 .eval_bindings
3784 .iter()
3785 .find(|binding| binding.name == name)
3786 else {
3787 return Ok(false);
3788 };
3789 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
3790 let strict = self.current_strict();
3791 let Some(owner) = self.frames.get_mut(frame) else {
3792 return Ok(false);
3793 };
3794 match slot {
3795 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
3796 cell if cell >= 0 => {
3797 if let Some(cell) = owner.cells.get(cell as usize) {
3798 cell.set(value.clone());
3799 }
3800 }
3801 _ => {
3802 if let Some(slot) = owner.args.get_mut(index) {
3803 *slot = value.clone();
3804 }
3805 }
3806 },
3807 EvalSlot::Local => {
3808 let declared = owner.code.code.vars.get(index);
3809 // A `const` is read-only even through `eval`. The realm records this for
3810 // globals (see `lexical_consts`), but a local's `const`-ness is only in
3811 // the bytecode, so this is where it has to be enforced.
3812 if declared.is_some_and(|var| var.is_const) {
3813 return Err(self.read_only_local(name));
3814 }
3815 // The name of a named function expression is read-only too, but only
3816 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
3817 // such a name is ignored, the same as a direct store would be.
3818 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
3819 return if strict {
3820 Err(self.read_only_local(name))
3821 } else {
3822 Ok(true)
3823 };
3824 }
3825 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
3826 cell if cell >= 0 => {
3827 if let Some(cell) = owner.cells.get(cell as usize) {
3828 cell.set(value.clone());
3829 }
3830 }
3831 _ => {
3832 if let Some(slot) = owner.locals.get_mut(index) {
3833 *slot = value.clone();
3834 }
3835 }
3836 }
3837 }
3838 }
3839 Ok(true)
3840 }
3841
3842 /// The `TypeError` an assignment to a read-only binding raises.
3843 fn read_only_local(&self, name: &str) -> Signal {
3844 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
3845 }
3846
3847 /// Declare `name` as a variable of the frame that called the running `eval`.
3848 ///
3849 /// `None` when there is no direct eval in progress, or it was called from the top
3850 /// level — then the caller's variable environment *is* the global one and the
3851 /// existing path is right.
3852 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
3853 let caller = self.eval_caller.flatten()?;
3854 // The bottom frame is the top-level script, whose variable environment *is* the
3855 // global one — so `eval("var x = 1")` at the top level still creates a global.
3856 if caller == 0 {
3857 return None;
3858 }
3859 // A name the eval's *own* variable environment already binds is not a new
3860 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
3861 // `arguments`, and creating a second binding would leave the first — the one
3862 // closures read — untouched. A binding of an *outer* frame does not count: a
3863 // declaration shadows it rather than writing through.
3864 if self
3865 .eval_bindings
3866 .iter()
3867 .any(|binding| binding.name == name && binding.frame == caller)
3868 {
3869 return None;
3870 }
3871 let phase = if self.in_parameter_list_at(caller) {
3872 0
3873 } else {
3874 1
3875 };
3876 self.frame_local_vars(caller)?;
3877 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
3878 if let Some(cell) = local_vars.get(name, 1) {
3879 return Some(cell);
3880 }
3881 let cell = self.new_cell(Value::Undefined);
3882 Some(local_vars.declare(name, phase, cell))
3883 }
3884
3885 /// Make sure `frame` has a `LocalVars`, creating it on demand.
3886 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
3887 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
3888 return Some(local_vars.clone());
3889 }
3890 let local_vars = Gc::new(self.heap, LocalVars::new());
3891 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
3892 Some(local_vars)
3893 }
3894
3895 /// Whether the realm already has a binding for `name`, lexically or as an *own*
3896 /// property of the global object. Used to decide whether a store inside an
3897 /// `eval` writes through to the realm or declares a binding of its own.
3898 ///
3899 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
3900 /// write to `Object.prototype.toString`, and must not shadow it either.
3901 fn global_knows(&mut self, name: &str) -> bool {
3902 if self.realm.globals.contains_key(name) {
3903 return true;
3904 }
3905 self.realm.global.own_property(name).is_some()
3906 }
3907
3908 /// Whether the code currently running is strict.
3909 ///
3910 /// Read off the frame's function, which is where the parser's answer ended up; a
3911 /// native function never runs strict-only checks, and there is no frame at all
3912 /// before the first script.
3913 pub fn current_strict(&self) -> bool {
3914 self.frames
3915 .last()
3916 .is_some_and(|frame| frame.code.code.strict)
3917 }
3918
3919 /// Initialise a declared global, which is what ends its dead zone.
3920 ///
3921 /// A `var` global becomes a property of the global object: writable, so a later
3922 /// assignment goes through, and non-configurable, so `delete` refuses.
3923 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
3924 let (name, lexical, _) = self.global_binding(slot);
3925 // A `var` declared by the strict `eval` currently running belongs to the
3926 // eval's scope, not to the global object: `eval("var v = 1")` must not make
3927 // `typeof v` answer `"number"` afterwards. A name the realm already has is
3928 // initialised in place, which is what a re-declaration inside eval does.
3929 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
3930 self.eval_scope
3931 .as_mut()
3932 .expect("checked above")
3933 .insert(name, value);
3934 return Ok(());
3935 }
3936 if let Some(scope) = self.eval_scope.as_mut()
3937 && scope.contains_key(&name)
3938 {
3939 scope.insert(name, value);
3940 return Ok(());
3941 }
3942 if lexical {
3943 // The cell exists (created at declaration time) holding the dead-zone
3944 // marker; storing the value is what makes the binding readable.
3945 if let Some(cell) = self.realm.globals.get(&name).cloned() {
3946 cell.set(value);
3947 return Ok(());
3948 }
3949 let cell = self.new_cell(value);
3950 self.realm.globals.insert(name, cell);
3951 return Ok(());
3952 }
3953 let global = self.realm.global.clone();
3954 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
3955 // to answer `false` and leave the binding in place. `with_attributes` ties
3956 // `configurable` to `writable`, so the property is built field by field.
3957 global.define(
3958 &name,
3959 Property {
3960 value: Some(value),
3961 writable: true,
3962 enumerable: true,
3963 configurable: false,
3964 ..Property::default()
3965 },
3966 );
3967 Ok(())
3968 }
3969
3970 /// The `TypeError` a store to a `const` global raises.
3971 fn read_only_global(&self, name: &str) -> Signal {
3972 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
3973 }
3974
3975 // -- properties ---------------------------------------------------------
3976
3977 /// Read `object[key]`, following the prototype chain.
3978 ///
3979 /// An inherited accessor runs with the *receiver* as `this`, which is why the
3980 /// lookup returns the owner rather than just the value.
3981 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
3982 self.get_property_key(object, &PropertyKey::from(key))
3983 }
3984
3985 /// [`Interp::get_property`] with a key that may be a symbol.
3986 pub fn get_property_key(
3987 &mut self,
3988 object: &Gc<JsObject>,
3989 key: &PropertyKey,
3990 ) -> JsResult<Option<Value>> {
3991 self.get_property_key_for(object, None, key)
3992 }
3993
3994 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
3995 ///
3996 /// The receiver matters when the property is found on a *prototype*: a getter has to
3997 /// see the object the read started from. For a primitive that is the primitive
3998 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
3999 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
4000 /// the owner.
4001 pub fn get_property_key_for(
4002 &mut self,
4003 object: &Gc<JsObject>,
4004 receiver: Option<&Value>,
4005 key: &PropertyKey,
4006 ) -> JsResult<Option<Value>> {
4007 // A proxy answers for itself, before any of the shortcuts below: `new
4008 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
4009 // have.
4010 if object.proxy_state().is_some() {
4011 let receiver = receiver
4012 .cloned()
4013 .unwrap_or_else(|| Value::Object(object.clone()));
4014 return self.proxy_get(object, &receiver, key);
4015 }
4016 // The element-vector and `length` shortcuts are string-only: an array index
4017 // has no symbol spelling.
4018 if let Some(text) = key.as_str() {
4019 if let Some(value) = self.own_element(object, text) {
4020 return Ok(Some(value));
4021 }
4022 // `length` is not stored as a property: an array's length is its element
4023 // count, and keeping one copy of it is what makes `push`/`pop` and
4024 // `a.length = n` agree.
4025 if let Some(length) = object.array_length()
4026 && text == "length"
4027 {
4028 // Not `Value::Int(length as i32)`: see [`length_value`].
4029 return Ok(Some(crate::object::length_value(length)));
4030 }
4031 }
4032 match lookup_key(object, key) {
4033 Some((_, property)) => {
4034 if property.is_accessor() {
4035 match &property.getter {
4036 Some(getter) if !matches!(getter, Value::Undefined) => {
4037 let receiver = receiver
4038 .cloned()
4039 .unwrap_or_else(|| Value::Object(object.clone()));
4040 self.call_value(getter.clone(), receiver, Vec::new())
4041 .map(Some)
4042 }
4043 // An accessor with no getter reads as `undefined`.
4044 _ => Ok(Some(Value::Undefined)),
4045 }
4046 } else {
4047 Ok(property.value)
4048 }
4049 }
4050 None => Ok(None),
4051 }
4052 }
4053
4054 /// `super.key` — start the search at `proto`, but report to `receiver`.
4055 ///
4056 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
4057 /// found on the prototype of a class has to see the *instance* as `this`, and a
4058 /// plain property read off `proto` would lose that.
4059 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
4060 let start = self.require_object(proto)?;
4061 let key = self.propkey(key)?;
4062 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
4063 if matches!(proto, Value::Null) {
4064 return Ok(Value::Undefined);
4065 }
4066 match lookup_key(&start, &key) {
4067 Some((_, property)) if property.is_accessor() => match &property.getter {
4068 Some(getter) if !matches!(getter, Value::Undefined) => {
4069 self.call_value(getter.clone(), receiver.clone(), Vec::new())
4070 }
4071 _ => Ok(Value::Undefined),
4072 },
4073 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
4074 None => Ok(Value::Undefined),
4075 }
4076 }
4077
4078 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
4079 ///
4080 /// A setter found on the prototype runs with `receiver` as `this`; a data property
4081 /// is shadowed by a new own property on the receiver, the same rule an ordinary
4082 /// assignment follows.
4083 fn super_write(
4084 &mut self,
4085 receiver: &Value,
4086 proto: &Value,
4087 key: &Value,
4088 value: Value,
4089 ) -> JsResult<()> {
4090 let target = self.require_object(receiver)?;
4091 let key = self.propkey(key)?;
4092 if !matches!(proto, Value::Null)
4093 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
4094 {
4095 if property.is_accessor() {
4096 if let Some(setter) = &property.setter
4097 && !matches!(setter, Value::Undefined)
4098 {
4099 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
4100 }
4101 return Ok(());
4102 }
4103 // A data property on the prototype is writable or not; reading `owner` at
4104 // all is only for the attribute check.
4105 if !property.writable {
4106 return Err(self.type_error(format!("'{key}' is read-only")));
4107 }
4108 let _ = owner;
4109 }
4110 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
4111 }
4112
4113 /// The object a `super` operation needs, or the `TypeError` the spec raises.
4114 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
4115 match value.as_object() {
4116 Some(object) => Ok(object.clone()),
4117 None => Err(Signal::Throw(
4118 self.make_error("TypeError", "value is not an object"),
4119 )),
4120 }
4121 }
4122
4123 /// Build the class object `define_class` produces.
4124 ///
4125 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
4126 /// whose prototype property is a fresh object inheriting from the parent's
4127 /// prototype, and whose own prototype is the parent constructor — which is what makes
4128 /// a static method inherited too.
4129 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
4130 let ctor = self.pop();
4131 let parent = self.pop();
4132 let Value::Object(function) = &ctor else {
4133 return Err(Signal::Throw(
4134 self.make_error("TypeError", "class constructor must be a function"),
4135 ));
4136 };
4137 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
4138 // but gives the instances no prototype at all.
4139 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
4140 match &parent {
4141 Value::Null => (Some(self.realm.function_proto.clone()), None),
4142 Value::Object(parent_class) => {
4143 if !parent_class.is_callable() {
4144 return Err(Signal::Throw(
4145 self.make_error("TypeError", "parent class must be constructor"),
4146 ));
4147 }
4148 let proto = self.get_property(parent_class, "prototype")?;
4149 match proto {
4150 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
4151 Some(Value::Null) => (Some(parent_class.clone()), None),
4152 _ => {
4153 return Err(Signal::Throw(self.make_error(
4154 "TypeError",
4155 "parent prototype must be an object or null",
4156 )));
4157 }
4158 }
4159 }
4160 _ => {
4161 return Err(Signal::Throw(
4162 self.make_error("TypeError", "parent class must be constructor"),
4163 ));
4164 }
4165 }
4166 } else {
4167 (
4168 Some(self.realm.function_proto.clone()),
4169 Some(self.realm.object_proto.clone()),
4170 )
4171 };
4172 let proto = self.new_object(parent_proto);
4173 function.set_proto(parent_ctor);
4174 // A class is not callable without `new`, and its `prototype` is not writable —
4175 // both follow from being a class and are what `class A {}; A()` throws on.
4176 function.set_class_constructor(true);
4177 function.set_home_object(None);
4178 self.set_function_name(&ctor, name);
4179 self.define_class_properties(function, &ctor, &proto)?;
4180 Ok((ctor, proto))
4181 }
4182
4183 /// Give the constructor its `prototype` and `length`, and the prototype its
4184 /// `constructor` back-pointer.
4185 fn define_class_properties(
4186 &mut self,
4187 function: &Gc<JsObject>,
4188 ctor: &Value,
4189 proto: &Gc<JsObject>,
4190 ) -> JsResult<()> {
4191 proto.define(
4192 "constructor",
4193 Property::with_attributes(ctor.clone(), true, false),
4194 );
4195 function.define(
4196 "prototype",
4197 Property::prototype_of(Value::Object(proto.clone()), false),
4198 );
4199 if let Some((code, _)) = bytecode_of(function) {
4200 let length = code.code.defined_args;
4201 function.define(
4202 "length",
4203 Property::name_or_length(Value::Int(length as i32)),
4204 );
4205 }
4206 Ok(())
4207 }
4208
4209 /// The own array element `key` names, if this object has one.
4210 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
4211 let index = array_index(key)?;
4212 // A typed array's elements live in its buffer, not in a property list: reading one
4213 // goes through the view's element type so a bounds check and a detached buffer are
4214 // both handled there.
4215 if object.typed_array_parts().is_some() {
4216 return object.typed_array_element(index as usize);
4217 }
4218 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
4219 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
4220 // search early, which is why `Array.prototype[1] = 9` could not be seen through
4221 // `[1,,3][1]`.
4222 match object.array_get(index as usize) {
4223 Some(Value::Hole) | None => None,
4224 other => other,
4225 }
4226 }
4227
4228 /// Store `object[key] = value`, honouring setters and inherited properties.
4229 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
4230 self.set_property_with(object, key, value, DeleteFailure::Throw)
4231 }
4232
4233 /// Store a property, choosing what to do when the object refuses.
4234 ///
4235 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
4236 /// mode, which is the one place assignment differs by mode. Native code (the array
4237 /// methods, `JSON`) always asks for the throw.
4238 pub fn set_property_with(
4239 &mut self,
4240 object: &Gc<JsObject>,
4241 key: &str,
4242 value: Value,
4243 on_failure: DeleteFailure,
4244 ) -> JsResult<()> {
4245 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
4246 }
4247
4248 /// [`Interp::set_property_with`] with a key that may be a symbol.
4249 pub fn set_property_with_key(
4250 &mut self,
4251 object: &Gc<JsObject>,
4252 key: &PropertyKey,
4253 value: Value,
4254 on_failure: DeleteFailure,
4255 ) -> JsResult<()> {
4256 // A proxy's `set` trap decides, and its `false` means the same thing an
4257 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
4258 if object.proxy_state().is_some() {
4259 let receiver = Value::Object(object.clone());
4260 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
4261 return match (accepted, on_failure) {
4262 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
4263 (false, DeleteFailure::Throw) => {
4264 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
4265 }
4266 };
4267 }
4268 }
4269 // The element and `length` shortcuts only exist for string keys: an array
4270 // index has no symbol spelling, and a symbol named `length` is an ordinary
4271 // property.
4272 let text = key.as_str();
4273 // A typed array's elements are a window onto its buffer: the store has to go
4274 // through the view's element type so the value is wrapped (or clamped) and so an
4275 // out-of-range or detached write is a silent no-op, as the spec says.
4276 if let Some(text) = text
4277 && let Some(index) = array_index(text)
4278 && let Some(element) = object.typed_array_element_type()
4279 {
4280 // §10.4.5.5: an out-of-bounds index answers `true` *before* `V` is converted,
4281 // so a `valueOf` with a side effect must not run. Checking the length first is
4282 // what keeps `valueOfCalled` at 0 in `key-is-out-of-bounds-receiver-is-…`.
4283 let length = object.typed_array_length().unwrap_or(0);
4284 if index as usize >= length {
4285 return Ok(());
4286 }
4287 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
4288 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
4289 // in `Interp`, because it is script-observable and the storage borrow inside
4290 // `typed_array_set` must not be held across it.
4291 let stored = self.element_value(element, value)?;
4292 if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
4293 return Err(self.type_error(reason));
4294 }
4295 return Ok(());
4296 }
4297 if let Some(text) = text
4298 && let Some(index) = array_index(text)
4299 && object.is_array()
4300 {
4301 // An accessor defined on an index lives in the property table while the
4302 // element slot is a hole, so the store has to go through the property first.
4303 // Writing the vector directly skipped the setter entirely.
4304 if let Some(existing) = object.own_property_key(key) {
4305 if existing.is_accessor() {
4306 return match existing.setter.clone() {
4307 Some(setter) if !matches!(setter, Value::Undefined) => {
4308 let receiver = Value::Object(object.clone());
4309 self.call_value(setter, receiver, vec![value]).map(|_| ())
4310 }
4311 _ => match on_failure {
4312 DeleteFailure::Throw => Err(self.type_error(format!(
4313 "cannot set property '{text}', it has only a getter"
4314 ))),
4315 DeleteFailure::Ignore => Ok(()),
4316 },
4317 };
4318 }
4319 if !existing.writable {
4320 return match on_failure {
4321 DeleteFailure::Throw => {
4322 Err(self.type_error(format!("'{text}' is read-only")))
4323 }
4324 DeleteFailure::Ignore => Ok(()),
4325 };
4326 }
4327 }
4328 {
4329 // Growing the array needs a writable `length`.
4330 if (index as usize) >= object.array_length().unwrap_or(0)
4331 && !object.length_writable()
4332 {
4333 return match on_failure {
4334 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4335 DeleteFailure::Ignore => Ok(()),
4336 };
4337 }
4338 // Adding an index past the end makes the array longer, which a
4339 // non-extensible array refuses.
4340 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
4341 return match on_failure {
4342 DeleteFailure::Throw => Err(self.type_error(format!(
4343 "cannot add property '{key}', object is not extensible"
4344 ))),
4345 DeleteFailure::Ignore => Ok(()),
4346 };
4347 }
4348 if object.element_is_locked(index) {
4349 return match on_failure {
4350 DeleteFailure::Throw => {
4351 Err(self.type_error(format!("'{key}' is read-only")))
4352 }
4353 DeleteFailure::Ignore => Ok(()),
4354 };
4355 }
4356 if object.array_set(self.heap, index as usize, value.clone()) {
4357 return Ok(());
4358 }
4359 // Past the dense limit the slot is too far out to be worth one `Value`
4360 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
4361 // constant time by keeping the index as an ordinary property. The store
4362 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
4363 // to a legal program.
4364 object.define_key(key, Property::with_attributes(value, true, true));
4365 // Extend, never shorten: the index may be *inside* the current length (a
4366 // huge `length` with a sparse store), and shortening would delete the
4367 // sparse properties above it — including the one just stored.
4368 if index as usize + 1 > object.array_length().unwrap_or(0) {
4369 object.array_set_length(self.heap, index as usize + 1);
4370 }
4371 return Ok(());
4372 }
4373 }
4374 if text == Some("length") && object.is_array() {
4375 if !object.length_writable() {
4376 return match on_failure {
4377 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4378 DeleteFailure::Ignore => Ok(()),
4379 };
4380 }
4381 let length = value.to_number();
4382 if length.is_finite() && length >= 0.0 {
4383 let length = length as usize;
4384 // `a.length = n` with `n` below a non-configurable element cannot
4385 // drop that element, so the whole assignment fails. The spec makes
4386 // this a `TypeError` rather than a silent no-op, in any mode.
4387 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
4388 // Sloppy mode stops the truncation at the blocking element
4389 // instead of failing; strict mode raises.
4390 // Both modes stop at the blocking element; they differ in
4391 // whether that is reported. The reference truncates *then*
4392 // throws, so the array is left in the shortened state.
4393 object.array_truncate(self.heap, blocked + 1);
4394 return match on_failure {
4395 DeleteFailure::Throw => {
4396 Err(self.type_error(format!("cannot delete property '{blocked}'")))
4397 }
4398 DeleteFailure::Ignore => Ok(()),
4399 };
4400 }
4401 object.array_set_length(self.heap, length);
4402 return Ok(());
4403 }
4404 }
4405 if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
4406 {
4407 return match on_failure {
4408 DeleteFailure::Throw => Err(self.type_error(format!(
4409 "cannot add property {}, object is not extensible",
4410 key
4411 ))),
4412 DeleteFailure::Ignore => Ok(()),
4413 };
4414 }
4415 if let Some((owner, property)) = lookup_key(object, key) {
4416 if property.is_accessor() {
4417 if let Some(setter) = &property.setter
4418 && !matches!(setter, Value::Undefined)
4419 {
4420 let receiver = Value::Object(object.clone());
4421 self.call_value(setter.clone(), receiver, vec![value])?;
4422 }
4423 return Ok(());
4424 }
4425 // An inherited *data* property is shadowed by an own property on the
4426 // receiver; a non-writable one is not.
4427 if owner.ptr_eq(object) && !property.writable {
4428 return match on_failure {
4429 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
4430 DeleteFailure::Ignore => Ok(()),
4431 };
4432 }
4433 // An existing writable own property keeps its attributes: only the value
4434 // moves. Redefining instead would reset them, which is how a
4435 // non-configurable global `var` used to become deletable.
4436 if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
4437 return Ok(());
4438 }
4439 }
4440 // No own data property: create one, shadowing whatever the prototype holds.
4441 object.define_data_key(key, value);
4442 Ok(())
4443 }
4444
4445 /// Delete `object[key]`.
4446 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
4447 self.delete_property_key(object, &PropertyKey::from(key))
4448 }
4449
4450 /// [`Interp::delete_property`] with a key that may be a symbol.
4451 pub fn delete_property_key(
4452 &mut self,
4453 object: &Gc<JsObject>,
4454 key: &PropertyKey,
4455 ) -> JsResult<bool> {
4456 // A proxy decides for itself, and may even throw; the invariant checks live in
4457 // `proxy_delete`.
4458 if let Some(answer) = self.proxy_delete(object, key)? {
4459 return Ok(answer);
4460 }
4461 if let Some(index) = key.as_str().and_then(array_index)
4462 && let Some(length) = object.array_length()
4463 && (index as usize) < length
4464 {
4465 // An accessor defined on an index lives in the property table rather than the
4466 // element vector, so both have to be cleared: `delete` after
4467 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
4468 object.delete_key(key);
4469 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
4470 // index stops answering `in`.
4471 if object.element_is_undeletable(index) {
4472 return Ok(false);
4473 }
4474 object.array_set(self.heap, index as usize, Value::Hole);
4475 return Ok(true);
4476 }
4477 Ok(object.delete_key(key))
4478 }
4479
4480 // -- proxy traps --------------------------------------------------------
4481 //
4482 // A proxy's internal methods all look the same: ask the handler for the trap, call it
4483 // with the target and the operation's own arguments, then check the answer against
4484 // the target. The checks are not decoration — they are what stops a proxy from
4485 // reporting a `non-configurable` property as missing, which would let a frozen object
4486 // be rewritten by standing in front of it.
4487
4488 /// The target and handler of `object`, or `None` when it is not a proxy.
4489 ///
4490 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
4491 /// one has to fail: the slots the traps would have been read from are gone.
4492 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
4493 let Some(state) = object.proxy_state() else {
4494 return Ok(None);
4495 };
4496 let state = state.borrow();
4497 match (&state.target, &state.handler) {
4498 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
4499 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
4500 }
4501 }
4502
4503 /// Call `handler[name]`, or answer `None` when the trap is absent.
4504 ///
4505 /// A trap that is present but not callable is a `TypeError` rather than "no trap":
4506 /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
4507 /// back to the target.
4508 fn proxy_trap(
4509 &mut self,
4510 handler: &Value,
4511 name: &str,
4512 args: Vec<Value>,
4513 ) -> JsResult<Option<Value>> {
4514 let Value::Object(table) = handler else {
4515 return Err(self.type_error("proxy handler is not an object"));
4516 };
4517 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
4518 match trap {
4519 Value::Undefined => Ok(None),
4520 Value::Object(function) if function.is_callable() => {
4521 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
4522 Ok(Some(answer))
4523 }
4524 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
4525 }
4526 }
4527
4528 /// Whether `object`'s own property `key` is one the target refuses to lose.
4529 ///
4530 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
4531 /// its value behind the target's back. This goes through
4532 /// [`Self::ordinary_own_property`] rather than the property table so that an array's
4533 /// elements and its `length` — both fixed, both outside the table — are covered.
4534 fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
4535 Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
4536 }
4537
4538 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
4539 fn proxy_get(
4540 &mut self,
4541 object: &Gc<JsObject>,
4542 receiver: &Value,
4543 key: &PropertyKey,
4544 ) -> JsResult<Option<Value>> {
4545 let Some((target, handler)) = self.proxy_parts(object)? else {
4546 return Ok(None);
4547 };
4548 let key_value = self.key_value(key);
4549 let Some(result) = self.proxy_trap(
4550 &handler,
4551 "get",
4552 vec![Value::Object(target.clone()), key_value, receiver.clone()],
4553 )?
4554 else {
4555 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
4556 // inherited getter still sees the proxy.
4557 return Ok(Some(
4558 self.get_property_key_for(&target, Some(receiver), key)?
4559 .unwrap_or(Value::Undefined),
4560 ));
4561 };
4562 if let Some(fixed) = Self::is_fixed_property(&target, key) {
4563 if fixed.is_accessor() {
4564 // A fixed accessor with no getter must read as `undefined`.
4565 let has_getter = fixed
4566 .getter
4567 .as_ref()
4568 .is_some_and(|getter| !matches!(getter, Value::Undefined));
4569 if !has_getter && !matches!(result, Value::Undefined) {
4570 return Err(self.type_error(format!(
4571 "proxy 'get' must report undefined for the non-configurable property '{key}'"
4572 )));
4573 }
4574 } else if !fixed.writable {
4575 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
4576 if !fixed_value.same_value(&result) {
4577 return Err(self.type_error(format!(
4578 "proxy 'get' disagrees with the non-configurable property '{key}'"
4579 )));
4580 }
4581 }
4582 }
4583 Ok(Some(result))
4584 }
4585
4586 /// `[[Set]]` on a proxy.
4587 ///
4588 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
4589 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
4590 /// read-only store has.
4591 fn proxy_set(
4592 &mut self,
4593 object: &Gc<JsObject>,
4594 key: &PropertyKey,
4595 value: Value,
4596 receiver: &Value,
4597 ) -> JsResult<Option<bool>> {
4598 let Some((target, handler)) = self.proxy_parts(object)? else {
4599 return Ok(None);
4600 };
4601 let key_value = self.key_value(key);
4602 let Some(result) = self.proxy_trap(
4603 &handler,
4604 "set",
4605 vec![
4606 Value::Object(target.clone()),
4607 key_value,
4608 value.clone(),
4609 receiver.clone(),
4610 ],
4611 )?
4612 else {
4613 // No trap: store on the target, which is where an ordinary proxy write lands.
4614 self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
4615 return Ok(Some(true));
4616 };
4617 if !result.to_boolean() {
4618 return Ok(Some(false));
4619 }
4620 if let Some(fixed) = Self::is_fixed_property(&target, key) {
4621 if fixed.is_accessor() {
4622 let has_setter = fixed
4623 .setter
4624 .as_ref()
4625 .is_some_and(|setter| !matches!(setter, Value::Undefined));
4626 if !has_setter {
4627 return Err(self.type_error(format!(
4628 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
4629 )));
4630 }
4631 } else if !fixed.writable {
4632 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
4633 if !fixed_value.same_value(&value) {
4634 return Err(self.type_error(format!(
4635 "proxy 'set' changed the non-configurable property '{key}'"
4636 )));
4637 }
4638 }
4639 }
4640 // A new property cannot appear on a target that refuses new properties.
4641 if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
4642 return Err(self.type_error(format!(
4643 "proxy 'set' added '{key}' to a non-extensible target"
4644 )));
4645 }
4646 Ok(Some(true))
4647 }
4648
4649 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
4650 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
4651 let Some((target, handler)) = self.proxy_parts(object)? else {
4652 return Ok(None);
4653 };
4654 let key_value = self.key_value(key);
4655 let Some(result) = self.proxy_trap(
4656 &handler,
4657 "has",
4658 vec![Value::Object(target.clone()), key_value],
4659 )?
4660 else {
4661 return Ok(Some(self.has_own_or_inherited(&target, key)?));
4662 };
4663 if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
4664 return Err(self.type_error(format!(
4665 "proxy 'has' denied the non-configurable property '{key}'"
4666 )));
4667 }
4668 // A non-extensible target cannot grow, so every own property it *has* is fixed.
4669 if !result.to_boolean()
4670 && !target.is_extensible()
4671 && Self::ordinary_own_property(&target, key).is_some()
4672 {
4673 return Err(self.type_error(format!(
4674 "proxy 'has' denied the own property '{key}' of a non-extensible target"
4675 )));
4676 }
4677 Ok(Some(result.to_boolean()))
4678 }
4679
4680 /// `[[Delete]]` on a proxy.
4681 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
4682 let Some((target, handler)) = self.proxy_parts(object)? else {
4683 return Ok(None);
4684 };
4685 let key_value = self.key_value(key);
4686 let Some(result) = self.proxy_trap(
4687 &handler,
4688 "deleteProperty",
4689 vec![Value::Object(target.clone()), key_value],
4690 )?
4691 else {
4692 return Ok(Some(self.delete_property_key(&target, key)?));
4693 };
4694 if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
4695 return Err(self.type_error(format!(
4696 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
4697 )));
4698 }
4699 if result.to_boolean()
4700 && !target.is_extensible()
4701 && Self::ordinary_own_property(&target, key).is_some()
4702 {
4703 return Err(self.type_error(format!(
4704 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
4705 )));
4706 }
4707 Ok(Some(result.to_boolean()))
4708 }
4709
4710 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
4711 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
4712 let Some((target, handler)) = self.proxy_parts(object)? else {
4713 return Ok(None);
4714 };
4715 let Some(result) =
4716 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
4717 else {
4718 // No trap: the target's own keys, already in the order an object reports.
4719 return Ok(Some(self.object_own_property_keys(&target)?));
4720 };
4721 // `CreateListFromArrayLike` with the string-or-symbol restriction.
4722 let list = self.list_from_array_like(&result, true)?;
4723 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
4724 for value in list {
4725 let key = self.propkey(&value)?;
4726 if keys.contains(&key) {
4727 return Err(self.type_error(format!(
4728 "proxy 'ownKeys' returned the duplicate key '{key}'"
4729 )));
4730 }
4731 keys.push(key);
4732 }
4733 for (key, property) in target.property_entries() {
4734 if !property.configurable && !keys.contains(&key) {
4735 return Err(self.type_error(format!(
4736 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
4737 )));
4738 }
4739 if !target.is_extensible() && !keys.contains(&key) {
4740 return Err(self.type_error(format!(
4741 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
4742 )));
4743 }
4744 }
4745 if !target.is_extensible() {
4746 let own = target.property_entries().len();
4747 if keys.len() != own {
4748 return Err(
4749 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
4750 );
4751 }
4752 }
4753 Ok(Some(keys))
4754 }
4755
4756 /// `[[GetOwnProperty]]` on a proxy.
4757 fn proxy_get_own_property(
4758 &mut self,
4759 object: &Gc<JsObject>,
4760 key: &PropertyKey,
4761 ) -> JsResult<Option<Option<Property>>> {
4762 let Some((target, handler)) = self.proxy_parts(object)? else {
4763 return Ok(None);
4764 };
4765 let key_value = self.key_value(key);
4766 let Some(result) = self.proxy_trap(
4767 &handler,
4768 "getOwnPropertyDescriptor",
4769 vec![Value::Object(target.clone()), key_value],
4770 )?
4771 else {
4772 // No trap: the target's own descriptor is the answer. This has to go through
4773 // the same synthesis an ordinary object gets, because a proxy's own property
4774 // table is empty by design — reading it directly reported `undefined` for
4775 // every key, including an array's indices and `length`.
4776 return Ok(Some(Self::ordinary_own_property(&target, key)));
4777 };
4778 let answer = if matches!(result, Value::Undefined) {
4779 None
4780 } else {
4781 Some(self.property_from_descriptor(&result)?)
4782 };
4783 let fixed = Self::is_fixed_property(&target, key);
4784 match (&answer, &fixed) {
4785 // A non-configurable property cannot be reported as absent.
4786 (None, Some(_)) => {
4787 return Err(self.type_error(format!(
4788 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
4789 )));
4790 }
4791 (Some(descriptor), Some(fixed)) => {
4792 if descriptor.configurable {
4793 return Err(self.type_error(format!(
4794 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
4795 )));
4796 }
4797 if fixed.is_accessor() != descriptor.is_accessor() {
4798 return Err(self.type_error(format!(
4799 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
4800 )));
4801 }
4802 if !fixed.is_accessor() && !fixed.writable {
4803 let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
4804 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
4805 if !fixed_value.same_value(&reported) {
4806 return Err(self.type_error(format!(
4807 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
4808 )));
4809 }
4810 }
4811 }
4812 _ => {}
4813 }
4814 Ok(Some(answer))
4815 }
4816
4817 /// `[[DefineOwnProperty]]` on a proxy.
4818 fn proxy_define_property(
4819 &mut self,
4820 object: &Gc<JsObject>,
4821 key: &PropertyKey,
4822 property: Property,
4823 ) -> JsResult<Option<bool>> {
4824 let Some((target, handler)) = self.proxy_parts(object)? else {
4825 return Ok(None);
4826 };
4827 let key_value = self.key_value(key);
4828 let descriptor = self.descriptor_from_property(&property);
4829 let Some(result) = self.proxy_trap(
4830 &handler,
4831 "defineProperty",
4832 vec![Value::Object(target.clone()), key_value, descriptor],
4833 )?
4834 else {
4835 return Ok(None);
4836 };
4837 if !result.to_boolean() {
4838 return Ok(Some(false));
4839 }
4840 let fixed = Self::is_fixed_property(&target, key);
4841 let creating = Self::ordinary_own_property(&target, key).is_none();
4842 if creating && !target.is_extensible() {
4843 return Err(self.type_error(format!(
4844 "proxy 'defineProperty' added '{key}' to a non-extensible target"
4845 )));
4846 }
4847 if let Some(fixed) = fixed {
4848 if property.configurable {
4849 return Err(self.type_error(format!(
4850 "proxy 'defineProperty' made the non-configurable '{key}' configurable"
4851 )));
4852 }
4853 if !fixed.writable && property.writable && !fixed.is_accessor() {
4854 return Err(self.type_error(format!(
4855 "proxy 'defineProperty' made the read-only '{key}' writable"
4856 )));
4857 }
4858 }
4859 Ok(Some(true))
4860 }
4861
4862 /// `[[GetPrototypeOf]]` on a proxy.
4863 fn proxy_get_prototype_of(
4864 &mut self,
4865 object: &Gc<JsObject>,
4866 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
4867 let Some((target, handler)) = self.proxy_parts(object)? else {
4868 return Ok(None);
4869 };
4870 let Some(result) = self.proxy_trap(
4871 &handler,
4872 "getPrototypeOf",
4873 vec![Value::Object(target.clone())],
4874 )?
4875 else {
4876 return Ok(Some(target.proto()));
4877 };
4878 let proto = match &result {
4879 Value::Null => None,
4880 Value::Object(proto) => Some(proto.clone()),
4881 _ => {
4882 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
4883 }
4884 };
4885 if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
4886 return Err(self.type_error(
4887 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
4888 ));
4889 }
4890 Ok(Some(proto))
4891 }
4892
4893 /// `[[SetPrototypeOf]]` on a proxy.
4894 fn proxy_set_prototype_of(
4895 &mut self,
4896 object: &Gc<JsObject>,
4897 proto: Option<Gc<JsObject>>,
4898 ) -> JsResult<Option<bool>> {
4899 let Some((target, handler)) = self.proxy_parts(object)? else {
4900 return Ok(None);
4901 };
4902 let proto_value = match &proto {
4903 Some(proto) => Value::Object(proto.clone()),
4904 None => Value::Null,
4905 };
4906 let Some(result) = self.proxy_trap(
4907 &handler,
4908 "setPrototypeOf",
4909 vec![Value::Object(target.clone()), proto_value],
4910 )?
4911 else {
4912 target.set_proto(proto);
4913 return Ok(Some(true));
4914 };
4915 if result.to_boolean()
4916 && !target.is_extensible()
4917 && !same_proto(proto.as_ref(), target.proto().as_ref())
4918 {
4919 return Err(self.type_error(
4920 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
4921 ));
4922 }
4923 Ok(Some(result.to_boolean()))
4924 }
4925
4926 /// `[[IsExtensible]]` on a proxy.
4927 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
4928 let Some((target, handler)) = self.proxy_parts(object)? else {
4929 return Ok(None);
4930 };
4931 let Some(result) = self.proxy_trap(
4932 &handler,
4933 "isExtensible",
4934 vec![Value::Object(target.clone())],
4935 )?
4936 else {
4937 return Ok(Some(target.is_extensible()));
4938 };
4939 // The answer is not the proxy's to invent: it must agree with the target, or a
4940 // script could learn `false` while the target keeps accepting new properties.
4941 if result.to_boolean() != target.is_extensible() {
4942 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
4943 }
4944 Ok(Some(result.to_boolean()))
4945 }
4946
4947 /// `[[PreventExtensions]]` on a proxy.
4948 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
4949 let Some((target, handler)) = self.proxy_parts(object)? else {
4950 return Ok(None);
4951 };
4952 let Some(result) = self.proxy_trap(
4953 &handler,
4954 "preventExtensions",
4955 vec![Value::Object(target.clone())],
4956 )?
4957 else {
4958 target.set_extensible(false);
4959 return Ok(Some(true));
4960 };
4961 if result.to_boolean() && target.is_extensible() {
4962 return Err(self.type_error(
4963 "proxy 'preventExtensions' reported success but the target is still extensible",
4964 ));
4965 }
4966 Ok(Some(result.to_boolean()))
4967 }
4968
4969 /// `[[Call]]` on a proxy, through the `apply` trap.
4970 fn proxy_apply(
4971 &mut self,
4972 object: &Gc<JsObject>,
4973 this: Value,
4974 args: Vec<Value>,
4975 ) -> JsResult<Option<Value>> {
4976 let Some((target, handler)) = self.proxy_parts(object)? else {
4977 return Ok(None);
4978 };
4979 // The trap gets the arguments as one array, which is the shape the spec passes
4980 // and the shape `apply` traps are written against (`args[0]` is the first one).
4981 let arguments = self.new_array(args.clone());
4982 let this_for_trap = this.clone();
4983 let Some(result) = self.proxy_trap(
4984 &handler,
4985 "apply",
4986 vec![
4987 Value::Object(target.clone()),
4988 this_for_trap,
4989 Value::Object(arguments),
4990 ],
4991 )?
4992 else {
4993 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
4994 };
4995 Ok(Some(result))
4996 }
4997
4998 /// `[[Construct]]` on a proxy, through the `construct` trap.
4999 fn proxy_construct(
5000 &mut self,
5001 object: &Gc<JsObject>,
5002 args: Vec<Value>,
5003 new_target: &Value,
5004 ) -> JsResult<Option<Value>> {
5005 let Some((target, handler)) = self.proxy_parts(object)? else {
5006 return Ok(None);
5007 };
5008 if !target.is_callable() {
5009 return Err(self.type_error("proxy target is not a constructor"));
5010 }
5011 let arguments = self.new_array(args.clone());
5012 let Some(result) = self.proxy_trap(
5013 &handler,
5014 "construct",
5015 vec![
5016 Value::Object(target.clone()),
5017 Value::Object(arguments),
5018 new_target.clone(),
5019 ],
5020 )?
5021 else {
5022 return Ok(Some(self.construct(
5023 Value::Object(target),
5024 new_target.clone(),
5025 args,
5026 )?));
5027 };
5028 if !matches!(result, Value::Object(_)) {
5029 return Err(self.type_error("proxy 'construct' must return an object"));
5030 }
5031 Ok(Some(result))
5032 }
5033
5034 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
5035 pub(crate) fn has_own_or_inherited(
5036 &mut self,
5037 object: &Gc<JsObject>,
5038 key: &PropertyKey,
5039 ) -> JsResult<bool> {
5040 // The object itself first: it may be a proxy, and then the answer is its trap's.
5041 if let Some(answer) = self.proxy_has(object, key)? {
5042 return Ok(answer);
5043 }
5044 // `has_own` rather than `own_property_key`: an array's elements and its derived
5045 // `length` are invisible to the property table, and `Array.prototype` is an array.
5046 if has_own(object, key) {
5047 return Ok(true);
5048 }
5049 // A hole is *not* the end of the search: the chain may still have the key, which
5050 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
5051 for ancestor in object.chain() {
5052 // A proxy further up the chain answers for itself.
5053 if let Some(answer) = self.proxy_has(&ancestor, key)? {
5054 return Ok(answer);
5055 }
5056 if has_own(&ancestor, key) {
5057 return Ok(true);
5058 }
5059 }
5060 Ok(false)
5061 }
5062
5063 /// `CreateListFromArrayLike`, optionally restricted to property keys.
5064 ///
5065 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
5066 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
5067 /// `TypeError` instead of a property named `"1.5"`.
5068 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
5069 let object = self.object_from(value)?;
5070 let length = self
5071 .get_property(&object, "length")?
5072 .map(|value| value.to_number())
5073 .unwrap_or(0.0);
5074 if !length.is_finite() || length < 0.0 {
5075 return Err(self.type_error("invalid array-like length"));
5076 }
5077 let length = length as usize;
5078 let mut items = Vec::with_capacity(length.min(1024));
5079 for index in 0..length {
5080 let item = self
5081 .get_property(&object, &index.to_string())?
5082 .unwrap_or(Value::Undefined);
5083 if keys_only && matches!(&item, Value::Symbol(_)) {
5084 items.push(item);
5085 continue;
5086 }
5087 if keys_only && !matches!(&item, Value::String(_)) {
5088 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
5089 }
5090 items.push(item);
5091 }
5092 Ok(items)
5093 }
5094
5095 /// A `Property` from the descriptor object a trap returned.
5096 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
5097 let object = self.object_from(value)?;
5098 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
5099 interp.get_property(&object, name)
5100 };
5101 let getter = field(self, "get")?;
5102 let setter = field(self, "set")?;
5103 let accessor = getter.is_some() || setter.is_some();
5104 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
5105 Ok(interp
5106 .get_property(&object, name)?
5107 .is_some_and(|value| value.to_boolean()))
5108 };
5109 let enumerable = boolean(self, "enumerable")?;
5110 let configurable = boolean(self, "configurable")?;
5111 if accessor {
5112 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
5113 return Err(
5114 self.type_error("a descriptor cannot be both a data property and an accessor")
5115 );
5116 }
5117 Ok(Property {
5118 getter: getter.or(Some(Value::Undefined)),
5119 setter: setter.or(Some(Value::Undefined)),
5120 enumerable,
5121 configurable,
5122 writable: false,
5123 value: None,
5124 })
5125 } else {
5126 Ok(Property {
5127 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
5128 writable: boolean(self, "writable")?,
5129 enumerable,
5130 configurable,
5131 getter: None,
5132 setter: None,
5133 })
5134 }
5135 }
5136
5137 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
5138 fn descriptor_from_property(&mut self, property: &Property) -> Value {
5139 let object = self.new_object(None);
5140 if property.is_accessor() {
5141 let getter = property.getter.clone().unwrap_or(Value::Undefined);
5142 let setter = property.setter.clone().unwrap_or(Value::Undefined);
5143 object.define_data("get", getter);
5144 object.define_data("set", setter);
5145 } else {
5146 let value = property.value.clone().unwrap_or(Value::Undefined);
5147 object.define_data("value", value);
5148 object.define_data("writable", Value::Bool(property.writable));
5149 }
5150 object.define_data("enumerable", Value::Bool(property.enumerable));
5151 object.define_data("configurable", Value::Bool(property.configurable));
5152 Value::Object(object)
5153 }
5154
5155 // -- calling ------------------------------------------------------------
5156
5157 /// Call `callee` with `this` and `args`.
5158 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
5159 let Value::Object(function) = &callee else {
5160 // `typeof x === "function"` is not enough to make `x()` legal: only a
5161 // callable object is. `null` and `undefined` need no special wording
5162 // here — their `ToString` already reads the way the reference's does.
5163 let what = format!("{} is not a function", callee.to_js_string());
5164 return Err(Signal::Throw(self.make_error("TypeError", &what)));
5165 };
5166 // A proxy of a function is called through its `apply` trap. It has no
5167 // `ObjectKind::Function` of its own, so this has to come before the dispatch
5168 // below, and a proxy of a non-function has nothing to forward to.
5169 if function.proxy_state().is_some() {
5170 return match self.proxy_apply(function, this, args)? {
5171 Some(result) => Ok(result),
5172 None => Err(Signal::Throw(
5173 self.make_error("TypeError", "proxy target is not callable"),
5174 )),
5175 };
5176 }
5177 let callable = function.with(|data| match &data.kind {
5178 ObjectKind::Function(callable) => match callable {
5179 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
5180 // The `Rc` is cloned out so the borrow of this object's data is released
5181 // before the closure runs: the closure may touch the same object.
5182 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
5183 Callable::Bound {
5184 target,
5185 this,
5186 args: leading,
5187 } => Some(NativeCall::Bound {
5188 target: target.clone(),
5189 this: this.clone(),
5190 leading: leading.clone(),
5191 }),
5192 Callable::Bytecode { code, env } => {
5193 Some(NativeCall::Bytecode(code.clone(), env.clone()))
5194 }
5195 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
5196 Callable::PromiseResolve(promise) => {
5197 Some(NativeCall::PromiseResolve(promise.clone()))
5198 }
5199 Callable::PromiseReject(promise) => {
5200 Some(NativeCall::PromiseReject(promise.clone()))
5201 }
5202 Callable::AwaitResume {
5203 coroutine,
5204 promise,
5205 kind,
5206 } => Some(NativeCall::AwaitResume {
5207 coroutine: coroutine.clone(),
5208 promise: promise.clone(),
5209 kind: *kind,
5210 }),
5211 Callable::CombinatorSettle {
5212 state,
5213 index,
5214 fulfilled,
5215 } => Some(NativeCall::CombinatorSettle {
5216 state: state.clone(),
5217 index: *index,
5218 fulfilled: *fulfilled,
5219 }),
5220 Callable::FinallyShim {
5221 callback,
5222 fulfilled,
5223 } => Some(NativeCall::FinallyShim {
5224 callback: callback.clone(),
5225 fulfilled: *fulfilled,
5226 }),
5227 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
5228 Callable::CompletedReturn {
5229 generator,
5230 promise,
5231 rejected,
5232 } => Some(NativeCall::CompletedReturn {
5233 generator: generator.clone(),
5234 promise: promise.clone(),
5235 rejected: *rejected,
5236 }),
5237 Callable::YieldResult {
5238 generator,
5239 promise,
5240 done,
5241 } => Some(NativeCall::YieldResult {
5242 generator: generator.clone(),
5243 promise: promise.clone(),
5244 done: *done,
5245 }),
5246 Callable::DisposeStep {
5247 remaining,
5248 promise,
5249 error,
5250 rejected,
5251 } => Some(NativeCall::DisposeStep {
5252 remaining: remaining.clone(),
5253 promise: promise.clone(),
5254 error: error.clone(),
5255 rejected: *rejected,
5256 }),
5257 Callable::GeneratorResume {
5258 generator,
5259 promise,
5260 kind,
5261 } => Some(NativeCall::GeneratorResume {
5262 generator: generator.clone(),
5263 promise: promise.clone(),
5264 kind: *kind,
5265 }),
5266 Callable::SettlePromise {
5267 promise,
5268 value,
5269 rejected,
5270 } => Some(NativeCall::SettlePromise {
5271 promise: promise.clone(),
5272 value: value.clone(),
5273 rejected: *rejected,
5274 }),
5275 },
5276 _ => None,
5277 });
5278 match callable {
5279 Some(NativeCall::Host(func)) => {
5280 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
5281 // function by name rather than stopping at the caller.
5282 let frame_less = function
5283 .own_property("_frame_less")
5284 .and_then(|property| property.value)
5285 .is_some_and(|value| value.to_boolean());
5286 let name = function
5287 .own_property("name")
5288 .and_then(|property| property.value)
5289 .map(|value| value.to_js_string())
5290 .unwrap_or_default();
5291 let outer = if frame_less {
5292 None
5293 } else {
5294 self.native_frames
5295 .push((name, function.clone(), self.frames.len()));
5296 Some(self.current_native.replace(function.clone()))
5297 };
5298 let result = {
5299 let mut body = func.borrow_mut();
5300 body(self, this, &args)
5301 };
5302 if !frame_less {
5303 self.native_frames.pop();
5304 self.current_native = outer.flatten();
5305 }
5306 result
5307 }
5308 Some(NativeCall::Native(func)) => {
5309 // A function marked `_frame_less` is one the reference implements
5310 // without a call frame — `eval` is the only one so far.
5311 let frame_less = function
5312 .own_property("_frame_less")
5313 .and_then(|property| property.value)
5314 .is_some_and(|value| value.to_boolean());
5315 let name = function
5316 .own_property("name")
5317 .and_then(|property| property.value)
5318 .map(|value| value.to_js_string())
5319 .unwrap_or_default();
5320 let outer = if frame_less {
5321 None
5322 } else {
5323 self.native_frames
5324 .push((name, function.clone(), self.frames.len()));
5325 Some(self.current_native.replace(function.clone()))
5326 };
5327 let result = func(self, this, &args);
5328 if !frame_less {
5329 self.native_frames.pop();
5330 self.current_native = outer.flatten();
5331 }
5332 result
5333 }
5334 Some(NativeCall::Revoker(slots)) => {
5335 // Idempotent: revoking twice answers `undefined` again rather than
5336 // complaining, which is what the spec says and what a `finally` block
5337 // relies on.
5338 let mut state = slots.borrow_mut();
5339 state.target = None;
5340 state.handler = None;
5341 Ok(Value::Undefined)
5342 }
5343 Some(NativeCall::PromiseResolve(promise)) => {
5344 // One-shot: a second call is silently ignored, which
5345 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
5346 let value = args.first().cloned().unwrap_or(Value::Undefined);
5347 self.resolve_promise_with(&promise, value)?;
5348 Ok(Value::Undefined)
5349 }
5350 Some(NativeCall::PromiseReject(promise)) => {
5351 let reason = args.first().cloned().unwrap_or(Value::Undefined);
5352 self.reject_promise(&promise, reason);
5353 Ok(Value::Undefined)
5354 }
5355 Some(NativeCall::CombinatorSettle {
5356 state,
5357 index,
5358 fulfilled,
5359 }) => {
5360 let value = args.first().cloned().unwrap_or(Value::Undefined);
5361 self.settle_combinator(&state, index, fulfilled, value)?;
5362 Ok(Value::Undefined)
5363 }
5364 Some(NativeCall::AwaitResume {
5365 coroutine,
5366 promise,
5367 kind,
5368 }) => {
5369 // Resume *inline*, in the reaction that delivered the value. Deferring it
5370 // by another job inserts a tick between every `await` and its
5371 // continuation, which reorders `await` against unrelated `then` chains —
5372 // `f().then(g)` then runs before `f`'s own next statement.
5373 self.drive_async(
5374 &coroutine,
5375 &promise,
5376 kind,
5377 args.first().cloned().unwrap_or(Value::Undefined),
5378 )
5379 .map(|()| Value::Undefined)
5380 }
5381 Some(NativeCall::FinallyShim {
5382 callback,
5383 fulfilled,
5384 }) => {
5385 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
5386 // that settles with the *original* outcome once the callback's result has
5387 // settled. The callback's own value is discarded — that is the whole
5388 // difference between `finally` and `then`.
5389 let original = args.first().cloned().unwrap_or(Value::Undefined);
5390 let result = match &callback {
5391 Some(callback) => {
5392 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
5393 }
5394 None => Value::Undefined,
5395 };
5396 let resolved = self.promise_resolve_value(result)?;
5397 let Value::Object(resolved) = resolved else {
5398 return Ok(original);
5399 };
5400 // The wait is a chained promise rather than a bare return, so a callback
5401 // that returns a slow promise really does delay the continuation.
5402 let waiting = self.new_promise();
5403 let pass = JsObject::function(
5404 self.heap,
5405 Some(self.realm.function_proto.clone()),
5406 Callable::SettlePromise {
5407 promise: waiting.clone(),
5408 value: original,
5409 rejected: !fulfilled,
5410 },
5411 );
5412 let pass = Value::Object(pass);
5413 // Whichever way the callback's promise settles, the original outcome wins.
5414 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
5415 Ok(Value::Object(waiting))
5416 }
5417 Some(NativeCall::DisposeStep {
5418 remaining,
5419 promise,
5420 error,
5421 rejected,
5422 }) => {
5423 let error = if rejected {
5424 let reason = args.first().cloned().unwrap_or(Value::Undefined);
5425 self.merge_dispose_error(reason, error)
5426 } else {
5427 error
5428 };
5429 self.dispose_step(&remaining, &promise, error)?;
5430 Ok(Value::Undefined)
5431 }
5432 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
5433 Some(NativeCall::CompletedReturn {
5434 generator,
5435 promise,
5436 rejected,
5437 }) => {
5438 let value = args.first().cloned().unwrap_or(Value::Undefined);
5439 let outcome = if rejected {
5440 AsyncOutcome::Error(value)
5441 } else {
5442 AsyncOutcome::Value(self.iterator_result(value, true)?)
5443 };
5444 self.settle_async_request(&generator, &promise, outcome)?;
5445 Ok(Value::Undefined)
5446 }
5447 Some(NativeCall::YieldResult {
5448 generator,
5449 promise,
5450 done,
5451 }) => {
5452 let value = args.first().cloned().unwrap_or(Value::Undefined);
5453 let result = self.iterator_result(value, done)?;
5454 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
5455 Ok(Value::Undefined)
5456 }
5457 Some(NativeCall::GeneratorResume {
5458 generator,
5459 promise,
5460 kind,
5461 }) => {
5462 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
5463 // tick and reorders the generator against other chains.
5464 self.step_async_generator(
5465 &generator,
5466 &promise,
5467 kind,
5468 args.first().cloned().unwrap_or(Value::Undefined),
5469 )
5470 .map(|()| Value::Undefined)
5471 }
5472 Some(NativeCall::SettlePromise {
5473 promise,
5474 value,
5475 rejected,
5476 }) => {
5477 if rejected {
5478 self.reject_promise(&promise, value);
5479 } else {
5480 self.fulfill_promise(&promise, value);
5481 }
5482 Ok(Value::Undefined)
5483 }
5484 Some(NativeCall::Bound {
5485 target,
5486 this: bound_this,
5487 leading,
5488 }) => {
5489 let mut all = leading;
5490 all.extend(args);
5491 self.call_value(target, bound_this, all)
5492 }
5493 Some(NativeCall::Bytecode(code, env)) => {
5494 if code.code.kind.is_generator() {
5495 return self.new_generator(callee, this, args);
5496 }
5497 if code.code.kind.is_async() {
5498 // Same coroutine machinery as a generator; the difference is only in
5499 // what the completion does — see `new_async_function`.
5500 return self.new_async_function(callee, this, args);
5501 }
5502 self.execute(code, env, this, args, callee)
5503 }
5504 None => Err(Signal::Throw(
5505 self.make_error("TypeError", "not a function"),
5506 )),
5507 }
5508 }
5509
5510 /// Give a freshly built function its own `prototype` object.
5511 ///
5512 /// Every function that can be used with `new` carries one, and its
5513 /// `constructor` points back at the function — a reference cycle, which is
5514 /// exactly what the collector's cycle pass exists to reclaim.
5515 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
5516 let prototype = self.new_object(Some(self.realm.object_proto.clone()));
5517 let constructor = Value::Object(function.clone());
5518 prototype.define(
5519 "constructor",
5520 Property::with_attributes(constructor, true, false),
5521 );
5522 let value = Value::Object(prototype);
5523 function.define("prototype", Property::prototype_of(value, true));
5524 }
5525
5526 /// The object `special_object` builds.
5527 ///
5528 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
5529 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
5530 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
5531 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
5532 /// write through `arguments` does not reach the parameter.
5533 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
5534 match magic {
5535 0 | 1 => {
5536 let args = self.frame().passed.clone();
5537 let proto = self.realm.object_proto.clone();
5538 let object = self.new_object(Some(proto));
5539 // The marker `Object.prototype.toString` needs: an arguments object is an
5540 // ordinary object apart from reporting `[object Arguments]`, and that has
5541 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
5542 // show up ahead of them in a key listing anyway — it is non-enumerable.
5543 self.internal_set(&object, "_class", self.string("Arguments"));
5544 // `length` is writable and configurable but neither enumerable nor a
5545 // plain data property: `Object.keys(arguments)` lists the indices only,
5546 // which is how `{...arguments}` copies them without the length.
5547 object.define(
5548 "length",
5549 Property::with_attributes(Value::Int(args.len() as i32), true, false),
5550 );
5551 for (index, value) in args.into_iter().enumerate() {
5552 object.define_data(&index.to_string(), value);
5553 }
5554 // An arguments object is iterable: `[...arguments]` and
5555 // `for (const a of arguments)` both work, through the *array* iterator
5556 // because the object is array-like. Without this the whole spread form
5557 // reported "not iterable".
5558 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
5559 let values = self
5560 .realm
5561 .array_proto
5562 .own_property("values")
5563 .and_then(|property| property.value);
5564 if let Some(values) = values {
5565 object.define_key(
5566 &iterator_key,
5567 Property::with_attributes(values, true, false),
5568 );
5569 }
5570 Ok(Value::Object(object))
5571 }
5572 // `this.active_func`: the constructor `super()` resolves against.
5573 //
5574 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
5575 // own, so it inherits this from the function it was written in along with `this`
5576 // — and that is a lexical relationship, not a stack one: an arrow that escaped
5577 // the constructor and is called back later (`iter.return = () => super()`) has
5578 // the constructor nowhere on the stack. The compiler therefore reads it out of
5579 // a closure variable of the enclosing function, exactly as the reference does
5580 // with its `this_active_func` local.
5581 2 => Ok(self
5582 .current_callee()
5583 .map_or(Value::Undefined, Value::Object)),
5584 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
5585 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
5586 // its own either, so the lookup walks out to the nearest non-arrow frame for
5587 // the same reason as `this.active_func` above — without that, `super()` inside
5588 // an arrow passed `undefined` as the new target and the parent constructor was
5589 // then rejected for being invoked without `new`.
5590 3 => Ok(self
5591 .eval_new_target
5592 .clone()
5593 .unwrap_or_else(|| self.frame().new_target.clone())),
5594 // `[[HomeObject]]` of the function being run: what `super` is relative to.
5595 // An arrow has none of its own, so the lookup walks out to the enclosing
5596 // method — which is why `super` works inside an arrow inside a method.
5597 4 => Ok(self
5598 .frames
5599 .iter()
5600 .rev()
5601 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
5602 .map_or(Value::Undefined, Value::Object)),
5603 // `import.meta`: the innermost module body's meta object. Outside a module
5604 // the compiler never emits this, so an empty fallback is unreachable rather
5605 // than permissive.
5606 6 => {
5607 let name = self.module_stack.last().cloned();
5608 let meta = name
5609 .and_then(|name| self.modules.get(&name).cloned())
5610 .and_then(|module| module.with(|r| r.import_meta.clone()));
5611 Ok(meta.map_or(Value::Undefined, Value::Object))
5612 }
5613 other => Err(Signal::Throw(self.make_error(
5614 "InternalError",
5615 &format!("special_object {other} is not implemented yet"),
5616 ))),
5617 }
5618 }
5619
5620 /// `[[HomeObject]]` of the innermost function that has one, if any.
5621 ///
5622 /// An arrow has none, so the search walks out to the enclosing method — the same
5623 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
5624 /// inside a method.
5625 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
5626 self.frames
5627 .iter()
5628 .rev()
5629 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
5630 }
5631
5632 /// The dispose method a `using` declaration should snapshot, or an error.
5633 ///
5634 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
5635 /// is what makes a resource that only knows the synchronous protocol usable in both
5636 /// forms.
5637 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
5638 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
5639 if value.is_nullish() {
5640 return Ok(Value::Undefined);
5641 }
5642 let Some(object) = value.as_object() else {
5643 return Err(self.type_error("not an object"));
5644 };
5645 let mut method = if await_form {
5646 let found = self.get_property_key(
5647 object,
5648 &self.realm.well_known_key(WellKnown::AsyncDisposable),
5649 )?;
5650 match found {
5651 Some(found) if !found.is_nullish() => Some(found),
5652 _ => self
5653 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
5654 }
5655 } else {
5656 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
5657 };
5658 let Some(found) = method.take() else {
5659 return Err(self.type_error("value is not disposable"));
5660 };
5661 if found.is_nullish() {
5662 return Err(self.type_error("value is not disposable"));
5663 }
5664 let callable = found.as_object().is_some_and(|object| object.is_callable());
5665 if !callable {
5666 return Err(self.type_error("dispose method is not a function"));
5667 }
5668 Ok(found)
5669 }
5670
5671 /// Call one resource's disposer, folding a failure into `error_state`.
5672 ///
5673 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
5674 /// because a captured `using` binding lives in its reference cell and the local slot is
5675 /// stale — a closure over the resource is legal and must not change what is disposed.
5676 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
5677 let value = self.get_loc(slot);
5678 let method = self.get_loc(slot + 1);
5679 // A resource that was never initialised — its declaration threw — or that is
5680 // `null`/`undefined` has nothing to dispose.
5681 if value.is_nullish() || matches!(value, Value::Uninitialized) {
5682 return Ok(error_state);
5683 }
5684 if matches!(method, Value::Undefined | Value::Uninitialized) {
5685 return Ok(error_state);
5686 }
5687 match self.call_value(method, value, Vec::new()) {
5688 Ok(_) => Ok(error_state),
5689 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
5690 Err(other) => Err(other),
5691 }
5692 }
5693
5694 /// Combine a disposal failure with whatever was already going wrong.
5695 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
5696 if matches!(error_state, Value::Uninitialized) {
5697 return new_error;
5698 }
5699 self.new_suppressed_error(new_error, error_state)
5700 }
5701
5702 /// A `SuppressedError` instance built straight from its prototype.
5703 ///
5704 /// Not through the constructor: a script that rewrites
5705 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
5706 /// error wrapping.
5707 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
5708 let proto = self
5709 .realm
5710 .suppressed_error_proto
5711 .clone()
5712 .unwrap_or_else(|| self.realm.error_proto.clone());
5713 let object = self.new_object(Some(proto));
5714 object.define("error", Property::with_attributes(error, true, true));
5715 object.define(
5716 "suppressed",
5717 Property::with_attributes(suppressed, true, true),
5718 );
5719 object.define(
5720 "message",
5721 Property::with_attributes(self.string("SuppressedError"), true, true),
5722 );
5723 self.internal_set(&object, "_class", self.string("Error"));
5724 self.add_stack(&object);
5725 Value::Object(object)
5726 }
5727
5728 /// Call `callee`, or push its frame and let the main loop run it.
5729 ///
5730 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
5731 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
5732 /// continues, so `function f(){ return f() }` costs heap and stops at
5733 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
5734 /// is entered directly, and natives do not re-enter JavaScript in this
5735 /// milestone.
5736 ///
5737 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
5738 /// because the returning frame will.
5739 /// The elements of an array-like value, as a call argument list.
5740 ///
5741 /// `apply` accepts any array-like, not only a real array: the reference reads
5742 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
5743 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
5744 let Some(object) = value.as_object().cloned() else {
5745 if value.is_nullish() {
5746 // `f.apply(this, null)` passes no arguments at all.
5747 return Ok(Vec::new());
5748 }
5749 return Err(self.type_error("createListFromArrayLike called on non-object"));
5750 };
5751 let length = match self.get_property(&object, "length")? {
5752 Some(length) => length.to_number(),
5753 None => 0.0,
5754 };
5755 if !length.is_finite() || length <= 0.0 {
5756 return Ok(Vec::new());
5757 }
5758 let length = (length as usize).min(1_000_000);
5759 let mut args = Vec::with_capacity(length);
5760 for index in 0..length {
5761 let element = self.get_property(&object, &index.to_string())?;
5762 args.push(element.unwrap_or(Value::Undefined));
5763 }
5764 Ok(args)
5765 }
5766
5767 /// Turn a call to a generator function into a generator object.
5768 ///
5769 /// The frame is built exactly as an ordinary call would build it, then detached and
5770 /// stored in the generator before any body instruction runs — which is what makes
5771 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
5772 /// is `initial_yield`, the first instruction of every suspending body.
5773 pub fn new_generator(
5774 &mut self,
5775 function: Value,
5776 this: Value,
5777 args: Vec<Value>,
5778 ) -> JsResult<Value> {
5779 let Some(object) = function.as_object().cloned() else {
5780 return Err(self.type_error("not a generator function"));
5781 };
5782 let Some((code, env)) = bytecode_of(&object) else {
5783 return Err(self.type_error("not a generator function"));
5784 };
5785 let is_async = code.code.kind.is_async();
5786 self.push_frame(code, env, this, args, function)?;
5787 let frame = self.frames.pop().expect("push_frame just pushed it");
5788 // A fresh generator is *suspended at start*: the body has not run, so a
5789 // `return`/`throw` on it finishes without executing anything.
5790 let mut state = GeneratorState {
5791 frame: Some(frame),
5792 phase: GeneratorPhase::SuspendedStart,
5793 parked_on_await: false,
5794 parked_on_yield_star: false,
5795 requests: std::collections::VecDeque::new(),
5796 async_busy: false,
5797 };
5798 // Run to the first suspension. For a generator that is `initial_yield`, so no
5799 // body code runs; for a malformed body it would be the first `yield`.
5800 // An `async function*` answers an async generator: same coroutine, but its
5801 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
5802 let proto = if is_async {
5803 self.realm
5804 .async_generator_proto
5805 .clone()
5806 .unwrap_or_else(|| self.realm.generator_proto.clone())
5807 } else {
5808 self.realm.generator_proto.clone()
5809 };
5810 let generator = self.new_object(Some(proto));
5811 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
5812 Ok(_) => {}
5813 Err(error) => return Err(error),
5814 }
5815 generator.with_mut(|data| {
5816 data.kind = ObjectKind::Generator(Box::new(state));
5817 });
5818 Ok(Value::Object(generator))
5819 }
5820
5821 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
5822 ///
5823 /// Returns the `{value, done}` object itself rather than the pair, because a
5824 /// `yield*` suspension already has one — the inner iterator's own result — and the
5825 /// protocol says to hand that straight through rather than nest it.
5826 /// Advance a generator and report *why* it parked.
5827 ///
5828 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
5829 /// "hand this value to the caller" — but an async generator does: an `await` has to
5830 /// settle before it can answer, while a `yield` is the answer.
5831 fn resume_generator_detailed(
5832 &mut self,
5833 generator: &Gc<JsObject>,
5834 kind: ResumeKind,
5835 value: Value,
5836 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
5837 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
5838 ObjectKind::Generator(state) => Some(std::mem::replace(
5839 state.as_mut(),
5840 GeneratorState {
5841 frame: None,
5842 phase: GeneratorPhase::Executing,
5843 parked_on_await: false,
5844 parked_on_yield_star: false,
5845 requests: std::collections::VecDeque::new(),
5846 async_busy: false,
5847 },
5848 )),
5849 _ => None,
5850 }) else {
5851 return Err(self.type_error("not a generator"));
5852 };
5853 let result = self.step_generator(&mut state, kind, value);
5854 generator.with_mut(|data| {
5855 data.kind = ObjectKind::Generator(Box::new(state));
5856 });
5857 result
5858 }
5859
5860 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
5861 ///
5862 /// Returns the `{value, done}` object itself rather than the pair, because a
5863 /// `yield*` suspension already has one — the inner iterator's own result — and the
5864 /// protocol says to hand that straight through rather than nest it.
5865 pub fn resume_generator(
5866 &mut self,
5867 generator: &Gc<JsObject>,
5868 kind: ResumeKind,
5869 value: Value,
5870 ) -> JsResult<Value> {
5871 let (value, done, ready, _reason) =
5872 self.resume_generator_detailed(generator, kind, value)?;
5873 if ready {
5874 return Ok(value);
5875 }
5876 self.iterator_result(value, done)
5877 }
5878
5879 /// `next`/`return`/`throw` on an async generator, which answer a promise.
5880 ///
5881 /// The body is the same coroutine a sync generator runs; what changes is that an
5882 /// `await` inside it has to settle before the method can answer, so the step is
5883 /// driven off the job queue rather than returning inline.
5884 pub fn resume_async_generator(
5885 &mut self,
5886 generator: &Gc<JsObject>,
5887 kind: ResumeKind,
5888 value: Value,
5889 ) -> JsResult<Value> {
5890 let promise = self.new_promise();
5891 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
5892 // that order, and the second value must reach the *second* `yield`.
5893 let idle = generator.with_mut(|data| match &mut data.kind {
5894 ObjectKind::Generator(state) => {
5895 state.requests.push_back(AsyncRequest {
5896 kind,
5897 value,
5898 promise: promise.clone(),
5899 });
5900 !state.async_busy
5901 }
5902 _ => false,
5903 });
5904 if idle {
5905 self.next_async_request(generator)?;
5906 }
5907 Ok(Value::Object(promise))
5908 }
5909
5910 /// Serve the front queued request, if the generator is free to run one.
5911 ///
5912 /// A finished generator answers from the queue without running anything:
5913 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
5914 /// first, and `throw(e)` rejects.
5915 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
5916 enum Front {
5917 Idle,
5918 Run(ResumeKind, Value, Gc<JsObject>),
5919 Finished(ResumeKind, Value, Gc<JsObject>),
5920 }
5921 let front = generator.with_mut(|data| match &mut data.kind {
5922 ObjectKind::Generator(state) => {
5923 let Some(request) = state.requests.front() else {
5924 return Front::Idle;
5925 };
5926 // Busy means a request is still in flight — awaiting inside the body, not
5927 // finished. Serving another now would interleave two requests.
5928 if state.async_busy && state.phase != GeneratorPhase::Completed {
5929 return Front::Idle;
5930 }
5931 let kind = request.kind;
5932 let value = request.value.clone();
5933 let promise = request.promise.clone();
5934 state.async_busy = true;
5935 if state.phase == GeneratorPhase::Completed {
5936 Front::Finished(kind, value, promise)
5937 } else {
5938 Front::Run(kind, value, promise)
5939 }
5940 }
5941 _ => Front::Idle,
5942 });
5943 match front {
5944 Front::Idle => Ok(()),
5945 Front::Run(kind, value, promise) => {
5946 self.step_async_generator(generator, &promise, kind, value)
5947 }
5948 Front::Finished(kind, value, promise) => match kind {
5949 ResumeKind::Throw => {
5950 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
5951 }
5952 ResumeKind::Next | ResumeKind::Start => {
5953 let result = self.iterator_result(Value::Undefined, true)?;
5954 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
5955 }
5956 ResumeKind::Return => {
5957 // `js_async_generator_completed_return`: the value is awaited before it
5958 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
5959 // finished generator answers `1`, not a promise.
5960 let resolved = match self.promise_resolve_value(value) {
5961 Ok(resolved) => resolved,
5962 Err(Signal::Throw(reason)) => {
5963 return self.settle_async_request(
5964 generator,
5965 &promise,
5966 AsyncOutcome::Error(reason),
5967 );
5968 }
5969 Err(other) => return Err(other),
5970 };
5971 let done = JsObject::function(
5972 self.heap,
5973 Some(self.realm.function_proto.clone()),
5974 Callable::CompletedReturn {
5975 generator: generator.clone(),
5976 promise: promise.clone(),
5977 rejected: false,
5978 },
5979 );
5980 let failed = JsObject::function(
5981 self.heap,
5982 Some(self.realm.function_proto.clone()),
5983 Callable::CompletedReturn {
5984 generator: generator.clone(),
5985 promise: promise.clone(),
5986 rejected: true,
5987 },
5988 );
5989 let Value::Object(resolved) = resolved else {
5990 return self.settle_async_request(
5991 generator,
5992 &promise,
5993 AsyncOutcome::Error(Value::Undefined),
5994 );
5995 };
5996 self.perform_then(
5997 &resolved,
5998 Some(Value::Object(done)),
5999 Some(Value::Object(failed)),
6000 )?;
6001 Ok(())
6002 }
6003 },
6004 }
6005 }
6006
6007 /// Settle the front request and start the next one.
6008 ///
6009 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
6010 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
6011 /// generator would strand every later request.
6012 fn settle_async_request(
6013 &mut self,
6014 generator: &Gc<JsObject>,
6015 promise: &Gc<JsObject>,
6016 outcome: AsyncOutcome,
6017 ) -> JsResult<()> {
6018 let settled = generator.with_mut(|data| match &mut data.kind {
6019 ObjectKind::Generator(state) => {
6020 let front = state.requests.front();
6021 debug_assert!(
6022 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
6023 "a request settled outside its turn"
6024 );
6025 state.requests.pop_front();
6026 state.async_busy = false;
6027 true
6028 }
6029 _ => false,
6030 });
6031 if settled {
6032 match outcome {
6033 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
6034 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
6035 }
6036 }
6037 self.next_async_request(generator)
6038 }
6039
6040 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
6041 ///
6042 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
6043 /// disposer runs **synchronously** — the reference starts it before returning, which
6044 /// a test can observe by logging after the call — and the rest follow once their
6045 /// predecessor settles.
6046 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
6047 let promise = self.new_promise();
6048 let mut pairs = Vec::with_capacity(resources.len());
6049 for (value, method) in resources {
6050 let pair = self.new_array(vec![value, method]);
6051 pairs.push(Value::Object(pair));
6052 }
6053 let remaining = self.new_array(pairs);
6054 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
6055 Ok(Value::Object(promise))
6056 }
6057
6058 /// One link of the `disposeAsync` chain.
6059 ///
6060 /// Loops while the disposers finish synchronously, and parks on the first thenable it
6061 /// meets — pushing itself back in as the continuation, with the accumulated error
6062 /// carried along so a later failure can still be folded into the `SuppressedError`.
6063 fn dispose_step(
6064 &mut self,
6065 remaining: &Gc<JsObject>,
6066 promise: &Gc<JsObject>,
6067 mut error: Value,
6068 ) -> JsResult<()> {
6069 loop {
6070 let length = remaining.array_length().unwrap_or(0);
6071 if length == 0 {
6072 if matches!(error, Value::Uninitialized) {
6073 self.fulfill_promise(promise, Value::Undefined);
6074 } else {
6075 self.reject_promise(promise, error);
6076 }
6077 return Ok(());
6078 }
6079 let Some(Value::Object(pair)) = remaining
6080 .array_get(length - 1)
6081 .filter(|v| !matches!(v, Value::Hole))
6082 else {
6083 remaining.array_truncate(self.heap, length - 1);
6084 continue;
6085 };
6086 remaining.array_truncate(self.heap, length - 1);
6087 let value = pair.array_get(0).unwrap_or(Value::Undefined);
6088 let Some(Value::Object(method)) = pair.array_get(1) else {
6089 continue;
6090 };
6091 if !method.is_callable() {
6092 continue;
6093 }
6094 match self.call_value(Value::Object(method), value, Vec::new()) {
6095 Ok(result) => {
6096 if !self.is_thenable(&result)? {
6097 // Finished synchronously; the next disposer is the next iteration.
6098 continue;
6099 }
6100 let awaited = match self.promise_resolve_value(result) {
6101 Ok(awaited) => awaited,
6102 Err(Signal::Throw(reason)) => {
6103 self.reject_promise(promise, reason);
6104 return Ok(());
6105 }
6106 Err(other) => return Err(other),
6107 };
6108 let Value::Object(awaited) = awaited else {
6109 continue;
6110 };
6111 let ok = JsObject::function(
6112 self.heap,
6113 Some(self.realm.function_proto.clone()),
6114 Callable::DisposeStep {
6115 remaining: remaining.clone(),
6116 promise: promise.clone(),
6117 error: error.clone(),
6118 rejected: false,
6119 },
6120 );
6121 let failed = JsObject::function(
6122 self.heap,
6123 Some(self.realm.function_proto.clone()),
6124 Callable::DisposeStep {
6125 remaining: remaining.clone(),
6126 promise: promise.clone(),
6127 error,
6128 rejected: true,
6129 },
6130 );
6131 self.perform_then(
6132 &awaited,
6133 Some(Value::Object(ok)),
6134 Some(Value::Object(failed)),
6135 )?;
6136 return Ok(());
6137 }
6138 Err(Signal::Throw(thrown)) => {
6139 error = self.merge_dispose_error(thrown, error);
6140 }
6141 Err(other) => return Err(other),
6142 }
6143 }
6144 }
6145
6146 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
6147 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
6148 let Value::Object(object) = value else {
6149 return Ok(false);
6150 };
6151 Ok(matches!(
6152 self.get_property(object, "then")?,
6153 Some(Value::Object(then)) if then.is_callable()
6154 ))
6155 }
6156
6157 /// One step of an async generator, settling `promise` with an `{value, done}` result.
6158 fn step_async_generator(
6159 &mut self,
6160 generator: &Gc<JsObject>,
6161 promise: &Gc<JsObject>,
6162 kind: ResumeKind,
6163 value: Value,
6164 ) -> JsResult<()> {
6165 let stepped = self.resume_generator_detailed(generator, kind, value);
6166 let (value, done, ready, reason) = match stepped {
6167 Ok(stepped) => stepped,
6168 Err(Signal::Throw(reason)) => {
6169 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
6170 }
6171 Err(other) => return Err(other),
6172 };
6173 // Only an `await` has to wait before the method can answer.
6174 if !done && reason == Some(SuspendKind::Await) {
6175 let awaited = match self.promise_resolve_value(value) {
6176 Ok(awaited) => awaited,
6177 Err(Signal::Throw(reason)) => {
6178 return self.settle_async_request(
6179 generator,
6180 promise,
6181 AsyncOutcome::Error(reason),
6182 );
6183 }
6184 Err(other) => return Err(other),
6185 };
6186 let Value::Object(awaited) = awaited else {
6187 return Ok(());
6188 };
6189 let resumed = JsObject::function(
6190 self.heap,
6191 Some(self.realm.function_proto.clone()),
6192 Callable::GeneratorResume {
6193 generator: generator.clone(),
6194 promise: promise.clone(),
6195 kind: ResumeKind::Next,
6196 },
6197 );
6198 let raised = JsObject::function(
6199 self.heap,
6200 Some(self.realm.function_proto.clone()),
6201 Callable::GeneratorResume {
6202 generator: generator.clone(),
6203 promise: promise.clone(),
6204 kind: ResumeKind::Throw,
6205 },
6206 );
6207 self.perform_then(
6208 &awaited,
6209 Some(Value::Object(resumed)),
6210 Some(Value::Object(raised)),
6211 )?;
6212 return Ok(());
6213 }
6214 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
6215 // completes it — both arrive as the settled value rather than as the promise
6216 // object. A plain value skips the round trip, which is also what keeps `yield 1`
6217 // from costing an extra tick.
6218 let awaits_value = self.is_thenable(&value)?;
6219 if awaits_value {
6220 let awaited = match self.promise_resolve_value(value) {
6221 Ok(awaited) => awaited,
6222 Err(Signal::Throw(reason)) => {
6223 return self.settle_async_request(
6224 generator,
6225 promise,
6226 AsyncOutcome::Error(reason),
6227 );
6228 }
6229 Err(other) => return Err(other),
6230 };
6231 let Value::Object(awaited) = awaited else {
6232 return Ok(());
6233 };
6234 // A rejected yield throws *at the yield* inside the body, so the rejection
6235 // resumes the generator rather than the method's promise.
6236 let answer = JsObject::function(
6237 self.heap,
6238 Some(self.realm.function_proto.clone()),
6239 Callable::YieldResult {
6240 generator: generator.clone(),
6241 promise: promise.clone(),
6242 done,
6243 },
6244 );
6245 let raise = JsObject::function(
6246 self.heap,
6247 Some(self.realm.function_proto.clone()),
6248 Callable::GeneratorResume {
6249 generator: generator.clone(),
6250 promise: promise.clone(),
6251 kind: ResumeKind::Throw,
6252 },
6253 );
6254 self.perform_then(
6255 &awaited,
6256 Some(Value::Object(answer)),
6257 Some(Value::Object(raise)),
6258 )?;
6259 return Ok(());
6260 }
6261 let result = if ready {
6262 // `yield*` handed back the inner iterator's own result object.
6263 value
6264 } else {
6265 self.iterator_result(value, done)?
6266 };
6267 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
6268 }
6269
6270 /// The `{value, done}` object an iterator method answers with.
6271 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
6272 let result = self.new_object(Some(self.realm.object_proto.clone()));
6273 result.define_data("value", value);
6274 result.define_data("done", Value::Bool(done));
6275 Ok(Value::Object(result))
6276 }
6277
6278 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
6279 fn step_generator(
6280 &mut self,
6281 state: &mut GeneratorState,
6282 kind: ResumeKind,
6283 value: Value,
6284 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
6285 match state.phase {
6286 GeneratorPhase::Executing => {
6287 return Err(self.type_error("cannot invoke a running generator"));
6288 }
6289 GeneratorPhase::Completed => {
6290 // A finished generator answers every resumption without running.
6291 return Ok(match kind {
6292 ResumeKind::Throw => return Err(Signal::Throw(value)),
6293 ResumeKind::Return => (value, true, false, None),
6294 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
6295 });
6296 }
6297 GeneratorPhase::SuspendedStart => {
6298 if kind != ResumeKind::Next && kind != ResumeKind::Start {
6299 // The body never started, so there is nothing to unwind or return
6300 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
6301 state.frame = None;
6302 state.phase = GeneratorPhase::Completed;
6303 return Ok(match kind {
6304 ResumeKind::Throw => return Err(Signal::Throw(value)),
6305 _ => (value, true, false, None),
6306 });
6307 }
6308 }
6309 GeneratorPhase::SuspendedYield => {}
6310 }
6311
6312 let Some(mut frame) = state.frame.take() else {
6313 return Ok((Value::Undefined, true, false, None));
6314 };
6315 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
6316 // number that says which method resumed it; the emitted `if_false` branches on
6317 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
6318 let mut raised = None;
6319 match kind {
6320 ResumeKind::Next | ResumeKind::Start => {
6321 if state.phase == GeneratorPhase::SuspendedYield {
6322 frame.stack.push(value);
6323 // An `await` resumes with its value alone; only a `yield` gets the
6324 // magic number that says which of `next`/`return` resumed it.
6325 if !state.parked_on_await {
6326 frame.stack.push(Value::Int(RESUME_NEXT));
6327 }
6328 }
6329 }
6330 ResumeKind::Return => {
6331 // A `return` on a not-yet-started generator is handled above, so this is
6332 // always a real resumption.
6333 frame.stack.push(value);
6334 frame.stack.push(Value::Int(RESUME_RETURN));
6335 }
6336 ResumeKind::Throw => {
6337 // At a `yield*` the exception is *data* for the delegation: the compiled
6338 // code resumes with the value and magic `2` and calls the inner iterator's
6339 // `throw`. Everywhere else it is raised at the suspension point, so the
6340 // body's own handler sees it.
6341 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
6342 frame.stack.push(value);
6343 frame.stack.push(Value::Int(RESUME_THROW));
6344 } else {
6345 raised = Some(value);
6346 }
6347 }
6348 }
6349 state.phase = GeneratorPhase::Executing;
6350
6351 let depth = self.frames.len();
6352 self.frames.push(frame);
6353 // A `throw` unwinds from where the frame parked, exactly as if the exception had
6354 // happened at the `yield`.
6355 if let Some(exception) = raised {
6356 if self.catch_here(exception.clone()).is_none() {
6357 self.frames.pop();
6358 state.phase = GeneratorPhase::Completed;
6359 return Err(Signal::Throw(exception));
6360 }
6361 }
6362
6363 // Only the generator's *own* frame ends the generator. The body may call ordinary
6364 // functions, and those push frames of their own: a `Step::Return` from one of them
6365 // is a nested call finishing, not the generator completing. Miscounting that is
6366 // silent — the generator reports the callee's value as its own result and marks
6367 // itself done — so the depth comparison is load-bearing, not defensive.
6368 let own_frame = depth + 1;
6369 loop {
6370 match self.step() {
6371 Ok(Step::Continue) => {}
6372 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
6373 let mut frame = self.frames.pop().expect("a frame is live");
6374 // `yield` left the value on the stack; `initial_yield` left nothing.
6375 let yielded = if reason == SuspendKind::Initial {
6376 Value::Undefined
6377 } else {
6378 frame.stack.pop().unwrap_or(Value::Undefined)
6379 };
6380 state.frame = Some(frame);
6381 state.parked_on_await = reason == SuspendKind::Await;
6382 state.parked_on_yield_star =
6383 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
6384 state.phase = if reason == SuspendKind::Initial {
6385 GeneratorPhase::SuspendedStart
6386 } else {
6387 GeneratorPhase::SuspendedYield
6388 };
6389 // `yield*` hands the inner iterator's own result object straight
6390 // back, so the caller sees one `{value, done}` rather than a nested
6391 // one — which is why the third field says "already a result".
6392 return Ok((
6393 yielded,
6394 false,
6395 reason == SuspendKind::YieldStar,
6396 Some(reason),
6397 ));
6398 }
6399 Ok(Step::Suspend(_)) => {
6400 // A `yield` in a frame other than the generator's would mean a
6401 // generator body entered as an ordinary call, which
6402 // `call_or_push` prevents.
6403 self.unwind_to(depth);
6404 state.phase = GeneratorPhase::Completed;
6405 return Err(Signal::Throw(self.make_error(
6406 "InternalError",
6407 "a generator body ran as an ordinary call",
6408 )));
6409 }
6410 Ok(Step::Return(value)) => {
6411 self.frames.pop();
6412 if self.frames.len() > depth {
6413 // A nested call finished: hand the value back to its caller and
6414 // keep running the generator body.
6415 self.frames
6416 .last_mut()
6417 .expect("a caller is live")
6418 .stack
6419 .push(value);
6420 continue;
6421 }
6422 state.phase = GeneratorPhase::Completed;
6423 // The reference closes the generator's closure variables here; ours
6424 // live in cells the frame owned, which the drop below releases.
6425 return Ok((value, true, false, None));
6426 }
6427 Err(Signal::Throw(exception)) => {
6428 // The frame that threw gets the first chance to catch, exactly as in
6429 // the ordinary call loop; a frame above the generator's is popped and
6430 // the exception carries on down.
6431 let exception = exception;
6432 loop {
6433 if self.frames.len() <= depth {
6434 // The generator's own frame is gone, so nothing here caught it.
6435 state.phase = GeneratorPhase::Completed;
6436 return Err(Signal::Throw(exception));
6437 }
6438 if self.catch_here(exception.clone()).is_some() {
6439 break;
6440 }
6441 self.frames.pop();
6442 }
6443 }
6444 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
6445 }
6446 }
6447 }
6448
6449 /// Pop frames until `depth` are left.
6450 fn unwind_to(&mut self, depth: usize) {
6451 self.frames.truncate(depth);
6452 }
6453 fn call_or_push(
6454 &mut self,
6455 callee: Value,
6456 this: Value,
6457 args: Vec<Value>,
6458 ) -> JsResult<Option<Value>> {
6459 if let Value::Object(function) = &callee
6460 && let Some((code, env)) = bytecode_of(function)
6461 {
6462 // Calling a generator function does not run anything: it captures the
6463 // arguments in a frame and hands back the generator object.
6464 if code.code.kind.is_generator() {
6465 return self.new_generator(callee, this, args).map(Some);
6466 }
6467 // An async function answers a promise and runs its body as a coroutine, so it
6468 // takes the same path as a plain call into it.
6469 if code.code.kind.is_async() {
6470 return self.new_async_function(callee, this, args).map(Some);
6471 }
6472 self.push_frame(code, env, this, args, callee)?;
6473 return Ok(None);
6474 }
6475 self.call_value(callee, this, args).map(Some)
6476 }
6477
6478 /// `new callee(args)`.
6479 ///
6480 /// A constructor differs from a plain call in three ways: it gets a fresh object
6481 /// as `this` whose prototype is the constructor's `prototype` property, its
6482 /// return value is *replaced* by that object unless it returns an object itself,
6483 /// and a native constructor is expected to initialise the object it is given
6484 /// rather than build one.
6485 pub fn construct(
6486 &mut self,
6487 callee: Value,
6488 new_target: Value,
6489 args: Vec<Value>,
6490 ) -> JsResult<Value> {
6491 // `new` on a bound function constructs its *target*, prepending the arguments
6492 // the bind fixed and ignoring the bound `this` — a bound function is a
6493 // constructor only when its target is one, and `new` always makes a fresh
6494 // object of the target's prototype rather than reusing the bound receiver.
6495 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
6496 // ran the body with `this === null` and threw on `this.x = a`.
6497 let mut callee = callee;
6498 let mut new_target = new_target;
6499 let mut args = args;
6500 loop {
6501 let Some(object) = callee.as_object().cloned() else {
6502 return Err(Signal::Throw(
6503 self.make_error("TypeError", "not a constructor"),
6504 ));
6505 };
6506 // A proxy of a function constructs through its `construct` trap, and the
6507 // trap's answer is the result directly — no fresh object is made here.
6508 if object.proxy_state().is_some() {
6509 return match self.proxy_construct(&object, args, &new_target)? {
6510 Some(result) => Ok(result),
6511 None => Err(Signal::Throw(
6512 self.make_error("TypeError", "proxy target is not a constructor"),
6513 )),
6514 };
6515 }
6516 // A generator function has no `[[Construct]]`, and the reference names it in
6517 // the message: `new (function* G(){})()` reports "G is not a constructor".
6518 if object.with(|data| match &data.kind {
6519 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
6520 code.code.kind.is_generator()
6521 }
6522 _ => false,
6523 }) {
6524 let name = object
6525 .own_property("name")
6526 .and_then(|property| property.value)
6527 .map(|value| value.to_js_string())
6528 .unwrap_or_default();
6529 return Err(Signal::Throw(
6530 self.make_error("TypeError", &format!("{name} is not a constructor")),
6531 ));
6532 }
6533 let bound = object.with(|data| match &data.kind {
6534 ObjectKind::Function(Callable::Bound {
6535 target,
6536 args: leading,
6537 ..
6538 }) => Some((target.clone(), leading.clone())),
6539 _ => None,
6540 });
6541 let Some((target, leading)) = bound else {
6542 // Not a bound function, so this object is the callee. §7.2.4
6543 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
6544 // refusals above cover only the built-ins the reference also refuses by
6545 // name. Everything else — a method, an arrow, an async function — has no
6546 // `[[Construct]]` either, and answering "yes" here made
6547 // `new (Array.prototype.map)` build an object instead of throwing.
6548 if !object.is_constructor() {
6549 let name = object
6550 .own_property("name")
6551 .and_then(|property| property.value)
6552 .map(|value| value.to_js_string())
6553 .unwrap_or_default();
6554 return Err(Signal::Throw(
6555 self.make_error("TypeError", &format!("{name} is not a constructor")),
6556 ));
6557 }
6558 break;
6559 };
6560 let mut all = leading;
6561 all.extend(args);
6562 args = all;
6563 // A bound function that is its own `new.target` stands in for its target:
6564 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
6565 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
6566 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
6567 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
6568 _ => false,
6569 };
6570 if same_wrapper {
6571 new_target = target.clone();
6572 }
6573 callee = target;
6574 }
6575 let Value::Object(function) = &callee else {
6576 unreachable!("the loop above only breaks on an object");
6577 };
6578 // The fresh object's prototype comes from `new.target`, not from the callee: a
6579 // derived constructor reaches here through `super()`, and the instance must be a
6580 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
6581 // an object inheriting `D.prototype` rather than `C.prototype`.
6582 let prototype_source = match new_target.as_object() {
6583 Some(target) => target.clone(),
6584 None => function.clone(),
6585 };
6586 // A native constructor builds its own instance, through `new_ctor_instance`, once it
6587 // has validated its arguments. Pre-building one here would read
6588 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
6589 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
6590 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
6591 let is_native = function.native_creates_own_instance();
6592 let this = if is_native {
6593 Value::Undefined
6594 } else {
6595 let prototype = self.get_property(&prototype_source, "prototype")?;
6596 let prototype = match prototype {
6597 Some(Value::Object(proto)) => Some(proto),
6598 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
6599 // object, the answer is the realm's *intrinsic* prototype for this
6600 // constructor, not `%Object.prototype%`.
6601 _ => {
6602 let fallback = self.get_property(function, "prototype")?;
6603 match fallback {
6604 Some(Value::Object(proto)) => Some(proto),
6605 _ => Some(self.realm.object_proto.clone()),
6606 }
6607 }
6608 };
6609 Value::Object(self.new_object(prototype))
6610 };
6611 // `new.target` inside the body is the constructor that was written, so a bound
6612 // function's target sees itself rather than the bound wrapper.
6613 //
6614 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
6615 // `?`, so assigning `None` after the call would be skipped and the failed
6616 // `new.target` would stay visible to every later native call. The symptom was a
6617 // native constructor refusing a plain call — `var s = Symbol(); new
6618 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
6619 // "FinalizationRegistry is not a constructor".
6620 let outer_new_target = self.pending_new_target.replace(new_target);
6621 let result = self.call_value(callee, this.clone(), args);
6622 self.pending_new_target = outer_new_target;
6623 let result = result?;
6624 // A constructor that returns an object overrides `this`; any other return
6625 // value (including `undefined`) is ignored.
6626 Ok(match result {
6627 Value::Object(_) => result,
6628 _ => this,
6629 })
6630 }
6631
6632 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
6633 ///
6634 /// The error classes themselves arrive with the builtins milestone; what
6635 /// matters here is that the thrown value stringifies the way a script printing
6636 /// the caught value expects.
6637 pub fn make_error(&self, name: &str, message: &str) -> Value {
6638 let proto = self
6639 .realm
6640 .errors
6641 .get(name)
6642 .map(|constructor| self.prototype_of(constructor))
6643 .unwrap_or_else(|| self.realm.error_proto.clone());
6644 let error = self.new_object(Some(proto));
6645 // `name` and `message` are own properties of the instance, which is what
6646 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
6647 // `Error`.
6648 error.define(
6649 "name",
6650 Property::with_attributes(self.string(name), true, false),
6651 );
6652 error.define(
6653 "message",
6654 Property::with_attributes(self.string(message), true, false),
6655 );
6656 // The internal class, which is what tells a printer this is an error rather than a
6657 // plain object with `name` and `message` properties. The constructor path sets it
6658 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
6659 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
6660 // literally `"Error"` in both places — the *name* is read from `name`, which is why
6661 // a `RangeError` still prints as `RangeError`.
6662 self.internal_set(&error, "_class", self.string("Error"));
6663 // The trace is captured where the error is *made*, which is where the reference
6664 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
6665 // way out, so a caught engine error already has its stack even if the handler
6666 // never rethrows it.
6667 self.add_stack(&error);
6668 Value::Object(error)
6669 }
6670
6671 /// Give an error object its `stack` property, from the current frame stack.
6672 ///
6673 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
6674 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
6675 /// `stack` a script set, is not rewritten.
6676 pub fn add_stack(&self, object: &Gc<JsObject>) {
6677 self.add_stack_skipping(object, 0);
6678 }
6679
6680 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
6681 ///
6682 /// An `Error` constructor passes 1: the reference builds those traces with
6683 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
6684 /// constructor itself, while a `RangeError` raised inside `toISOString` does
6685 /// report `at toISOString (native)`.
6686 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
6687 if object.has_own("stack") {
6688 return;
6689 }
6690 let trace = self.stack_trace_skipping(skip);
6691 let text = self.string(trace);
6692 object.define("stack", Property::with_attributes(text, true, true));
6693 }
6694
6695 /// The function object currently being called, if any.
6696 ///
6697 /// A native function is a bare `fn` pointer, so it cannot capture which class
6698 /// it belongs to; it reads that from the callee instead. This is also what a
6699 /// stack trace would use.
6700 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
6701 match &self.frames.last()?.callee {
6702 Value::Object(object) => Some(object.clone()),
6703 _ => None,
6704 }
6705 }
6706
6707 /// The `prototype` property of a constructor, falling back to
6708 /// `Object.prototype` for anything that is not shaped like one.
6709 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
6710 constructor
6711 .own_property("prototype")
6712 .and_then(|property| property.value)
6713 .and_then(|value| value.as_object().cloned())
6714 .unwrap_or_else(|| self.realm.object_proto.clone())
6715 }
6716
6717 /// Throw a `TypeError` carrying `message`.
6718 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
6719 Signal::Throw(self.make_error("TypeError", message.as_ref()))
6720 }
6721
6722 /// Throw a `RangeError` carrying `message`.
6723 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
6724 Signal::Throw(self.make_error("RangeError", message.as_ref()))
6725 }
6726
6727 /// The `ReferenceError` a read of an uninitialised binding raises.
6728 /// The name of the binding `slot` refers to, for an error message.
6729 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
6730 match kind {
6731 VarSlot::Loc => self
6732 .frame()
6733 .code
6734 .code
6735 .vars
6736 .get(slot)
6737 .map(|v| v.name.clone()),
6738 VarSlot::Closure => self
6739 .frame()
6740 .code
6741 .code
6742 .closure_vars
6743 .get(slot)
6744 .map(|c| c.name.clone()),
6745 }
6746 .unwrap_or_default()
6747 }
6748
6749 /// Whether `slot` names a `const` binding, which rejects every store after its
6750 /// initialiser.
6751 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
6752 match kind {
6753 VarSlot::Loc => self
6754 .frame()
6755 .code
6756 .code
6757 .vars
6758 .get(slot)
6759 .is_some_and(|v| v.is_const),
6760 VarSlot::Closure => self
6761 .frame()
6762 .code
6763 .code
6764 .closure_vars
6765 .get(slot)
6766 .is_some_and(|c| c.is_const),
6767 }
6768 }
6769
6770 /// The `TypeError` a store to a `const` binding raises.
6771 ///
6772 /// `const` is enforced here rather than at compile time because the binding can be
6773 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
6774 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
6775 /// both halves of what "checked store" means: the dead zone is over, and the
6776 /// binding is writable.
6777 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
6778 let name = self.binding_name(slot, kind);
6779 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6780 }
6781
6782 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
6783 let name = match kind {
6784 VarSlot::Loc => self
6785 .frame()
6786 .code
6787 .code
6788 .vars
6789 .get(slot)
6790 .map(|v| v.name.clone()),
6791 VarSlot::Closure => self
6792 .frame()
6793 .code
6794 .code
6795 .closure_vars
6796 .get(slot)
6797 .map(|c| c.name.clone()),
6798 }
6799 .unwrap_or_default();
6800 Signal::Throw(self.make_error(
6801 "ReferenceError",
6802 &format!("cannot access '{name}' before initialization"),
6803 ))
6804 }
6805
6806 fn throw_reference(&self, name: &str) -> Signal {
6807 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
6808 }
6809
6810 // -- the instruction loop -----------------------------------------------
6811
6812 fn step(&mut self) -> JsResult<Step> {
6813 // Decode inside a scope that borrows the frame, and keep only the `Copy` fields.
6814 // The obvious version cloned the `Gc<CompiledCode>` first — a reference-count
6815 // increment and decrement on *every instruction* — which showed up as
6816 // `dispatch:empty-loop` running 25× slower than the reference.
6817 let (pc, decoded) = {
6818 let frame = self
6819 .frames
6820 .last()
6821 .expect("step() is only called with a live frame");
6822 let bytes = &frame.code.code.code;
6823 let pc = frame.pc;
6824 if pc >= bytes.len() {
6825 return Ok(Step::Return(Value::Undefined));
6826 }
6827 (pc, decode(bytes, pc))
6828 };
6829 let Some((op, a, b, next)) = decoded else {
6830 return Err(Signal::Throw(
6831 self.make_error("InternalError", "undecodable bytecode"),
6832 ));
6833 };
6834 {
6835 // One borrow for both writes: `at` is where a stack trace points and `pc` is
6836 // where execution resumes, and they are always set together.
6837 let frame = self
6838 .frames
6839 .last_mut()
6840 .expect("the frame was live a moment ago");
6841 frame.at = pc;
6842 frame.pc = next;
6843 }
6844 self.check_memory()?;
6845 self.execute_instruction(op, a, b, next)
6846 }
6847
6848 fn push(&mut self, value: Value) {
6849 self.frame_mut().stack.push(value);
6850 }
6851
6852 fn pop(&mut self) -> Value {
6853 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
6854 }
6855
6856 fn pop_n(&mut self, count: usize) -> Vec<Value> {
6857 let frame = self.frame_mut();
6858 let start = frame.stack.len().saturating_sub(count);
6859 frame.stack.split_off(start)
6860 }
6861
6862 fn peek(&self, back: usize) -> Value {
6863 let frame = self.frame();
6864 frame
6865 .stack
6866 .get(frame.stack.len().wrapping_sub(1 + back))
6867 .cloned()
6868 .unwrap_or(Value::Undefined)
6869 }
6870
6871 #[allow(clippy::too_many_lines)]
6872 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
6873 use Opcode::*;
6874 match op {
6875 // -- constants and stack shuffling -----------------------------
6876 Nop => {}
6877 PushMinus1 => self.push(Value::Int(-1)),
6878 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
6879 let value = match op {
6880 Push0 => 0,
6881 Push1 => 1,
6882 Push2 => 2,
6883 Push3 => 3,
6884 Push4 => 4,
6885 Push5 => 5,
6886 Push6 => 6,
6887 _ => 7,
6888 };
6889 self.push(Value::Int(value));
6890 }
6891 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
6892 PushBigintI32 => {
6893 // The immediate form of a `BigInt` literal; the reference has the same
6894 // split between this and a constant-pool entry.
6895 let value = crate::bigint::BigInt::from_i64(a as i64);
6896 self.push(self.bigint(value));
6897 }
6898 PushTrue => self.push(Value::Bool(true)),
6899 PushFalse => self.push(Value::Bool(false)),
6900 PushEmptyString => self.push(self.string("")),
6901 Undefined => self.push(Value::Undefined),
6902 Null => self.push(Value::Null),
6903 Object => {
6904 let proto = self.realm.object_proto.clone();
6905 self.push(Value::Object(self.new_object(Some(proto))));
6906 }
6907 PushThis => {
6908 let this = self.frame().this.clone();
6909 self.push(this);
6910 }
6911 PushConst | PushConst8 => {
6912 let value = self.constant(a as usize)?;
6913 self.push(value);
6914 }
6915 PushAtomValue => {
6916 let text = self.atom_text(a as usize);
6917 self.push(self.string(text));
6918 }
6919 Dup => {
6920 let value = self.peek(0);
6921 self.push(value);
6922 }
6923 Dup2 => {
6924 // `a b -> a b a b`
6925 let b = self.peek(0);
6926 let a = self.peek(1);
6927 self.push(a);
6928 self.push(b);
6929 }
6930 Dup3 => {
6931 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
6932 // prototype and key while reading the current value through them.
6933 let c = self.peek(0);
6934 let b = self.peek(1);
6935 let a = self.peek(2);
6936 self.push(a);
6937 self.push(b);
6938 self.push(c);
6939 }
6940 Swap => {
6941 // `a b -> b a`
6942 let bottom = self.pop();
6943 let top = self.pop();
6944 self.push(bottom);
6945 self.push(top);
6946 }
6947 Perm3 => {
6948 // `a b c -> b a c`, the reference's reordering for a spread method
6949 // call: `obj func array` becomes the `func this array` that `apply`
6950 // takes.
6951 let c = self.pop();
6952 let b = self.pop();
6953 let a = self.pop();
6954 self.push(b);
6955 self.push(a);
6956 self.push(c);
6957 }
6958 Dup1 => {
6959 let value = self.peek(1);
6960 self.push(value);
6961 }
6962 Drop => {
6963 self.pop();
6964 }
6965 Nip => {
6966 // `a b -> b`
6967 let top = self.pop();
6968 self.pop();
6969 self.push(top);
6970 }
6971 Perm4 => {
6972 // `obj prop a b -> a obj prop b`, the reference's reordering for a
6973 // postfix update of a computed element: it puts the *old* value
6974 // underneath the receiver and key so `put_array_el` can consume them
6975 // and leave the old value as the expression's result.
6976 let d = self.pop();
6977 let c = self.pop();
6978 let b = self.pop();
6979 let a = self.pop();
6980 self.push(c);
6981 self.push(a);
6982 self.push(b);
6983 self.push(d);
6984 }
6985 Insert2 => {
6986 // `obj a -> a obj a`
6987 let value = self.pop();
6988 let object = self.pop();
6989 self.push(value.clone());
6990 self.push(object);
6991 self.push(value);
6992 }
6993 Insert3 => {
6994 // `obj prop a -> a obj prop a`
6995 let value = self.pop();
6996 let key = self.pop();
6997 let object = self.pop();
6998 self.push(value.clone());
6999 self.push(object);
7000 self.push(key);
7001 self.push(value);
7002 }
7003 Insert4 => {
7004 // `this obj prop a -> a this obj prop a`
7005 //
7006 // `put_super_value` consumes all four and yields nothing, so the copy
7007 // underneath is what leaves the assignment an expression value.
7008 let value = self.pop();
7009 let key = self.pop();
7010 let object = self.pop();
7011 let receiver = self.pop();
7012 self.push(value.clone());
7013 self.push(receiver);
7014 self.push(object);
7015 self.push(key);
7016 self.push(value);
7017 }
7018 Swap2 => {
7019 // `a b c d -> c d a b`
7020 let d = self.pop();
7021 let c = self.pop();
7022 let b = self.pop();
7023 let a = self.pop();
7024 self.push(c);
7025 self.push(d);
7026 self.push(a);
7027 self.push(b);
7028 }
7029 Rot3l => {
7030 // `x a b -> a b x`
7031 let b = self.pop();
7032 let a = self.pop();
7033 let x = self.pop();
7034 self.push(a);
7035 self.push(b);
7036 self.push(x);
7037 }
7038 Rot3r => {
7039 // `a b c -> c a b`
7040 let c = self.pop();
7041 let b = self.pop();
7042 let a_value = self.pop();
7043 self.push(c);
7044 self.push(a_value);
7045 self.push(b);
7046 }
7047
7048 Rest => {
7049 // `...rest` in a parameter list: the arguments from index `a` on, as a
7050 // real array. It takes nothing off the stack — the arguments are in the
7051 // frame, not on it.
7052 let frame = self.frame();
7053 let from = a as usize;
7054 let collected: Vec<Value> = frame.passed.iter().skip(from).cloned().collect();
7055 let array = self.new_array(collected);
7056 self.push(Value::Object(array));
7057 }
7058
7059 // -- slots ------------------------------------------------------
7060 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
7061 let slot = self.slot_operand(op, a);
7062 let value = self.get_loc(slot);
7063 self.push(value);
7064 }
7065 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
7066 let slot = self.slot_operand(op, a);
7067 let value = self.pop();
7068 self.put_loc(slot, value);
7069 }
7070 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
7071 let slot = self.slot_operand(op, a);
7072 let value = self.pop();
7073 self.put_loc(slot, value.clone());
7074 self.push(value);
7075 }
7076 // The `_check` forms are the temporal dead zone: they throw when the
7077 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
7078 // *reads*, so only the two writes may pop — mishandling that quietly
7079 // consumes the value the caller pushed just before.
7080 GetLocCheck => {
7081 let slot = self.slot_operand(op, a);
7082 let value = self.get_loc(slot);
7083 if matches!(value, Value::Uninitialized) {
7084 return Err(self.dead_zone(slot, VarSlot::Loc));
7085 }
7086 self.push(value);
7087 }
7088 PutLocCheck | SetLocCheck => {
7089 let slot = self.slot_operand(op, a);
7090 let value = self.pop();
7091 if matches!(value, Value::Uninitialized) {
7092 return Err(self.dead_zone(slot, VarSlot::Loc));
7093 }
7094 // The initialiser goes through `put_loc`, not this, so any store that
7095 // reaches here is a later assignment — which a `const` refuses.
7096 if self.is_read_only(slot, VarSlot::Loc) {
7097 return Err(self.read_only(slot, VarSlot::Loc));
7098 }
7099 if op == SetLocCheck {
7100 self.put_loc(slot, value.clone());
7101 self.push(value);
7102 } else {
7103 self.put_loc(slot, value);
7104 }
7105 }
7106 PutLocCheckInit => {
7107 // The one store that *initialises* a lexical slot: `this` in a derived
7108 // constructor, which only exists after `super()` has run. A second
7109 // initialisation is the error the reference reports as
7110 // "'this' can be initialized only once".
7111 let slot = self.slot_operand(op, a);
7112 let value = self.pop();
7113 if !matches!(self.get_loc(slot), Value::Uninitialized) {
7114 return Err(Signal::Throw(self.make_error(
7115 "ReferenceError",
7116 "'this' can be initialized only once",
7117 )));
7118 }
7119 self.put_loc(slot, value);
7120 }
7121 CheckCtor => {
7122 // A class constructor may only run under `new`, which is what makes
7123 // `class A {}; A()` a TypeError.
7124 if matches!(self.frame().new_target, Value::Undefined) {
7125 return Err(Signal::Throw(self.make_error(
7126 "TypeError",
7127 "class constructors must be invoked with 'new'",
7128 )));
7129 }
7130 }
7131 InitCtor => {
7132 // The body a derived class gets when it declares no constructor:
7133 // forward every argument to the parent constructor, keeping `new.target`.
7134 if matches!(self.frame().new_target, Value::Undefined) {
7135 return Err(Signal::Throw(self.make_error(
7136 "TypeError",
7137 "class constructors must be invoked with 'new'",
7138 )));
7139 }
7140 let Some(callee) = self.current_callee() else {
7141 return Err(Signal::Throw(
7142 self.make_error("TypeError", "no constructor to inherit from"),
7143 ));
7144 };
7145 let parent = callee.proto().map_or(Value::Null, Value::Object);
7146 let new_target = self.frame().new_target.clone();
7147 let args = self.frame().passed.clone();
7148 let result = self.construct(parent, new_target, args)?;
7149 self.push(result);
7150 }
7151 SetLocUninitialized => {
7152 let slot = self.slot_operand(op, a);
7153 self.put_loc(slot, Value::Uninitialized);
7154 }
7155 CloseLoc => {
7156 // "Close" a binding: give it a *fresh* cell holding the current
7157 // value. Closures created before this point keep the old cell and the
7158 // ones created after see the new one, which is what makes every
7159 // iteration of `for (let i ...)` capture its own `i`, and what freezes
7160 // a block-scoped binding when the block ends.
7161 //
7162 // Clearing the slot instead (which this used to do) broke both: a
7163 // closure over a captured block variable read `undefined`, and a loop
7164 // terminated after one iteration.
7165 let slot = self.slot_operand(op, a);
7166 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
7167 if index >= 0 {
7168 let current = self.frame().cells[index as usize].get();
7169 let fresh = self.new_cell(current);
7170 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
7171 *cell = fresh;
7172 }
7173 }
7174 }
7175 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
7176 let slot = self.slot_operand(op, a);
7177 let value = self.get_arg(slot);
7178 self.push(value);
7179 }
7180 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
7181 let slot = self.slot_operand(op, a);
7182 let value = self.pop();
7183 self.put_arg(slot, value);
7184 }
7185 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
7186 let slot = self.slot_operand(op, a);
7187 let value = self.pop();
7188 self.put_arg(slot, value.clone());
7189 self.push(value);
7190 }
7191
7192 // -- closure variables ------------------------------------------
7193 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
7194 let slot = self.slot_operand(op, a);
7195 // A name a direct `eval` created shadows the binding the compiler chose.
7196 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
7197 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
7198 // and only a runtime lookup can know that.
7199 if let Some(cell) = self.eval_created_local(slot) {
7200 self.push(cell.get());
7201 return self.step();
7202 }
7203 let value = self.cell_value(slot)?;
7204 self.push(value);
7205 }
7206 GetVarRefCheck => {
7207 let slot = self.slot_operand(op, a);
7208 let value = self.cell_value(slot)?;
7209 if matches!(value, Value::Uninitialized) {
7210 return Err(self.dead_zone(slot, VarSlot::Closure));
7211 }
7212 self.push(value);
7213 }
7214 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
7215 let slot = self.slot_operand(op, a);
7216 let value = self.pop();
7217 if let Some(cell) = self.eval_created_local(slot) {
7218 cell.set(value);
7219 return self.step();
7220 }
7221 // Same rule as `PutLocCheck`: a checked store to a captured binding
7222 // refuses a `const` once its initialiser has run.
7223 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
7224 return Err(self.read_only(slot, VarSlot::Closure));
7225 }
7226 self.set_cell(slot, value)?;
7227 }
7228 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
7229 let slot = self.slot_operand(op, a);
7230 let value = self.pop();
7231 if let Some(cell) = self.eval_created_local(slot) {
7232 cell.set(value.clone());
7233 self.push(value);
7234 return self.step();
7235 }
7236 self.set_cell(slot, value.clone())?;
7237 self.push(value);
7238 }
7239
7240 // -- globals ----------------------------------------------------
7241 GetVar => {
7242 let value = self.get_global(a as usize)?;
7243 self.push(value);
7244 }
7245 GetVarUndef => {
7246 let value = self
7247 .get_global(a as usize)
7248 .or_else(|_| Ok(Value::Undefined))?;
7249 self.push(value);
7250 }
7251 DeleteVar => {
7252 // `delete name` for a name that is not a declared binding. A lexical
7253 // global lives in the reference table and cannot be deleted; anything
7254 // reachable only as a property of the global object is *implicit* —
7255 // `x = 1` with no declaration — and goes away if it is configurable,
7256 // which is what `delete` on an implicit global answers.
7257 let name = self.atom_text(a as usize);
7258 let global = self.realm.global.clone();
7259 let deleted = if self.realm.globals.contains_key(&name) {
7260 false
7261 } else if global.own_property(&name).is_some() {
7262 self.delete_property(&global, &name)?
7263 } else {
7264 true
7265 };
7266 self.push(Value::Bool(deleted));
7267 }
7268 PutVar => {
7269 let value = self.pop();
7270 self.put_global(a as usize, value)?;
7271 }
7272 PutVarInit => {
7273 let slot = a as usize;
7274 let value = self.pop();
7275 self.init_global(slot, value)?;
7276 }
7277
7278 // -- arithmetic -------------------------------------------------
7279 Add => self.binary_add()?,
7280 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
7281 let raw_right = self.pop();
7282 let raw_left = self.pop();
7283 // BigInt arithmetic is a separate path, and not only for the type of the
7284 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
7285 // rather than a silent conversion.
7286 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
7287 let left = self.primitive_of(raw_left)?;
7288 let right = self.primitive_of(raw_right)?;
7289 let value = self.bigint_arithmetic(op, left, right)?;
7290 self.push(value);
7291 } else {
7292 let right = self.numeric(raw_right)?;
7293 let left = self.numeric(raw_left)?;
7294 self.push(arithmetic(op, left, right)?);
7295 }
7296 }
7297 Neg => {
7298 let raw = self.pop();
7299 match raw {
7300 // A bigint negates exactly, however wide it is.
7301 Value::BigInt(big) => {
7302 let negated = big.negate();
7303 self.push(self.bigint(negated));
7304 }
7305 other => {
7306 let value = self.numeric(other)?;
7307 self.push(negate(value));
7308 }
7309 }
7310 }
7311 Plus => {
7312 let value = self.pop();
7313 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
7314 // unary plus is defined to produce a *number*, which a bigint cannot
7315 // become without loss. It used to fall through to `NaN`.
7316 if matches!(value, Value::BigInt(_)) {
7317 return Err(self.type_error("cannot convert bigint to number"));
7318 }
7319 let numeric = self.numeric_of(value)?;
7320 self.push(numeric);
7321 }
7322 Inc => {
7323 let raw = self.pop();
7324 let (_, updated) = self.advance_numeric(raw, true)?;
7325 self.push(updated);
7326 }
7327 Dec => {
7328 let raw = self.pop();
7329 let (_, updated) = self.advance_numeric(raw, false)?;
7330 self.push(updated);
7331 }
7332 PostInc | PostDec => {
7333 // `x -> x x+1`: the *new* value ends up on top, so the store the
7334 // compiler emits right after (`put_var`) writes the incremented
7335 // one, while the old value stays underneath for the expression's
7336 // own result. Getting this backwards makes `i++` a no-op, which
7337 // turns `while (i < 3)` into an infinite loop.
7338 let raw = self.pop();
7339 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
7340 self.push(old);
7341 self.push(updated);
7342 }
7343 Not => {
7344 let raw = self.pop();
7345 match raw {
7346 // `~x` on a bigint is `-x - 1`, exact at any width.
7347 Value::BigInt(big) => {
7348 let inverted = big.bitnot();
7349 self.push(self.bigint(inverted));
7350 }
7351 other => {
7352 let value = self.numeric(other)?;
7353 self.push(Value::Int(!value.to_int32()));
7354 }
7355 }
7356 }
7357 Lnot => {
7358 let value = self.pop();
7359 self.push(Value::Bool(!value.to_boolean()));
7360 }
7361
7362 // -- comparison -------------------------------------------------
7363 Lt | Lte | Gt | Gte => {
7364 let right = self.pop();
7365 let left = self.pop();
7366 let answer = self.relational(op, left, right);
7367 self.push(answer);
7368 }
7369 Eq | Neq => {
7370 let right = self.pop();
7371 let left = self.pop();
7372 let equal = self.abstract_equals(left, right)?;
7373 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
7374 }
7375 StrictEq => {
7376 let right = self.pop();
7377 let left = self.pop();
7378 self.push(Value::Bool(left.strict_equals(&right)));
7379 }
7380 StrictNeq => {
7381 let right = self.pop();
7382 let left = self.pop();
7383 self.push(Value::Bool(!left.strict_equals(&right)));
7384 }
7385 IsUndefined => {
7386 // `=== undefined`, which is what a destructuring default tests. It is
7387 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
7388 let value = self.pop();
7389 self.push(Value::Bool(matches!(value, Value::Undefined)));
7390 }
7391 IsUndefinedOrNull => {
7392 let value = self.pop();
7393 self.push(Value::Bool(value.is_nullish()));
7394 }
7395 Typeof => {
7396 let value = self.pop();
7397 self.push(self.string(value.type_of()));
7398 }
7399 ToObject => {
7400 // A destructuring *object* pattern starts here, which is why
7401 // `var {} = null` throws. Only `undefined` and `null` are refused; a
7402 // primitive is boxed.
7403 let value = self.pop();
7404 let object = self.object_from(&value)?;
7405 self.push(Value::Object(object));
7406 }
7407 Instanceof => {
7408 let constructor = self.pop();
7409 let object = self.pop();
7410 let answer = self.instance_of(&object, &constructor)?;
7411 self.push(Value::Bool(answer));
7412 }
7413 In => {
7414 let object = self.pop();
7415 let key = self.pop();
7416 let answer = self.has_property(&key, &object)?;
7417 self.push(Value::Bool(answer));
7418 }
7419
7420 // -- control flow -----------------------------------------------
7421 Goto | Goto8 | Goto16 => {
7422 self.frame_mut().pc = a as usize;
7423 }
7424 IfTrue | IfTrue8 => {
7425 let value = self.pop();
7426 if value.to_boolean() {
7427 self.frame_mut().pc = a as usize;
7428 }
7429 }
7430 IfFalse | IfFalse8 => {
7431 let value = self.pop();
7432 if !value.to_boolean() {
7433 self.frame_mut().pc = a as usize;
7434 }
7435 }
7436 Catch => {
7437 // Pushes the handler target onto the value stack; `unwind` finds it.
7438 self.push(Value::CatchOffset(a));
7439 }
7440 Gosub => {
7441 self.push(Value::ReturnAddress(next as u32));
7442 self.frame_mut().pc = a as usize;
7443 }
7444 Ret => {
7445 let value = self.pop();
7446 match value {
7447 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
7448 _ => {
7449 return Err(Signal::Throw(
7450 self.make_error("InternalError", "invalid return address"),
7451 ));
7452 }
7453 }
7454 }
7455 NipCatch => {
7456 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
7457 // including the marker, keeping the top value.
7458 let top = self.pop();
7459 loop {
7460 match self.pop() {
7461 Value::CatchOffset(_) | Value::Undefined => break,
7462 _ => {}
7463 }
7464 if self.frame().stack.is_empty() {
7465 break;
7466 }
7467 }
7468 self.push(top);
7469 }
7470 Throw => {
7471 let value = self.pop();
7472 return Err(Signal::Throw(value));
7473 }
7474 ThrowError => {
7475 let name = self.atom_text(a as usize);
7476 let (class, message) = match b {
7477 0 => ("TypeError", format!("'{name}' is read-only")),
7478 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
7479 2 => ("ReferenceError", format!("'{name}' is not initialized")),
7480 // `delete super.x` is a syntax-level mistake the reference reports
7481 // with this wording, not a property-access failure.
7482 3 => (
7483 "ReferenceError",
7484 "unsupported reference to 'super'".to_string(),
7485 ),
7486 4 => (
7487 "TypeError",
7488 "iterator does not have a throw method".to_string(),
7489 ),
7490 5 => (
7491 "ReferenceError",
7492 "invalid assignment left-hand side".to_string(),
7493 ),
7494 _ => ("TypeError", format!("invalid operation on '{name}'")),
7495 };
7496 return Err(Signal::Throw(self.make_error(class, &message)));
7497 }
7498 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
7499 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
7500 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
7501 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
7502 Await => return Ok(Step::Suspend(SuspendKind::Await)),
7503 ReturnAsync => {
7504 // The reference's `return_async` returns `undefined` and lets the resume
7505 // machinery pick the real value off `sp[-1]`, which is how it tells a
7506 // completion from a suspension. Carrying the value explicitly says the
7507 // same thing without the implicit stack slot.
7508 let value = self.pop();
7509 return Ok(Step::Return(value));
7510 }
7511 Return => {
7512 let value = self.pop();
7513 return Ok(Step::Return(value));
7514 }
7515 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
7516
7517 // -- calls ------------------------------------------------------
7518 Call | Call0 | Call1 | Call2 | Call3 => {
7519 let argc = self.argc_operand(op, a);
7520 let args = self.pop_n(argc);
7521 let callee = self.pop();
7522 // A plain call has no receiver; the callee decides what to do with
7523 // `undefined` (a sloppy function substitutes the global object).
7524 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
7525 self.push(result);
7526 }
7527 }
7528 CallConstructor => {
7529 // `constructor this_obj args… -> object`. The duplicated
7530 // constructor is `new.target`; this milestone does not expose it,
7531 // so the extra copy is simply consumed here.
7532 let argc = a as usize;
7533 let args = self.pop_n(argc);
7534 let new_target = self.pop();
7535 let callee = self.pop();
7536 let result = self.construct(callee, new_target, args)?;
7537 self.push(result);
7538 }
7539 CallMethod => {
7540 let argc = a as usize;
7541 let args = self.pop_n(argc);
7542 let callee = self.pop();
7543 let this = self.pop();
7544 if let Some(result) = self.call_or_push(callee, this, args)? {
7545 self.push(result);
7546 }
7547 }
7548 Apply => {
7549 // `func this array -> result`, the spread-call form: the compiler
7550 // builds one array of arguments, and all that is left here is to
7551 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
7552 let array = self.pop();
7553 let this = self.pop();
7554 let callee = self.pop();
7555 let args = self.array_like_to_args(&array)?;
7556 if a & 1 != 0 {
7557 let result = self.construct(callee, this, args)?;
7558 self.push(result);
7559 } else if let Some(result) = self.call_or_push(callee, this, args)? {
7560 self.push(result);
7561 }
7562 }
7563 TailCall | TailCallMethod => {
7564 // `tail_call` is `call` whose result is returned immediately — the
7565 // reference jumps straight to `done` instead of storing the value and
7566 // running on. The callee still gets its own frame, so deep tail
7567 // recursion hits the stack limit exactly like plain recursion does;
7568 // marking this frame lets the return path unwind without needing
7569 // instructions after the call.
7570 let argc = if op == TailCallMethod {
7571 a as usize
7572 } else {
7573 self.argc_operand(op, a)
7574 };
7575 let args = self.pop_n(argc);
7576 let callee = self.pop();
7577 let this = if op == TailCallMethod {
7578 self.pop()
7579 } else {
7580 Value::Undefined
7581 };
7582 if let Value::Object(function) = &callee
7583 && let Some((code, env)) = bytecode_of(function)
7584 {
7585 // A generator or async body is not run here at all: calling it only
7586 // *creates* the generator/coroutine, so it must not inherit this
7587 // frame. Doing so made `function f(){ return g() }` push `g`'s body
7588 // onto `f`'s frame, and the first `yield`/`await` then reported
7589 // "a generator body ran as an ordinary call".
7590 if code.code.kind.is_generator() || code.code.kind.is_async() {
7591 let value = self.call_value(callee, this, args)?;
7592 return Ok(Step::Return(value));
7593 }
7594 self.frame_mut().tail = true;
7595 self.push_frame(code, env, this, args, callee)?;
7596 return Ok(Step::Continue);
7597 }
7598 // A native callee has no frame to reuse, so its value is simply
7599 // returned.
7600 let value = self.call_value(callee, this, args)?;
7601 return Ok(Step::Return(value));
7602 }
7603
7604 // -- objects ----------------------------------------------------
7605 SpecialObject => {
7606 let value = self.special_object(a)?;
7607 self.push(value);
7608 }
7609 PrivateSymbol => {
7610 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
7611 // symbol each time it is evaluated, which is why the compiler evaluates it
7612 // once (at class definition) and stores it in a class-scope binding.
7613 let name = self.atom_text(a as usize);
7614 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
7615 self.push(Value::Symbol(symbol));
7616 }
7617 GetPrivateField => {
7618 // `obj symbol -> value`. A missing private field is a TypeError, which is what
7619 // makes `#x` inaccessible on any object not built by this class.
7620 let symbol = self.pop();
7621 let object = self.pop();
7622 let value = self.read_private_field(&object, &symbol)?;
7623 self.push(value);
7624 }
7625 PutPrivateField => {
7626 // `obj value symbol ->`, and the store is a plain assignment to a property the
7627 // class already created, so there is no setter to consult.
7628 let symbol = self.pop();
7629 let value = self.pop();
7630 let object = self.pop();
7631 self.write_private_field(&object, &symbol, value)?;
7632 }
7633 DefinePrivateField => {
7634 // `obj symbol value -> obj`: a field initialiser creates the property, and
7635 // redefining one is a TypeError ("already exists").
7636 let value = self.pop();
7637 let symbol = self.pop();
7638 let object = self.pop();
7639 self.define_private_field(&object, &symbol, value)?;
7640 self.push(object);
7641 }
7642 PrivateIn => {
7643 // `obj key -> bool`: `#x in o`. The second operand decides which question is
7644 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
7645 // is a field, so this is an own-property test; a *function* is a method or
7646 // accessor, so this is a brand check.
7647 let key = self.pop();
7648 let object = self.pop();
7649 let Some(target) = object.as_object() else {
7650 return Err(Signal::Throw(
7651 self.make_error("TypeError", "invalid 'in' operand"),
7652 ));
7653 };
7654 let present = match &key {
7655 Value::Object(_) => self.check_brand(target, &key)?,
7656 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
7657 };
7658 self.push(Value::Bool(present));
7659 }
7660 AddBrand => {
7661 // `obj home ->`: create the class brand on `home` if it has none, then give
7662 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
7663 // class definition: only the prototype's copy of the symbol is wanted.
7664 let home = self.pop();
7665 let object = self.pop();
7666 self.add_brand(&object, &home)?;
7667 }
7668 CheckBrand => {
7669 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
7670 // Both stay, because the caller needs them — `nip` halves a read into its
7671 // value and `call_method` uses the pair as receiver and callee.
7672 let function = self.peek(0);
7673 let object = self.peek(1);
7674 let Some(target) = object.as_object() else {
7675 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
7676 };
7677 if !self.check_brand(target, &function)? {
7678 return Err(Signal::Throw(
7679 self.make_error("TypeError", "invalid brand on object"),
7680 ));
7681 }
7682 }
7683 GetLength => {
7684 // `get_length` is the `.length` read; an array and a string answer
7685 // from their own length, anything else from the property.
7686 let target = self.pop();
7687 let value = match &target {
7688 Value::Object(object) => match object.array_length() {
7689 Some(length) => crate::object::length_value(length),
7690 None => self.read_field(&target, "length")?,
7691 },
7692 Value::String(text) => Value::Int(text.utf16_len() as i32),
7693 _ => self.read_field(&target, "length")?,
7694 };
7695 self.push(value);
7696 }
7697 GetField | GetField2 => {
7698 let object = self.pop();
7699 let key = self.atom_key(a as usize);
7700 let value = self.read_field_cached(&object, &key, next)?;
7701 if op == GetField2 {
7702 self.push(object);
7703 }
7704 self.push(value);
7705 }
7706 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
7707 let key = self.pop();
7708 let object = self.pop();
7709 let key = self.propkey(&key)?;
7710 let value = self.read_field_key(&object, &key)?;
7711 if matches!(op, GetArrayEl2 | GetArrayEl3) {
7712 self.push(object);
7713 }
7714 if op == GetArrayEl3 {
7715 // The key goes back in its *value* form, which the compiler stores
7716 // into the target of a destructuring assignment.
7717 self.push(match &key {
7718 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
7719 PropertyKey::String(text) => self.string_wtf8(text.clone()),
7720 });
7721 }
7722 self.push(value);
7723 }
7724 PutField => {
7725 let value = self.pop();
7726 let object = self.pop();
7727 let key = self.atom_key(a as usize);
7728 self.write_field_key(&object, &key, value)?;
7729 }
7730 PutArrayEl => {
7731 let value = self.pop();
7732 let key = self.pop();
7733 let object = self.pop();
7734 let key = self.propkey(&key)?;
7735 self.write_field_key(&object, &key, value)?;
7736 }
7737 DefineField => {
7738 let value = self.pop();
7739 let object = self.pop();
7740 let key = self.atom_text(a as usize);
7741 // No naming here. `{m: function(){}}` is named by the *compiler*, which
7742 // emits `set_name` — and only where `NamedEvaluation` applies, so
7743 // `{m: (0, function(){})}` stays anonymous. Naming every function that
7744 // reaches a property definition got that case wrong, and the compiler is
7745 // the only place that can tell the two apart.
7746 if let Some(target) = object.as_object() {
7747 // Only an *array* stores into the element vector. A numeric key
7748 // on an ordinary object is an ordinary property, which is what
7749 // makes `{1: 'a'}` iterate as a key rather than disappear.
7750 let stored = target.is_array()
7751 && array_index(&key).is_some_and(|index| {
7752 target.array_set(self.heap, index as usize, value.clone())
7753 });
7754 if !stored {
7755 target.define_data(&key, value);
7756 }
7757 }
7758 self.push(object);
7759 }
7760 DefineArrayEl => {
7761 // `obj key value -> obj key`. The *value* form of the key is what goes
7762 // back on the stack — the compiler stores it into the pattern's binding —
7763 // so the symbol is not stringified on the way through.
7764 let value = self.pop();
7765 let key_value = self.pop();
7766 let object = self.peek(0);
7767 let key = self.propkey(&key_value)?;
7768 self.write_field_key(&object, &key, value)?;
7769 self.push(key_value);
7770 }
7771 SetHomeObject => {
7772 // `obj func -> obj func`: records the object a method was defined on so
7773 // `super` inside it resolves against that object's prototype.
7774 let function = self.peek(0);
7775 let home = self.peek(1);
7776 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
7777 function.set_home_object(Some(home.clone()));
7778 }
7779 }
7780 Regexp => {
7781 // `pattern flags -> regexp`. A literal compiles here rather than through the
7782 // constructor, which is both what the reference's dedicated opcode is for
7783 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
7784 let flags = self.pop();
7785 let pattern = self.pop();
7786 let pattern = self.to_js_string(&pattern)?;
7787 let flags = self.to_js_string(&flags)?;
7788 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
7789 self.push(Value::Object(object));
7790 }
7791 UsingDisposeInit => {
7792 // The error state a disposal accumulates into. Uninitialised means "no
7793 // failure yet"; anything else is the exception being propagated.
7794 self.push(Value::Uninitialized);
7795 }
7796 UsingCheck => {
7797 // `value -> value, method`: validate and snapshot the disposer now, so a
7798 // later change to `Symbol.dispose` cannot change what gets called, and so a
7799 // value that is not disposable fails before the body runs.
7800 let value = self.pop();
7801 let method = self.using_method_for(&value, a as u8 == 1)?;
7802 self.push(value);
7803 self.push(method);
7804 }
7805 UsingDispose => {
7806 // `error_state -> error_state'`: dispose the variable at `slot` — its value
7807 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
7808 // the pending error.
7809 let slot = self.slot_operand(op, a);
7810 let error_state = self.pop();
7811 let merged = self.using_dispose_once(slot, error_state)?;
7812 self.push(merged);
7813 }
7814 UsingDisposeMerge => {
7815 let new_error = self.pop();
7816 let error_state = self.pop();
7817 let merged = self.merge_dispose_error(new_error, error_state);
7818 self.push(merged);
7819 }
7820 UsingDisposeEnd => {
7821 // A disposal that failed replaces the block's normal completion, so the
7822 // error state becomes a real throw here rather than at the call site.
7823 let error_state = self.pop();
7824 if !matches!(error_state, Value::Uninitialized) {
7825 return Err(Signal::Throw(error_state));
7826 }
7827 }
7828 UsingDisposeAsync => {
7829 // `await using` needs a promise to await and this runtime has no
7830 // `Promise` builtin, so the disposer is called synchronously and its result
7831 // discarded. That is correct for a disposer that returns nothing and is
7832 // reported as a gap rather than silently skipped.
7833 let slot = self.slot_operand(op, a);
7834 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
7835 self.push(error_state);
7836 }
7837 GetSuper => {
7838 // `obj -> obj's prototype`: the starting point of a `super` lookup.
7839 let object = self.pop();
7840 let proto = match &object {
7841 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
7842 _ => Value::Null,
7843 };
7844 self.push(proto);
7845 }
7846 GetSuperValue => {
7847 // `receiver proto key -> value`, searching from `proto` but reporting to
7848 // `receiver`, which is what `super.g` must do for a getter to see `this`.
7849 //
7850 // Three values in, one out: the receiver is *consumed*, not left under the
7851 // result. Leaving it there was invisible for `super.x` in `return` or
7852 // statement position (the result is what gets popped) and corrupted the
7853 // frame everywhere else — `print(super.x)` left the class where the call
7854 // opcode looks for the receiver and called the class itself.
7855 let key = self.pop();
7856 let proto = self.pop();
7857 let receiver = self.pop();
7858 let value = self.super_read(&receiver, &proto, &key)?;
7859 self.push(value);
7860 }
7861 PutSuperValue => {
7862 // `receiver proto key value ->`: a store that starts at `proto` but
7863 // assigns to `receiver`.
7864 let value = self.pop();
7865 let key = self.pop();
7866 let proto = self.pop();
7867 let receiver = self.pop();
7868 self.super_write(&receiver, &proto, &key, value)?;
7869 }
7870 DefineClass => {
7871 // `parent ctor -> ctor proto`: the constructor becomes the class and a
7872 // fresh prototype object lands on top for the methods to go on.
7873 let name = self.atom_text(a as usize);
7874 let (ctor, proto) = self.define_class(&name, b)?;
7875 self.push(ctor);
7876 self.push(Value::Object(proto));
7877 }
7878 DefineClassComputed => {
7879 // `parent ctor key -> ctor proto key`: the computed name stays put so
7880 // `define_field`-style consumers can still read it.
7881 let key = self.pop();
7882 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
7883 let (ctor, proto) = self.define_class(&name, b)?;
7884 self.push(ctor);
7885 self.push(Value::Object(proto));
7886 self.push(key);
7887 }
7888 DefineMethod => {
7889 let function = self.pop();
7890 let object = self.pop();
7891 let key = self.atom_text(a as usize);
7892 // A method's `[[HomeObject]]` is the object it was defined on, which is
7893 // what `super` inside it resolves against.
7894 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
7895 function.set_home_object(Some(object.clone()));
7896 }
7897 self.set_function_name(&function, &key_with_accessor_prefix(&key, b));
7898 if let Some(array) = object.as_object() {
7899 define_function_property(array, &PropertyKey::from(key.as_str()), function, b);
7900 }
7901 self.push(object);
7902 }
7903 DefineMethodComputed => {
7904 let function = self.pop();
7905 let key = self.pop();
7906 let object = self.pop();
7907 let key = self.propkey(&key)?;
7908 self.set_function_name(&function, &key_with_accessor_prefix(&key.to_string(), a));
7909 if let Some(array) = object.as_object() {
7910 define_function_property(array, &key, function, a);
7911 }
7912 self.push(object);
7913 }
7914 SetProto => {
7915 let proto = self.pop();
7916 let object = self.pop();
7917 if let Some(target) = object.as_object() {
7918 target.set_proto(proto.as_object().cloned());
7919 }
7920 self.push(object);
7921 }
7922 CopyDataProperties => {
7923 let exclusion = self.pop();
7924 let source = self.pop();
7925 let target = self.peek(0);
7926 self.copy_properties(&target, &source, &exclusion)?;
7927 self.push(source);
7928 self.push(exclusion);
7929 }
7930 ToPropkey => {
7931 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
7932 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
7933 // ordinary `"Symbol(b)"` property.
7934 let value = self.pop();
7935 let key = match self.propkey(&value)? {
7936 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
7937 PropertyKey::String(text) => self.string_wtf8(text),
7938 };
7939 self.push(key);
7940 }
7941 SetName => {
7942 let function = self.peek(0);
7943 let name = self.atom_text(a as usize);
7944 self.set_function_name(&function, &name);
7945 }
7946 SetNameComputed => {
7947 let key = self.peek(1);
7948 let function = self.peek(0);
7949 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
7950 self.set_function_name(&function, &name);
7951 }
7952
7953 // -- arrays -----------------------------------------------------
7954 ArrayFrom => {
7955 let count = a as usize;
7956 let elements = self.pop_n(count);
7957 let array = self.new_array(elements);
7958 self.push(Value::Object(array));
7959 }
7960 Append => {
7961 // `array index iterable -> array new_index`
7962 let iterable = self.pop();
7963 self.pop();
7964 let array = self.peek(0);
7965 let added = self.append_enumerate(&array, &iterable)?;
7966 self.push(Value::Int(added));
7967 }
7968
7969 // -- iteration --------------------------------------------------
7970 ForInStart => {
7971 let value = self.pop();
7972 let record = self.for_in_record(&value)?;
7973 self.push(Value::Object(record));
7974 }
7975 ForInNext => {
7976 // `record -> record key done`. The flag is *done*, not "found":
7977 // the compiler tests it with `if_false` to jump back into the body,
7978 // so reporting `true` while keys remain would end the loop at once.
7979 let record = self.peek(0);
7980 match self.for_in_advance(&record)? {
7981 Some(key) => {
7982 let text = self.string(key);
7983 self.push(text);
7984 self.push(Value::Bool(false));
7985 }
7986 None => {
7987 self.push(Value::Undefined);
7988 self.push(Value::Bool(true));
7989 }
7990 }
7991 }
7992 ForOfStart => {
7993 let value = self.pop();
7994 let iterator = self.get_iterator(&value)?;
7995 self.push(iterator.object);
7996 self.push(iterator.next);
7997 self.push(Value::CatchOffset(0));
7998 }
7999 ForOfNext => {
8000 // `iter next catch_offset -> iter next catch_offset value done`.
8001 //
8002 // The operand is how many values sit *above* the iterator triple: a
8003 // destructuring rest element keeps its target array and running index
8004 // there while draining the iterator, so the triple is not at the top.
8005 let extra = a as usize;
8006 let iterator_slot = 2 + extra;
8007 // An exhausted iterator is replaced by `undefined` (see below), so a
8008 // second step must not call `next` again — `Array.from` and a
8009 // destructuring pattern both keep stepping past the end.
8010 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
8011 (Value::Undefined, true)
8012 } else {
8013 let iterator = Iterator {
8014 object: self.peek(iterator_slot),
8015 next: self.peek(1 + extra),
8016 };
8017 self.iterator_step(&iterator)?
8018 };
8019 if done {
8020 // The result's `value` is meaningless once the iterator is done:
8021 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
8022 // rather than binding the generator's return value.
8023 let top = self.frame().stack.len() - 1 - iterator_slot;
8024 self.frame_mut().stack[top] = Value::Undefined;
8025 self.push(Value::Undefined);
8026 self.push(Value::Bool(true));
8027 } else {
8028 self.push(value);
8029 self.push(Value::Bool(false));
8030 }
8031 }
8032 IteratorNext => {
8033 // `iter next catch val -> iter next catch val'`: replace the argument with
8034 // the result of `next(val)`. The triple below stays put, which is why the
8035 // three instructions of the `yield*` loop all address the stack the same way.
8036 let value = self.pop();
8037 let object = self.peek(2);
8038 let next = self.peek(1);
8039 let result = self.call_value(next, object, vec![value])?;
8040 self.push(result);
8041 }
8042 IteratorCall => {
8043 // `iter next catch val -> iter next catch val' flag`.
8044 //
8045 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
8046 // The flag is `true` when the method was missing, which is how the
8047 // caller learns that the inner iterator cannot take part in the
8048 // unwinding.
8049 let value = self.pop();
8050 let object = self.peek(2);
8051 let key = if a & 1 != 0 { "throw" } else { "return" };
8052 let method = self.read_field(&object, key)?;
8053 if matches!(method, Value::Undefined | Value::Null) {
8054 self.push(value);
8055 self.push(Value::Bool(true));
8056 } else {
8057 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
8058 let result = self.call_value(method, object, argument)?;
8059 self.push(result);
8060 self.push(Value::Bool(false));
8061 }
8062 }
8063 IteratorCheckObject => {
8064 if !matches!(self.peek(0), Value::Object(_)) {
8065 return Err(Signal::Throw(
8066 self.make_error("TypeError", "iterator must return an object"),
8067 ));
8068 }
8069 }
8070 IteratorClose => {
8071 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
8072 // calling the iterator's `return` so it can release whatever it holds.
8073 //
8074 // The catch offset goes first, so an exception from `return` is not caught
8075 // by the loop being abandoned. This used to pop the three operands and call
8076 // nothing at all, which made `break` out of a `for of` invisible to an
8077 // iterator with a `return` method.
8078 self.pop();
8079 self.pop();
8080 let iterator = self.pop();
8081 if !matches!(iterator, Value::Undefined) {
8082 let method = self.read_field(&iterator, "return")?;
8083 if !matches!(method, Value::Undefined | Value::Null) {
8084 let result = self.call_value(method, iterator.clone(), Vec::new())?;
8085 // §7.4.6: a `return` that answers a non-object is a TypeError.
8086 if !matches!(result, Value::Object(_)) {
8087 return Err(Signal::Throw(
8088 self.make_error("TypeError", "iterator must return an object"),
8089 ));
8090 }
8091 }
8092 }
8093 }
8094 Import => {
8095 // `import(specifier)`: the options slot is on top and is not read yet.
8096 let _options = self.pop();
8097 let specifier = self.pop();
8098 let promise = self.dynamic_import(specifier)?;
8099 self.push(promise);
8100 }
8101 ForAwaitOfStart => {
8102 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
8103 // `Symbol.iterator` fallback.
8104 let value = self.pop();
8105 let iterator = self.get_async_iterator(&value)?;
8106 self.push(iterator.object);
8107 self.push(iterator.next);
8108 self.push(Value::CatchOffset(0));
8109 }
8110 ForAwaitOfNext => {
8111 // `for await` steps the iterator and leaves the *result* wrapped in a
8112 // promise, so the `await` the compiler emits right after this can suspend
8113 // on it. Unwrapping happens in `iterator_get_value_done`.
8114 let extra = a as usize;
8115 let iterator_slot = 2 + extra;
8116 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
8117 Value::Undefined
8118 } else {
8119 let iterator = Iterator {
8120 object: self.peek(iterator_slot),
8121 next: self.peek(1 + extra),
8122 };
8123 let next = iterator.next.clone();
8124 self.call_value(next, iterator.object, Vec::new())?
8125 };
8126 let promise = self.promise_resolve_value(result)?;
8127 self.push(promise);
8128 }
8129 IteratorGetValueDone => {
8130 // `result -> value done`. A missing result object means the iterator was
8131 // already exhausted, which the loop treats as `done`.
8132 let result = self.pop();
8133 let done = match &result {
8134 Value::Object(object) => self
8135 .get_property(object, "done")?
8136 .is_some_and(|value| value.to_boolean()),
8137 _ => true,
8138 };
8139 if done {
8140 // Clear the iterator object so the `iterator_close` the loop emits on
8141 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
8142 // on normal completion, and this is where a normal completion is
8143 // recognised — the same trick `for_of_next` uses, which also replaces
8144 // the slot with `undefined`.
8145 //
8146 // The layout is fixed because only `for await` emits this opcode:
8147 // `iter next catch [result]`, so the iterator is three below the top.
8148 let depth = self.frame().stack.len();
8149 if depth >= 3 {
8150 self.frame_mut().stack[depth - 3] = Value::Undefined;
8151 }
8152 self.push(Value::Undefined);
8153 self.push(Value::Bool(true));
8154 } else {
8155 let Value::Object(object) = &result else {
8156 self.push(Value::Undefined);
8157 self.push(Value::Bool(true));
8158 return Ok(Step::Continue);
8159 };
8160 let value = self
8161 .get_property(object, "value")?
8162 .unwrap_or(Value::Undefined);
8163 self.push(value);
8164 self.push(Value::Bool(false));
8165 }
8166 }
8167
8168 Delete => {
8169 // `delete obj[key]`, where the key was just pushed. Deleting an array
8170 // index leaves a *hole* rather than closing the gap, and a
8171 // non-configurable property answers `false` and stays.
8172 let key = self.pop();
8173 let target = self.pop();
8174 let key = self.propkey(&key)?;
8175 let text_label = key.as_str().unwrap_or("").to_string();
8176 let deleted = match &target {
8177 Value::Object(object) => {
8178 let object = object.clone();
8179 self.delete_property_key(&object, &key)?
8180 }
8181 // A string's `length` and its index properties are
8182 // non-configurable, so deleting one answers `false`.
8183 Value::String(text) => {
8184 !(text_label == "length"
8185 || array_index(&text_label)
8186 .is_some_and(|index| (index as usize) < text.utf16_len()))
8187 }
8188 // "delete null.a" is a TypeError, not a no-op: the operator needs an
8189 // object to delete from, and only a *boxable* primitive has one.
8190 Value::Undefined | Value::Null => {
8191 return Err(Signal::Throw(
8192 self.make_error("TypeError", "cannot convert to object"),
8193 ));
8194 }
8195 // Any other primitive has no own properties; deleting nothing
8196 // succeeds.
8197 _ => true,
8198 };
8199 self.push(Value::Bool(deleted));
8200 }
8201
8202 // -- exceptions and bookkeeping ---------------------------------
8203 Fclosure | Fclosure8 => {
8204 let value = self.closure(a as usize)?;
8205 self.push(value);
8206 }
8207
8208 other => {
8209 let name = other.info().name;
8210 return Err(Signal::Throw(self.make_error(
8211 "InternalError",
8212 &format!("{name} is not implemented yet"),
8213 )));
8214 }
8215 }
8216 Ok(Step::Continue)
8217 }
8218
8219 // -- operand helpers ----------------------------------------------------
8220
8221 /// The slot index an operand names, taking short forms into account.
8222 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
8223 use Opcode::*;
8224 match op {
8225 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
8226 | SetVarRef0 => 0,
8227 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
8228 | SetVarRef1 => 1,
8229 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
8230 | SetVarRef2 => 2,
8231 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
8232 | SetVarRef3 => 3,
8233 _ => a as usize,
8234 }
8235 }
8236
8237 /// The argument count of a call, taking `call0`…`call3` into account.
8238 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
8239 use Opcode::*;
8240 match op {
8241 Call0 => 0,
8242 Call1 => 1,
8243 Call2 => 2,
8244 Call3 => 3,
8245 _ => a as usize,
8246 }
8247 }
8248
8249 /// The atom's name as a property key.
8250 ///
8251 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
8252 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
8253 /// `String::clone` was a heap allocation and a copy — per property access.
8254 fn atom_key(&self, index: usize) -> PropertyKey {
8255 self.frame()
8256 .code
8257 .code
8258 .atoms
8259 .get(index)
8260 .map(|atom| match atom {
8261 Atom::Str(text) => PropertyKey::String(crate::value::Wtf8::from_rc_str(text)),
8262 Atom::Index(value) => {
8263 PropertyKey::String(crate::value::Wtf8::new(value.to_string()))
8264 }
8265 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
8266 // `throw_error`, `delete super.x`) never read it.
8267 Atom::Null => PropertyKey::String(crate::value::Wtf8::new(String::new())),
8268 })
8269 .unwrap_or_else(|| PropertyKey::String(crate::value::Wtf8::new(String::new())))
8270 }
8271
8272 fn atom_text(&self, index: usize) -> String {
8273 self.frame()
8274 .code
8275 .code
8276 .atoms
8277 .get(index)
8278 .map(|atom| match atom {
8279 Atom::Str(text) => text.clone(),
8280 Atom::Index(value) => value.to_string(),
8281 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
8282 // `throw_error`, `delete super.x`) never read it.
8283 Atom::Null => String::new(),
8284 })
8285 .unwrap_or_default()
8286 }
8287
8288 fn constant(&mut self, index: usize) -> JsResult<Value> {
8289 let constant = self.frame().code.code.cpool.get(index).cloned();
8290 Ok(match &constant {
8291 Some(Constant::Number(number)) => Value::Float(*number),
8292 Some(Constant::String(text)) => self.string(text.clone()),
8293 Some(Constant::BigInt { digits, radix }) => {
8294 match crate::bigint::BigInt::from_radix(digits, *radix) {
8295 Some(big) => self.bigint(big),
8296 // A literal the parser accepted is always parseable; a failure here
8297 // would be a compiler bug, so it reads as an `InternalError`.
8298 None => {
8299 return Err(Signal::Throw(
8300 self.make_error("InternalError", "unparseable bigint literal"),
8301 ));
8302 }
8303 }
8304 }
8305 Some(Constant::Function(_)) => {
8306 return Err(Signal::Throw(
8307 self.make_error("InternalError", "a bare function constant"),
8308 ));
8309 }
8310 // A tagged template's call site: a frozen array of the cooked chunks with a
8311 // frozen `raw` array beside it, which is what `String.raw` reads back.
8312 Some(Constant::Template { cooked, raw }) => {
8313 let cooked_values: Vec<Value> = cooked
8314 .iter()
8315 .map(|chunk| match chunk {
8316 Some(text) => self.string(text.clone()),
8317 None => Value::Undefined,
8318 })
8319 .collect();
8320 let raw_values: Vec<Value> =
8321 raw.iter().map(|text| self.string(text.clone())).collect();
8322 let raw_array = self.new_array(raw_values);
8323 raw_array.set_extensible(false);
8324 let template = self.new_array(cooked_values);
8325 template.define(
8326 "raw",
8327 Property::with_attributes(Value::Object(raw_array), false, false),
8328 );
8329 template.set_extensible(false);
8330 Value::Object(template)
8331 }
8332 _ => Value::Undefined,
8333 })
8334 }
8335
8336 /// The reference cell a closure-variable slot names.
8337 ///
8338 /// Two kinds of binding share this addressing: a genuine closure variable
8339 /// (captured from an enclosing function) lives in this frame's environment,
8340 /// while a *declared global* lives in the realm so that a script, a function
8341 /// declaration and their uses all see one binding. A plain `Global` — an
8342 /// undeclared name that may be satisfied by the global object — has no cell at
8343 /// all, which is how `typeof x` still works for a name that does not exist.
8344 /// The reference cell a closure-variable slot names.
8345 ///
8346 /// The environment is resolved once, when the closure is built, and this is
8347 /// just the lookup afterwards. A *declared global* is in there too, pointing at
8348 /// the realm's cell, so a script, a hoisted function declaration and their uses
8349 /// all share one binding. A plain `Global` — a name the script never declared —
8350 /// is read and written through `get_var`/`put_var` by name instead, which is
8351 /// what lets the global object satisfy it.
8352 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
8353 self.frame().env.cells.get(slot).cloned()
8354 }
8355
8356 /// Whether `slot` refers to a global binding through the reference table.
8357 ///
8358 /// A global's cell in the closure environment only exists so the slot has
8359 /// something to point at; the binding itself lives on the global object (a `var`)
8360 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
8361 /// be routed, not performed on the placeholder.
8362 fn is_global_slot(&self, slot: usize) -> bool {
8363 self.frame()
8364 .code
8365 .code
8366 .closure_vars
8367 .get(slot)
8368 .is_some_and(|c| {
8369 // A module's declarations and imports are *not* globals: their cells are
8370 // the module environment's, filled by the host, so the placeholder routing
8371 // must not apply to them.
8372 matches!(
8373 c.closure_type,
8374 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
8375 )
8376 })
8377 }
8378
8379 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
8380 if self.is_global_slot(slot) {
8381 return self.get_global(slot);
8382 }
8383 Ok(self
8384 .var_ref_cell(slot)
8385 .map(|cell| cell.get())
8386 .unwrap_or(Value::Undefined))
8387 }
8388
8389 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
8390 // A function declaration is hoisted by storing into a global reference before
8391 // the body runs, so this path is also what puts it on the global object.
8392 if self.is_global_slot(slot) {
8393 return self.put_global(slot, value);
8394 }
8395 if let Some(cell) = self.var_ref_cell(slot) {
8396 cell.set(value);
8397 }
8398 Ok(())
8399 }
8400
8401 // -- closures -----------------------------------------------------------
8402
8403 /// Build the closure for the function constant `index`.
8404 ///
8405 /// Every entry in the child's closure table names where its binding lives in
8406 /// *this* frame: a local or argument slot that was marked captured, or a cell
8407 /// this frame is itself holding. That is how a variable three functions deep
8408 /// stays one binding.
8409 fn closure(&mut self, index: usize) -> JsResult<Value> {
8410 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
8411 else {
8412 return Err(Signal::Throw(
8413 self.make_error("InternalError", "fclosure of a non-function"),
8414 ));
8415 };
8416 let mut cells = Vec::with_capacity(function.closure_vars.len());
8417 for closure_var in &function.closure_vars {
8418 let cell = match closure_var.closure_type {
8419 ClosureType::Arg => {
8420 let slot = closure_var.var_idx as usize;
8421 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
8422 }
8423 ClosureType::Local => {
8424 let slot = closure_var.var_idx as usize;
8425 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
8426 }
8427 ClosureType::Ref | ClosureType::GlobalRef => {
8428 // A `Ref` names a cell in this frame's own closure table; a
8429 // `GlobalRef` also starts there, then resolves by name below.
8430 let slot = closure_var.var_idx as usize;
8431 if let Some(cell) = self.frame().env.cells.get(slot) {
8432 cells.push(cell.clone());
8433 continue;
8434 }
8435 -1
8436 }
8437 _ => -1,
8438 };
8439 if cell >= 0 {
8440 let cell = self.frame().cells[cell as usize].clone();
8441 cells.push(cell);
8442 continue;
8443 }
8444 // A global: the cell is created on demand and shared through the realm,
8445 // so every function sees one binding.
8446 let name = closure_var.name.clone();
8447 let cell = match self.realm.globals.get(&name) {
8448 Some(cell) => cell.clone(),
8449 None => {
8450 let cell = self.new_cell(Value::Undefined);
8451 self.realm.globals.insert(name.clone(), cell.clone());
8452 cell
8453 }
8454 };
8455 cells.push(cell);
8456 }
8457 let name = function.name.clone();
8458 // `.length` is the arity before any default or rest parameter, not the number
8459 // of slots a pattern parameter needs.
8460 let length = function.defined_args;
8461 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
8462 // function and an arrow function do not. A *method* also does not, but that is not
8463 // known here — the method is marked when the `[[HomeObject]]` is attached (see
8464 // `set_home_object`), which is the moment it becomes a method.
8465 let function_kind = function.kind;
8466 let constructible =
8467 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
8468 let code = Gc::new(self.heap, CompiledCode::new(*function));
8469 // A closure built inside an `eval` inherits the eval's view of the enclosing
8470 // bindings, so it can still read them once the eval has returned.
8471 let eval_scope = self
8472 .active_eval_scope
8473 .clone()
8474 .or_else(|| self.frame().env.eval_scope.clone());
8475 // A closure sees the variables a direct `eval` declared in the frame it was
8476 // created in — the ones declared before *and after* it, so the same object is
8477 // shared; only the phase bounds which of them are visible.
8478 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
8479 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
8480 let env = Gc::new(
8481 self.heap,
8482 ClosureEnv {
8483 cells,
8484 eval_scope,
8485 local_vars,
8486 local_phase,
8487 },
8488 );
8489 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
8490 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
8491 // the only thing that carries `Symbol.toStringTag`, so without it
8492 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
8493 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
8494 let proto = match function_kind {
8495 js_compile::bytecode::FunctionKind::AsyncGenerator => self
8496 .realm
8497 .async_generator_function_proto
8498 .clone()
8499 .or_else(|| self.realm.function_proto.clone().into()),
8500 js_compile::bytecode::FunctionKind::Generator => self
8501 .realm
8502 .generator_function_proto
8503 .clone()
8504 .or_else(|| self.realm.function_proto.clone().into()),
8505 js_compile::bytecode::FunctionKind::Async => self
8506 .realm
8507 .async_function_proto
8508 .clone()
8509 .or_else(|| self.realm.function_proto.clone().into()),
8510 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
8511 };
8512 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
8513 object.set_constructible(constructible);
8514 object.define(
8515 "length",
8516 Property::name_or_length(Value::Int(length as i32)),
8517 );
8518 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
8519 // that checks the own-property descriptor fails if the property is missing.
8520 object.define("name", Property::name_or_length(self.string(name)));
8521 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
8522 // when `[[Construct]]` is created, so a generator, an async function and an arrow
8523 // function have none of their own. Installing it unconditionally gave
8524 // `Array.fromAsync` (an async function) an own `prototype` property, which
8525 // `builtin.js` checks for absence.
8526 if constructible {
8527 self.install_function_prototype(&object);
8528 }
8529 Ok(Value::Object(object))
8530 }
8531
8532 // -- conversions used by the operators ----------------------------------
8533
8534 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
8535 // `+x` is `ToNumber`, which for a string parses it and for an object runs
8536 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
8537 // string, which then behaves differently in every later comparison.
8538 match value {
8539 Value::Int(_) | Value::Float(_) => Ok(value),
8540 other => Ok(Value::Float(self.to_js_number(&other)?)),
8541 }
8542 }
8543
8544 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
8545 ///
8546 /// Returns the *converted* old value and the new one, because the two callers need
8547 /// different halves: `++x` yields the new value, while `x++` yields the old one and
8548 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
8549 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
8550 /// boolean.
8551 ///
8552 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
8553 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
8554 /// a bigint algorithm then ran exactly once.
8555 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
8556 if let Value::BigInt(big) = &value {
8557 let one = crate::bigint::BigInt::from_i64(1);
8558 let next = if up { big.add(&one) } else { big.sub(&one) };
8559 return Ok((value, self.bigint(next)));
8560 }
8561 let old = self.numeric(value)?;
8562 let new = if up {
8563 increment(old.clone())
8564 } else {
8565 decrement(old.clone())
8566 };
8567 Ok((old, new))
8568 }
8569
8570 fn numeric(&mut self, value: Value) -> JsResult<Value> {
8571 // `ToNumber` on an object runs `ToPrimitive` first, which is how
8572 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
8573 // heard at all. Reading the object's own tag instead (`other.to_number()`)
8574 // turned the whole operand into `NaN` and swallowed the exception.
8575 match value {
8576 Value::Int(_) | Value::Float(_) => Ok(value),
8577 other => Ok(Value::Float(self.to_js_number(&other)?)),
8578 }
8579 }
8580
8581 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
8582 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
8583 match value {
8584 Value::BigInt(big) => Ok((**big).clone()),
8585 // The reference words this the same way for every operator, so a failing
8586 // script reads identically; the operator itself adds nothing a caller can use.
8587 _ => Err(Signal::Throw(
8588 self.make_error("TypeError", "cannot convert bigint to number"),
8589 )),
8590 }
8591 }
8592
8593 /// Arithmetic where at least one operand is a `BigInt`.
8594 ///
8595 /// The two numeric types never mix, so a bigint paired with anything else is an error
8596 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
8597 /// that the relational operators handle it separately.
8598 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
8599 use Opcode::*;
8600 let a = self.bigint_operand(&left)?;
8601 let b = self.bigint_operand(&right)?;
8602 let result = match op {
8603 Add => a.add(&b),
8604 Sub => a.sub(&b),
8605 Mul => a.mul(&b),
8606 Div | Mod => {
8607 let Some((quotient, remainder)) = a.div_rem(&b) else {
8608 return Err(Signal::Throw(
8609 self.make_error("RangeError", "division by zero"),
8610 ));
8611 };
8612 if op == Div { quotient } else { remainder }
8613 }
8614 Pow => {
8615 let Some(value) = a.pow(&b) else {
8616 return Err(Signal::Throw(self.make_error(
8617 "RangeError",
8618 "BigInt exponent must be non-negative and not absurdly large",
8619 )));
8620 };
8621 value
8622 }
8623 And => a.bitand(&b),
8624 Or => a.bitor(&b),
8625 Xor => a.bitxor(&b),
8626 Shl | Sar => {
8627 // A shift count is a `BigInt` here, and both directions are exact; a
8628 // negative count would be the other direction, which the spec forbids.
8629 let Some(count) = b.to_i64() else {
8630 return Err(Signal::Throw(
8631 self.make_error("RangeError", "BigInt shift count is too large"),
8632 ));
8633 };
8634 if count < 0 {
8635 return Err(Signal::Throw(self.make_error(
8636 "RangeError",
8637 "BigInt shift count must be non-negative",
8638 )));
8639 }
8640 if op == Shl {
8641 a.shl(count as u64)
8642 } else {
8643 a.shr(count as u64)
8644 }
8645 }
8646 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
8647 _ => {
8648 return Err(Signal::Throw(self.make_error(
8649 "TypeError",
8650 "BigInts have no unsigned right shift, use >> instead",
8651 )));
8652 }
8653 };
8654 Ok(self.bigint(result))
8655 }
8656
8657 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
8658 ///
8659 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
8660 /// is on the mathematical values, and nothing is rounded first.
8661 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> Value {
8662 use Opcode::*;
8663 let ordering = match (&left, &right) {
8664 (Value::String(a), Value::String(b)) => {
8665 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
8666 }
8667 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
8668 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
8669 // is true even though `2.5` has no bigint form.
8670 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
8671 let b = other.to_number();
8672 if b.is_nan() {
8673 None
8674 } else {
8675 compare_bigint_and_f64(a, b)
8676 }
8677 }
8678 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
8679 let a = other.to_number();
8680 if a.is_nan() {
8681 None
8682 } else {
8683 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
8684 }
8685 }
8686 _ => left.to_number().partial_cmp(&right.to_number()),
8687 };
8688 let _ = self;
8689 let answer = match (op, ordering) {
8690 (_, None) => false,
8691 (Lt, Some(ordering)) => ordering.is_lt(),
8692 (Lte, Some(ordering)) => ordering.is_le(),
8693 (Gt, Some(ordering)) => ordering.is_gt(),
8694 (Gte, Some(ordering)) => ordering.is_ge(),
8695 _ => false,
8696 };
8697 Value::Bool(answer)
8698 }
8699
8700 fn binary_add(&mut self) -> JsResult<()> {
8701 let right = self.pop();
8702 let left = self.pop();
8703 let left = self.primitive_of(left)?;
8704 let right = self.primitive_of(right)?;
8705 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
8706 // that check comes before the bigint one: `"" + 1n` is a string, not a
8707 // mixed-type error.
8708 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
8709 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
8710 // `TypeError`, the one place a symbol and a string do not mix.
8711 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
8712 // between a copy and a rope from their lengths, and a rope is what turns
8713 // `text += "abc"` in a loop from quadratic into linear.
8714 if let (Value::String(left), Value::String(right)) = (&left, &right) {
8715 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
8716 // reports as `InternalError: string too long`.
8717 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
8718 return Err(Signal::Throw(
8719 self.make_error("InternalError", "string too long"),
8720 ));
8721 };
8722 self.push(Value::String(Gc::new(self.heap, joined)));
8723 return Ok(());
8724 }
8725 // At least one operand was not a string, so `ToString` it. This rejects a
8726 // symbol, which is the one place a symbol and a string do not mix.
8727 let left = self.checked_to_wtf8(&left)?;
8728 let right = self.checked_to_wtf8(&right)?;
8729 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
8730 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
8731 let text = left.concat(&right);
8732 self.push(self.string_wtf8(text));
8733 return Ok(());
8734 }
8735 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
8736 // not a conversion.
8737 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
8738 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
8739 self.push(value);
8740 return Ok(());
8741 }
8742 let left = self.numeric(left)?;
8743 let right = self.numeric(right)?;
8744 self.push(add_numbers(left, right));
8745 Ok(())
8746 }
8747
8748 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
8749 self.to_primitive(value, Hint::Default)
8750 }
8751
8752 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
8753 ///
8754 /// The order depends on the hint: the "number" order tries `valueOf` first and
8755 /// `toString` second, the "string" order the other way round, and the default
8756 /// hint uses the number order. A result that is still an object is a `TypeError`,
8757 /// because no built-in `valueOf`/`toString` returns one.
8758 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
8759 let Value::Object(object) = &value else {
8760 return Ok(value);
8761 };
8762 // A Date overrides the default hint to mean "string", which is what
8763 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
8764 // this, `"" + new Date()` would print the milliseconds, not the date.
8765 let hint = if hint == Hint::Default && is_date_object(self, object) {
8766 Hint::String
8767 } else {
8768 hint
8769 };
8770 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
8771 // handed the hint as a string. This is the hook a Date uses for its default hint
8772 // and a script uses to take over conversion entirely.
8773 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
8774 if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
8775 if !function.is_callable() {
8776 return Err(self.type_error("Symbol.toPrimitive is not a function"));
8777 }
8778 let hint = match hint {
8779 Hint::String => "string",
8780 Hint::Number => "number",
8781 Hint::Default => "default",
8782 };
8783 let hint = self.string(hint);
8784 let result = self.call_value(
8785 Value::Object(function),
8786 Value::Object(object.clone()),
8787 vec![hint],
8788 )?;
8789 if matches!(result, Value::Object(_)) {
8790 return Err(self.type_error("cannot convert object to primitive value"));
8791 }
8792 return Ok(result);
8793 }
8794 let order: [&str; 2] = match hint {
8795 Hint::String => ["toString", "valueOf"],
8796 Hint::Number | Hint::Default => ["valueOf", "toString"],
8797 };
8798 let receiver = object.clone();
8799 for method in order {
8800 if let Some(function) = self.get_property(&receiver, method)?
8801 && matches!(&function, Value::Object(object) if object.is_callable())
8802 {
8803 let result =
8804 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
8805 if !matches!(result, Value::Object(_)) {
8806 return Ok(result);
8807 }
8808 }
8809 }
8810 Err(self.type_error("cannot convert object to primitive value"))
8811 }
8812
8813 /// `ToString` with the object case going through `ToPrimitive`.
8814 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
8815 if matches!(value, Value::Object(_)) {
8816 let primitive = self.to_primitive(value.clone(), Hint::String)?;
8817 return Ok(primitive.to_js_string());
8818 }
8819 Ok(value.to_js_string())
8820 }
8821
8822 /// `ToString` that keeps the string's code units instead of flattening them.
8823 ///
8824 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
8825 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
8826 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
8827 if matches!(value, Value::Symbol(_)) {
8828 return Err(Signal::Throw(
8829 self.make_error("TypeError", "cannot convert symbol to string"),
8830 ));
8831 }
8832 // An object runs `ToPrimitive` first, which may itself produce a symbol.
8833 let value = self.to_primitive(value.clone(), Hint::String)?;
8834 match value {
8835 Value::Symbol(_) => Err(Signal::Throw(
8836 self.make_error("TypeError", "cannot convert symbol to string"),
8837 )),
8838 Value::String(text) => Ok(text.wtf8().clone()),
8839 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
8840 }
8841 }
8842
8843 /// `ToNumber` with the object case going through `ToPrimitive`.
8844 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
8845 let value = if matches!(value, Value::Object(_)) {
8846 self.to_primitive(value.clone(), Hint::Number)?
8847 } else {
8848 value.clone()
8849 };
8850 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
8851 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
8852 // `NaN` to stay total, and the operators check for the bigint themselves — but
8853 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
8854 // refuse, and answering `NaN` made them silently wrong instead.
8855 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
8856 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
8857 match value {
8858 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
8859 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
8860 other => Ok(other.to_number()),
8861 }
8862 }
8863
8864 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
8865 /// [`ElementType::write`].
8866 ///
8867 /// This is separated from the write because both conversions are observable script —
8868 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
8869 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
8870 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
8871 /// setters, and a plain `a[i] = v`.
8872 pub(crate) fn element_value(
8873 &mut self,
8874 element: crate::builtins::typedarray::ElementType,
8875 value: Value,
8876 ) -> JsResult<Value> {
8877 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
8878 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
8879 let primitive = match &value {
8880 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
8881 _ => value,
8882 };
8883 if element.is_bigint() {
8884 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
8885 Ok(Value::BigInt(Gc::new(self.heap, big)))
8886 } else {
8887 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
8888 Ok(Value::Float(self.to_js_number(&primitive)?))
8889 }
8890 }
8891
8892 /// `ToPropertyKey`: what a computed member access uses as its key.
8893 ///
8894 /// A symbol is returned as itself, never stringified — that is what keeps
8895 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
8896 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
8897 match value {
8898 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
8899 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
8900 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
8901 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
8902 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
8903 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
8904 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
8905 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
8906 other.to_js_string(),
8907 ))),
8908 },
8909 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
8910 }
8911 }
8912
8913 /// `ToPropertyKey` for the callers that can only use a string key.
8914 ///
8915 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
8916 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
8917 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
8918 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
8919 /// program continues with a value nobody asked for.
8920 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
8921 use crate::value::Wtf8;
8922 Ok(match value {
8923 // A string key keeps its code units. Going through a lossy `String` would make
8924 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
8925 Value::String(text) => text.wtf8().clone(),
8926 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
8927 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
8928 // falling back to its `ToString` would print `[object Object]`.
8929 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
8930 Value::String(text) => text.wtf8().clone(),
8931 other => Wtf8::new(other.to_js_string()),
8932 },
8933 other => Wtf8::new(other.to_js_string()),
8934 })
8935 }
8936
8937 // -- object operations used by instructions -----------------------------
8938
8939 /// Read `object[key]`, returning `undefined` when the property is missing.
8940 ///
8941 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
8942 /// primitive (looking through its prototype) as well as an object — which is what
8943 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
8944 /// argument needs too.
8945 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
8946 self.read_field_key(object, &PropertyKey::from(key))
8947 }
8948
8949 /// [`Interp::read_field`] with a key that may be a symbol.
8950 ///
8951 /// A symbol key never reaches the string shortcuts: a string's `length` and its
8952 /// indices are string properties, and a symbol named `length` is a different
8953 /// property that a string primitive cannot have.
8954 /// [`Interp::read_field_key`], with an inline cache in front of it.
8955 ///
8956 /// Only own *data* properties of ordinary objects are cached. Everything else — a
8957 /// prototype hit, a getter, a proxy, a string primitive, a missing property — goes
8958 /// straight through, because those are the cases whose answer depends on more than "the
8959 /// object and the name", and caching them would need the shape machinery this engine
8960 /// deliberately does not have.
8961 ///
8962 /// A hit is re-validated: the object must still be the same one (weakly, so a collected
8963 /// and reallocated object is a miss, not a wrong answer) and the property table must
8964 /// still have this key at this index as a plain value.
8965 pub fn read_field_cached(
8966 &mut self,
8967 object: &Value,
8968 key: &PropertyKey,
8969 slot: usize,
8970 ) -> JsResult<Value> {
8971 let index = Self::field_cache_slot(object, key, slot);
8972 let Value::Object(target) = object else {
8973 return self.read_field_key(object, key);
8974 };
8975 if target.proxy_state().is_some() {
8976 return self.read_field_key(object, key);
8977 }
8978 if let Some(cached) = &self.field_cache[index]
8979 && target.upgrades_to(&cached.object)
8980 && cached.key == *key
8981 && let Some(value) = target.cached_data_property(cached.index, key)
8982 {
8983 return Ok(value);
8984 }
8985 let value = self.read_field_key(object, key)?;
8986 // Only a successful own-data lookup is worth remembering. `own_property_index`
8987 // declines an accessor, which is exactly the case that must not be cached.
8988 if let Some((found, _)) = target.own_property_index(key) {
8989 self.field_cache[index] = Some(FieldCache {
8990 object: target.downgrade(),
8991 key: key.clone(),
8992 index: found,
8993 });
8994 }
8995 Ok(value)
8996 }
8997
8998 /// Which cache slot a lookup uses.
8999 ///
9000 /// Mixes the object's address, the name and the site, so that two properties of one
9001 /// object, and one property of two objects, land in different slots — which is what lets
9002 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
9003 /// other iteration.
9004 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
9005 let mut hash = match object {
9006 Value::Object(object) => object.address(),
9007 _ => 0,
9008 };
9009 hash = hash
9010 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
9011 .rotate_left(17)
9012 .wrapping_add(key.hash_code());
9013 hash = hash.wrapping_add(site.wrapping_mul(31));
9014 // The table is a power of two, so the low bits are the slot.
9015 hash & (FIELD_CACHE_SLOTS - 1)
9016 }
9017
9018 /// Read `key` from `object`, without the inline cache.
9019 ///
9020 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
9021 /// prototype chain, while the cached form answers an own data property from memory.
9022 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
9023 let text = key.as_str().unwrap_or("");
9024 let Value::Object(object) = object else {
9025 // Reading a property of `undefined`/`null` is the classic TypeError.
9026 if object.is_nullish() {
9027 return Err(Signal::Throw(self.make_error(
9028 "TypeError",
9029 &format!("cannot read property '{key}' of {}", object.to_js_string()),
9030 )));
9031 }
9032 // A string has `length` and index access without being boxed.
9033 if let Value::String(value) = object {
9034 if text == "length" {
9035 return Ok(Value::Int(value.utf16_len() as i32));
9036 }
9037 if let Some(index) = array_index(text) {
9038 return Ok(match value.wtf8().unit_at(index as usize) {
9039 Some(unit) => self.string_wtf8(unit),
9040 None => Value::Undefined,
9041 });
9042 }
9043 }
9044 // A property of a primitive is looked up on its prototype: this is what
9045 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
9046 let prototype = match object {
9047 Value::String(_) => self.realm.string_proto.clone(),
9048 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
9049 Value::Bool(_) => self.realm.boolean_proto.clone(),
9050 // A symbol's methods live on `Symbol.prototype`, reached the same way —
9051 // `sym.description` reads through the prototype, not off the symbol.
9052 Value::Symbol(_) => self.realm.symbol_proto.clone(),
9053 // …and a bigint's on `BigInt.prototype`, which is how
9054 // `(255n).toString(16)` reaches its method.
9055 Value::BigInt(_) => self.realm.bigint_proto.clone(),
9056 _ => None,
9057 };
9058 if let Some(prototype) = prototype
9059 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
9060 {
9061 return Ok(value);
9062 }
9063 return Ok(Value::Undefined);
9064 };
9065 Ok(self
9066 .get_property_key(object, key)?
9067 .unwrap_or(Value::Undefined))
9068 }
9069
9070 /// The `#name` a private symbol stands for, for error messages.
9071 ///
9072 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
9073 /// was made from.
9074 fn private_name(symbol: &Value) -> Option<String> {
9075 match symbol {
9076 Value::Symbol(symbol) if symbol.is_private() => Some(
9077 symbol
9078 .description()
9079 .map(|text| text.to_string())
9080 .unwrap_or_default(),
9081 ),
9082 _ => None,
9083 }
9084 }
9085
9086 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
9087 ///
9088 /// Every private-field opcode takes the symbol the class stored in its own scope; a
9089 /// non-symbol here would be a compiler bug, and the reference guards it with
9090 /// `JS_ThrowTypeErrorNotASymbol`.
9091 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
9092 match symbol {
9093 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
9094 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
9095 }
9096 }
9097
9098 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
9099 ///
9100 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
9101 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
9102 /// would hit if the parser did not reject it first.
9103 fn define_private_field(
9104 &mut self,
9105 object: &Value,
9106 symbol: &Value,
9107 value: Value,
9108 ) -> JsResult<()> {
9109 let key = self.private_key(symbol)?;
9110 let Some(target) = object.as_object() else {
9111 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9112 };
9113 if !target.is_extensible() {
9114 return Err(Signal::Throw(
9115 self.make_error("TypeError", "object is not extensible"),
9116 ));
9117 }
9118 if target.own_property_key(&key).is_some() {
9119 let name = Self::private_name(symbol).unwrap_or_default();
9120 return Err(Signal::Throw(self.make_error(
9121 "TypeError",
9122 &format!("private class field '{name}' already exists"),
9123 )));
9124 }
9125 target.define_data_key(&key, value);
9126 Ok(())
9127 }
9128
9129 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
9130 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
9131 let key = self.private_key(symbol)?;
9132 let Some(target) = object.as_object() else {
9133 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9134 };
9135 match target.own_property_key(&key) {
9136 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
9137 None => {
9138 let name = Self::private_name(symbol).unwrap_or_default();
9139 Err(Signal::Throw(self.make_error(
9140 "TypeError",
9141 &format!("private class field '{name}' does not exist"),
9142 )))
9143 }
9144 }
9145 }
9146
9147 /// `JS_SetPrivateField`: the store half of the same rule.
9148 fn write_private_field(
9149 &mut self,
9150 object: &Value,
9151 symbol: &Value,
9152 value: Value,
9153 ) -> JsResult<()> {
9154 let key = self.private_key(symbol)?;
9155 let Some(target) = object.as_object() else {
9156 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9157 };
9158 if target.write_value_key(&key, value) {
9159 return Ok(());
9160 }
9161 let name = Self::private_name(symbol).unwrap_or_default();
9162 Err(Signal::Throw(self.make_error(
9163 "TypeError",
9164 &format!("private class field '{name}' does not exist"),
9165 )))
9166 }
9167
9168 /// The `in` half: does `object` have this private field?
9169 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
9170 ///
9171 /// The symbol is created once per class — the first `add_brand` on a given home object
9172 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
9173 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
9174 /// emit for the *instance* brand passes null because all it wants is the symbol.
9175 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
9176 let Some(home_object) = home.as_object() else {
9177 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9178 };
9179 let symbol = match home_object.private_brand() {
9180 Some(symbol) => symbol,
9181 None => {
9182 let symbol = Gc::new(
9183 self.heap,
9184 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
9185 );
9186 home_object.set_private_brand(symbol.clone());
9187 symbol
9188 }
9189 };
9190 let Some(target) = object.as_object() else {
9191 // Not an object: nothing to brand. The reference does the same, and `undefined`
9192 // here would otherwise turn a field initialiser into a TypeError.
9193 return Ok(());
9194 };
9195 if !target.is_extensible() {
9196 return Err(Signal::Throw(
9197 self.make_error("TypeError", "object is not extensible"),
9198 ));
9199 }
9200 if target.carries_brand(&symbol) {
9201 return Err(Signal::Throw(
9202 self.make_error("TypeError", "private method is already present"),
9203 ));
9204 }
9205 target.add_brand(symbol);
9206 Ok(())
9207 }
9208
9209 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
9210 ///
9211 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
9212 /// decides whether to throw.
9213 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
9214 let Some(function) = function.as_object() else {
9215 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9216 };
9217 let Some(home) = function.home_object() else {
9218 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9219 };
9220 let Some(brand) = home.private_brand() else {
9221 return Err(Signal::Throw(
9222 self.make_error("TypeError", "expecting <brand> private field"),
9223 ));
9224 };
9225 Ok(object.carries_brand(&brand))
9226 }
9227
9228 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
9229 let Value::Object(object) = object else {
9230 return Err(Signal::Throw(self.make_error(
9231 "TypeError",
9232 &format!("cannot set property '{key}' of {}", object.to_js_string()),
9233 )));
9234 };
9235 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
9236 let on_failure = if self.frame().code.code.strict {
9237 DeleteFailure::Throw
9238 } else {
9239 DeleteFailure::Ignore
9240 };
9241 self.set_property_with_key(object, key, value, on_failure)
9242 }
9243
9244 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
9245 ///
9246 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
9247 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
9248 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
9249 /// `Number.parseInt(sym)` — so those callers use this instead.
9250 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
9251 if matches!(value, Value::Symbol(_)) {
9252 return Err(Signal::Throw(
9253 self.make_error("TypeError", "cannot convert symbol to string"),
9254 ));
9255 }
9256 // An object runs `ToPrimitive` first, which may itself produce a symbol —
9257 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
9258 let value = self.to_primitive(value.clone(), Hint::String)?;
9259 if matches!(value, Value::Symbol(_)) {
9260 return Err(Signal::Throw(
9261 self.make_error("TypeError", "cannot convert symbol to string"),
9262 ));
9263 }
9264 Ok(value.to_js_string())
9265 }
9266
9267 /// `ToPropertyKey` for a builtin that takes a key argument.
9268 ///
9269 /// Fallible: a key whose `toString` throws has to propagate that error, both for
9270 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
9271 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
9272 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
9273 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
9274 self.propkey(value)
9275 }
9276
9277 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
9278 ///
9279 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
9280 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
9281 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
9282 /// `RangeError` — and why this cannot be a plain `ToNumber`.
9283 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
9284 let number = match value {
9285 Value::Int(number) => *number as f64,
9286 Value::Float(number) => *number,
9287 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
9288 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
9289 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
9290 // reference answers 0.
9291 Value::Null | Value::Bool(_) => value.to_number(),
9292 _ => {
9293 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
9294 match primitive {
9295 Value::Int(number) => number as f64,
9296 Value::Float(number) => number,
9297 other => {
9298 // `ToString` then `ToNumber`, so a string length goes through the
9299 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
9300 // `Value::to_number` on the string already implements exactly that.
9301 let text = self.to_js_string(&other)?;
9302 crate::value::string_to_number(&text)
9303 }
9304 }
9305 }
9306 };
9307 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
9308 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
9309 // is a `RangeError`, not `0`.
9310 if !number.is_finite()
9311 || number.fract() != 0.0
9312 || !(0.0..=u32::MAX as f64).contains(&number)
9313 {
9314 return Err(self.range_error("invalid array length"));
9315 }
9316 Ok(number as u32)
9317 }
9318
9319 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
9320 /// `Object.getOwnPropertySymbols` put in their result array.
9321 pub fn key_value(&self, key: &PropertyKey) -> Value {
9322 match key {
9323 PropertyKey::String(text) => self.string_wtf8(text.clone()),
9324 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9325 }
9326 }
9327
9328 /// Fill in a String exotic object: `_value`, `length` and the index properties.
9329 ///
9330 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
9331 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
9332 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
9333 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
9334 /// the two paths had drifted; this is the one both now use.
9335 ///
9336 /// The indices are *code units*, so an astral character occupies two of them — the
9337 /// same rule `s.length` and `s[i]` follow.
9338 /// Give an already-created object the internal slot that makes it a wrapper of
9339 /// `value`, so the primitive's prototype methods work on it.
9340 ///
9341 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
9342 /// which are wrappers of their own type holding the empty value.
9343 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
9344 self.internal_set(object, "_value", value);
9345 }
9346
9347 pub(crate) fn init_string_wrapper(
9348 &mut self,
9349 object: &Gc<JsObject>,
9350 text: &Gc<crate::value::JsString>,
9351 ) {
9352 object.define(
9353 "length",
9354 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
9355 );
9356 for index in 0..text.utf16_len() {
9357 if let Some(unit) = text.wtf8().unit_at(index) {
9358 object.define(
9359 &index.to_string(),
9360 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
9361 Property::with_attributes(self.string_wtf8(unit), false, true),
9362 );
9363 }
9364 }
9365 object.define_key(
9366 &self.internal_slot("_value"),
9367 Property::with_attributes(Value::String(text.clone()), false, false),
9368 );
9369 }
9370
9371 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
9372 ///
9373 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
9374 /// throws. The wrapper carries its primitive in `_value` — the same slot
9375 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
9376 /// on a boxed value no constructor ever built.
9377 pub(crate) fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
9378 let (prototype, primitive) = match value {
9379 Value::Object(object) => return Ok(object.clone()),
9380 Value::String(text) => {
9381 let object = self.new_object(self.realm.string_proto.clone());
9382 self.init_string_wrapper(&object, text);
9383 return Ok(object);
9384 }
9385 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
9386 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
9387 // A symbol and a bigint box into wrappers whose methods live on
9388 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
9389 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
9390 // branch below instead produced an object with *no* prototype, so those
9391 // methods were unreachable on a box.
9392 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
9393 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
9394 Value::Undefined | Value::Null => {
9395 return Err(Signal::Throw(self.make_error(
9396 "TypeError",
9397 &format!("cannot convert {} to object", value.to_js_string()),
9398 )));
9399 }
9400 _ => (None, value.clone()),
9401 };
9402 let object = self.new_object(prototype);
9403 self.internal_set(&object, "_value", primitive);
9404 Ok(object)
9405 }
9406
9407 /// `a == b`, the coercing comparison.
9408 ///
9409 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
9410 /// which is what makes `[] == ""` true: `[]` becomes `""` via
9411 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
9412 /// because the conversion is allowed to call script code, so the two primitive
9413 /// operands are handed back to it.
9414 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
9415 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
9416 return Ok(left.loose_equals(&right));
9417 }
9418 // `null == undefined` holds even though neither is an object.
9419 if matches!(left, Value::Undefined | Value::Null)
9420 && matches!(right, Value::Undefined | Value::Null)
9421 {
9422 return Ok(true);
9423 }
9424 if matches!(left, Value::Undefined | Value::Null)
9425 || matches!(right, Value::Undefined | Value::Null)
9426 {
9427 return Ok(false);
9428 }
9429 // Two objects compare by identity. Only an object *against a primitive* is
9430 // converted, which is why `{} == {}` is false while `[] == ""` is true.
9431 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
9432 return Ok(a.ptr_eq(b));
9433 }
9434 let left = self.to_primitive(left, Hint::Default)?;
9435 let right = self.to_primitive(right, Hint::Default)?;
9436 Ok(left.loose_equals(&right))
9437 }
9438
9439 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
9440 let Value::Object(object) = object else {
9441 return Err(Signal::Throw(
9442 self.make_error("TypeError", "cannot use 'in' on a non-object"),
9443 ));
9444 };
9445 let key = self.propkey(key)?;
9446 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
9447 // trap. One implementation, so an array's derived `length` and its inherited holes
9448 // cannot be right in one caller and wrong in another.
9449 self.has_own_or_inherited(object, &key)
9450 }
9451
9452 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
9453 let Value::Object(target) = object else {
9454 return Ok(false);
9455 };
9456 let Value::Object(function) = constructor else {
9457 return Err(Signal::Throw(self.make_error(
9458 "TypeError",
9459 "right-hand side of 'instanceof' is not callable",
9460 )));
9461 };
9462 let prototype = self.get_property(function, "prototype")?;
9463 let Some(Value::Object(prototype)) = prototype else {
9464 return Ok(false);
9465 };
9466 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
9467 // which is also what makes `proxyOfInstance instanceof C` work.
9468 let mut current = Some(target.clone());
9469 while let Some(object) = current {
9470 if object.ptr_eq(&prototype) {
9471 return Ok(true);
9472 }
9473 current = self.object_prototype_of(&object)?;
9474 }
9475 Ok(false)
9476 }
9477
9478 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
9479 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
9480 if let Some(proto) = self.proxy_get_prototype_of(object)? {
9481 return Ok(proto);
9482 }
9483 Ok(object.proto())
9484 }
9485
9486 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
9487 pub fn object_set_prototype_of(
9488 &mut self,
9489 object: &Gc<JsObject>,
9490 proto: Option<Gc<JsObject>>,
9491 ) -> JsResult<bool> {
9492 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
9493 return Ok(answer);
9494 }
9495 object.set_proto(proto);
9496 Ok(true)
9497 }
9498
9499 /// `[[IsExtensible]]`, with the proxy trap when there is one.
9500 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
9501 if let Some(answer) = self.proxy_is_extensible(object)? {
9502 return Ok(answer);
9503 }
9504 Ok(object.is_extensible())
9505 }
9506
9507 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
9508 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
9509 if let Some(answer) = self.proxy_prevent_extensions(object)? {
9510 return Ok(answer);
9511 }
9512 object.set_extensible(false);
9513 Ok(true)
9514 }
9515
9516 fn copy_properties(
9517 &mut self,
9518 target: &Value,
9519 source: &Value,
9520 exclusion: &Value,
9521 ) -> JsResult<()> {
9522 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
9523 // does contribute: its index properties are own, enumerable and writable, which
9524 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
9525 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
9526 // is a no-op.
9527 let Some(target) = target.as_object() else {
9528 return Ok(());
9529 };
9530 let source_object = match source {
9531 Value::Object(object) => object.clone(),
9532 Value::String(text) => {
9533 // Untaken keys are the string's indices, which are code units.
9534 for index in 0..text.utf16_len() {
9535 if let Some(unit) = text.wtf8().unit_at(index) {
9536 target.define_data(&index.to_string(), self.string_wtf8(unit));
9537 }
9538 }
9539 return Ok(());
9540 }
9541 _ => return Ok(()),
9542 };
9543 // An object *rest* element passes the keys already taken by the literal part as
9544 // an array of strings; a spread passes `null`, which excludes nothing. Only the
9545 // string keys of the exclusion array are meaningful, so an array is read by its
9546 // elements rather than by its own property names.
9547 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
9548 if let Value::Object(list) = exclusion
9549 && let Some(length) = list.array_length()
9550 {
9551 for index in 0..length {
9552 if let Some(value) = list.array_get(index) {
9553 excluded.push(self.propkey_of(&value)?);
9554 }
9555 }
9556 }
9557 let source = &source_object;
9558 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
9559 // Reading the property table directly made every spread of a proxy empty.
9560 let keys = self.object_own_property_keys(source)?;
9561 for as_key in keys {
9562 if as_key.is_symbol() {
9563 // A spread copies string-keyed properties only.
9564 continue;
9565 }
9566 if excluded.contains(&crate::value::Wtf8::new(
9567 as_key.as_str().unwrap_or_default(),
9568 )) {
9569 continue;
9570 }
9571 let enumerable = self
9572 .object_get_own_property(source, &as_key)?
9573 .is_some_and(|property| property.enumerable);
9574 if !enumerable {
9575 continue;
9576 }
9577 let value = self
9578 .get_property_key(source, &as_key)?
9579 .unwrap_or(Value::Undefined);
9580 target.define_data_key(&as_key, value);
9581 }
9582 Ok(())
9583 }
9584
9585 // -- iteration ---------------------------------------------------------
9586
9587 /// One object's own keys in enumeration order: array indices ascending, then the
9588 /// rest in insertion order.
9589 ///
9590 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
9591 /// whether the key is enumerable, which the caller resolves per key because an
9592 /// array's elements are not in the same store as its named properties.
9593 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
9594 // An index can arrive twice, once from the array's element store and once from
9595 // its property map, so the numeric keys go through a map that keeps the
9596 // enumerable answer if either source gave one.
9597 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
9598 for (key, enumerable) in &own {
9599 if let Some(index) = key.as_str().and_then(array_index) {
9600 let entry = numeric.entry(index).or_insert(false);
9601 *entry = *entry || *enumerable;
9602 }
9603 }
9604 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
9605 .into_iter()
9606 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
9607 .collect();
9608 ordered.extend(
9609 own.into_iter()
9610 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
9611 );
9612 ordered
9613 }
9614
9615 /// Build the key list a `for-in` loop walks.
9616 ///
9617 /// The order is the specification's: own properties before inherited ones, and
9618 /// within one object the integer-like keys in ascending numeric order ahead of the
9619 /// string keys in insertion order. A shadowed key only appears once, and a key that
9620 /// is a non-enumerable own property anywhere nearer is skipped entirely.
9621 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
9622 let record = self.new_object(None);
9623 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
9624 // A proxy supplies its own key list, and — the reason this is not just another
9625 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
9626 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
9627 // descriptor there.
9628 if let Value::Object(object) = value
9629 && object.proxy_state().is_some()
9630 {
9631 let own = self
9632 .proxy_own_keys(object)?
9633 .unwrap_or_else(|| object.own_property_keys());
9634 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
9635 let mut numeric: Vec<u32> = Vec::new();
9636 let mut rest: Vec<PropertyKey> = Vec::new();
9637 for key in own {
9638 match key.as_str().and_then(array_index) {
9639 Some(index) => numeric.push(index),
9640 None => rest.push(key),
9641 }
9642 }
9643 numeric.sort_unstable();
9644 ordered.extend(
9645 numeric
9646 .into_iter()
9647 .map(|index| PropertyKey::from(index.to_string())),
9648 );
9649 ordered.extend(rest);
9650 for (index, key) in ordered.into_iter().enumerate() {
9651 record.define_data(&index.to_string(), self.key_value(&key));
9652 }
9653 record.define_data("__index", Value::Int(0));
9654 // The mark that makes `for_in_advance` re-ask the proxy per key.
9655 record.define_data("__proxy", Value::Object(object.clone()));
9656 return Ok(record);
9657 }
9658 if let Value::Object(object) = value {
9659 let mut chain = vec![object.clone()];
9660 chain.extend(object.chain());
9661 // Every own string key the walk has seen, enumerable or not. A
9662 // non-enumerable own property still hides a same-named enumerable one
9663 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
9664 // keeps `x` out of the loop even when the prototype has one.
9665 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
9666 for object in chain {
9667 let mut own: Vec<(crate::value::Wtf8, bool)> = object
9668 .own_property_keys()
9669 .iter()
9670 .filter_map(|key| key.as_wtf8().cloned())
9671 .map(|key| {
9672 let enumerable = object
9673 .own_property(&key.to_string_lossy())
9674 .map(|property| property.enumerable)
9675 .unwrap_or(false);
9676 (key, enumerable)
9677 })
9678 .collect();
9679 if let Some(length) = object.array_length() {
9680 own.retain(|(key, _)| key.as_str() != Some("length"));
9681 for index in 0..length {
9682 if object.array_get(index).is_some() {
9683 own.push((crate::value::Wtf8::new(index.to_string()), true));
9684 }
9685 }
9686 }
9687 // Integer-like keys come first in ascending order, then the rest in
9688 // insertion order — and the ordering is *per object*, not for the chain
9689 // as a whole: one pass over every collected key lifted a prototype's
9690 // `"4"` above the target's own `x`/`y`, which is not the order
9691 // `for…in` reports.
9692 for (key, enumerable) in Self::order_own_keys(own) {
9693 if visited.contains(&key) {
9694 continue;
9695 }
9696 visited.push(key.clone());
9697 if enumerable {
9698 keys.push(key);
9699 }
9700 }
9701 }
9702 }
9703 for (index, key) in keys.into_iter().enumerate() {
9704 record.define_data(&index.to_string(), self.string_wtf8(key));
9705 }
9706 record.define_data("__index", Value::Int(0));
9707 Ok(record)
9708 }
9709
9710 /// The next key of a `for…in` record, `None` when the loop is done.
9711 ///
9712 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
9713 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
9714 /// the loop reaches it, so a handler that stops reporting a key partway through drops
9715 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
9716 /// key the handler had already withdrawn.
9717 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
9718 let Value::Object(record) = record else {
9719 return Ok(None);
9720 };
9721 let proxy = record
9722 .own_property("__proxy")
9723 .and_then(|property| property.value);
9724 loop {
9725 let index = record
9726 .own_property("__index")
9727 .and_then(|property| property.value)
9728 .map(|value| value.to_int32())
9729 .unwrap_or(0);
9730 let Some(candidate) = record
9731 .own_property(&index.to_string())
9732 .and_then(|property| property.value)
9733 else {
9734 return Ok(None);
9735 };
9736 record.define_data("__index", Value::Int(index + 1));
9737 let text = candidate.to_js_string();
9738 let Some(Value::Object(proxy)) = &proxy else {
9739 return Ok(Some(text));
9740 };
9741 // The candidate is already a key string here, so the lookup does not need a
9742 // second `ToPropertyKey` conversion.
9743 let key = PropertyKey::from(text.as_str());
9744 let live = match self.proxy_get_own_property(proxy, &key)? {
9745 Some(descriptor) => descriptor,
9746 // Not a proxy after all, or it lost its state: fall back to the target.
9747 None => proxy.own_property_key(&key),
9748 };
9749 if live.is_some_and(|property| property.enumerable) {
9750 return Ok(Some(text));
9751 }
9752 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
9753 // next one.
9754 }
9755 }
9756
9757 /// The iterator for `for-of`: the object and its `next` method.
9758 ///
9759 /// An object that already carries a `next` method is used as it is — that is what
9760 /// `arr.values()` returns — and only arrays and strings get the built-in
9761 /// sequence iterator.
9762 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
9763 ///
9764 /// Callers that must choose between the iterable and the array-like protocol — the
9765 /// typed-array constructor is the main one — need to ask *before* committing to one.
9766 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
9767 let key = self.realm.well_known_key(WellKnown::Iterator);
9768 let method = self.read_field_key(value, &key)?;
9769 if matches!(method, Value::Undefined | Value::Null) {
9770 return Ok(false);
9771 }
9772 if !matches!(&method, Value::Object(object) if object.is_callable()) {
9773 return Err(Signal::Throw(
9774 self.make_error("TypeError", "Symbol.iterator is not callable"),
9775 ));
9776 }
9777 Ok(true)
9778 }
9779
9780 /// Collect everything an iterable yields, closing it if the walk is abandoned.
9781 ///
9782 /// The cap is a guard against a generator that never ends: an unbounded collect would
9783 /// be an out-of-memory abort rather than a catchable error.
9784 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
9785 const MAX_ITEMS: usize = 1 << 24;
9786 let iterator = self.get_iterator(value)?;
9787 let mut out = Vec::new();
9788 loop {
9789 let (element, done) = self.iterator_step(&iterator)?;
9790 if done {
9791 return Ok(out);
9792 }
9793 out.push(element);
9794 if out.len() > MAX_ITEMS {
9795 return Err(self.range_error("iterable is too long to collect"));
9796 }
9797 }
9798 }
9799
9800 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
9801 ///
9802 /// A native constructor calls this once it has validated its arguments, which is the
9803 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
9804 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
9805 /// never reached. The prototype comes from `new.target` when it is an object, and from
9806 /// `default_proto` otherwise.
9807 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
9808 let Some(target) = self.pending_new_target.clone() else {
9809 return Ok(self.new_object(Some(default_proto)));
9810 };
9811 let Some(target) = target.as_object().cloned() else {
9812 return Ok(self.new_object(Some(default_proto)));
9813 };
9814 let proto = match self.get_property(&target, "prototype")? {
9815 Some(Value::Object(proto)) => proto,
9816 _ => default_proto,
9817 };
9818 Ok(self.new_object(Some(proto)))
9819 }
9820
9821 /// Whether this call is a construction, i.e. `new.target` is defined.
9822 ///
9823 /// A native constructor receives `this = undefined` (it builds its own instance), so it
9824 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
9825 /// The native function currently executing, if any.
9826 pub fn current_native(&self) -> Option<Gc<JsObject>> {
9827 self.current_native.clone()
9828 }
9829
9830 /// Whether this call is a construction, i.e. `new.target` is defined.
9831 pub fn is_constructing(&self) -> bool {
9832 self.pending_new_target.is_some()
9833 }
9834
9835 /// The `TypeError` a constructor too primitive to have a wrapper raises.
9836 ///
9837 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
9838 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
9839 /// happens inside the native function, which is why the trace carries an
9840 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
9841 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
9842 /// constructor`, and an unnamed one reports the leading space of `" is not a
9843 /// constructor"` because the reference formats the empty name as it is.
9844 ///
9845 /// It is also the answer for a `new.target` that cannot be named at all — not a
9846 /// function, or a throwing `name` getter — where the reference falls back to the bare
9847 /// `not a constructor`.
9848 pub fn not_a_constructor_error(&mut self) -> Signal {
9849 let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
9850 self.not_a_constructor_error_for(target)
9851 }
9852
9853 /// The same `TypeError` for an explicit target, for the callers that check
9854 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
9855 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
9856 let target = match target {
9857 Value::Object(target) if target.is_callable() => target,
9858 _ => return self.type_error("not a constructor"),
9859 };
9860 let name = match self.get_property(&target, "name") {
9861 Ok(Some(value)) => value.to_js_string(),
9862 _ => return self.type_error("not a constructor"),
9863 };
9864 self.type_error(format!("{name} is not a constructor"))
9865 }
9866
9867 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
9868 ///
9869 /// True whenever `new.target` is not the callee itself, or when it has no usable
9870 /// `prototype` — the cases where reading the property is observable at all.
9871 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
9872 match &self.pending_new_target {
9873 Some(Value::Object(target)) => !target.ptr_eq(callee),
9874 Some(_) => true,
9875 None => false,
9876 }
9877 }
9878
9879 /// The symbol key for one of the engine's own hidden slots.
9880 ///
9881 /// Cached on the realm, so every object of a kind shares one key and a slot can be
9882 /// read back by name.
9883 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
9884 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
9885 return PropertyKey::Symbol(symbol.clone());
9886 }
9887 let symbol = Gc::new(
9888 self.heap,
9889 crate::value::JsSymbol::new(Some(name.to_string())),
9890 );
9891 self.realm
9892 .internal_slots
9893 .borrow_mut()
9894 .insert(name, Value::Symbol(symbol.clone()));
9895 PropertyKey::Symbol(symbol)
9896 }
9897
9898 /// Read a hidden slot, or `None` when the object has none of that name.
9899 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
9900 let slots = self.realm.internal_slots.borrow();
9901 let Value::Symbol(symbol) = slots.get(name)? else {
9902 return None;
9903 };
9904 object
9905 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
9906 .and_then(|property| property.value)
9907 }
9908
9909 /// Define a hidden slot.
9910 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
9911 let key = self.internal_slot(name);
9912 object.define_key(&key, Property::with_attributes(value, false, false));
9913 }
9914
9915 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
9916 ///
9917 /// The method is looked up on the value (through its prototype), called with no
9918 /// arguments, and its result becomes the iterator. A generator gets here through
9919 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
9920 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
9921 ///
9922 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
9923 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
9924 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
9925 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
9926 /// does, and a user-defined iterable works without a special case.
9927 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
9928 /// `Symbol.iterator`.
9929 ///
9930 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
9931 /// iterable is legal there, and each value it produces is simply already settled by
9932 /// the time the `await` around it runs.
9933 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
9934 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
9935 let method = self.read_field_key(value, &async_key)?;
9936 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
9937 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
9938 // is *present but not callable* is a TypeError — it does not mean "try the other
9939 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
9940 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
9941 // guard is there to catch.
9942 let absent = matches!(method, Value::Undefined | Value::Null);
9943 if !absent {
9944 let Value::Object(object) = &method else {
9945 return Err(Signal::Throw(
9946 self.make_error("TypeError", "value is not iterable"),
9947 ));
9948 };
9949 if !object.is_callable() {
9950 return Err(Signal::Throw(
9951 self.make_error("TypeError", "value is not iterable"),
9952 ));
9953 }
9954 }
9955 if absent {
9956 return self.get_iterator(value);
9957 }
9958 let iterator = self.call_value(method, value.clone(), Vec::new())?;
9959 if !matches!(iterator, Value::Object(_)) {
9960 return Err(Signal::Throw(
9961 self.make_error("TypeError", "iterator is not an object"),
9962 ));
9963 }
9964 let next = self.read_field(&iterator, "next")?;
9965 Ok(Iterator {
9966 object: iterator,
9967 next,
9968 })
9969 }
9970
9971 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
9972 let key = self.realm.well_known_key(WellKnown::Iterator);
9973 let method = self.read_field_key(value, &key)?;
9974 let Value::Object(function) = &method else {
9975 return Err(Signal::Throw(self.make_error(
9976 "TypeError",
9977 &format!("{} is not iterable", value.to_js_string()),
9978 )));
9979 };
9980 if !function.is_callable() {
9981 return Err(Signal::Throw(self.make_error(
9982 "TypeError",
9983 &format!("{} is not iterable", value.to_js_string()),
9984 )));
9985 }
9986 let iterator = self.call_value(method, value.clone(), Vec::new())?;
9987 // The spec requires an object here; a primitive iterator has no `next` to call
9988 // and would fail one step later with a confusing message.
9989 if !matches!(iterator, Value::Object(_)) {
9990 return Err(Signal::Throw(
9991 self.make_error("TypeError", "iterator is not an object"),
9992 ));
9993 }
9994 let next = self.read_field(&iterator, "next")?;
9995 Ok(Iterator {
9996 object: iterator,
9997 next,
9998 })
9999 }
10000
10001 /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
10002 /// not iterable.
10003 ///
10004 /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
10005 /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
10006 /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
10007 /// was `[]`.
10008 pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
10009 let key = self.realm.well_known_key(WellKnown::Iterator);
10010 let method = self.read_field_key(value, &key)?;
10011 if !matches!(&method, Value::Object(object) if object.is_callable()) {
10012 return Ok(None);
10013 }
10014 let iterator = self.get_iterator(value)?;
10015 let mut out = Vec::new();
10016 loop {
10017 let (element, done) = self.iterator_step(&iterator)?;
10018 if done {
10019 return Ok(Some(out));
10020 }
10021 out.push(element);
10022 }
10023 }
10024
10025 /// One step of an internal iterator: the value and whether it is exhausted.
10026 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
10027 // A real iterator (`next` is a function) answers with a result object.
10028 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
10029 let result =
10030 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
10031 let Some(result) = result.as_object().cloned() else {
10032 return Err(self.type_error("iterator result is not an object"));
10033 };
10034 let done = self
10035 .get_property(&result, "done")?
10036 .is_some_and(|value| value.to_boolean());
10037 let value = self
10038 .get_property(&result, "value")?
10039 .unwrap_or(Value::Undefined);
10040 return Ok((value, done));
10041 }
10042 // An iterator whose `next` is not callable is treated as exhausted, which is
10043 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
10044 // that are not iterable at all.
10045 Ok((Value::Undefined, true))
10046 }
10047
10048 /// `[...iterable]`: append everything the iterator yields, and answer the next
10049 /// index.
10050 ///
10051 /// This goes through the same iterator machinery `for-of` uses rather than copying
10052 /// an array's elements, because a spread source is any iterable: a string spreads
10053 /// into its characters and an array iterator spreads into its results. Handling
10054 /// only arrays made `[..."ab"]` come out empty with no error at all.
10055 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
10056 let Some(target) = array.as_object().cloned() else {
10057 return Ok(0);
10058 };
10059 let start = target.array_length().unwrap_or(0);
10060 let mut added = 0;
10061 let iterator = self.get_iterator(iterable)?;
10062 loop {
10063 let (value, done) = self.iterator_step(&iterator)?;
10064 if done {
10065 break;
10066 }
10067 target.array_set(self.heap, start + added, value);
10068 added += 1;
10069 }
10070 Ok((start + added) as i32)
10071 }
10072
10073 /// How an uncaught exception is reported.
10074 ///
10075 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
10076 /// with `ToString` — `js_std_dump_error` is three lines that end in
10077 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
10078 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
10079 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
10080 ///
10081 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
10082 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
10083 /// `toString`"; it does call it, but only for objects of a class it does not know how
10084 /// to walk, and never for errors, arrays or plain objects.
10085 ///
10086 /// A printer that fails must not take the reporter down with it, so that case falls
10087 /// back to the `ToString` rendering.
10088 pub fn describe_exception(&mut self, value: &Value) -> String {
10089 match crate::print::sprint(self, value) {
10090 Ok(text) => text,
10091 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
10092 }
10093 }
10094
10095 /// The file name of whatever is running, innermost frame first.
10096 ///
10097 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
10098 /// innermost frame's file name, without distinguishing a module body from a plain
10099 /// script. `import()` uses it as the base for a relative specifier, which is why
10100 /// `import('./x.js')` inside a script resolves next to the script and not next to the
10101 /// process's working directory.
10102 pub fn script_or_module_name(&self) -> Option<String> {
10103 self.frames
10104 .iter()
10105 .rev()
10106 .find_map(|frame| frame.code.code.filename.clone())
10107 }
10108
10109 /// The current call stack, formatted the way `qjs` prints `error.stack`.
10110 ///
10111 /// One ` at name (file:line:col)` line per active frame, innermost first. The
10112 /// position is the one recorded for the instruction each frame is stopped on, which
10113 /// is why the compiler builds a pc-to-position table per function: without it a
10114 /// trace could only name the function, not the line inside it.
10115 ///
10116 /// A frame whose code has no positions prints just `(file)`, matching the
10117 /// reference's output for stripped bytecode.
10118 pub fn stack_trace(&self) -> String {
10119 self.stack_trace_skipping(0)
10120 }
10121
10122 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
10123 fn stack_trace_skipping(&self, skip: usize) -> String {
10124 // One ordered list, innermost first, so `skip` counts the same thing whether the
10125 // frames it leaves out are native or bytecode. Indices rather than references: a
10126 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
10127 let depth = self.frames.len();
10128 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
10129 // A native entered while `at` bytecode frames were live was called *from* the
10130 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
10131 // entered at the current depth are therefore innermost of all.
10132 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
10133 for (index, (_, _, at)) in self.native_frames.iter().enumerate().rev() {
10134 if *at == wanted {
10135 order.push((true, index));
10136 }
10137 }
10138 };
10139 push_natives(&mut order, depth);
10140 for index in (0..depth).rev() {
10141 order.push((false, index));
10142 push_natives(&mut order, index);
10143 }
10144 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
10145 // barrier. Natives entered at exactly the barrier depth are the eval entry point
10146 // itself (`evalScript (native)`), and the reference leaves those out too.
10147 if let Some(barrier) = self.trace_barriers.last().copied() {
10148 order.retain(|(is_native, index)| match is_native {
10149 true => *index == usize::MAX || self.native_frames[*index].2 > barrier,
10150 false => *index >= barrier,
10151 });
10152 }
10153
10154 let mut out = String::new();
10155 for (is_native, index) in order.into_iter().skip(skip) {
10156 match is_native {
10157 true => {
10158 out.push_str(" at ");
10159 out.push_str(&self.native_frames[index].0);
10160 out.push_str(" (native)\n");
10161 }
10162 false => {
10163 let frame = &self.frames[index];
10164 let code = &frame.code.code;
10165 let file = code.filename.as_deref().unwrap_or("<input>");
10166 // The name comes from the function *object*, not from the compiled code:
10167 // an anonymous function expression is named by the property it is stored
10168 // in (`{valueOf: function(){}}`), which only the object knows.
10169 let bound_name = match &frame.callee {
10170 Value::Object(object) => {
10171 object
10172 .own_property("name")
10173 .and_then(|property| match property.value {
10174 Some(Value::String(text)) if !text.wtf8().is_empty() => {
10175 Some(text.to_string_lossy().into_owned())
10176 }
10177 _ => None,
10178 })
10179 }
10180 _ => None,
10181 };
10182 // No callee object means the body was entered by the host, so the
10183 // name has to come from the compiled code. Two cases differ:
10184 //
10185 // * an *unnamed* function of any kind — the reference reads the
10186 // `name` property, finds it empty, and prints `<anonymous>`;
10187 // * a *module* body, which has no `name` property at all: the
10188 // reference builds that function object with `js_closure2` and
10189 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
10190 // so a trace reaching it also prints `<anonymous>` — while a
10191 // *script* body prints `<eval>`, its `name`.
10192 let unnamed = code.name.is_empty() || code.module.is_some();
10193 out.push_str(" at ");
10194 match bound_name.as_deref() {
10195 Some(name) => out.push_str(name),
10196 None if unnamed => out.push_str("<anonymous>"),
10197 None => out.push_str(&code.name),
10198 }
10199 match code.position_at(frame.at as u32) {
10200 Some((line, column)) => {
10201 out.push_str(&format!(" ({file}:{line}:{column})\n"));
10202 }
10203 None => out.push_str(&format!(" ({file})\n")),
10204 }
10205 }
10206 }
10207 }
10208 out
10209 }
10210
10211 /// Give an anonymous function the name of the property it is stored in.
10212 ///
10213 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
10214 /// enumerable and not configurable, and a function that already has a real name
10215 /// keeps it.
10216 ///
10217 /// "Already named" means a *non-empty* name: every function object is created with
10218 /// a `name` of `""` so the property exists on all of them, and treating that empty
10219 /// string as a name left every anonymous function nameless — which is how a stack
10220 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
10221 fn set_function_name(&mut self, function: &Value, name: &str) {
10222 let Value::Object(object) = function else {
10223 return;
10224 };
10225 // `SetFunctionName` applies to *functions* and classes only, and only when they are
10226 // anonymous. Without the callability guard, `{value: someObject}` renamed
10227 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
10228 // on the right-hand side of a property. That is how a `zipKeyed` result object
10229 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
10230 // has no `NamedEvaluation` at all.
10231 if !object.is_callable() {
10232 return;
10233 }
10234 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
10235 && !existing.wtf8().is_empty()
10236 {
10237 return;
10238 }
10239 let text = self.string(name);
10240 object.define("name", Property::name_or_length(text));
10241 }
10242
10243 // -- global declarations -----------------------------------------------
10244
10245 /// Declare a global binding, creating its reference cell.
10246 /// Declare a `var` or function global, whose home is the global object.
10247 ///
10248 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
10249 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
10250 /// such as `print`, or a redeclaration — is left alone.
10251 pub fn declare_var_global(&mut self, name: &str) {
10252 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
10253 // global object is exactly the leak `typeof my_var === "undefined"` after
10254 // `eval("var my_var=2")` rules out.
10255 if let Some(scope) = self.eval_scope.as_mut() {
10256 scope.entry(name.to_string()).or_insert(Value::Undefined);
10257 return;
10258 }
10259 // A sloppy direct eval declares into its *caller's* variable environment. Doing
10260 // this on the global object instead made `eval("var c = 1")` inside a parameter
10261 // list overwrite a global `c`, and made two calls to the same function share one
10262 // binding.
10263 if let Some(cell) = self.declare_eval_local(name) {
10264 cell.set(Value::Undefined);
10265 return;
10266 }
10267 let global = self.realm.global.clone();
10268 if global.own_property(name).is_some() {
10269 return;
10270 }
10271 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
10272 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
10273 // whole point of that trick and what lets `Object.defineProperty` reshape it
10274 // afterwards. `eval_scope` is `Some` while an eval is running.
10275 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
10276 global.define(
10277 name,
10278 Property {
10279 value: Some(Value::Undefined),
10280 writable: true,
10281 enumerable: true,
10282 configurable: from_eval,
10283 ..Property::default()
10284 },
10285 );
10286 }
10287
10288 /// Declare a *lexical* global binding, which starts in its dead zone.
10289 ///
10290 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
10291 /// global object and is created when its initialiser runs.
10292 pub fn declare_global(&mut self, name: &str, is_const: bool) {
10293 if is_const {
10294 self.realm.lexical_consts.insert(name.to_string());
10295 }
10296 if !self.realm.globals.contains_key(name) {
10297 // `Uninitialized` rather than `Undefined`: the binding exists but is not
10298 // readable until its initialiser runs, and that is what `let x` before
10299 // `x = 1` has to observe.
10300 let cell = self.new_cell(Value::Uninitialized);
10301 self.realm.globals.insert(name.to_string(), cell);
10302 self.realm.declared.push(name.to_string());
10303 }
10304 }
10305}
10306
10307/// The bytecode and environment of a function object, if it is a bytecode function.
10308///
10309/// Extracted before a call so no borrow of the object is held across it.
10310fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
10311 function.with(|data| match &data.kind {
10312 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
10313 _ => None,
10314 })
10315}
10316
10317/// A native call target, extracted before the call so no borrow is held.
10318enum NativeCall {
10319 Native(NativeFn),
10320 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
10321 /// not hold that object's `RefCell` borrow.
10322 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
10323 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
10324 Bound {
10325 target: Value,
10326 this: Value,
10327 leading: Vec<Value>,
10328 },
10329 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
10330 Revoker(crate::object::ProxyRef),
10331 /// A promise's `resolve`.
10332 PromiseResolve(Gc<JsObject>),
10333 /// A promise's `reject`.
10334 PromiseReject(Gc<JsObject>),
10335 /// One continuation of an `await`.
10336 AwaitResume {
10337 coroutine: Gc<JsObject>,
10338 promise: Gc<JsObject>,
10339 kind: ResumeKind,
10340 },
10341 /// One element of a `Promise` combinator settling.
10342 CombinatorSettle {
10343 state: Gc<JsObject>,
10344 index: usize,
10345 fulfilled: bool,
10346 },
10347 /// One of `Promise.prototype.finally`'s two shims.
10348 FinallyShim {
10349 callback: Option<Value>,
10350 fulfilled: bool,
10351 },
10352 /// Settle a promise with a fixed outcome.
10353 SettlePromise {
10354 promise: Gc<JsObject>,
10355 value: Value,
10356 rejected: bool,
10357 },
10358 /// Continue an async generator after its `await` settled.
10359 GeneratorResume {
10360 generator: Gc<JsObject>,
10361 promise: Gc<JsObject>,
10362 kind: ResumeKind,
10363 },
10364 /// Read a module namespace's binding out of its cell.
10365 ModuleBinding(Gc<Cell>),
10366 /// Finish a completed async generator's `return(v)` once `v` has settled.
10367 CompletedReturn {
10368 generator: Gc<JsObject>,
10369 promise: Gc<JsObject>,
10370 rejected: bool,
10371 },
10372 /// Answer a pending async-generator method with `{value, done}`.
10373 YieldResult {
10374 generator: Gc<JsObject>,
10375 promise: Gc<JsObject>,
10376 done: bool,
10377 },
10378 /// One step of `AsyncDisposableStack.disposeAsync`.
10379 DisposeStep {
10380 remaining: Gc<JsObject>,
10381 promise: Gc<JsObject>,
10382 error: Value,
10383 rejected: bool,
10384 },
10385}
10386
10387/// What a store does when the object refuses the write.
10388#[derive(Clone, Copy, PartialEq, Eq)]
10389pub enum DeleteFailure {
10390 /// Raise a `TypeError`, which is what strict mode and every built-in does.
10391 Throw,
10392 /// Ignore the write, which is what a sloppy-mode assignment does.
10393 Ignore,
10394}
10395
10396/// Whether `object` is a `Date` instance, by the class tag it carries.
10397///
10398/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
10399/// builtins module depending on the interpreter's conversion order.
10400fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
10401 interp
10402 .internal_get(object, "_class")
10403 .is_some_and(|value| value.to_js_string() == "Date")
10404}
10405
10406/// Which type `ToPrimitive` prefers when it converts an object.
10407#[derive(Clone, Copy, PartialEq, Eq)]
10408pub enum Hint {
10409 /// The default hint, which behaves like [`Hint::Number`].
10410 Default,
10411 /// `Number(obj)` and the arithmetic operators.
10412 Number,
10413 /// `String(obj)` and `ToPropertyKey`.
10414 String,
10415}
10416
10417/// Which table a binding slot indexes, for the messages that name it.
10418#[derive(Clone, Copy)]
10419enum VarSlot {
10420 Loc,
10421 Closure,
10422}
10423
10424/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
10425fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
10426 Ok(this)
10427}
10428
10429/// An internal iterator: the sequence plus a cursor.
10430pub(crate) struct Iterator {
10431 pub(crate) object: Value,
10432 pub(crate) next: Value,
10433}
10434
10435/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
10436/// and plain `a` for a method.
10437///
10438/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
10439/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
10440/// reads `at get a (file:1:2)`.
10441fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
10442 match flags & 3 {
10443 1 => format!("get {key}"),
10444 2 => format!("set {key}"),
10445 _ => key.to_string(),
10446 }
10447}
10448
10449/// Define a method or accessor property, per the `define_method` flag byte.
10450///
10451/// The low two bits pick value/getter/setter and bit 2 marks the property
10452/// enumerable.
10453///
10454/// A getter and a setter arrive as two separate `define_method` instructions, and the
10455/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
10456/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
10457/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
10458/// `JS_DefineProperty`, which leaves the other half alone.
10459fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
10460 let enumerable = flags & 4 != 0;
10461 let kind = flags & 3;
10462 let existing = object.own_property_key(key);
10463 let property = match kind {
10464 1 => Property {
10465 getter: Some(function),
10466 // The setter half, if this literal already defined one.
10467 setter: existing
10468 .filter(Property::is_accessor)
10469 .and_then(|p| p.setter),
10470 enumerable,
10471 configurable: true,
10472 ..Property::default()
10473 },
10474 2 => Property {
10475 getter: existing
10476 .filter(Property::is_accessor)
10477 .and_then(|p| p.getter),
10478 setter: Some(function),
10479 enumerable,
10480 configurable: true,
10481 ..Property::default()
10482 },
10483 _ => Property {
10484 value: Some(function),
10485 writable: true,
10486 enumerable,
10487 configurable: true,
10488 ..Property::default()
10489 },
10490 };
10491 object.define_key(key, property);
10492}
10493
10494// ---------------------------------------------------------------------------
10495// Operand decoding
10496// ---------------------------------------------------------------------------
10497
10498/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
10499///
10500/// Jump operands are resolved to absolute byte offsets here, because the encoding
10501/// stores them relative to the byte after the opcode and every use site would
10502/// otherwise repeat that arithmetic.
10503fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
10504 let op = Opcode::from_u8(*code.get(pc)?)?;
10505 let info = op.info();
10506 let base = pc + 1;
10507 let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
10508 let read_u16 = |offset: usize| -> u32 {
10509 let mut value = 0u32;
10510 for index in 0..2 {
10511 value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
10512 }
10513 value
10514 };
10515 let read_u32 = |offset: usize| -> u32 {
10516 let mut value = 0u32;
10517 for index in 0..4 {
10518 value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
10519 }
10520 value
10521 };
10522 let jump = |offset: usize, width: usize| -> u32 {
10523 let raw = match width {
10524 1 => read_u8(offset) as u8 as i8 as i64,
10525 2 => read_u16(offset) as u16 as i16 as i64,
10526 _ => read_u32(offset) as i32 as i64,
10527 };
10528 (base as i64 + raw) as u32
10529 };
10530 let (a, b) = match info.format {
10531 OpFormat::None
10532 | OpFormat::NoneInt
10533 | OpFormat::NoneLoc
10534 | OpFormat::NoneArg
10535 | OpFormat::NoneVarRef
10536 | OpFormat::Npopx => (0, 0),
10537 OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
10538 OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
10539 OpFormat::Label8 => (jump(0, 1), 0),
10540 OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
10541 (read_u16(0), 0)
10542 }
10543 OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
10544 OpFormat::Label16 => (jump(0, 2), 0),
10545 OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
10546 OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
10547 OpFormat::I32 | OpFormat::Label => (
10548 if info.format == OpFormat::Label {
10549 jump(0, 4)
10550 } else {
10551 read_u32(0) as i32 as u32
10552 },
10553 0,
10554 ),
10555 OpFormat::AtomU8 | OpFormat::AtomLabelU8 => (read_u32(0), read_u8(4)),
10556 OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
10557 (read_u32(0), read_u16(4))
10558 }
10559 };
10560 Some((op, a, b, pc + info.size as usize))
10561}
10562
10563/// How `print` renders a value: the reference's `JS_PrintValue`.
10564///
10565/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
10566/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
10567/// The format is reproduced closely because the test suite compares output text:
10568///
10569/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
10570/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
10571/// * a cycle prints `[circular N]` with `N` the stack index of the object;
10572/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
10573/// end print as `<N empty item(s)>`;
10574/// * a string is quoted inside a container but raw at the top level, which is why
10575/// `print("x")` and `print(["x"])` differ.
10576pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
10577 // A string argument is printed raw: `js_print` converts it with `ToString`
10578 // instead of dumping it, and the quoting only appears inside a container.
10579 if let Value::String(text) = value {
10580 return text.to_string_lossy().into_owned();
10581 }
10582 let mut printer = Printer {
10583 interp,
10584 out: String::new(),
10585 stack: Vec::new(),
10586 };
10587 printer.value(value, 0);
10588 printer.out
10589}
10590
10591/// The internal class name an object carries, when it has one.
10592fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
10593 interp
10594 .internal_get(object, "_class")
10595 .map(|value| value.to_js_string())
10596}
10597
10598/// A string property, looked up the way `GetProperty` does: own first, then the
10599/// prototype chain. Needed because the print formatter holds the interpreter
10600/// immutably and so cannot run getters.
10601fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
10602 let mut current = Some(object.clone());
10603 // Bounded, because a prototype cycle would otherwise loop forever.
10604 for _ in 0..100 {
10605 let node = current?;
10606 if let Some(property) = node.own_property(name)
10607 && let Some(value) = property.value
10608 {
10609 return Some(value.to_js_string());
10610 }
10611 current = node.with(|data| data.proto.clone());
10612 }
10613 None
10614}
10615
10616/// The `JS_PrintValue` state: output, and the objects currently being printed.
10617struct Printer<'a, 'rt> {
10618 /// Kept for the class-name lookups that typed arrays and `Date` will need.
10619 #[allow(dead_code)]
10620 interp: &'a Interp<'rt>,
10621 out: String,
10622 stack: Vec<Gc<JsObject>>,
10623}
10624
10625impl Printer<'_, '_> {
10626 /// Depth past which a container is summarised by its class name.
10627 const MAX_DEPTH: usize = 2;
10628
10629 fn value(&mut self, value: &Value, level: usize) {
10630 match value {
10631 Value::Undefined
10632 | Value::Uninitialized
10633 | Value::Hole
10634 | Value::CatchOffset(_)
10635 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
10636 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
10637 // The printer writes a bigint the way the language spells one, so a dump is
10638 // unambiguous about which kind of number it is showing.
10639 Value::BigInt(big) => {
10640 self.out.push_str(&big.to_decimal_string());
10641 self.out.push('n');
10642 }
10643 Value::Null => self.out.push_str("null"),
10644 Value::Bool(true) => self.out.push_str("true"),
10645 Value::Bool(false) => self.out.push_str("false"),
10646 Value::Int(number) => self.out.push_str(&number.to_string()),
10647 Value::Float(number) => {
10648 self.out
10649 .push_str(&crate::value::number_to_string_for_print(*number));
10650 }
10651 Value::String(text) => self.print_string(&text.to_string_lossy()),
10652 Value::Object(object) => self.object(object, level),
10653 }
10654 }
10655
10656 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
10657 // A cycle is reported rather than followed; the index is where the object
10658 // already sits in the print stack, which is what the reference shows.
10659 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
10660 self.out.push_str(&format!("[circular {index}]"));
10661 return;
10662 }
10663 if object.is_callable() {
10664 let name = object
10665 .own_property("name")
10666 .and_then(|property| property.value)
10667 .map(|value| value.to_js_string())
10668 .unwrap_or_default();
10669 if name.is_empty() {
10670 self.out.push_str("[Function (anonymous)]");
10671 } else {
10672 self.out.push_str(&format!("[Function {name}]"));
10673 }
10674 return;
10675 }
10676 if level >= Self::MAX_DEPTH {
10677 let class = if object.is_array() { "Array" } else { "Object" };
10678 self.out.push_str(&format!("[{class}]"));
10679 return;
10680 }
10681 // `Date` and `Error` print as themselves rather than as bags of properties:
10682 // the ISO string, and `Name: message` followed by the trace.
10683 if let Some(class) = class_of(self.interp, object) {
10684 if class == "Date" {
10685 self.date(object);
10686 return;
10687 }
10688 if class == "Error" {
10689 self.error(object);
10690 return;
10691 }
10692 }
10693 self.stack.push(object.clone());
10694 if object.is_array() {
10695 self.array(object, level);
10696 } else {
10697 self.plain_object(object, level);
10698 }
10699 self.stack.pop();
10700 }
10701
10702 /// A Date prints as its ISO string; an invalid one falls through to the plain
10703 /// object form, the way the reference falls back when `toISOString` throws.
10704 fn date(&mut self, object: &Gc<JsObject>) {
10705 let value = self
10706 .interp
10707 .internal_get(object, "_date_value")
10708 .map(|value| value.to_number());
10709 match value.and_then(crate::builtins::date::iso_string) {
10710 Some(text) => self.out.push_str(&text),
10711 None => self.plain_object(object, 0),
10712 }
10713 }
10714
10715 /// `Name: message`, then the trace with its trailing newline removed.
10716 fn error(&mut self, object: &Gc<JsObject>) {
10717 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
10718 self.out.push_str(&name);
10719 if let Some(message) = inherited(object, "message")
10720 && !message.is_empty()
10721 {
10722 self.out.push_str(": ");
10723 self.out.push_str(&message);
10724 }
10725 if let Some(stack) = inherited(object, "stack") {
10726 self.out.push('\n');
10727 self.out.push_str(stack.trim_end_matches('\n'));
10728 }
10729 }
10730
10731 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
10732 let elements = object.array_elements().unwrap_or_default();
10733 self.out.push_str("[ ");
10734 // An interior hole means the array is "sparse": the reference prints those
10735 // as `index: value` pairs and says nothing about the holes themselves, while
10736 // a hole run at the end becomes a single `<N empty items>` note.
10737 let last_present = elements
10738 .iter()
10739 .rposition(|value| !matches!(value, Value::Hole));
10740 let has_interior_hole = match last_present {
10741 Some(last) => elements[..last]
10742 .iter()
10743 .any(|value| matches!(value, Value::Hole)),
10744 None => false,
10745 };
10746 let mut first = true;
10747 if has_interior_hole {
10748 let mut index = 0;
10749 while index < elements.len() {
10750 let value = &elements[index];
10751 if matches!(value, Value::Hole) {
10752 index += 1;
10753 continue;
10754 }
10755 if !first {
10756 self.out.push_str(", ");
10757 }
10758 first = false;
10759 self.out.push_str(&format!("{index}: "));
10760 self.value(value, level + 1);
10761 index += 1;
10762 }
10763 } else {
10764 for (index, value) in elements.iter().enumerate() {
10765 if matches!(value, Value::Hole) {
10766 continue;
10767 }
10768 if !first {
10769 self.out.push_str(", ");
10770 }
10771 first = false;
10772 let _ = index;
10773 self.value(value, level + 1);
10774 }
10775 if let Some(last) = last_present {
10776 let trailing = elements.len() - last - 1;
10777 if trailing > 0 {
10778 if !first {
10779 self.out.push_str(", ");
10780 }
10781 self.out.push_str(&format!(
10782 "<{trailing} empty item{}>",
10783 if trailing > 1 { "s" } else { "" }
10784 ));
10785 }
10786 } else if !elements.is_empty() {
10787 let count = elements.len();
10788 self.out.push_str(&format!(
10789 "<{count} empty item{}>",
10790 if count > 1 { "s" } else { "" }
10791 ));
10792 }
10793 }
10794 self.out.push_str(" ]");
10795 }
10796
10797 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
10798 self.out.push_str("{ ");
10799 let mut first = true;
10800 for key in object.own_keys() {
10801 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
10802 continue;
10803 };
10804 if !property.enumerable {
10805 continue;
10806 }
10807 if !first {
10808 self.out.push_str(", ");
10809 }
10810 first = false;
10811 self.out
10812 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
10813 &key.to_string_lossy(),
10814 )));
10815 self.out.push_str(": ");
10816 // An accessor has no value to dump; the reference names the half that
10817 // exists instead of calling it.
10818 if property.is_accessor() {
10819 let text = match (property.getter.is_some(), property.setter.is_some()) {
10820 (true, true) => "[Getter/Setter]",
10821 (false, true) => "[Setter]",
10822 _ => "[Getter]",
10823 };
10824 self.out.push_str(text);
10825 } else {
10826 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
10827 }
10828 }
10829 self.out.push_str(" }");
10830 }
10831
10832 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
10833 fn print_string(&mut self, text: &str) {
10834 self.out.push('"');
10835 for character in text.chars() {
10836 match character {
10837 '"' => self.out.push_str("\\\""),
10838 '\\' => self.out.push_str("\\\\"),
10839 '\n' => self.out.push_str("\\n"),
10840 '\r' => self.out.push_str("\\r"),
10841 '\t' => self.out.push_str("\\t"),
10842 c if (c as u32) < 0x20 => {
10843 self.out.push_str(&format!("\\u{:04x}", c as u32));
10844 }
10845 c => self.out.push(c),
10846 }
10847 }
10848 self.out.push('"');
10849 }
10850}
10851
10852/// How `print` renders a value.
10853///
10854/// `ToString`, except that negative zero keeps its sign — the reference's host
10855/// printer does that while `String(-0)` is `"0"`.
10856pub fn display(value: &Value) -> String {
10857 match value {
10858 Value::Float(number) => crate::value::number_to_string_for_print(*number),
10859 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
10860 "undefined".to_string()
10861 }
10862 other => other.to_js_string(),
10863 }
10864}
10865
10866// ---------------------------------------------------------------------------
10867// Numeric operators
10868// ---------------------------------------------------------------------------
10869
10870/// `a + b` keeping the `Int` representation when it fits.
10871fn add_numbers(left: Value, right: Value) -> Value {
10872 match (&left, &right) {
10873 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10874 Some(sum) => Value::Int(sum),
10875 None => Value::Float(*a as f64 + *b as f64),
10876 },
10877 _ => Value::Float(left.to_number() + right.to_number()),
10878 }
10879}
10880
10881/// The arithmetic operators other than `+`, which needs string concatenation.
10882fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10883 use Opcode::*;
10884 let (a, b) = (left.to_number(), right.to_number());
10885 Ok(match op {
10886 Sub => match (&left, &right) {
10887 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
10888 Some(value) => Value::Int(value),
10889 None => Value::Float(a - b),
10890 },
10891 _ => Value::Float(a - b),
10892 },
10893 Mul => Value::Float(a * b),
10894 Div => Value::Float(a / b),
10895 Mod => Value::Float(js_mod(a, b)),
10896 Pow => Value::Float(a.powf(b)),
10897 And => Value::Int(left.to_int32() & right.to_int32()),
10898 Or => Value::Int(left.to_int32() | right.to_int32()),
10899 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
10900 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
10901 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
10902 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
10903 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
10904 // fits the small-integer representation stays an `Int`; the rest become a
10905 // float, which is how the reference keeps `n >>> 0` non-negative.
10906 Shr => {
10907 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
10908 match i32::try_from(shifted) {
10909 Ok(value) => Value::Int(value),
10910 Err(_) => Value::Float(shifted as f64),
10911 }
10912 }
10913 _ => Value::Float(a),
10914 })
10915}
10916
10917/// `%`, which follows the sign of the dividend rather than Rust's.
10918fn js_mod(left: f64, right: f64) -> f64 {
10919 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
10920 return f64::NAN;
10921 }
10922 if right.is_infinite() {
10923 return left;
10924 }
10925 let remainder = left % right;
10926 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
10927 // the spec makes the sign match the dividend.
10928 if remainder == 0.0 {
10929 0.0f64.copysign(left)
10930 } else {
10931 remainder
10932 }
10933}
10934
10935fn negate(value: Value) -> Value {
10936 match value {
10937 Value::Int(0) => Value::Float(-0.0),
10938 Value::Int(i) => Value::Int(-i),
10939 other => Value::Float(-other.to_number()),
10940 }
10941}
10942
10943fn increment(value: Value) -> Value {
10944 match value {
10945 Value::Int(i) => match i.checked_add(1) {
10946 Some(next) => Value::Int(next),
10947 None => Value::Float(i as f64 + 1.0),
10948 },
10949 other => Value::Float(other.to_number() + 1.0),
10950 }
10951}
10952
10953fn decrement(value: Value) -> Value {
10954 match value {
10955 Value::Int(i) => match i.checked_sub(1) {
10956 Some(next) => Value::Int(next),
10957 None => Value::Float(i as f64 - 1.0),
10958 },
10959 other => Value::Float(other.to_number() - 1.0),
10960 }
10961}
10962
10963/// Compare a `BigInt` with an `f64` on their mathematical values.
10964///
10965/// Neither side is rounded to the other's precision: the number is split into its integer
10966/// part (compared as an exact bigint) and its fraction, which is what decides the answer
10967/// when the integer parts are equal. An infinite value is larger than every bigint.
10968fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
10969 use std::cmp::Ordering;
10970 if number.is_nan() {
10971 return None;
10972 }
10973 if number.is_infinite() {
10974 return Some(if number > 0.0 {
10975 Ordering::Less
10976 } else {
10977 Ordering::Greater
10978 });
10979 }
10980 let truncated = number.trunc();
10981 // A number wider than `i128` still has an exact integer part, but no bigint form we can
10982 // build cheaply; the sign of the difference is all that is needed, so compare against
10983 // the bigint's own magnitude instead.
10984 if truncated.abs() >= 1.7e38 {
10985 let big_as_f64 = big.to_f64();
10986 return big_as_f64.partial_cmp(&number);
10987 }
10988 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
10989 match big.cmp(&integer) {
10990 Ordering::Equal => {
10991 // Same integer part: the fraction decides, and a negative number's fraction is
10992 // below the integer (`-1.5` truncates to `-1`).
10993 if number > truncated {
10994 Some(Ordering::Less)
10995 } else if number < truncated {
10996 Some(Ordering::Greater)
10997 } else {
10998 Some(Ordering::Equal)
10999 }
11000 }
11001 other => Some(other),
11002 }
11003}