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