quickjs/object.rs
1//! The object model: property tables, arrays, functions, and the prototype chain.
2//!
3//! QuickJS splits an object into a *shape* (the property names and their
4//! attributes, shared between objects with the same layout) and a *property
5//! vector* (the values). That split is a performance feature, not a semantic one,
6//! and it only pays off once objects are created in bulk; this model keeps the
7//! property table per object, in insertion order, and therefore reproduces the
8//! ordering rules directly.
9//!
10//! Insertion order is load-bearing: `for (k in o)` and `Object.keys` iterate in the
11//! order properties were defined, with integer-like keys first in ascending order.
12
13use std::cell::RefCell;
14
15use js_compile::bytecode::Function as CompiledFunction;
16use js_gc::{Gc, Trace, Tracer};
17
18use std::fmt;
19use std::rc::Rc;
20
21use crate::value::{Cell, JsSymbol, Value};
22
23/// The bytes an `ArrayBuffer` owns, plus whether they have been detached.
24///
25/// `transfer()` moves the bytes to a new buffer and leaves this one empty and detached; a
26/// view of a detached buffer reads `undefined` from every index.
27pub struct BufferStorage {
28 /// The bytes, in memory order.
29 pub bytes: Vec<u8>,
30 /// Whether `transfer()` has taken the bytes away.
31 pub detached: bool,
32}
33
34impl JsObject {
35 /// The storage of this object, when it is an `ArrayBuffer`.
36 pub fn array_buffer_storage(&self) -> Option<Rc<RefCell<BufferStorage>>> {
37 match &self.data.borrow().kind {
38 ObjectKind::ArrayBuffer(storage) => Some(storage.clone()),
39 _ => None,
40 }
41 }
42
43 /// Make this object an `ArrayBuffer` owning `storage`.
44 pub fn set_array_buffer(&self, storage: Rc<RefCell<BufferStorage>>) {
45 self.data.borrow_mut().kind = ObjectKind::ArrayBuffer(storage);
46 }
47
48 /// The entries of this object, when it is a `Map` or a `Set`.
49 pub fn collection_entries(&self) -> Option<Vec<(Value, Value)>> {
50 match &self.data.borrow().kind {
51 ObjectKind::Collection { entries, .. } => Some(entries.clone()),
52 _ => None,
53 }
54 }
55
56 /// Whether this object is a `Set` rather than a `Map`.
57 pub fn collection_is_set(&self) -> Option<bool> {
58 match &self.data.borrow().kind {
59 ObjectKind::Collection { is_set, .. } => Some(*is_set),
60 _ => None,
61 }
62 }
63
64 /// Make this object a `Map` or `Set` holding `entries`.
65 pub fn set_collection(&self, entries: Vec<(Value, Value)>, is_set: bool) {
66 self.data.borrow_mut().kind = ObjectKind::Collection { entries, is_set };
67 }
68
69 /// `(buffer, element, offset, length)`, when this object is a typed-array view.
70 pub fn typed_array_parts(
71 &self,
72 ) -> Option<(
73 Gc<JsObject>,
74 crate::builtins::typedarray::ElementType,
75 usize,
76 usize,
77 )> {
78 match &self.data.borrow().kind {
79 ObjectKind::TypedArray {
80 buffer,
81 element,
82 offset,
83 length,
84 } => Some((buffer.clone(), *element, *offset, *length)),
85 _ => None,
86 }
87 }
88
89 /// Whether this callable is a native function rather than compiled JavaScript.
90 ///
91 /// `construct` uses it to decide who builds the instance: a native constructor creates
92 /// its own, after validating its arguments.
93 pub fn is_native_function(&self) -> bool {
94 matches!(
95 &self.data.borrow().kind,
96 ObjectKind::Function(Callable::Native { .. })
97 )
98 }
99
100 /// Whether this native constructor builds its own instance, so `new` must not pass one.
101 pub fn native_creates_own_instance(&self) -> bool {
102 matches!(
103 &self.data.borrow().kind,
104 ObjectKind::Function(Callable::Native {
105 own_instance: true,
106 ..
107 })
108 )
109 }
110
111 /// Make this object a `DataView` over `buffer`.
112 pub fn set_data_view(&self, buffer: Gc<JsObject>, offset: usize, length: usize) {
113 self.data.borrow_mut().kind = ObjectKind::DataView {
114 buffer,
115 offset,
116 length,
117 };
118 }
119
120 /// The `(buffer, offset, length)` of a `DataView`, or `None` when this is not one.
121 pub fn data_view_parts(&self) -> Option<(Gc<JsObject>, usize, usize)> {
122 match &self.data.borrow().kind {
123 ObjectKind::DataView {
124 buffer,
125 offset,
126 length,
127 } => Some((buffer.clone(), *offset, *length)),
128 _ => None,
129 }
130 }
131
132 /// Make this object a typed-array view of `length` elements.
133 pub fn set_typed_array(
134 &self,
135 buffer: Gc<JsObject>,
136 element: crate::builtins::typedarray::ElementType,
137 offset: usize,
138 length: usize,
139 ) {
140 self.data.borrow_mut().kind = ObjectKind::TypedArray {
141 buffer,
142 element,
143 offset,
144 length,
145 };
146 }
147
148 /// The element type, when this object is a typed-array view.
149 pub fn typed_array_element_type(&self) -> Option<crate::builtins::typedarray::ElementType> {
150 self.typed_array_parts().map(|(_, element, _, _)| element)
151 }
152
153 /// How many elements the view exposes, or `None` when this is not a view.
154 ///
155 /// A detached buffer reports `0`: the storage is gone, so there is nothing to index.
156 pub fn typed_array_length(&self) -> Option<usize> {
157 let (buffer, _, _, length) = self.typed_array_parts()?;
158 let storage = buffer.array_buffer_storage()?;
159 if storage.borrow().detached {
160 return Some(0);
161 }
162 Some(length)
163 }
164
165 /// Read one view element.
166 ///
167 /// Out-of-range and detached reads are `undefined` rather than an error, which is what
168 /// makes `a[999]` and a detached `a[0]` behave the way the language says.
169 pub fn typed_array_element(&self, index: usize) -> Option<Value> {
170 let (buffer, element, offset, length) = self.typed_array_parts()?;
171 let storage = buffer.array_buffer_storage()?;
172 let storage = storage.borrow();
173 if storage.detached || index >= length {
174 return Some(Value::Undefined);
175 }
176 // The buffer's own handle is where the heap comes from, so a BigInt element can be
177 // allocated without every caller having to thread one through.
178 Some(element.read(
179 buffer.heap(),
180 &storage.bytes,
181 offset + index * element.size(),
182 ))
183 }
184
185 /// Store one view element, applying the type's wrap or clamp.
186 ///
187 /// `Some(Ok(()))` stored, `Some(Err(()))` refused the *value* — a Number into a BigInt
188 /// view, which the caller turns into a `TypeError` — and `None` when this is not a
189 /// view at all or the index is out of range, which is a silent no-op.
190 pub fn typed_array_set(&self, index: usize, value: Value) -> Option<Result<(), &'static str>> {
191 let (buffer, element, offset, length) = self.typed_array_parts()?;
192 if index >= length {
193 return Some(Ok(()));
194 }
195 let storage = buffer.array_buffer_storage()?;
196 let mut storage = storage.borrow_mut();
197 if storage.detached {
198 return Some(Ok(()));
199 }
200 let stored = element.write(&mut storage.bytes, offset + index * element.size(), value);
201 Some(stored)
202 }
203}
204
205/// A property of an object.
206#[derive(Clone, Default)]
207pub struct Property {
208 /// The value of a data property.
209 pub value: Option<Value>,
210 /// The getter of an accessor property.
211 pub getter: Option<Value>,
212 /// The setter of an accessor property.
213 pub setter: Option<Value>,
214 /// Whether the value can be replaced.
215 pub writable: bool,
216 /// Whether `for`/`Object.keys` sees the property.
217 pub enumerable: bool,
218 /// Whether the property can be deleted or redefined.
219 pub configurable: bool,
220}
221
222impl Property {
223 /// A writable, enumerable, configurable data property.
224 ///
225 /// This is what a plain assignment or an object literal creates, and the
226 /// attributes only differ for built-ins and `Object.defineProperty`.
227 pub fn data(value: Value) -> Property {
228 Property {
229 value: Some(value),
230 writable: true,
231 enumerable: true,
232 configurable: true,
233 ..Property::default()
234 }
235 }
236
237 /// A data property with explicit attributes.
238 ///
239 /// `configurable` is derived from `writable`, because that derivation is right for the
240 /// case this is overwhelmingly used for: a built-in method or constructor, which the
241 /// spec gives `{writable: true, enumerable: false, configurable: true}`.
242 ///
243 /// It is *not* right for the two other shapes the spec uses on functions, and both were
244 /// wrong here for a long time — `name`/`length` are `{writable: false, enumerable:
245 /// false, configurable: true}`, and a function's `prototype` is `{writable: true,
246 /// enumerable: false, configurable: false}`. Use [`Property::name_or_length`] and
247 /// [`Property::prototype_of`] for those rather than spelling them out, so that the two
248 /// exceptions to the rule stay in one place.
249 pub fn with_attributes(value: Value, writable: bool, enumerable: bool) -> Property {
250 Property {
251 value: Some(value),
252 writable,
253 enumerable,
254 configurable: writable,
255 ..Property::default()
256 }
257 }
258
259 /// A `name` or `length` property: writable and enumerable are false, configurable true.
260 ///
261 /// Every function has both, and the spec makes them configurable so that a definition
262 /// can replace them (`Object.defineProperty(f, "length", {value: 0})`, and
263 /// `Function.prototype.bind` renaming its result). With them non-configurable, those
264 /// definitions throw and about five hundred conformance tests fail.
265 pub fn name_or_length(value: Value) -> Property {
266 Property {
267 value: Some(value),
268 writable: false,
269 enumerable: false,
270 configurable: true,
271 ..Property::default()
272 }
273 }
274
275 /// A function's `prototype`: not configurable, and writable only for user functions.
276 ///
277 /// A built-in constructor's `prototype` is read-only — assigning to `Object.prototype`
278 /// must not stick — while a user function's is writable, since that is how
279 /// `Ctor.prototype.method = f` sets up inheritance. Neither is configurable, so
280 /// `delete Ctor.prototype` fails in both cases.
281 pub fn prototype_of(value: Value, writable: bool) -> Property {
282 Property {
283 value: Some(value),
284 writable,
285 enumerable: false,
286 configurable: false,
287 ..Property::default()
288 }
289 }
290
291 /// An accessor property.
292 /// An accessor property with explicit `enumerable`/`configurable` flags, which is
293 /// what `Symbol.prototype.description` needs: it is enumerable: false in the spec.
294 pub fn accessor_with(
295 getter: Option<Value>,
296 setter: Option<Value>,
297 enumerable: bool,
298 ) -> Property {
299 Property {
300 getter,
301 setter,
302 enumerable,
303 configurable: true,
304 ..Property::default()
305 }
306 }
307
308 /// An accessor property with the default `enumerable`/`configurable` flags.
309 pub fn accessor(getter: Option<Value>, setter: Option<Value>) -> Property {
310 Property {
311 getter,
312 setter,
313 enumerable: true,
314 configurable: true,
315 ..Property::default()
316 }
317 }
318
319 /// Whether this is an accessor rather than a data property.
320 pub fn is_accessor(&self) -> bool {
321 self.getter.is_some() || self.setter.is_some()
322 }
323}
324
325impl Trace for Property {
326 fn trace(&self, tracer: &mut Tracer) {
327 self.value.trace(tracer);
328 self.getter.trace(tracer);
329 self.setter.trace(tracer);
330 }
331}
332
333/// A native (Rust) function reachable from JavaScript.
334///
335/// It receives the interpreter so a builtin can allocate (which needs the heap),
336/// call back into JavaScript (which needs the frame stack) and raise exceptions.
337pub type NativeFn =
338 fn(&mut crate::interp::Interp<'_>, Value, &[Value]) -> crate::interp::JsResult<Value>;
339
340/// The body of a callable object.
341pub enum Callable {
342 /// A function compiled from JavaScript source.
343 Bytecode {
344 /// The bytecode and slot mapping.
345 code: Gc<CompiledCode>,
346 /// The captured environment.
347 env: Gc<ClosureEnv>,
348 },
349 /// A function produced by `Function.prototype.bind`.
350 ///
351 /// This is a variant rather than a native function carrying the state in
352 /// properties because the state is not observable: `bind` has to remember its
353 /// target, `this` and leading arguments, and a native trampoline cannot capture
354 /// them.
355 Bound {
356 /// The function being called.
357 target: Value,
358 /// The `this` every call uses.
359 this: Value,
360 /// Arguments prepended to every call's own.
361 args: Vec<Value>,
362 },
363 /// A built-in implemented in Rust.
364 ///
365 /// The `name` and `length` a script observes are ordinary properties on the
366 /// function object, not fields here: they are writable (`f.name = "x"` works)
367 /// and would otherwise be two sources of truth.
368 Native {
369 /// The implementation.
370 func: NativeFn,
371 /// Whether this constructor builds its own instance instead of being handed one.
372 ///
373 /// The spec has a constructor validate its arguments *before*
374 /// `OrdinaryCreateFromConstructor` reads `new.target.prototype`, and only the ones
375 /// with real validation need to: `new Promise(nonCallable)` and `new DataView(…)`
376 /// must refuse the argument before a throwing `prototype` getter can run. The rest
377 /// keep the simpler shape where `new` has already made the object.
378 own_instance: bool,
379 },
380 /// The `revoke` function `Proxy.revocable` hands back.
381 ///
382 /// It is a variant rather than a `Native` with the slots in a property because a
383 /// `NativeFn` is a plain function pointer: it cannot capture, and the slots are
384 /// precisely what this function exists to hold. Keeping them here also means the
385 /// collector sees them, so a proxy stays alive while only its `revoke` is reachable.
386 Revoker(crate::object::ProxyRef),
387 /// The `resolve` a `Promise` executor receives.
388 ///
389 /// Like [`Callable::Revoker`], this cannot be a plain `Native` with the state in a
390 /// property: a `NativeFn` is a function pointer and cannot capture, and the promise
391 /// it settles is exactly what it has to remember. Both are one-shot per §27.2.1.3.1 —
392 /// the second call is a no-op rather than a second settlement.
393 ///
394 /// The promise object is held directly rather than the state behind its `Rc`, because
395 /// settling has to run *that object's* reactions.
396 PromiseResolve(Gc<JsObject>),
397 /// The `reject` half of that pair.
398 PromiseReject(Gc<JsObject>),
399 /// One of the two continuations an `await` parks on.
400 ///
401 /// Reached through the ordinary reaction machinery, which is why it has to be a
402 /// callable object rather than a queue entry: `await x` is specified as
403 /// `PerformPromiseThen(x, resume, rethrow)`.
404 AwaitResume {
405 /// The body to continue.
406 coroutine: Gc<JsObject>,
407 /// The promise the async function returned.
408 promise: Gc<JsObject>,
409 /// Whether this continuation delivers the value or raises the reason.
410 kind: crate::interp::ResumeKind,
411 },
412 /// One element of `Promise.all`/`allSettled`/`any`/`race` settling.
413 CombinatorSettle {
414 /// The hidden object holding the results array, the remaining count and the
415 /// combinator's own resolve/reject pair.
416 state: Gc<JsObject>,
417 /// Which element this callback belongs to.
418 index: usize,
419 /// Whether the element fulfilled or rejected.
420 fulfilled: bool,
421 },
422 /// Settle a promise with a fixed outcome when called.
423 ///
424 /// `finally` needs "wait for this promise, then re-deliver that value", and a
425 /// `NativeFn` cannot carry the value to re-deliver.
426 SettlePromise {
427 /// The promise to settle.
428 promise: Gc<JsObject>,
429 /// The outcome to settle it with, which is the *original* one.
430 value: Value,
431 /// Whether that outcome is a rejection.
432 rejected: bool,
433 },
434 /// One continuation of an `await` inside an async generator.
435 GeneratorResume {
436 /// The async generator to continue.
437 generator: Gc<JsObject>,
438 /// The promise the pending `next`/`return`/`throw` returned.
439 promise: Gc<JsObject>,
440 /// Whether this delivers the value or raises the reason.
441 kind: crate::interp::ResumeKind,
442 },
443 /// Reads a module namespace's binding out of the cell it is stored in.
444 ///
445 /// A namespace object is an ordinary object whose exports are getters, so a getter
446 /// is what `ns.x` calls — and it has to be a callable object carrying the cell, for
447 /// the same reason `PromiseResolve` carries its promise.
448 ModuleBinding {
449 /// The binding's cell, shared with the exporting module.
450 cell: Gc<Cell>,
451 },
452 /// Answer a pending async-generator method with `{value, done: false}`.
453 ///
454 /// `yield v` in an async generator awaits `v` first, so the value can arrive after
455 /// the body has already parked; this is what turns it into the result object.
456 YieldResult {
457 /// The promise the pending method returned.
458 promise: Gc<JsObject>,
459 /// Whether this answers a completed generator rather than a `yield`.
460 done: bool,
461 },
462 /// One step of `AsyncDisposableStack.disposeAsync`.
463 ///
464 /// The remaining resources ride along as a JS array so the collector can see them:
465 /// `disposeAsync` awaits each disposer in turn, which means the list has to survive
466 /// across microtasks rather than living on the Rust stack.
467 DisposeStep {
468 /// Pairs of `[resource, disposeMethod]`, consumed from the end.
469 remaining: Gc<JsObject>,
470 /// The promise `disposeAsync` returned.
471 promise: Gc<JsObject>,
472 /// The `SuppressedError` chain built so far, or `Uninitialized` for none.
473 error: Value,
474 /// Whether this continuation is being called with a rejection reason.
475 rejected: bool,
476 },
477 /// One of the two shims `Promise.prototype.finally` installs.
478 FinallyShim {
479 /// The script's callback, or `None` to pass the outcome straight through.
480 callback: Option<Value>,
481 /// Whether this is the fulfil side.
482 fulfilled: bool,
483 },
484}
485
486impl Trace for Callable {
487 fn trace(&self, tracer: &mut Tracer) {
488 match self {
489 Callable::Bytecode { code, env } => {
490 tracer.visit(code);
491 tracer.visit(env);
492 }
493 Callable::Bound { target, this, args } => {
494 target.trace(tracer);
495 this.trace(tracer);
496 for argument in args {
497 argument.trace(tracer);
498 }
499 }
500 Callable::Native { .. } => {}
501 Callable::Revoker(slots) => slots.borrow().trace(tracer),
502 Callable::PromiseResolve(promise) | Callable::PromiseReject(promise) => {
503 tracer.visit(promise)
504 }
505 Callable::AwaitResume {
506 coroutine, promise, ..
507 } => {
508 tracer.visit(coroutine);
509 tracer.visit(promise);
510 }
511 Callable::CombinatorSettle { state, .. } => tracer.visit(state),
512 Callable::GeneratorResume {
513 generator, promise, ..
514 } => {
515 tracer.visit(generator);
516 tracer.visit(promise);
517 }
518 Callable::YieldResult { promise, .. } => tracer.visit(promise),
519 Callable::ModuleBinding { cell } => tracer.visit(cell),
520 Callable::DisposeStep {
521 remaining,
522 promise,
523 error,
524 ..
525 } => {
526 tracer.visit(remaining);
527 tracer.visit(promise);
528 error.trace(tracer);
529 }
530 Callable::SettlePromise { promise, value, .. } => {
531 tracer.visit(promise);
532 value.trace(tracer);
533 }
534 Callable::FinallyShim { callback, .. } => {
535 if let Some(callback) = callback {
536 callback.trace(tracer);
537 }
538 }
539 }
540 }
541}
542
543/// The bytecode of one function, plus the slot-to-cell mapping.
544///
545/// This is a separate GC object from the closure so that a frame can hold a handle
546/// to it and read it while the function object itself is free to be borrowed.
547/// Holding a `RefCell` borrow across a call would deadlock the moment a function
548/// referred to itself.
549pub struct CompiledCode {
550 /// The resolved bytecode.
551 pub code: CompiledFunction,
552 /// For each argument slot, the index of its reference cell, or `-1` when the
553 /// slot holds its value directly.
554 ///
555 /// A captured binding lives in a cell so that closures outlive the frame; every
556 /// other slot is a plain value. Precomputing the mapping keeps the hot
557 /// `get_arg`/`put_arg` paths to one array read instead of a lookup.
558 pub arg_cell: Vec<i32>,
559 /// The same, for local slots.
560 pub loc_cell: Vec<i32>,
561}
562
563impl CompiledCode {
564 /// Build the slot-to-cell mapping for `code`.
565 ///
566 /// Cells are numbered the way [`CompiledFunction::var_ref_count`] counts them:
567 /// the captured arguments first, then the captured locals, each in slot order.
568 pub fn new(code: CompiledFunction) -> CompiledCode {
569 let mut next = 0i32;
570 let mut arg_cell = vec![-1; code.args.len()];
571 for (slot, arg) in code.args.iter().enumerate() {
572 if arg.is_captured {
573 arg_cell[slot] = next;
574 next += 1;
575 }
576 }
577 let mut loc_cell = vec![-1; code.vars.len()];
578 for (slot, local) in code.vars.iter().enumerate() {
579 if local.is_captured {
580 loc_cell[slot] = next;
581 next += 1;
582 }
583 }
584 CompiledCode {
585 code,
586 arg_cell,
587 loc_cell,
588 }
589 }
590}
591
592impl Trace for CompiledCode {
593 fn trace(&self, _tracer: &mut Tracer) {}
594}
595
596/// The reference cells a closure captured from enclosing scopes.
597pub struct ClosureEnv {
598 /// Indexed the way the bytecode's closure-variable table indexes them.
599 pub cells: Vec<Gc<Cell>>,
600 /// The `eval` scope this closure was created in, if any.
601 ///
602 /// A function built by `eval` has to keep seeing the caller's bindings after the
603 /// eval has returned — `for (let i …) eval("push(() => i)")` collects closures that
604 /// read `i` later. Those bindings live in the *caller's* frame, which is long gone
605 /// by then, so the environment carries them by name instead. Ordinary closures leave
606 /// this `None` and resolve globals exactly as before.
607 pub eval_scope: Option<Gc<EvalScope>>,
608 /// Variables a direct `eval` declared in the frame this closure was created in, and
609 /// how much of that frame it may see.
610 ///
611 /// A closure is created at a *place* in a function, and a direct `eval` can add
612 /// variables after that point. Those variables belong to the variable environment
613 /// that was current at the closure's creation — the parameter list or the body — which
614 /// is what `local_phase` records.
615 pub local_vars: Option<Gc<LocalVars>>,
616 /// `0` for a closure created in a parameter list, `1` for one in a body. A parameter
617 /// list's closure must not see variables a later `eval` in the body declared:
618 /// `function f(a, p = () => c) { eval("var c = 1") }` has `p()` resolve `c` outside
619 /// the function entirely.
620 pub local_phase: u8,
621}
622
623/// Variables a direct `eval` declared in one function call.
624///
625/// A sloppy `eval` declares its `var`s in the caller's variable environment, not on the
626/// global object: `function f() { eval("var x = 1") } f(); x` is a `ReferenceError`, and
627/// two calls to `f` get two `x`s. Each entry therefore records the phase it was declared
628/// in, so a lookup from the parameter list cannot see a body declaration.
629pub struct LocalVars {
630 names: std::cell::RefCell<Vec<(String, Gc<Cell>, u8)>>,
631}
632
633impl Default for LocalVars {
634 fn default() -> LocalVars {
635 LocalVars::new()
636 }
637}
638
639impl LocalVars {
640 /// An empty set.
641 pub fn new() -> LocalVars {
642 LocalVars {
643 names: std::cell::RefCell::new(Vec::new()),
644 }
645 }
646
647 /// The cell `name` resolves to, when it was declared in `phase` or earlier.
648 pub fn get(&self, name: &str, phase: u8) -> Option<Gc<Cell>> {
649 self.names
650 .borrow()
651 .iter()
652 .find(|(bound, _, at)| bound == name && *at <= phase)
653 .map(|(_, cell, _)| cell.clone())
654 }
655
656 /// The cell for `name`, declaring it if this is the first time.
657 pub fn declare(&self, name: &str, phase: u8, cell: Gc<Cell>) -> Gc<Cell> {
658 let mut names = self.names.borrow_mut();
659 if let Some((_, cell, _)) = names.iter().find(|(bound, _, _)| bound == name) {
660 return cell.clone();
661 }
662 names.push((name.to_string(), cell.clone(), phase));
663 cell
664 }
665
666 /// Whether `name` has been declared at all.
667 pub fn contains(&self, name: &str) -> bool {
668 self.names
669 .borrow()
670 .iter()
671 .any(|(bound, _, _)| bound == name)
672 }
673}
674
675impl Trace for LocalVars {
676 fn trace(&self, tracer: &mut Tracer) {
677 for (_, cell, _) in self.names.borrow().iter() {
678 tracer.visit(cell);
679 }
680 }
681}
682
683impl Trace for ClosureEnv {
684 fn trace(&self, tracer: &mut Tracer) {
685 for cell in &self.cells {
686 tracer.visit(cell);
687 }
688 if let Some(scope) = &self.eval_scope {
689 tracer.visit(scope);
690 }
691 if let Some(local_vars) = &self.local_vars {
692 tracer.visit(local_vars);
693 }
694 }
695}
696
697/// The bindings a direct `eval` made visible, as name → cell.
698///
699/// Only bindings that already live in a cell appear here, because sharing their
700/// identity is the point: a closure created by the eval must observe later writes to
701/// the same variable, and a copy would not. The compiler puts every binding of a
702/// function that contains a direct `eval` into a cell, so in practice that is all of
703/// them.
704pub struct EvalScope {
705 /// In lookup order: the innermost binding for a name first.
706 pub names: Vec<(String, Gc<Cell>)>,
707}
708
709impl EvalScope {
710 /// The cell `name` resolves to, if this scope binds it.
711 pub fn get(&self, name: &str) -> Option<&Gc<Cell>> {
712 self.names
713 .iter()
714 .find(|(bound, _)| bound == name)
715 .map(|(_, cell)| cell)
716 }
717}
718
719impl Trace for EvalScope {
720 fn trace(&self, tracer: &mut Tracer) {
721 for (_, cell) in &self.names {
722 tracer.visit(cell);
723 }
724 }
725}
726
727/// What kind of object this is.
728pub enum ObjectKind {
729 /// An ordinary object: only its property table.
730 Ordinary,
731 /// An array: a dense element vector plus a property table for everything else.
732 ///
733 /// `length` is stored **separately** rather than derived from `elements.len()`, so a
734 /// sparse array costs nothing to poke at a far index: the reference answers
735 /// `a = []; a.length = 4294967295` instantly, while deriving the length from a dense
736 /// vector meant allocating one `Value` per slot — 62 GB and 24 seconds for that one
737 /// statement. An index past the vector is a hole, and `length` alone records how many
738 /// holes there are at the end.
739 ///
740 /// Invariant: `elements.len() <= length`. A truncation drops both, so the reverse
741 /// (`length < elements.len()`) never holds.
742 Array {
743 /// The dense prefix: everything before the first trailing hole.
744 elements: Vec<Value>,
745 /// The logical length, which may exceed `elements.len()`.
746 length: usize,
747 },
748 /// A function or a class constructor.
749 Function(Callable),
750 /// A regular expression: the compiled pattern, plus `lastIndex` as a property.
751 RegExp(crate::builtins::regexp::RegExpData),
752 /// A `DisposableStack` or `AsyncDisposableStack`: the resources it holds.
753 DisposableStack(crate::builtins::disposable::StackState),
754 /// An `ArrayBuffer`: a byte range that typed-array views share.
755 ///
756 /// The bytes sit behind an `Rc<RefCell<…>>` rather than in the object so that every view
757 /// of the buffer sees the same storage; the *views* hold the `Gc<JsObject>` of this
758 /// buffer, which is what keeps it alive and what the collector traces.
759 ArrayBuffer(std::rc::Rc<std::cell::RefCell<BufferStorage>>),
760 /// A `Map` or a `Set`: insertion-ordered entries with `SameValueZero` key equality.
761 ///
762 /// One variant for both, because a `Set` is exactly a `Map` whose value is unused — the
763 /// difference is a flag, and `is_set` is what makes `entries` yield `[v, v]` pairs.
764 Collection {
765 /// The entries, in insertion order.
766 entries: Vec<(Value, Value)>,
767 /// Whether this is a `Set` rather than a `Map`.
768 is_set: bool,
769 },
770 /// A `DataView`: a byte-oriented window onto an `ArrayBuffer`.
771 ///
772 /// Separate from `TypedArray` because the two index differently: a typed array has an
773 /// element type and counts *elements*, while a `DataView` is untyped and every accessor
774 /// names its own width and byte offset. Sharing one variant would mean carrying an
775 /// element type that is always "bytes" and a length that means something else.
776 DataView {
777 /// The buffer whose bytes this view reads.
778 buffer: Gc<JsObject>,
779 /// Byte offset of the view's first byte.
780 offset: usize,
781 /// How many bytes the view exposes.
782 length: usize,
783 },
784 /// A typed-array view: a window onto an `ArrayBuffer`.
785 TypedArray {
786 /// The buffer whose bytes this view reads.
787 buffer: Gc<JsObject>,
788 /// What one element is.
789 element: crate::builtins::typedarray::ElementType,
790 /// Byte offset of element zero.
791 offset: usize,
792 /// How many elements the view exposes.
793 length: usize,
794 },
795 /// A generator object: a detached frame plus how far it got.
796 ///
797 /// The frame lives here rather than in the interpreter because a suspended generator
798 /// has to keep its locals and operand stack alive for as long as the script can reach
799 /// the generator object — and the collector has to see them, which it only does for
800 /// things hanging off a `Gc`.
801 Generator(Box<crate::interp::GeneratorState>),
802 /// A `Proxy`: a stand-in that forwards every internal method to a target through a
803 /// handler's traps.
804 ///
805 /// The state sits behind an `Rc` because `Proxy.revocable` hands the script a
806 /// `revoke` function that has to reach *this* proxy's two slots later, from a call
807 /// site that has no pointer to the object. Revoking clears them, which also drops
808 /// the collector's references to the target and the handler.
809 Proxy(ProxyRef),
810 /// A `Promise`.
811 ///
812 /// The state sits behind an `Rc` for the same reason a proxy's slots do: the
813 /// `resolve`/`reject` pair handed to an executor has to settle *this* promise later,
814 /// and those are function objects with no pointer back to it otherwise.
815 Promise(PromiseRef),
816}
817
818/// The two slots of a proxy, shared with its `revoke` function.
819///
820/// `None` in both slots means revoked: every operation then throws a `TypeError`, and
821/// the target and handler are no longer reachable — which is the whole point of
822/// `Proxy.revocable`.
823#[derive(Default)]
824pub struct ProxyState {
825 /// The object the traps receive, or `None` once revoked.
826 pub target: Option<Gc<JsObject>>,
827 /// The trap table, or `None` once revoked.
828 pub handler: Option<Value>,
829 /// Whether this proxy has a `[[Call]]`, decided once when it is created.
830 ///
831 /// Revoking drops the target but does not take `[[Call]]` away, so this cannot be
832 /// re-derived from `target` being `Some`: `typeof p.proxy` has to stay `"function"`
833 /// after `Proxy.revocable(function(){}, {}).revoke()`, and the reference agrees.
834 pub callable: bool,
835 /// Whether this proxy has a `[[Construct]]`, decided once when it is created.
836 ///
837 /// Same reasoning as [`ProxyState::callable`], and the two are genuinely independent:
838 /// `Proxy.revocable(function(){}, {})` is both callable and constructible, while a
839 /// proxy over an arrow function is callable and not constructible.
840 pub constructible: bool,
841}
842
843/// A `Promise`'s state, shared between the promise object and its resolve/reject
844/// functions.
845///
846/// Behind an `Rc` for the same reason a proxy's slots are: the `resolve` and `reject`
847/// functions handed to an executor have to settle *this* promise later, from a call site
848/// that only has the function.
849pub struct PromiseState {
850 /// Pending, or the value it settled with.
851 pub status: PromiseStatus,
852 /// The `then` reactions waiting on it, in registration order.
853 pub reactions: Vec<PromiseReaction>,
854 /// Whether a rejection has been seen by a handler.
855 ///
856 /// A rejection that never is becomes an unhandled-rejection report, which the
857 /// reference makes fatal at the end of the job queue.
858 pub handled: bool,
859}
860
861impl Default for PromiseState {
862 fn default() -> Self {
863 PromiseState {
864 status: PromiseStatus::Pending,
865 reactions: Vec::new(),
866 handled: false,
867 }
868 }
869}
870
871/// What a `Promise` combinator does when its elements settle.
872#[derive(Debug, Clone, Copy, PartialEq, Eq)]
873pub enum CombinatorKind {
874 /// The first rejection wins, otherwise an array in input order.
875 All,
876 /// Never rejects; each entry is `{status, value}` or `{status, reason}`.
877 AllSettled,
878 /// The first fulfilment wins, otherwise an `AggregateError`.
879 Any,
880 /// Whichever element settles first.
881 Race,
882}
883
884/// Which of §27.2.1.2's three states a promise is in.
885#[derive(Clone, Default)]
886pub enum PromiseStatus {
887 /// Neither settled: reactions queue up.
888 #[default]
889 Pending,
890 /// Settled with a value, which no further settle may change.
891 Fulfilled(Value),
892 /// Settled with a reason.
893 Rejected(Value),
894}
895
896/// One `then` registration.
897#[derive(Clone)]
898pub struct PromiseReaction {
899 /// Called with the value if the promise fulfils.
900 pub on_fulfilled: Option<Value>,
901 /// Called with the reason if it rejects.
902 pub on_rejected: Option<Value>,
903 /// The promise to settle with whatever the handler returns.
904 pub promise: Gc<JsObject>,
905}
906
907impl Trace for PromiseState {
908 fn trace(&self, tracer: &mut Tracer) {
909 match &self.status {
910 PromiseStatus::Pending => {}
911 PromiseStatus::Fulfilled(value) | PromiseStatus::Rejected(value) => value.trace(tracer),
912 }
913 for reaction in &self.reactions {
914 if let Some(on_fulfilled) = &reaction.on_fulfilled {
915 on_fulfilled.trace(tracer);
916 }
917 if let Some(on_rejected) = &reaction.on_rejected {
918 on_rejected.trace(tracer);
919 }
920 tracer.visit(&reaction.promise);
921 }
922 }
923}
924
925/// A promise's shareable state.
926pub type PromiseRef = std::rc::Rc<std::cell::RefCell<PromiseState>>;
927
928/// A proxy's mutable state, shared between the proxy object and its `revoke`.
929pub type ProxyRef = std::rc::Rc<std::cell::RefCell<ProxyState>>;
930
931impl Trace for ProxyState {
932 fn trace(&self, tracer: &mut Tracer) {
933 if let Some(target) = &self.target {
934 tracer.visit(target);
935 }
936 if let Some(handler) = &self.handler {
937 handler.trace(tracer);
938 }
939 }
940}
941
942impl Trace for ObjectKind {
943 fn trace(&self, tracer: &mut Tracer) {
944 match self {
945 // Nothing in a compiled pattern is a GC value: it holds characters and
946 // integers only.
947 ObjectKind::RegExp(_) => {}
948 ObjectKind::DisposableStack(state) => state.trace(tracer),
949 // A buffer's bytes are plain bytes and hold no GC values; a view keeps its
950 // buffer alive through the `Gc` it carries.
951 ObjectKind::ArrayBuffer(_) => {}
952 ObjectKind::TypedArray { buffer, .. } | ObjectKind::DataView { buffer, .. } => {
953 tracer.visit(buffer)
954 }
955 ObjectKind::Collection { entries, .. } => {
956 for (key, value) in entries {
957 key.trace(tracer);
958 value.trace(tracer);
959 }
960 }
961 ObjectKind::Ordinary => {}
962 ObjectKind::Array { elements, .. } => {
963 for element in elements {
964 element.trace(tracer);
965 }
966 }
967 ObjectKind::Function(callable) => callable.trace(tracer),
968 ObjectKind::Generator(state) => state.trace(tracer),
969 ObjectKind::Proxy(state) => state.borrow().trace(tracer),
970 ObjectKind::Promise(state) => state.borrow().trace(tracer),
971 }
972 }
973}
974
975/// The mutable half of an object.
976/// What a property is keyed by.
977///
978/// A string and a symbol are separate key spaces even when they look alike: `o["a"]`
979/// and `o[Symbol("a")]` are two properties, and `o[Symbol("a")]` is not reachable by
980/// any string. Symbols are also invisible to `for`/`Object.keys`/`JSON.stringify`,
981/// which is the whole point of them, so the distinction has to survive into the
982/// property table rather than being flattened into a name.
983#[derive(Clone)]
984pub enum PropertyKey {
985 /// An ordinary string key, held as WTF-8 so a key containing an unpaired surrogate
986 /// addresses one property rather than colliding with its `U+FFFD` replacement.
987 String(crate::value::Wtf8),
988 /// A symbol key.
989 Symbol(Gc<JsSymbol>),
990}
991
992impl PropertyKey {
993 /// The key as a string, for the operations that only accept one.
994 ///
995 /// A symbol has no string form that would address it, so this answers `None` —
996 /// which is what makes `get_field` on a symbol key fall through to the general
997 /// path instead of silently reading a same-named string property.
998 pub fn as_str(&self) -> Option<&str> {
999 match self {
1000 PropertyKey::String(text) => text.as_str(),
1001 PropertyKey::Symbol(_) => None,
1002 }
1003 }
1004
1005 /// The key's bytes, which a string key always has and a symbol never does.
1006 pub fn as_wtf8(&self) -> Option<&crate::value::Wtf8> {
1007 match self {
1008 PropertyKey::String(text) => Some(text),
1009 PropertyKey::Symbol(_) => None,
1010 }
1011 }
1012
1013 /// Whether this is an ordinary string key.
1014 pub fn is_symbol(&self) -> bool {
1015 matches!(self, PropertyKey::Symbol(_))
1016 }
1017}
1018
1019impl fmt::Display for PropertyKey {
1020 /// How a key reads inside an error message: strings bare, symbols in their
1021 /// `Symbol(description)` form.
1022 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1023 match self {
1024 PropertyKey::String(text) => write!(f, "{}", text.to_string_lossy()),
1025 PropertyKey::Symbol(symbol) => write!(f, "{}", symbol.to_display_string()),
1026 }
1027 }
1028}
1029
1030impl PartialEq for PropertyKey {
1031 fn eq(&self, other: &Self) -> bool {
1032 match (self, other) {
1033 (PropertyKey::String(a), PropertyKey::String(b)) => a == b,
1034 // Symbols compare by identity, never by description.
1035 (PropertyKey::Symbol(a), PropertyKey::Symbol(b)) => a.ptr_eq(b),
1036 _ => false,
1037 }
1038 }
1039}
1040
1041impl From<&str> for PropertyKey {
1042 fn from(text: &str) -> PropertyKey {
1043 PropertyKey::String(crate::value::Wtf8::new(text))
1044 }
1045}
1046
1047impl From<String> for PropertyKey {
1048 fn from(text: String) -> PropertyKey {
1049 PropertyKey::String(crate::value::Wtf8::new(text))
1050 }
1051}
1052
1053impl From<crate::value::Wtf8> for PropertyKey {
1054 fn from(text: crate::value::Wtf8) -> PropertyKey {
1055 PropertyKey::String(text)
1056 }
1057}
1058
1059impl Trace for PropertyKey {
1060 fn trace(&self, tracer: &mut Tracer) {
1061 if let PropertyKey::Symbol(symbol) = self {
1062 tracer.visit(symbol);
1063 }
1064 }
1065}
1066
1067/// An object's mutable state: its prototype, property table and internal slots.
1068pub struct ObjectData {
1069 /// The prototype, or `None` for `Object.prototype` and for a null-prototype
1070 /// object created with `Object.create(null)`.
1071 pub proto: Option<Gc<JsObject>>,
1072 /// Properties in definition order, string and symbol keys interleaved.
1073 pub props: Vec<(PropertyKey, Property)>,
1074 /// What kind of object this is.
1075 pub kind: ObjectKind,
1076 /// Whether new properties may be added. `Object.preventExtensions`, `seal` and
1077 /// `freeze` clear it, and nothing clears it back.
1078 pub extensible: bool,
1079 /// Whether array elements may be replaced.
1080 ///
1081 /// Elements are not in the property table, so their attributes need somewhere to
1082 /// live; `Object.freeze` clears this and `Object.isFrozen` reads it. A *single*
1083 /// non-writable element is recorded in the property table instead, which is what
1084 /// `Object.defineProperty(a, "3", {configurable: false})` does.
1085 pub elements_writable: bool,
1086 /// Whether an array's `length` may be changed.
1087 ///
1088 /// `Object.defineProperty(a, "length", {writable: false})` makes it read-only without
1089 /// touching the elements, so it cannot share `elements_writable`: the two mean
1090 /// different things and `Object.freeze` sets both.
1091 pub length_writable: bool,
1092 /// The object a method was defined on, which is what `super` resolves against.
1093 ///
1094 /// Kept here rather than as a property because it is not observable: the spec calls
1095 /// it `[[HomeObject]]` and no script can read it, so putting it in the property
1096 /// table would leak it to `Object.getOwnPropertyNames` and `JSON.stringify`.
1097 pub home_object: Option<Gc<JsObject>>,
1098 /// Whether this function is a class constructor, which may not be called without
1099 /// `new`.
1100 pub class_constructor: bool,
1101 /// Whether this function has a `[[Construct]]`, i.e. may appear as the target of
1102 /// `new` or `Reflect.construct`.
1103 ///
1104 /// Not derivable from being callable, and that is the whole point: an ordinary
1105 /// method, an arrow function, a generator, an async function and most built-in
1106 /// methods are all callable and none of them may be constructed (§10.2.1,
1107 /// §15.3.1). Deriving it from `is_callable` made `new (Array.prototype.map)` succeed,
1108 /// which test262 checks for every built-in (`not-a-constructor.js`, 515 files).
1109 pub constructible: bool,
1110}
1111
1112impl Trace for ObjectData {
1113 fn trace(&self, tracer: &mut Tracer) {
1114 if let Some(proto) = &self.proto {
1115 tracer.visit(proto);
1116 }
1117 if let Some(home) = &self.home_object {
1118 tracer.visit(home);
1119 }
1120 for (key, property) in &self.props {
1121 key.trace(tracer);
1122 property.trace(tracer);
1123 }
1124 self.kind.trace(tracer);
1125 }
1126}
1127
1128/// A JavaScript object.
1129///
1130/// The interior mutability is what makes `const o = {}; o.x = 1` work: the handle
1131/// is immutable, the object it points at is not.
1132pub struct JsObject {
1133 data: RefCell<ObjectData>,
1134}
1135
1136impl JsObject {
1137 fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
1138 JsObject {
1139 data: RefCell::new(ObjectData {
1140 proto,
1141 props: Vec::new(),
1142 kind,
1143 extensible: true,
1144 elements_writable: true,
1145 length_writable: true,
1146 home_object: None,
1147 class_constructor: false,
1148 constructible: false,
1149 }),
1150 }
1151 }
1152
1153 /// An ordinary object with the given prototype.
1154 pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1155 Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
1156 }
1157
1158 /// An array with the given prototype and initial capacity.
1159 /// An empty array with room for `capacity` elements.
1160 ///
1161 /// The length starts at 0: `capacity` is a `Vec` hint, not a length. Callers that want
1162 /// holes use [`Self::array_set_length`], which no longer allocates them.
1163 pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
1164 Gc::new(
1165 heap,
1166 JsObject::new(
1167 ObjectKind::Array {
1168 elements: Vec::with_capacity(capacity),
1169 length: 0,
1170 },
1171 proto,
1172 ),
1173 )
1174 }
1175
1176 /// A callable object.
1177 pub fn function(
1178 heap: &js_gc::Heap,
1179 proto: Option<Gc<JsObject>>,
1180 callable: Callable,
1181 ) -> Gc<JsObject> {
1182 Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
1183 }
1184
1185 /// Run `f` with the object's data borrowed.
1186 pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
1187 f(&self.data.borrow())
1188 }
1189
1190 /// Run `f` with the object's data mutably borrowed.
1191 pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
1192 f(&mut self.data.borrow_mut())
1193 }
1194
1195 /// Whether this object can be called.
1196 ///
1197 /// Covers every [`Callable`] variant, `Bound` included: `typeof bound ===
1198 /// "function"` and `bound()` works, so from a script's point of view a bound
1199 /// function is a function.
1200 pub fn is_callable(&self) -> bool {
1201 match &self.data.borrow().kind {
1202 ObjectKind::Function(_) => true,
1203 // A proxy is callable exactly when its target was when the proxy was built.
1204 // Not "when its target still is": revoking drops the target but leaves
1205 // `[[Call]]` in place, so a revoked proxy over a function stays a function.
1206 // This is what makes `typeof proxyOfFunction === "function"` survive revoke.
1207 ObjectKind::Proxy(state) => state.borrow().callable,
1208 _ => false,
1209 }
1210 }
1211
1212 /// Whether this object has a `[[Construct]]`, i.e. may be the target of `new` or
1213 /// `Reflect.construct`.
1214 pub fn is_constructor(&self) -> bool {
1215 let data = self.data.borrow();
1216 match &data.kind {
1217 // The flag, not "is a function": a plain method is a function and is not a
1218 // constructor. Set at creation by whoever knows what was built.
1219 ObjectKind::Function(_) => data.constructible,
1220 // Recorded at creation for the same reason as callability: revoking drops the
1221 // target without taking `[[Construct]]` away.
1222 ObjectKind::Proxy(state) => state.borrow().constructible,
1223 _ => false,
1224 }
1225 }
1226
1227 /// Give this function a `[[Construct]]`.
1228 ///
1229 /// Only for callables that are constructors by definition: ordinary functions, class
1230 /// constructors, and the built-in constructors. Everything else — methods, arrows,
1231 /// generators, async functions — keeps the default `false`.
1232 pub fn set_constructible(&self, yes: bool) {
1233 self.data.borrow_mut().constructible = yes;
1234 }
1235
1236 /// This object's proxy slots, when it is one (revoked or not).
1237 pub fn proxy_state(&self) -> Option<ProxyRef> {
1238 match &self.data.borrow().kind {
1239 ObjectKind::Proxy(state) => Some(state.clone()),
1240 _ => None,
1241 }
1242 }
1243
1244 /// A proxy over `target` reading its traps from `handler`.
1245 ///
1246 /// The prototype stays empty on purpose: `[[GetPrototypeOf]]` on a proxy forwards to
1247 /// the target through the `getPrototypeOf` trap, so copying the target's prototype
1248 /// here would be a second, disagreeing source of truth.
1249 pub fn proxy(heap: &js_gc::Heap, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
1250 // Read callability from the target *now*: it is the one moment the answer is
1251 // available, and it outlives revocation.
1252 let callable = target.is_callable();
1253 let constructible = target.is_constructor();
1254 Gc::new(
1255 heap,
1256 JsObject::new(
1257 ObjectKind::Proxy(std::rc::Rc::new(std::cell::RefCell::new(ProxyState {
1258 callable,
1259 constructible,
1260 target: Some(target),
1261 handler: Some(handler),
1262 }))),
1263 None,
1264 ),
1265 )
1266 }
1267
1268 /// The prototype.
1269 pub fn proto(&self) -> Option<Gc<JsObject>> {
1270 self.data.borrow().proto.clone()
1271 }
1272
1273 /// Replace the prototype.
1274 pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
1275 self.data.borrow_mut().proto = proto;
1276 }
1277
1278 /// The object a method was defined on, for `super` to resolve against.
1279 pub fn home_object(&self) -> Option<Gc<JsObject>> {
1280 self.data.borrow().home_object.clone()
1281 }
1282
1283 /// Record the object a method was defined on.
1284 ///
1285 /// A method has no `[[Construct]]` (§10.2.1): `new (o.m)` is a `TypeError` even
1286 /// though `o.m` is a function. Acquiring a home object is exactly the moment a
1287 /// function becomes a method, so the flag is cleared here rather than left to every
1288 /// method-defining call site to remember.
1289 pub fn set_home_object(&self, home: Option<Gc<JsObject>>) {
1290 let mut data = self.data.borrow_mut();
1291 data.home_object = home.clone();
1292 if home.is_some() {
1293 data.constructible = false;
1294 }
1295 }
1296
1297 /// Whether this is a class constructor.
1298 pub fn is_class_constructor(&self) -> bool {
1299 self.data.borrow().class_constructor
1300 }
1301
1302 /// Mark this function as a class constructor.
1303 pub fn set_class_constructor(&self, yes: bool) {
1304 self.data.borrow_mut().class_constructor = yes;
1305 }
1306
1307 /// The elements of an array object, if this is one.
1308 pub fn array_elements(&self) -> Option<Vec<Value>> {
1309 match &self.data.borrow().kind {
1310 ObjectKind::Array { elements, .. } => Some(elements.clone()),
1311 _ => None,
1312 }
1313 }
1314
1315 /// Every own key with its descriptor, array indices included.
1316 ///
1317 /// [`JsObject::own_property_keys`] answers the same question without the
1318 /// descriptors; a proxy invariant needs both at once, because it has to check the
1319 /// *value* of a key it is told about and the presence of a key it is not.
1320 pub fn property_entries(&self) -> Vec<(PropertyKey, Property)> {
1321 let data = self.data.borrow();
1322 let mut out: Vec<(PropertyKey, Property)> = data.props.to_vec();
1323 // An array's elements live in their own vector rather than the property table, so
1324 // they have to be synthesized — with the attributes an ordinary element has.
1325 if let ObjectKind::Array { elements, .. } = &data.kind {
1326 for (index, element) in elements.iter().enumerate() {
1327 if matches!(element, Value::Hole) {
1328 continue;
1329 }
1330 let key = PropertyKey::from(index.to_string());
1331 if !out.iter().any(|(existing, _)| *existing == key) {
1332 out.push((key, Property::data(element.clone())));
1333 }
1334 }
1335 }
1336 // `length` is own on an array without being in the property table either. It is
1337 // writable, non-enumerable and — the part proxy invariants care about —
1338 // non-configurable, so leaving it out let a handler hide or redefine it.
1339 if matches!(data.kind, ObjectKind::Array { .. })
1340 && let Some(length) = self.array_length()
1341 {
1342 let key = PropertyKey::from("length");
1343 if !out.iter().any(|(existing, _)| *existing == key) {
1344 out.push((
1345 key,
1346 Property {
1347 value: Some(length_value(length)),
1348 writable: self.length_writable(),
1349 enumerable: false,
1350 configurable: false,
1351 getter: None,
1352 setter: None,
1353 },
1354 ));
1355 }
1356 }
1357 out
1358 }
1359
1360 /// Whether this object has array elements at all.
1361 pub fn is_array(&self) -> bool {
1362 match &self.data.borrow().kind {
1363 ObjectKind::Array { .. } => true,
1364 // `Array.isArray` is specified to see *through* a proxy: it forwards
1365 // `[[Get]]`/prototype checks to the target, and the answer for a proxy of an
1366 // array is yes.
1367 ObjectKind::Proxy(state) => state
1368 .borrow()
1369 .target
1370 .as_ref()
1371 .is_some_and(|target| target.is_array()),
1372 _ => false,
1373 }
1374 }
1375
1376 /// `length` for an array, reading it out of the element vector.
1377 /// The compiled pattern, when this object is a `RegExp`.
1378 pub fn regexp(&self) -> Option<crate::builtins::regexp::RegExpData> {
1379 match &self.data.borrow().kind {
1380 ObjectKind::RegExp(data) => Some(data.clone()),
1381 _ => None,
1382 }
1383 }
1384
1385 /// The held resources, when this object is a `DisposableStack`.
1386 pub fn disposable_stack(&self) -> Option<crate::builtins::disposable::StackState> {
1387 match &self.data.borrow().kind {
1388 ObjectKind::DisposableStack(state) => Some(state.clone()),
1389 _ => None,
1390 }
1391 }
1392
1393 /// Make this object a `DisposableStack` holding `state`.
1394 pub fn set_disposable_stack(&self, state: crate::builtins::disposable::StackState) {
1395 self.data.borrow_mut().kind = ObjectKind::DisposableStack(state);
1396 }
1397
1398 /// Make this object a `RegExp` carrying `data`.
1399 pub fn set_regexp(&self, data: crate::builtins::regexp::RegExpData) {
1400 self.data.borrow_mut().kind = ObjectKind::RegExp(data);
1401 }
1402
1403 /// Whether this object is a `RegExp`.
1404 pub fn is_regexp(&self) -> bool {
1405 matches!(self.data.borrow().kind, ObjectKind::RegExp(_))
1406 }
1407
1408 /// An array's element count, when this object is an array.
1409 pub fn array_length(&self) -> Option<usize> {
1410 match &self.data.borrow().kind {
1411 ObjectKind::Array { length, .. } => Some(*length),
1412 _ => None,
1413 }
1414 }
1415
1416 /// Read one array element.
1417 pub fn array_get(&self, index: usize) -> Option<Value> {
1418 match &self.data.borrow().kind {
1419 ObjectKind::Array { elements, .. } => elements.get(index).cloned(),
1420 _ => None,
1421 }
1422 }
1423
1424 /// Append to an array and return the new length.
1425 pub fn array_push(&self, value: Value) -> usize {
1426 match &mut self.data.borrow_mut().kind {
1427 ObjectKind::Array { elements, length } => {
1428 elements.push(value);
1429 *length = elements.len();
1430 *length
1431 }
1432 _ => 0,
1433 }
1434 }
1435
1436 /// Store into an array, and return whether the write happened.
1437 ///
1438 /// The gap an out-of-range store leaves behind is filled with [`Value::Hole`], not
1439 /// `undefined`: `a = [1]; a[3] = 4` has holes at 1 and 2, which `forEach` skips
1440 /// and the debug printer reports. A store *of* `undefined` is a real element.
1441 pub fn array_set(&self, index: usize, value: Value) -> bool {
1442 match &mut self.data.borrow_mut().kind {
1443 ObjectKind::Array { elements, length } => {
1444 if index >= *length {
1445 // Growing has to fill the gap, and filling it means the vector really
1446 // does hold `index + 1` slots — a store at `2^32-2` is 68 GB whatever
1447 // the length field says. Refuse instead of aborting the process: the
1448 // reference throws `RangeError` from the allocation. A caller that
1449 // cares converts this `false` into the spec's answer.
1450 if index + 1 > ARRAY_ELEMENT_LIMIT {
1451 return false;
1452 }
1453 elements.resize(index + 1, Value::Hole);
1454 *length = elements.len();
1455 } else if index >= elements.len() {
1456 // Inside the logical length but past the dense prefix: a hole that is
1457 // being filled, so the vector has to catch up first.
1458 elements.resize(index + 1, Value::Hole);
1459 }
1460 elements[index] = value;
1461 true
1462 }
1463 _ => false,
1464 }
1465 }
1466
1467 /// Store an element, honouring its attributes, reporting whether it happened.
1468 ///
1469 /// Array methods that write back (`sort`, `reverse`, `splice`, …) use this rather
1470 /// than [`Self::array_set`]: the spec has them go through `[[Set]]`, so a frozen
1471 /// element makes them throw instead of being quietly overwritten.
1472 pub fn array_store(&self, index: usize, value: Value) -> bool {
1473 if self.elements_writable() {
1474 return self.array_set(index, value);
1475 }
1476 if self.element_attributes(index as u32).is_some() {
1477 // A recorded descriptor decides on its own.
1478 return !self.element_is_locked(index as u32) && self.array_set(index, value);
1479 }
1480 false
1481 }
1482
1483 /// Store `value` as a plain element without creating holes, used by `push`.
1484 pub fn array_push_hole(&self) -> bool {
1485 match &mut self.data.borrow_mut().kind {
1486 ObjectKind::Array { elements, length } => {
1487 elements.push(Value::Hole);
1488 *length = elements.len();
1489 true
1490 }
1491 _ => false,
1492 }
1493 }
1494
1495 /// Set the length of an array, truncating or extending with holes.
1496 ///
1497 /// `a.length = 5` on a two-element array leaves three holes, so the fill value is
1498 /// [`Value::Hole`] rather than `undefined`.
1499 /// Growing only records the new length: the extra slots are holes, and a hole needs
1500 /// no storage. That is what makes `a = []; a.length = 4294967295` an O(1) operation
1501 /// instead of a 62 GB allocation.
1502 pub fn array_set_length(&self, new_length: usize) -> bool {
1503 match &mut self.data.borrow_mut().kind {
1504 ObjectKind::Array { elements, length } => {
1505 if new_length < *length {
1506 // Shrinking really does drop the trailing elements.
1507 elements.truncate(new_length);
1508 }
1509 *length = new_length;
1510 true
1511 }
1512 _ => false,
1513 }
1514 }
1515
1516 /// Truncate an array to `length` elements without extending it.
1517 ///
1518 /// This is what `arr.length = n` does for `n` smaller than the current length;
1519 /// it is separate from [`Self::array_set_length`] because growing an array by
1520 /// assignment produces holes, which are indistinguishable from `undefined`
1521 /// here.
1522 pub fn array_truncate(&self, new_length: usize) -> bool {
1523 match &mut self.data.borrow_mut().kind {
1524 ObjectKind::Array { elements, length } => {
1525 if new_length < elements.len() {
1526 elements.truncate(new_length);
1527 }
1528 if new_length < *length {
1529 *length = new_length;
1530 }
1531 true
1532 }
1533 _ => false,
1534 }
1535 }
1536
1537 /// The own data property `key`, if there is one.
1538 pub fn own_property_key(&self, key: &PropertyKey) -> Option<Property> {
1539 let data = self.data.borrow();
1540 data.props
1541 .iter()
1542 .find(|(existing, _)| existing == key)
1543 .map(|(_, property)| property.clone())
1544 }
1545
1546 /// The own data property `name`, if there is one.
1547 pub fn own_property(&self, name: &str) -> Option<Property> {
1548 self.own_property_key(&PropertyKey::from(name))
1549 }
1550
1551 /// Whether the object has an own property `key`.
1552 pub fn has_own_key(&self, key: &PropertyKey) -> bool {
1553 let data = self.data.borrow();
1554 data.props.iter().any(|(existing, _)| existing == key)
1555 }
1556
1557 /// Whether the object has an own property `name`.
1558 pub fn has_own(&self, name: &str) -> bool {
1559 self.has_own_key(&PropertyKey::from(name))
1560 }
1561
1562 /// Define or replace an own property, keeping the original position when the
1563 /// key already exists.
1564 pub fn define_key(&self, key: &PropertyKey, property: Property) {
1565 let mut data = self.data.borrow_mut();
1566 match data.props.iter_mut().find(|(existing, _)| existing == key) {
1567 Some((_, slot)) => *slot = property,
1568 None => data.props.push((key.clone(), property)),
1569 }
1570 }
1571
1572 /// Define or replace an own property under a string key.
1573 pub fn define(&self, name: &str, property: Property) {
1574 self.define_key(&PropertyKey::from(name), property);
1575 }
1576
1577 /// Define an own data property, with the default attributes.
1578 ///
1579 /// This *creates*: on an existing property it overwrites the attributes too, so
1580 /// it is the wrong call for a plain assignment. Use [`Self::write_value`] for that.
1581 pub fn define_data(&self, name: &str, value: Value) {
1582 self.define(name, Property::data(value));
1583 }
1584
1585 /// Define an own data property under `key`.
1586 pub fn define_data_key(&self, key: &PropertyKey, value: Value) {
1587 self.define_key(key, Property::data(value));
1588 }
1589
1590 /// Store a value into an existing own data property, keeping its attributes.
1591 ///
1592 /// Returns `false` when the property is absent, is an accessor, or is not
1593 /// writable. An assignment has to go through this rather than
1594 /// [`Self::define_data`], because redefining is how a non-configurable global
1595 /// silently became configurable again and started answering `delete` with `true`.
1596 pub fn write_value(&self, name: &str, value: Value) -> bool {
1597 self.write_value_key(&PropertyKey::from(name), value)
1598 }
1599
1600 /// Store a value into an existing own data property under `key`.
1601 pub fn write_value_key(&self, key: &PropertyKey, value: Value) -> bool {
1602 let mut data = self.data.borrow_mut();
1603 let Some((_, property)) = data.props.iter_mut().find(|(existing, _)| existing == key)
1604 else {
1605 return false;
1606 };
1607 if property.is_accessor() || !property.writable {
1608 return false;
1609 }
1610 property.value = Some(value);
1611 true
1612 }
1613
1614 /// Delete an own property, reporting whether it was there and removable.
1615 pub fn delete(&self, name: &str) -> bool {
1616 self.delete_key(&PropertyKey::from(name))
1617 }
1618
1619 /// Delete an own property under `key`.
1620 pub fn delete_key(&self, key: &PropertyKey) -> bool {
1621 let mut data = self.data.borrow_mut();
1622 match data.props.iter().position(|(existing, _)| existing == key) {
1623 Some(index) => {
1624 if data.props[index].1.configurable {
1625 data.props.remove(index);
1626 true
1627 } else {
1628 false
1629 }
1630 }
1631 None => true,
1632 }
1633 }
1634
1635 /// Whether new properties may be added.
1636 pub fn is_extensible(&self) -> bool {
1637 self.data.borrow().extensible
1638 }
1639
1640 /// Make the object non-extensible.
1641 pub fn set_extensible(&self, extensible: bool) {
1642 self.data.borrow_mut().extensible = extensible;
1643 }
1644
1645 /// Whether array elements may be replaced.
1646 pub fn elements_writable(&self) -> bool {
1647 self.data.borrow().elements_writable
1648 }
1649
1650 /// Whether an array's `length` may be changed.
1651 pub fn length_writable(&self) -> bool {
1652 self.data.borrow().length_writable
1653 }
1654
1655 /// Record whether `length` may be changed.
1656 pub fn set_length_writable(&self, writable: bool) {
1657 self.data.borrow_mut().length_writable = writable;
1658 }
1659
1660 /// Make array elements read-only, as `Object.freeze` does.
1661 pub fn set_elements_writable(&self, writable: bool) {
1662 self.data.borrow_mut().elements_writable = writable;
1663 }
1664
1665 /// The attributes recorded for an array index, if `defineProperty` set any.
1666 pub fn element_attributes(&self, index: u32) -> Option<Property> {
1667 self.own_property(&index.to_string())
1668 }
1669
1670 /// Whether `delete` at `index` would be rejected.
1671 ///
1672 /// Separate from [`JsObject::element_is_locked`]: a store needs the element to be
1673 /// non-writable, but a *delete* — which is what truncating an array does — only needs
1674 /// it to be non-configurable. `Object.defineProperty(a, "3", {configurable: false})`
1675 /// leaves `a[3]` writable and yet undeletable, so `a.length = 2` must fail.
1676 pub fn element_is_undeletable(&self, index: u32) -> bool {
1677 if !self.elements_writable() {
1678 return true;
1679 }
1680 self.element_attributes(index)
1681 .is_some_and(|property| !property.configurable)
1682 }
1683
1684 /// Whether a store at `index` would be rejected.
1685 ///
1686 /// An element is locked either by `Object.freeze` on the whole object or by a
1687 /// non-configurable, non-writable descriptor recorded for that one index.
1688 pub fn element_is_locked(&self, index: u32) -> bool {
1689 if !self.elements_writable() {
1690 return true;
1691 }
1692 self.element_attributes(index)
1693 .is_some_and(|property| !property.writable && !property.configurable)
1694 }
1695
1696 /// The own property *names*, in definition order. Symbol keys are excluded:
1697 /// `Object.keys` and `for…in` cannot see them.
1698 pub fn own_keys(&self) -> Vec<crate::value::Wtf8> {
1699 self.data
1700 .borrow()
1701 .props
1702 .iter()
1703 .filter_map(|(key, _)| key.as_wtf8().cloned())
1704 .collect()
1705 }
1706
1707 /// The own *enumerable* property names, in definition order.
1708 pub fn own_enumerable_keys(&self) -> Vec<crate::value::Wtf8> {
1709 self.data
1710 .borrow()
1711 .props
1712 .iter()
1713 .filter(|(_, property)| property.enumerable)
1714 .filter_map(|(key, _)| key.as_wtf8().cloned())
1715 .collect()
1716 }
1717
1718 /// The own symbol keys, in definition order, for `Object.getOwnPropertySymbols`.
1719 pub fn own_symbol_keys(&self) -> Vec<Gc<JsSymbol>> {
1720 self.data
1721 .borrow()
1722 .props
1723 .iter()
1724 .filter_map(|(key, _)| match key {
1725 PropertyKey::Symbol(symbol) => Some(symbol.clone()),
1726 PropertyKey::String(_) => None,
1727 })
1728 .collect()
1729 }
1730
1731 /// Every own key, strings first then symbols — the order `Reflect.ownKeys` and
1732 /// `Object.getOwnPropertyDescriptors` report, and the order `JSON.stringify`
1733 /// walks before it skips the symbols.
1734 pub fn own_property_keys(&self) -> Vec<PropertyKey> {
1735 let data = self.data.borrow();
1736 let mut strings: Vec<PropertyKey> = Vec::new();
1737 let mut symbols: Vec<PropertyKey> = Vec::new();
1738 for (key, _) in &data.props {
1739 if key.is_symbol() {
1740 symbols.push(key.clone());
1741 } else {
1742 strings.push(key.clone());
1743 }
1744 }
1745 strings.extend(symbols);
1746 strings
1747 }
1748
1749 /// The prototype chain, starting with the prototypes of this object.
1750 pub fn chain(&self) -> Vec<Gc<JsObject>> {
1751 let mut out = Vec::new();
1752 let mut proto = self.proto();
1753 while let Some(object) = proto {
1754 proto = object.proto();
1755 out.push(object);
1756 }
1757 out
1758 }
1759}
1760
1761/// Whether two prototypes are the same one, `None` included.
1762///
1763/// A proxy's prototype invariants have to compare "no prototype" against "no
1764/// prototype" without unwrapping either side first.
1765pub(crate) fn same_proto(a: Option<&Gc<JsObject>>, b: Option<&Gc<JsObject>>) -> bool {
1766 match (a, b) {
1767 (None, None) => true,
1768 (Some(a), Some(b)) => a.ptr_eq(b),
1769 _ => false,
1770 }
1771}
1772
1773/// Walk the prototype chain from `object` looking for `name`.
1774///
1775/// Returns the object that owns the property along with the property itself. The
1776/// owner matters for a store: an inherited accessor is invoked on the receiver,
1777/// while an inherited *data* property is shadowed by a new own property.
1778/// The own property `key` names on `object`, arrays included.
1779///
1780/// An array keeps its elements in an element vector and derives its `length`, so its
1781/// property table knows about neither: a hole is a slot in the vector, not a missing
1782/// property, and `length` is not stored at all. `Array.prototype` is itself an array, so
1783/// every walk down the chain needs this same care — without it `1 in [1,,3]` stayed false
1784/// with `Array.prototype[1]` defined, `"length" in []` was false outright, and a hole did
1785/// not read an inherited element.
1786pub fn own_property_including_array(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
1787 if let Some(property) = object.own_property_key(key) {
1788 return Some(property);
1789 }
1790 // A typed array's indices are its elements in the buffer, which the property table
1791 // does not hold either. Checked before the `is_array` return below, because a typed
1792 // array is not one.
1793 if object.typed_array_parts().is_some() {
1794 // A detached view exposes no indices at all: `Reflect.has(detached, "0")` is false
1795 // even though index 0 was in range before the buffer went away.
1796 let index = key.as_str().and_then(array_index)?;
1797 let in_range = (index as usize) < object.typed_array_length()?;
1798 return match object.typed_array_element(index as usize) {
1799 Some(value) if in_range => Some(Property::data(value)),
1800 _ => None,
1801 };
1802 }
1803 if !object.is_array() {
1804 return None;
1805 }
1806 let text = key.as_str()?;
1807 // `length` is non-enumerable and non-configurable; `writable` unless a definition
1808 // turned it off.
1809 if text == "length" {
1810 return Some(Property {
1811 value: Some(length_value(object.array_length()?)),
1812 writable: object.length_writable(),
1813 enumerable: false,
1814 configurable: false,
1815 getter: None,
1816 setter: None,
1817 });
1818 }
1819 // An element is a plain writable/enumerable/configurable data property, and a hole is
1820 // not one at all.
1821 let index = array_index(text)?;
1822 match object.array_get(index as usize) {
1823 Some(Value::Hole) | None => None,
1824 Some(value) => Some(Property::data(value)),
1825 }
1826}
1827
1828/// Whether `object` has `key` as an *own* property, arrays included.
1829pub fn has_own(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
1830 own_property_including_array(object, key).is_some()
1831}
1832
1833/// `key` on `object` or anywhere up its prototype chain, with the owner.
1834///
1835/// Array-aware at every step: an array's elements and its derived `length` are not in the
1836/// property table, and `Array.prototype` is itself an array.
1837pub fn lookup_key(object: &Gc<JsObject>, key: &PropertyKey) -> Option<(Gc<JsObject>, Property)> {
1838 if let Some(property) = own_property_including_array(object, key) {
1839 return Some((object.clone(), property));
1840 }
1841 for ancestor in object.chain() {
1842 if let Some(property) = own_property_including_array(&ancestor, key) {
1843 return Some((ancestor, property));
1844 }
1845 }
1846 None
1847}
1848
1849/// [`lookup_key`] for a string key.
1850pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
1851 lookup_key(object, &PropertyKey::from(name))
1852}
1853
1854/// The largest array index that may be *stored*, i.e. the largest dense vector this engine
1855/// will grow to an index for.
1856///
1857/// The spec's `length` limit is `2^32-1`, but the elements are a dense `Vec<Value>` here,
1858/// so a store at index `2^32-2` is a 68 GB reservation. The reference (which keeps
1859/// elements in a hash map) answers instantly. Refusing past this bound keeps the process
1860/// alive; the conformance tests that really do store near `2^32` are recorded in
1861/// `docs/test262-status.md` as a limitation rather than quietly answered wrong.
1862pub const ARRAY_ELEMENT_LIMIT: usize = 1 << 26;
1863
1864/// An array's `length` as a JavaScript number.
1865///
1866/// `Value::Int` only holds an `i32`, and an array's length may legitimately reach
1867/// `2^32-1`, so a plain cast is not enough: `a[2**32-2] = 1; a.length` came back as `-1`,
1868/// and `Object.getOwnPropertyDescriptor(a, "length").value` with it. Every
1869/// `LengthOfArrayLike` over such an array then ran to `-1`, and the paths without their
1870/// own `RangeError` check turned into `memory allocation of 68719476720 bytes failed`.
1871pub fn length_value(length: usize) -> Value {
1872 if length <= i32::MAX as usize {
1873 Value::Int(length as i32)
1874 } else {
1875 Value::Float(length as f64)
1876 }
1877}
1878
1879/// An array *index* as a JavaScript number.
1880///
1881/// Same problem as [`length_value`] and the same fix: an index may be as large as
1882/// `2^32-2`, which `Value::Int` cannot hold. `a[2**32-2] = 1; a.indexOf(1)` was answering
1883/// `-2` because the index was truncated on the way out.
1884pub fn index_value(index: usize) -> Value {
1885 length_value(index)
1886}
1887
1888/// The array index a property key names, if it names one.
1889///
1890/// A key is an index when it is the canonical decimal spelling of an integer below
1891/// `2^32 - 1` — the same rule the atom table uses to decide whether a key is a
1892/// tagged index. `"01"` and `"-1"` are ordinary string keys.
1893pub fn array_index(key: &str) -> Option<u32> {
1894 if key.is_empty() || key.len() > 10 {
1895 return None;
1896 }
1897 let bytes = key.as_bytes();
1898 if !bytes.iter().all(u8::is_ascii_digit) {
1899 return None;
1900 }
1901 if bytes[0] == b'0' && bytes.len() != 1 {
1902 return None;
1903 }
1904 let value: u32 = key.parse().ok()?;
1905 // `2^32 - 1` is reserved for the array length, so it is not an index.
1906 (value < u32::MAX).then_some(value)
1907}
1908
1909impl Trace for JsObject {
1910 fn trace(&self, tracer: &mut Tracer) {
1911 self.data.borrow().trace(tracer);
1912 }
1913}