Skip to main content

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