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    /// The bytecode decoded once, into fixed-width records.
741    ///
742    /// Decoding is per instruction and never changes its answer — the bytecode is
743    /// immutable once compiled — so doing it at compile time is free and doing it on
744    /// every dispatch is not. See [`crate::insn`].
745    pub insns: Vec<crate::insn::Insn>,
746    /// The atom table as property keys, built once.
747    ///
748    /// `get_field x` needs `x` as a [`PropertyKey`], and building one per access meant
749    /// `Wtf8::from_rc_str`, which allocates a fresh `Rc<[u8]>` and copies the bytes —
750    /// despite its name, it does not share the atom's storage. That put a `malloc` on
751    /// every property read: 5.3% of `property:monomorphic`, plus 1.6% in the `memmove`
752    /// inside it.
753    ///
754    /// Built here instead, so a lookup clones an `Rc` — a pointer bump — rather than
755    /// allocating. Same trick, and the same reason, as `arg_cell` and `insns`.
756    pub atom_keys: Vec<PropertyKey>,
757}
758
759impl CompiledCode {
760    /// Build the slot-to-cell mapping for `code`.
761    ///
762    /// Cells are numbered the way [`CompiledFunction::var_ref_count`] counts them:
763    /// the captured arguments first, then the captured locals, each in slot order.
764    pub fn new(code: CompiledFunction) -> CompiledCode {
765        let mut next = 0i32;
766        let mut arg_cell = vec![-1; code.args.len()];
767        for (slot, arg) in code.args.iter().enumerate() {
768            if arg.is_captured {
769                arg_cell[slot] = next;
770                next += 1;
771            }
772        }
773        let mut loc_cell = vec![-1; code.vars.len()];
774        for (slot, local) in code.vars.iter().enumerate() {
775            if local.is_captured {
776                loc_cell[slot] = next;
777                next += 1;
778            }
779        }
780        let insns = crate::insn::predecode(&code.code);
781        let atom_keys = code.atoms.iter().map(atom_key_of).collect();
782        CompiledCode {
783            code,
784            arg_cell,
785            loc_cell,
786            insns,
787            atom_keys,
788        }
789    }
790}
791
792impl Trace for CompiledCode {
793    fn trace(&self, _tracer: &mut Tracer) {}
794
795    /// The decoded instruction array, which is the one thing here that is not shared
796    /// with the compiler's own table.
797    ///
798    /// Counted because `--memory-limit` has to see it: twenty bytes per instruction
799    /// for every function in the program, and a program with ten thousand small
800    /// functions is a few megabytes that used to be invisible.
801    fn external_bytes(&self) -> usize {
802        self.insns.len() * std::mem::size_of::<crate::insn::Insn>()
803            + self.atom_keys.len() * std::mem::size_of::<PropertyKey>()
804    }
805}
806
807/// One atom of a compiled function's atom table, as the property key a lookup needs.
808///
809/// Kept beside [`CompiledCode::new`] rather than inline in it so the three `Atom`
810/// variants are matched in one place: `Str` shares its bytes through the `Rc` in
811/// [`Wtf8::from_rc_str`], and `Index` formats the number once instead of once per read.
812fn atom_key_of(atom: &js_compile::bytecode::Atom) -> PropertyKey {
813    use js_compile::bytecode::Atom;
814    PropertyKey::String(match atom {
815        Atom::Str(text) => crate::value::Wtf8::from_rc_str(text),
816        Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
817        // `JS_ATOM_NULL`: no name. The opcodes that take one never read it.
818        Atom::Null => crate::value::Wtf8::new(String::new()),
819    })
820}
821
822/// The reference cells a closure captured from enclosing scopes.
823pub struct ClosureEnv {
824    /// Indexed the way the bytecode's closure-variable table indexes them.
825    pub cells: Vec<Gc<Cell>>,
826    /// The `eval` scope this closure was created in, if any.
827    ///
828    /// A function built by `eval` has to keep seeing the caller's bindings after the
829    /// eval has returned — `for (let i …) eval("push(() => i)")` collects closures that
830    /// read `i` later. Those bindings live in the *caller's* frame, which is long gone
831    /// by then, so the environment carries them by name instead. Ordinary closures leave
832    /// this `None` and resolve globals exactly as before.
833    pub eval_scope: Option<Gc<EvalScope>>,
834    /// Variables a direct `eval` declared in the frame this closure was created in, and
835    /// how much of that frame it may see.
836    ///
837    /// A closure is created at a *place* in a function, and a direct `eval` can add
838    /// variables after that point. Those variables belong to the variable environment
839    /// that was current at the closure's creation — the parameter list or the body — which
840    /// is what `local_phase` records.
841    pub local_vars: Option<Gc<LocalVars>>,
842    /// `0` for a closure created in a parameter list, `1` for one in a body. A parameter
843    /// list's closure must not see variables a later `eval` in the body declared:
844    /// `function f(a, p = () => c) { eval("var c = 1") }` has `p()` resolve `c` outside
845    /// the function entirely.
846    pub local_phase: u8,
847}
848
849/// Variables a direct `eval` declared in one function call.
850///
851/// A sloppy `eval` declares its `var`s in the caller's variable environment, not on the
852/// global object: `function f() { eval("var x = 1") } f(); x` is a `ReferenceError`, and
853/// two calls to `f` get two `x`s. Each entry therefore records the phase it was declared
854/// in, so a lookup from the parameter list cannot see a body declaration.
855pub struct LocalVars {
856    names: std::cell::RefCell<Vec<(String, Gc<Cell>, u8)>>,
857}
858
859impl Default for LocalVars {
860    fn default() -> LocalVars {
861        LocalVars::new()
862    }
863}
864
865impl LocalVars {
866    /// An empty set.
867    pub fn new() -> LocalVars {
868        LocalVars {
869            names: std::cell::RefCell::new(Vec::new()),
870        }
871    }
872
873    /// The cell `name` resolves to, when it was declared in `phase` or earlier.
874    pub fn get(&self, name: &str, phase: u8) -> Option<Gc<Cell>> {
875        self.names
876            .borrow()
877            .iter()
878            .find(|(bound, _, at)| bound == name && *at <= phase)
879            .map(|(_, cell, _)| cell.clone())
880    }
881
882    /// The cell for `name`, declaring it if this is the first time.
883    pub fn declare(&self, name: &str, phase: u8, cell: Gc<Cell>) -> Gc<Cell> {
884        let mut names = self.names.borrow_mut();
885        if let Some((_, cell, _)) = names.iter().find(|(bound, _, _)| bound == name) {
886            return cell.clone();
887        }
888        names.push((name.to_string(), cell.clone(), phase));
889        cell
890    }
891
892    /// Whether `name` has been declared at all.
893    pub fn contains(&self, name: &str) -> bool {
894        self.names
895            .borrow()
896            .iter()
897            .any(|(bound, _, _)| bound == name)
898    }
899}
900
901impl Trace for LocalVars {
902    fn trace(&self, tracer: &mut Tracer) {
903        for (_, cell, _) in self.names.borrow().iter() {
904            tracer.visit(cell);
905        }
906    }
907}
908
909impl Trace for ClosureEnv {
910    fn trace(&self, tracer: &mut Tracer) {
911        for cell in &self.cells {
912            tracer.visit(cell);
913        }
914        if let Some(scope) = &self.eval_scope {
915            tracer.visit(scope);
916        }
917        if let Some(local_vars) = &self.local_vars {
918            tracer.visit(local_vars);
919        }
920    }
921}
922
923/// The bindings a direct `eval` made visible, as name → cell.
924///
925/// Only bindings that already live in a cell appear here, because sharing their
926/// identity is the point: a closure created by the eval must observe later writes to
927/// the same variable, and a copy would not. The compiler puts every binding of a
928/// function that contains a direct `eval` into a cell, so in practice that is all of
929/// them.
930pub struct EvalScope {
931    /// In lookup order: the innermost binding for a name first.
932    pub names: Vec<(String, Gc<Cell>)>,
933}
934
935impl EvalScope {
936    /// The cell `name` resolves to, if this scope binds it.
937    pub fn get(&self, name: &str) -> Option<&Gc<Cell>> {
938        self.names
939            .iter()
940            .find(|(bound, _)| bound == name)
941            .map(|(_, cell)| cell)
942    }
943}
944
945impl Trace for EvalScope {
946    fn trace(&self, tracer: &mut Tracer) {
947        for (_, cell) in &self.names {
948            tracer.visit(cell);
949        }
950    }
951}
952
953/// What kind of object this is.
954pub enum ObjectKind {
955    /// An ordinary object: only its property table.
956    Ordinary,
957    /// An array: a dense element vector plus a property table for everything else.
958    ///
959    /// `length` is stored **separately** rather than derived from `elements.len()`, so a
960    /// sparse array costs nothing to poke at a far index: the reference answers
961    /// `a = []; a.length = 4294967295` instantly, while deriving the length from a dense
962    /// vector meant allocating one `Value` per slot — 62 GB and 24 seconds for that one
963    /// statement. An index past the vector is a hole, and `length` alone records how many
964    /// holes there are at the end.
965    ///
966    /// Invariant: `elements.len() <= length`. A truncation drops both, so the reverse
967    /// (`length < elements.len()`) never holds.
968    Array {
969        /// The dense prefix: everything before the first trailing hole.
970        elements: Vec<Value>,
971        /// The logical length, which may exceed `elements.len()`.
972        length: usize,
973    },
974    /// A function or a class constructor.
975    Function(Callable),
976    /// A regular expression: the compiled pattern, plus `lastIndex` as a property.
977    RegExp(crate::builtins::regexp::RegExpData),
978    /// A `DisposableStack` or `AsyncDisposableStack`: the resources it holds.
979    DisposableStack(crate::builtins::disposable::StackState),
980    /// An `ArrayBuffer`: a byte range that typed-array views share.
981    ///
982    /// The bytes sit behind an `Rc<RefCell<…>>` rather than in the object so that every view
983    /// of the buffer sees the same storage; the *views* hold the `Gc<JsObject>` of this
984    /// buffer, which is what keeps it alive and what the collector traces.
985    ArrayBuffer(std::rc::Rc<std::cell::RefCell<BufferStorage>>),
986    /// A `Map` or a `Set`: insertion-ordered entries with `SameValueZero` key equality.
987    ///
988    /// One variant for both, because a `Set` is exactly a `Map` whose value is unused — the
989    /// difference is a flag, and `is_set` is what makes `entries` yield `[v, v]` pairs.
990    Collection {
991        /// The entries, in insertion order.
992        entries: Vec<(Value, Value)>,
993        /// Whether this is a `Set` rather than a `Map`.
994        is_set: bool,
995    },
996    /// A `DataView`: a byte-oriented window onto an `ArrayBuffer`.
997    ///
998    /// Separate from `TypedArray` because the two index differently: a typed array has an
999    /// element type and counts *elements*, while a `DataView` is untyped and every accessor
1000    /// names its own width and byte offset. Sharing one variant would mean carrying an
1001    /// element type that is always "bytes" and a length that means something else.
1002    DataView {
1003        /// The buffer whose bytes this view reads.
1004        buffer: Gc<JsObject>,
1005        /// Byte offset of the view's first byte.
1006        offset: usize,
1007        /// How many bytes the view exposes.
1008        length: usize,
1009    },
1010    /// A typed-array view: a window onto an `ArrayBuffer`.
1011    TypedArray {
1012        /// The buffer whose bytes this view reads.
1013        buffer: Gc<JsObject>,
1014        /// What one element is.
1015        element: crate::builtins::typedarray::ElementType,
1016        /// Byte offset of element zero.
1017        offset: usize,
1018        /// How many elements the view exposes.
1019        length: usize,
1020    },
1021    /// A generator object: a detached frame plus how far it got.
1022    ///
1023    /// The frame lives here rather than in the interpreter because a suspended generator
1024    /// has to keep its locals and operand stack alive for as long as the script can reach
1025    /// the generator object — and the collector has to see them, which it only does for
1026    /// things hanging off a `Gc`.
1027    Generator(Box<crate::interp::GeneratorState>),
1028    /// A `Proxy`: a stand-in that forwards every internal method to a target through a
1029    /// handler's traps.
1030    ///
1031    /// The state sits behind an `Rc` because `Proxy.revocable` hands the script a
1032    /// `revoke` function that has to reach *this* proxy's two slots later, from a call
1033    /// site that has no pointer to the object. Revoking clears them, which also drops
1034    /// the collector's references to the target and the handler.
1035    Proxy(ProxyRef),
1036    /// A `Promise`.
1037    ///
1038    /// The state sits behind an `Rc` for the same reason a proxy's slots do: the
1039    /// `resolve`/`reject` pair handed to an executor has to settle *this* promise later,
1040    /// and those are function objects with no pointer back to it otherwise.
1041    Promise(PromiseRef),
1042    /// A `WeakMap` or `WeakSet`: like a collection, but the *keys* are weak.
1043    ///
1044    /// The distinction lives entirely in [`Trace`]: a `Collection` traces its keys, a
1045    /// `WeakCollection` does not. An entry keyed by an otherwise-unreachable object is
1046    /// therefore reclaimed together with that object instead of keeping it alive, and the
1047    /// entry simply stops being found — `upgrade` fails and a liveness sweep drops the
1048    /// pair. That is the "ephemeron" behaviour `WeakMap` promises, and it falls out of
1049    /// reference counting rather than needing a second collection pass.
1050    WeakCollection {
1051        /// The entries, in insertion order, keyed by a non-owning handle.
1052        entries: Vec<(WeakKey, Value)>,
1053        /// Whether this is a `WeakSet` rather than a `WeakMap`.
1054        is_set: bool,
1055    },
1056    /// A `WeakRef`: one non-owning handle to a target object.
1057    WeakRef {
1058        /// The target. Once `upgrade` fails the reference is dead for good, because a box
1059        /// whose strong count reached zero never comes back.
1060        ///
1061        /// A `WeakKey` rather than a `WeakGc<JsObject>`, because a symbol is a valid target
1062        /// too — `new WeakRef(Symbol())` works and `deref` has to answer it back.
1063        target: WeakKey,
1064    },
1065    /// A `FinalizationRegistry`: the cleanup callback and its live registrations.
1066    Finalization(Box<FinalizationState>),
1067}
1068
1069/// The mutable half of a `FinalizationRegistry`.
1070///
1071/// Boxed inside the [`ObjectKind`] variant because it holds a vector plus a value, and every
1072/// `ObjectKind` is stored inline in the object header — an unboxed field this wide would
1073/// make *every* object in the realm that much larger.
1074pub struct FinalizationState {
1075    /// One entry per successful `register` call.
1076    pub registrations: Vec<Registration>,
1077    /// The cleanup callback, validated as callable when the registry was built.
1078    pub cleanup: Value,
1079}
1080
1081/// A key that can be held weakly: an object, or a symbol.
1082///
1083/// Both are heap allocations in this engine (`Value::Symbol` carries a `Gc<JsSymbol>`), so a
1084/// `WeakGc` holds either one just as well. Symbols became valid keys with the
1085/// `symbols-as-weakmap-keys` proposal, which is what test262 already tests.
1086#[derive(Clone)]
1087pub enum WeakKey {
1088    /// An object target.
1089    Object(WeakGc<JsObject>),
1090    /// A symbol target.
1091    Symbol(WeakGc<JsSymbol>),
1092}
1093
1094impl WeakKey {
1095    /// Whether the allocation behind this key has been released.
1096    pub fn is_expired(&self) -> bool {
1097        match self {
1098            WeakKey::Object(handle) => handle.is_expired(),
1099            WeakKey::Symbol(handle) => handle.is_expired(),
1100        }
1101    }
1102
1103    /// Whether two weak keys are the same allocation.
1104    pub fn same(&self, other: &WeakKey) -> bool {
1105        match (self, other) {
1106            (WeakKey::Object(left), WeakKey::Object(right)) => left.ptr_eq(right),
1107            (WeakKey::Symbol(left), WeakKey::Symbol(right)) => left.ptr_eq(right),
1108            _ => false,
1109        }
1110    }
1111
1112    /// Whether this key is the same allocation as `value`, without upgrading it.
1113    ///
1114    /// Upgrading would resurrect the key, which for a `WeakMap` lookup is exactly what must
1115    /// not happen — a dead key has to compare equal to nothing.
1116    pub fn matches(&self, value: &Value) -> bool {
1117        match (self, value) {
1118            (WeakKey::Object(handle), Value::Object(object)) => object.upgrades_to(handle),
1119            (WeakKey::Symbol(handle), Value::Symbol(symbol)) => symbol.upgrades_to(handle),
1120            _ => false,
1121        }
1122    }
1123
1124    /// The key as a strong value, when it is still alive.
1125    pub fn upgrade(&self) -> Option<Value> {
1126        match self {
1127            WeakKey::Object(handle) => handle.upgrade().map(Value::Object),
1128            WeakKey::Symbol(handle) => handle.upgrade().map(Value::Symbol),
1129        }
1130    }
1131}
1132
1133impl Trace for WeakKey {
1134    fn trace(&self, _tracer: &mut Tracer) {}
1135}
1136
1137/// Turn a script value into a weak key, if `CanBeHeldWeakly` allows it.
1138///
1139/// The rule is "an object, or a symbol that is not in the registry". A registered symbol —
1140/// one from `Symbol.for` — is refused on purpose: it lives in the realm's registry for the
1141/// lifetime of the realm, so it never dies, and a weak entry keyed by it could never be
1142/// observed to be collected. A plain `Symbol()` is a fresh allocation each time and so has
1143/// a lifetime worth observing.
1144pub fn weak_key(value: &Value) -> Option<WeakKey> {
1145    match value {
1146        Value::Object(object) => Some(WeakKey::Object(object.downgrade())),
1147        Value::Symbol(symbol) if symbol.registry_key().is_none() => {
1148            Some(WeakKey::Symbol(symbol.downgrade()))
1149        }
1150        _ => None,
1151    }
1152}
1153
1154/// One `FinalizationRegistry.register` call.
1155///
1156/// `token` is compared with `SameValue`, not `SameValueZero`, which is why it is kept as
1157/// the original `Value` rather than normalised into a key.
1158pub struct Registration {
1159    /// The handle whose death fires the callback.
1160    pub target: WeakKey,
1161    /// What the callback receives: the script's held value, kept alive until it fires.
1162    pub held_value: Value,
1163    /// The cancellation token, if one was given.
1164    pub token: Option<Value>,
1165}
1166
1167/// The two slots of a proxy, shared with its `revoke` function.
1168///
1169/// `None` in both slots means revoked: every operation then throws a `TypeError`, and
1170/// the target and handler are no longer reachable — which is the whole point of
1171/// `Proxy.revocable`.
1172#[derive(Default)]
1173pub struct ProxyState {
1174    /// The object the traps receive, or `None` once revoked.
1175    pub target: Option<Gc<JsObject>>,
1176    /// The trap table, or `None` once revoked.
1177    pub handler: Option<Value>,
1178    /// Whether this proxy has a `[[Call]]`, decided once when it is created.
1179    ///
1180    /// Revoking drops the target but does not take `[[Call]]` away, so this cannot be
1181    /// re-derived from `target` being `Some`: `typeof p.proxy` has to stay `"function"`
1182    /// after `Proxy.revocable(function(){}, {}).revoke()`, and the reference agrees.
1183    pub callable: bool,
1184    /// Whether this proxy has a `[[Construct]]`, decided once when it is created.
1185    ///
1186    /// Same reasoning as [`ProxyState::callable`], and the two are genuinely independent:
1187    /// `Proxy.revocable(function(){}, {})` is both callable and constructible, while a
1188    /// proxy over an arrow function is callable and not constructible.
1189    pub constructible: bool,
1190}
1191
1192/// A `Promise`'s state, shared between the promise object and its resolve/reject
1193/// functions.
1194///
1195/// Behind an `Rc` for the same reason a proxy's slots are: the `resolve` and `reject`
1196/// functions handed to an executor have to settle *this* promise later, from a call site
1197/// that only has the function.
1198pub struct PromiseState {
1199    /// Pending, or the value it settled with.
1200    pub status: PromiseStatus,
1201    /// The `then` reactions waiting on it, in registration order.
1202    pub reactions: Vec<PromiseReaction>,
1203    /// Whether a rejection has been seen by a handler.
1204    ///
1205    /// A rejection that never is becomes an unhandled-rejection report, which the
1206    /// reference makes fatal at the end of the job queue.
1207    pub handled: bool,
1208}
1209
1210impl Default for PromiseState {
1211    fn default() -> Self {
1212        PromiseState {
1213            status: PromiseStatus::Pending,
1214            reactions: Vec::new(),
1215            handled: false,
1216        }
1217    }
1218}
1219
1220/// What a `Promise` combinator does when its elements settle.
1221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1222pub enum CombinatorKind {
1223    /// The first rejection wins, otherwise an array in input order.
1224    All,
1225    /// Never rejects; each entry is `{status, value}` or `{status, reason}`.
1226    AllSettled,
1227    /// The first fulfilment wins, otherwise an `AggregateError`.
1228    Any,
1229    /// Whichever element settles first.
1230    Race,
1231}
1232
1233/// Which of §27.2.1.2's three states a promise is in.
1234#[derive(Clone, Default)]
1235pub enum PromiseStatus {
1236    /// Neither settled: reactions queue up.
1237    #[default]
1238    Pending,
1239    /// Settled with a value, which no further settle may change.
1240    Fulfilled(Value),
1241    /// Settled with a reason.
1242    Rejected(Value),
1243}
1244
1245/// One `then` registration.
1246#[derive(Clone)]
1247pub struct PromiseReaction {
1248    /// Called with the value if the promise fulfils.
1249    pub on_fulfilled: Option<Value>,
1250    /// Called with the reason if it rejects.
1251    pub on_rejected: Option<Value>,
1252    /// The promise to settle with whatever the handler returns.
1253    pub promise: Gc<JsObject>,
1254}
1255
1256impl Trace for PromiseState {
1257    fn trace(&self, tracer: &mut Tracer) {
1258        match &self.status {
1259            PromiseStatus::Pending => {}
1260            PromiseStatus::Fulfilled(value) | PromiseStatus::Rejected(value) => value.trace(tracer),
1261        }
1262        for reaction in &self.reactions {
1263            if let Some(on_fulfilled) = &reaction.on_fulfilled {
1264                on_fulfilled.trace(tracer);
1265            }
1266            if let Some(on_rejected) = &reaction.on_rejected {
1267                on_rejected.trace(tracer);
1268            }
1269            tracer.visit(&reaction.promise);
1270        }
1271    }
1272}
1273
1274/// A promise's shareable state.
1275pub type PromiseRef = std::rc::Rc<std::cell::RefCell<PromiseState>>;
1276
1277/// A proxy's mutable state, shared between the proxy object and its `revoke`.
1278pub type ProxyRef = std::rc::Rc<std::cell::RefCell<ProxyState>>;
1279
1280impl Trace for ProxyState {
1281    fn trace(&self, tracer: &mut Tracer) {
1282        if let Some(target) = &self.target {
1283            tracer.visit(target);
1284        }
1285        if let Some(handler) = &self.handler {
1286            handler.trace(tracer);
1287        }
1288    }
1289}
1290
1291impl Trace for ObjectKind {
1292    fn trace(&self, tracer: &mut Tracer) {
1293        match self {
1294            // Nothing in a compiled pattern is a GC value: it holds characters and
1295            // integers only.
1296            ObjectKind::RegExp(_) => {}
1297            ObjectKind::DisposableStack(state) => state.trace(tracer),
1298            // A buffer's bytes are plain bytes and hold no GC values; a view keeps its
1299            // buffer alive through the `Gc` it carries.
1300            ObjectKind::ArrayBuffer(_) => {}
1301            ObjectKind::TypedArray { buffer, .. } | ObjectKind::DataView { buffer, .. } => {
1302                tracer.visit(buffer)
1303            }
1304            ObjectKind::Collection { entries, .. } => {
1305                for (key, value) in entries {
1306                    key.trace(tracer);
1307                    value.trace(tracer);
1308                }
1309            }
1310            ObjectKind::Ordinary => {}
1311            ObjectKind::Array { elements, .. } => {
1312                for element in elements {
1313                    element.trace(tracer);
1314                }
1315            }
1316            ObjectKind::Function(callable) => callable.trace(tracer),
1317            ObjectKind::Generator(state) => state.trace(tracer),
1318            ObjectKind::Proxy(state) => state.borrow().trace(tracer),
1319            ObjectKind::Promise(state) => state.borrow().trace(tracer),
1320            // The *keys* are deliberately not visited: that absence is what makes the
1321            // collection weak, and it is also why a `WeakMap` cannot keep its key alive
1322            // through a cycle that only the map closes. The values are traced, so
1323            // `wm.set(k, v)` keeping `v` alive while `k` is reachable is the right half of
1324            // the ephemeron rule to get right here — the other half (dropping the pair once
1325            // the key dies) needs no liveness test, because `upgrade` on a dead key fails.
1326            ObjectKind::WeakCollection { entries, .. } => {
1327                for (_, value) in entries {
1328                    value.trace(tracer);
1329                }
1330            }
1331            // A `WeakRef` owns nothing at all: that is its whole purpose.
1332            ObjectKind::WeakRef { .. } => {}
1333            // A registry keeps its held values and its callback alive — the held value has
1334            // to survive until the callback can run — but not the targets, which is the
1335            // handle type's job rather than the tracer's.
1336            ObjectKind::Finalization(state) => {
1337                state.cleanup.trace(tracer);
1338                for registration in &state.registrations {
1339                    registration.held_value.trace(tracer);
1340                    registration.token.trace(tracer);
1341                }
1342            }
1343        }
1344    }
1345}
1346
1347/// The mutable half of an object.
1348/// What a property is keyed by.
1349///
1350/// A string and a symbol are separate key spaces even when they look alike: `o["a"]`
1351/// and `o[Symbol("a")]` are two properties, and `o[Symbol("a")]` is not reachable by
1352/// any string. Symbols are also invisible to `for`/`Object.keys`/`JSON.stringify`,
1353/// which is the whole point of them, so the distinction has to survive into the
1354/// property table rather than being flattened into a name.
1355#[derive(Clone)]
1356pub enum PropertyKey {
1357    /// An ordinary string key, held as WTF-8 so a key containing an unpaired surrogate
1358    /// addresses one property rather than colliding with its `U+FFFD` replacement.
1359    String(crate::value::Wtf8),
1360    /// A symbol key.
1361    Symbol(Gc<JsSymbol>),
1362}
1363
1364impl PropertyKey {
1365    /// A cheap hash of this key, for an inline cache's slot choice.
1366    ///
1367    /// Not a hash of the whole string: a long property name would make the cache slower than
1368    /// the lookup it is caching. Mixing the length with the first and last byte is enough to
1369    /// separate the names that appear on one object (`x`/`y`, `value`/`add`), and a
1370    /// collision only costs a miss.
1371    pub fn hash_code(&self) -> usize {
1372        match self {
1373            PropertyKey::String(text) => {
1374                let bytes = text.as_bytes();
1375                let mut hash = bytes.len();
1376                for &byte in bytes.iter().take(4).chain(bytes.iter().rev().take(2)) {
1377                    hash = hash.wrapping_mul(31).wrapping_add(byte as usize);
1378                }
1379                hash
1380            }
1381            // A symbol's identity is its allocation, which is exactly what the cache needs —
1382            // two symbols with the same description are two keys.
1383            PropertyKey::Symbol(symbol) => symbol.identity(),
1384        }
1385    }
1386}
1387
1388impl PropertyKey {
1389    /// The key as a string, for the operations that only accept one.
1390    ///
1391    /// A symbol has no string form that would address it, so this answers `None` —
1392    /// which is what makes `get_field` on a symbol key fall through to the general
1393    /// path instead of silently reading a same-named string property.
1394    pub fn as_str(&self) -> Option<&str> {
1395        match self {
1396            PropertyKey::String(text) => text.as_str(),
1397            PropertyKey::Symbol(_) => None,
1398        }
1399    }
1400
1401    /// The key's bytes, which a string key always has and a symbol never does.
1402    pub fn as_wtf8(&self) -> Option<&crate::value::Wtf8> {
1403        match self {
1404            PropertyKey::String(text) => Some(text),
1405            PropertyKey::Symbol(_) => None,
1406        }
1407    }
1408
1409    /// Whether this is an ordinary string key.
1410    pub fn is_symbol(&self) -> bool {
1411        matches!(self, PropertyKey::Symbol(_))
1412    }
1413}
1414
1415impl fmt::Display for PropertyKey {
1416    /// How a key reads inside an error message: strings bare, symbols in their
1417    /// `Symbol(description)` form.
1418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1419        match self {
1420            PropertyKey::String(text) => write!(f, "{}", text.to_string_lossy()),
1421            PropertyKey::Symbol(symbol) => write!(f, "{}", symbol.to_display_string()),
1422        }
1423    }
1424}
1425
1426impl PartialEq for PropertyKey {
1427    fn eq(&self, other: &Self) -> bool {
1428        match (self, other) {
1429            (PropertyKey::String(a), PropertyKey::String(b)) => a == b,
1430            // Symbols compare by identity, never by description.
1431            (PropertyKey::Symbol(a), PropertyKey::Symbol(b)) => a.ptr_eq(b),
1432            _ => false,
1433        }
1434    }
1435}
1436
1437impl From<&str> for PropertyKey {
1438    fn from(text: &str) -> PropertyKey {
1439        PropertyKey::String(crate::value::Wtf8::new(text))
1440    }
1441}
1442
1443impl From<String> for PropertyKey {
1444    fn from(text: String) -> PropertyKey {
1445        PropertyKey::String(crate::value::Wtf8::new(text))
1446    }
1447}
1448
1449impl From<crate::value::Wtf8> for PropertyKey {
1450    fn from(text: crate::value::Wtf8) -> PropertyKey {
1451        PropertyKey::String(text)
1452    }
1453}
1454
1455impl Trace for PropertyKey {
1456    fn trace(&self, tracer: &mut Tracer) {
1457        if let PropertyKey::Symbol(symbol) = self {
1458            tracer.visit(symbol);
1459        }
1460    }
1461}
1462
1463/// An object's mutable state: its prototype, property table and internal slots.
1464pub struct ObjectData {
1465    /// The prototype, or `None` for `Object.prototype` and for a null-prototype
1466    /// object created with `Object.create(null)`.
1467    pub proto: Option<Gc<JsObject>>,
1468    /// Properties in definition order, string and symbol keys interleaved.
1469    pub props: Vec<(PropertyKey, Property)>,
1470    /// What kind of object this is.
1471    pub kind: ObjectKind,
1472    /// Whether new properties may be added. `Object.preventExtensions`, `seal` and
1473    /// `freeze` clear it, and nothing clears it back.
1474    pub extensible: bool,
1475    /// Whether array elements may be replaced.
1476    ///
1477    /// Elements are not in the property table, so their attributes need somewhere to
1478    /// live; `Object.freeze` clears this and `Object.isFrozen` reads it. A *single*
1479    /// non-writable element is recorded in the property table instead, which is what
1480    /// `Object.defineProperty(a, "3", {configurable: false})` does.
1481    pub elements_writable: bool,
1482    /// Whether an array's `length` may be changed.
1483    ///
1484    /// `Object.defineProperty(a, "length", {writable: false})` makes it read-only without
1485    /// touching the elements, so it cannot share `elements_writable`: the two mean
1486    /// different things and `Object.freeze` sets both.
1487    pub length_writable: bool,
1488    /// The object a method was defined on, which is what `super` resolves against.
1489    ///
1490    /// Kept here rather than as a property because it is not observable: the spec calls
1491    /// it `[[HomeObject]]` and no script can read it, so putting it in the property
1492    /// table would leak it to `Object.getOwnPropertyNames` and `JSON.stringify`.
1493    pub home_object: Option<Gc<JsObject>>,
1494    /// The brand symbol this object *owns*, when it is the home object of a class.
1495    ///
1496    /// The reference keeps two separate things under private names it never exposes. The
1497    /// first is `[[PrivateBrand]]`: one symbol per class, stored on the home object — the
1498    /// prototype for the instance brand, the constructor for the static one. Creating it the
1499    /// first time and reusing it after is what ties a prototype, its instances and the class
1500    /// itself to one identity.
1501    ///
1502    /// Kept off the property table for the same reason as `home_object`: a property would be
1503    /// reachable from `Object.getOwnPropertyNames`.
1504    pub private_brand: Option<Gc<crate::value::JsSymbol>>,
1505    /// The brand symbols this object *carries*, as an instance of one or more classes.
1506    ///
1507    /// A list rather than one symbol because brands accumulate down an inheritance chain:
1508    /// `class D extends C` with a private method in each means a `D` instance carries both,
1509    /// since `C`'s field initialiser runs on it and so does `D`'s. Membership is what
1510    /// `check_brand` — and so `#m()` and `#a` — tests before it runs.
1511    pub brands: Vec<Gc<crate::value::JsSymbol>>,
1512    /// Whether this function is a class constructor, which may not be called without
1513    /// `new`.
1514    pub class_constructor: bool,
1515    /// Whether this function has a `[[Construct]]`, i.e. may appear as the target of
1516    /// `new` or `Reflect.construct`.
1517    ///
1518    /// Not derivable from being callable, and that is the whole point: an ordinary
1519    /// method, an arrow function, a generator, an async function and most built-in
1520    /// methods are all callable and none of them may be constructed (§10.2.1,
1521    /// §15.3.1). Deriving it from `is_callable` made `new (Array.prototype.map)` succeed,
1522    /// which test262 checks for every built-in (`not-a-constructor.js`, 515 files).
1523    pub constructible: bool,
1524}
1525
1526impl Trace for ObjectData {
1527    fn trace(&self, tracer: &mut Tracer) {
1528        if let Some(proto) = &self.proto {
1529            tracer.visit(proto);
1530        }
1531        if let Some(home) = &self.home_object {
1532            tracer.visit(home);
1533        }
1534        if let Some(brand) = &self.private_brand {
1535            tracer.visit(brand);
1536        }
1537        for brand in &self.brands {
1538            tracer.visit(brand);
1539        }
1540        for (key, property) in &self.props {
1541            key.trace(tracer);
1542            property.trace(tracer);
1543        }
1544        self.kind.trace(tracer);
1545    }
1546}
1547
1548/// A JavaScript object.
1549///
1550/// The interior mutability is what makes `const o = {}; o.x = 1` work: the handle
1551/// is immutable, the object it points at is not.
1552pub struct JsObject {
1553    data: RefCell<ObjectData>,
1554}
1555
1556impl JsObject {
1557    fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
1558        JsObject {
1559            data: RefCell::new(ObjectData {
1560                proto,
1561                props: Vec::new(),
1562                kind,
1563                extensible: true,
1564                elements_writable: true,
1565                length_writable: true,
1566                home_object: None,
1567                private_brand: None,
1568                brands: Vec::new(),
1569                class_constructor: false,
1570                constructible: false,
1571            }),
1572        }
1573    }
1574
1575    /// An ordinary object with the given prototype.
1576    pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1577        Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
1578    }
1579
1580    /// An array with the given prototype and initial capacity.
1581    /// An empty array with room for `capacity` elements.
1582    ///
1583    /// The length starts at 0: `capacity` is a `Vec` hint, not a length. Callers that want
1584    /// holes use [`Self::array_set_length`], which no longer allocates them.
1585    pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
1586        Gc::new(
1587            heap,
1588            JsObject::new(
1589                ObjectKind::Array {
1590                    elements: Vec::with_capacity(capacity),
1591                    length: 0,
1592                },
1593                proto,
1594            ),
1595        )
1596    }
1597
1598    /// A callable object.
1599    pub fn function(
1600        heap: &js_gc::Heap,
1601        proto: Option<Gc<JsObject>>,
1602        callable: Callable,
1603    ) -> Gc<JsObject> {
1604        Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
1605    }
1606
1607    /// Run `f` with the object's data borrowed.
1608    pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
1609        f(&self.data.borrow())
1610    }
1611
1612    /// Run `f` with the object's data mutably borrowed.
1613    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
1614        f(&mut self.data.borrow_mut())
1615    }
1616
1617    /// Whether this object can be called.
1618    ///
1619    /// Covers every [`Callable`] variant, `Bound` included: `typeof bound ===
1620    /// "function"` and `bound()` works, so from a script's point of view a bound
1621    /// function is a function.
1622    pub fn is_callable(&self) -> bool {
1623        match &self.data.borrow().kind {
1624            ObjectKind::Function(_) => true,
1625            // A proxy is callable exactly when its target was when the proxy was built.
1626            // Not "when its target still is": revoking drops the target but leaves
1627            // `[[Call]]` in place, so a revoked proxy over a function stays a function.
1628            // This is what makes `typeof proxyOfFunction === "function"` survive revoke.
1629            ObjectKind::Proxy(state) => state.borrow().callable,
1630            _ => false,
1631        }
1632    }
1633
1634    /// Whether this object has a `[[Construct]]`, i.e. may be the target of `new` or
1635    /// `Reflect.construct`.
1636    pub fn is_constructor(&self) -> bool {
1637        let data = self.data.borrow();
1638        match &data.kind {
1639            // The flag, not "is a function": a plain method is a function and is not a
1640            // constructor. Set at creation by whoever knows what was built.
1641            ObjectKind::Function(_) => data.constructible,
1642            // Recorded at creation for the same reason as callability: revoking drops the
1643            // target without taking `[[Construct]]` away.
1644            ObjectKind::Proxy(state) => state.borrow().constructible,
1645            _ => false,
1646        }
1647    }
1648
1649    /// Give this function a `[[Construct]]`.
1650    ///
1651    /// Only for callables that are constructors by definition: ordinary functions, class
1652    /// constructors, and the built-in constructors. Everything else — methods, arrows,
1653    /// generators, async functions — keeps the default `false`.
1654    pub fn set_constructible(&self, yes: bool) {
1655        self.data.borrow_mut().constructible = yes;
1656    }
1657
1658    /// This object's proxy slots, when it is one (revoked or not).
1659    pub fn proxy_state(&self) -> Option<ProxyRef> {
1660        match &self.data.borrow().kind {
1661            ObjectKind::Proxy(state) => Some(state.clone()),
1662            _ => None,
1663        }
1664    }
1665
1666    /// A proxy over `target` reading its traps from `handler`.
1667    ///
1668    /// The prototype stays empty on purpose: `[[GetPrototypeOf]]` on a proxy forwards to
1669    /// the target through the `getPrototypeOf` trap, so copying the target's prototype
1670    /// here would be a second, disagreeing source of truth.
1671    pub fn proxy(heap: &js_gc::Heap, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
1672        // Read callability from the target *now*: it is the one moment the answer is
1673        // available, and it outlives revocation.
1674        let callable = target.is_callable();
1675        let constructible = target.is_constructor();
1676        Gc::new(
1677            heap,
1678            JsObject::new(
1679                ObjectKind::Proxy(std::rc::Rc::new(std::cell::RefCell::new(ProxyState {
1680                    callable,
1681                    constructible,
1682                    target: Some(target),
1683                    handler: Some(handler),
1684                }))),
1685                None,
1686            ),
1687        )
1688    }
1689
1690    /// The prototype.
1691    pub fn proto(&self) -> Option<Gc<JsObject>> {
1692        self.data.borrow().proto.clone()
1693    }
1694
1695    /// Replace the prototype.
1696    pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
1697        self.data.borrow_mut().proto = proto;
1698    }
1699
1700    /// The object a method was defined on, for `super` to resolve against.
1701    pub fn home_object(&self) -> Option<Gc<JsObject>> {
1702        self.data.borrow().home_object.clone()
1703    }
1704
1705    /// Record the object a method was defined on.
1706    ///
1707    /// A method has no `[[Construct]]` (§10.2.1): `new (o.m)` is a `TypeError` even
1708    /// though `o.m` is a function. Acquiring a home object is exactly the moment a
1709    /// function becomes a method, so the flag is cleared here rather than left to every
1710    /// method-defining call site to remember.
1711    pub fn set_home_object(&self, home: Option<Gc<JsObject>>) {
1712        let mut data = self.data.borrow_mut();
1713        data.home_object = home.clone();
1714        if home.is_some() {
1715            data.constructible = false;
1716        }
1717    }
1718
1719    /// The brand symbol this object owns as a class home object, if it is one.
1720    pub fn private_brand(&self) -> Option<Gc<crate::value::JsSymbol>> {
1721        self.data.borrow().private_brand.clone()
1722    }
1723
1724    /// Record `symbol` as the brand this object owns.
1725    pub fn set_private_brand(&self, symbol: Gc<crate::value::JsSymbol>) {
1726        self.data.borrow_mut().private_brand = Some(symbol);
1727    }
1728
1729    /// Whether this object carries `symbol` among its brands.
1730    ///
1731    /// This is the question `check_brand` asks of the receiver, and the one `add_brand`
1732    /// asks before adding — a second `add_brand` with the same symbol is the reference's
1733    /// "private method is already present".
1734    pub fn carries_brand(&self, symbol: &Gc<crate::value::JsSymbol>) -> bool {
1735        self.data
1736            .borrow()
1737            .brands
1738            .iter()
1739            .any(|own| Gc::ptr_eq(own, symbol))
1740    }
1741
1742    /// Give this object the brand `symbol`.
1743    pub fn add_brand(&self, symbol: Gc<crate::value::JsSymbol>) {
1744        self.data.borrow_mut().brands.push(symbol);
1745    }
1746
1747    /// Whether this is a class constructor.
1748    pub fn is_class_constructor(&self) -> bool {
1749        self.data.borrow().class_constructor
1750    }
1751
1752    /// Mark this function as a class constructor.
1753    pub fn set_class_constructor(&self, yes: bool) {
1754        self.data.borrow_mut().class_constructor = yes;
1755    }
1756
1757    /// The elements of an array object, if this is one.
1758    pub fn array_elements(&self) -> Option<Vec<Value>> {
1759        match &self.data.borrow().kind {
1760            ObjectKind::Array { elements, .. } => Some(elements.clone()),
1761            _ => None,
1762        }
1763    }
1764
1765    /// Every own key with its descriptor, array indices included.
1766    ///
1767    /// [`JsObject::own_property_keys`] answers the same question without the
1768    /// descriptors; a proxy invariant needs both at once, because it has to check the
1769    /// *value* of a key it is told about and the presence of a key it is not.
1770    pub fn property_entries(&self) -> Vec<(PropertyKey, Property)> {
1771        let data = self.data.borrow();
1772        let mut out: Vec<(PropertyKey, Property)> = data.props.to_vec();
1773        // An array's elements live in their own vector rather than the property table, so
1774        // they have to be synthesized — with the attributes an ordinary element has.
1775        if let ObjectKind::Array { elements, .. } = &data.kind {
1776            for (index, element) in elements.iter().enumerate() {
1777                if matches!(element, Value::Hole) {
1778                    continue;
1779                }
1780                let key = PropertyKey::from(index.to_string());
1781                if !out.iter().any(|(existing, _)| *existing == key) {
1782                    out.push((key, Property::data(element.clone())));
1783                }
1784            }
1785        }
1786        // `length` is own on an array without being in the property table either. It is
1787        // writable, non-enumerable and — the part proxy invariants care about —
1788        // non-configurable, so leaving it out let a handler hide or redefine it.
1789        if matches!(data.kind, ObjectKind::Array { .. })
1790            && let Some(length) = self.array_length()
1791        {
1792            let key = PropertyKey::from("length");
1793            if !out.iter().any(|(existing, _)| *existing == key) {
1794                out.push((
1795                    key,
1796                    Property {
1797                        value: Some(length_value(length)),
1798                        writable: self.length_writable(),
1799                        enumerable: false,
1800                        configurable: false,
1801                        getter: None,
1802                        setter: None,
1803                    },
1804                ));
1805            }
1806        }
1807        out
1808    }
1809
1810    /// Whether this object has array elements at all.
1811    pub fn is_array(&self) -> bool {
1812        match &self.data.borrow().kind {
1813            ObjectKind::Array { .. } => true,
1814            // `Array.isArray` is specified to see *through* a proxy: it forwards
1815            // `[[Get]]`/prototype checks to the target, and the answer for a proxy of an
1816            // array is yes.
1817            ObjectKind::Proxy(state) => state
1818                .borrow()
1819                .target
1820                .as_ref()
1821                .is_some_and(|target| target.is_array()),
1822            _ => false,
1823        }
1824    }
1825
1826    /// `length` for an array, reading it out of the element vector.
1827    /// The compiled pattern, when this object is a `RegExp`.
1828    pub fn regexp(&self) -> Option<crate::builtins::regexp::RegExpData> {
1829        match &self.data.borrow().kind {
1830            ObjectKind::RegExp(data) => Some(data.clone()),
1831            _ => None,
1832        }
1833    }
1834
1835    /// The held resources, when this object is a `DisposableStack`.
1836    pub fn disposable_stack(&self) -> Option<crate::builtins::disposable::StackState> {
1837        match &self.data.borrow().kind {
1838            ObjectKind::DisposableStack(state) => Some(state.clone()),
1839            _ => None,
1840        }
1841    }
1842
1843    /// Make this object a `DisposableStack` holding `state`.
1844    pub fn set_disposable_stack(&self, state: crate::builtins::disposable::StackState) {
1845        self.data.borrow_mut().kind = ObjectKind::DisposableStack(state);
1846    }
1847
1848    /// Make this object a `RegExp` carrying `data`.
1849    pub fn set_regexp(&self, data: crate::builtins::regexp::RegExpData) {
1850        self.data.borrow_mut().kind = ObjectKind::RegExp(data);
1851    }
1852
1853    /// Whether this object is a `RegExp`.
1854    pub fn is_regexp(&self) -> bool {
1855        matches!(self.data.borrow().kind, ObjectKind::RegExp(_))
1856    }
1857
1858    /// An array's element count, when this object is an array.
1859    pub fn array_length(&self) -> Option<usize> {
1860        match &self.data.borrow().kind {
1861            ObjectKind::Array { length, .. } => Some(*length),
1862            _ => None,
1863        }
1864    }
1865
1866    /// How many elements are actually allocated, which is at most the length.
1867    ///
1868    /// Distinct from [`Self::array_length`] on purpose: `new Array(5)` has a length of 5
1869    /// and nothing allocated, and the difference is what tells a store that fills a hole
1870    /// (it has to grow the vector) from one that overwrites an existing element.
1871    pub fn array_allocated(&self) -> usize {
1872        match &self.data.borrow().kind {
1873            ObjectKind::Array { elements, .. } => elements.len(),
1874            _ => 0,
1875        }
1876    }
1877
1878    /// Read one array element.
1879    pub fn array_get(&self, index: usize) -> Option<Value> {
1880        match &self.data.borrow().kind {
1881            ObjectKind::Array { elements, .. } => elements.get(index).cloned(),
1882            _ => None,
1883        }
1884    }
1885
1886    /// Append to an array and return the new length.
1887    pub fn array_push(&self, heap: &js_gc::Heap, value: Value) -> usize {
1888        let mut data = self.data.borrow_mut();
1889        match &mut data.kind {
1890            ObjectKind::Array { elements, length } => {
1891                let before = elements.capacity();
1892                elements.push(value);
1893                *length = elements.len();
1894                charge_capacity::<Value>(heap, before, elements.capacity());
1895                *length
1896            }
1897            _ => 0,
1898        }
1899    }
1900
1901    /// Store into an array, and return whether the write happened.
1902    ///
1903    /// The gap an out-of-range store leaves behind is filled with [`Value::Hole`], not
1904    /// `undefined`: `a = [1]; a[3] = 4` has holes at 1 and 2, which `forEach` skips
1905    /// and the debug printer reports. A store *of* `undefined` is a real element.
1906    pub fn array_set(&self, heap: &js_gc::Heap, index: usize, value: Value) -> bool {
1907        let mut data = self.data.borrow_mut();
1908        match &mut data.kind {
1909            ObjectKind::Array { elements, length } => {
1910                let before = elements.capacity();
1911                // Growing has to fill the gap, and filling it means the vector really does
1912                // hold `index + 1` slots — a store at `2^32-2` is 68 GB whatever the length
1913                // field says, which is why the reference's allocation fails there. Refuse
1914                // instead of aborting the process, and let the caller take the sparse path
1915                // (an ordinary property plus a longer `length`).
1916                //
1917                // The bound is checked for *both* branches. It used to be checked only when
1918                // the index was past `length`, on the reasoning that an index inside the
1919                // length is at most `length` — true, and useless once `length` is 2^32-1:
1920                // `a.length` can be set to 4 billion without allocating anything, so the
1921                // very next store inside it asked for a 68 GB vector. That took eight
1922                // seconds and tens of gigabytes to discover.
1923                if index + 1 > ARRAY_ELEMENT_LIMIT {
1924                    return false;
1925                }
1926                if index >= *length {
1927                    elements.resize(index + 1, Value::Hole);
1928                    *length = elements.len();
1929                } else if index >= elements.len() {
1930                    // Inside the logical length but past the dense prefix: a hole that is
1931                    // being filled, so the vector has to catch up first.
1932                    elements.resize(index + 1, Value::Hole);
1933                }
1934                elements[index] = value;
1935                charge_capacity::<Value>(heap, before, elements.capacity());
1936                true
1937            }
1938            _ => false,
1939        }
1940    }
1941
1942    /// Store an element, honouring its attributes, reporting whether it happened.
1943    ///
1944    /// Array methods that write back (`sort`, `reverse`, `splice`, …) use this rather
1945    /// than [`Self::array_set`]: the spec has them go through `[[Set]]`, so a frozen
1946    /// element makes them throw instead of being quietly overwritten.
1947    pub fn array_store(&self, heap: &js_gc::Heap, index: usize, value: Value) -> bool {
1948        if self.elements_writable() {
1949            return self.array_set(heap, index, value);
1950        }
1951        if self.element_attributes(index as u32).is_some() {
1952            // A recorded descriptor decides on its own.
1953            return !self.element_is_locked(index as u32) && self.array_set(heap, index, value);
1954        }
1955        false
1956    }
1957
1958    /// Store `value` as a plain element without creating holes, used by `push`.
1959    pub fn array_push_hole(&self, heap: &js_gc::Heap) -> bool {
1960        let mut data = self.data.borrow_mut();
1961        match &mut data.kind {
1962            ObjectKind::Array { elements, length } => {
1963                let before = elements.capacity();
1964                elements.push(Value::Hole);
1965                *length = elements.len();
1966                charge_capacity::<Value>(heap, before, elements.capacity());
1967                true
1968            }
1969            _ => false,
1970        }
1971    }
1972
1973    /// Set the length of an array, truncating or extending with holes.
1974    ///
1975    /// `a.length = 5` on a two-element array leaves three holes, so the fill value is
1976    /// [`Value::Hole`] rather than `undefined`.
1977    /// Growing only records the new length: the extra slots are holes, and a hole needs
1978    /// no storage. That is what makes `a = []; a.length = 4294967295` an O(1) operation
1979    /// instead of a 62 GB allocation.
1980    pub fn array_set_length(&self, heap: &js_gc::Heap, new_length: usize) -> bool {
1981        let mut data = self.data.borrow_mut();
1982        let ObjectData { kind, props, .. } = &mut *data;
1983        match kind {
1984            ObjectKind::Array { elements, length } => {
1985                let before = elements.capacity();
1986                if new_length < *length {
1987                    // Shrinking really does drop the trailing elements.
1988                    elements.truncate(new_length);
1989                    // …and the sparse ones, which live in the property table: §10.4.2.4
1990                    // deletes *every* index at or above the new length, not only the dense
1991                    // prefix. An index past the dense limit is an ordinary property (see
1992                    // [`Self::array_set`]), so without this `x[4294967294] = 1; x.length = 2`
1993                    // left the value readable — `S15.4.5.2_A3_T4` is that case.
1994                    drop_sparse_indices(props, new_length);
1995                }
1996                *length = new_length;
1997                charge_capacity::<Value>(heap, before, elements.capacity());
1998                true
1999            }
2000            _ => false,
2001        }
2002    }
2003
2004    /// Truncate an array to `length` elements without extending it.
2005    ///
2006    /// This is what `arr.length = n` does for `n` smaller than the current length;
2007    /// it is separate from [`Self::array_set_length`] because growing an array by
2008    /// assignment produces holes, which are indistinguishable from `undefined`
2009    /// here.
2010    pub fn array_truncate(&self, heap: &js_gc::Heap, new_length: usize) -> bool {
2011        let mut data = self.data.borrow_mut();
2012        let ObjectData { kind, props, .. } = &mut *data;
2013        match kind {
2014            ObjectKind::Array { elements, length } => {
2015                let before = elements.capacity();
2016                if new_length < elements.len() {
2017                    elements.truncate(new_length);
2018                }
2019                if new_length < *length {
2020                    *length = new_length;
2021                    drop_sparse_indices(props, new_length);
2022                }
2023                charge_capacity::<Value>(heap, before, elements.capacity());
2024                true
2025            }
2026            _ => false,
2027        }
2028    }
2029
2030    /// The own data property `key`, if there is one.
2031    pub fn own_property_key(&self, key: &PropertyKey) -> Option<Property> {
2032        let data = self.data.borrow();
2033        data.props
2034            .iter()
2035            .find(|(existing, _)| existing == key)
2036            .map(|(_, property)| property.clone())
2037    }
2038
2039    /// The address of this object, for an inline cache's hash.
2040    ///
2041    /// Only ever hashed, never dereferenced — and a hash collision is caught by the
2042    /// re-validation, never trusted. Compare a cached handle instead when identity matters.
2043    pub fn address(&self) -> usize {
2044        self as *const JsObject as usize
2045    }
2046
2047    /// The data property at `index`, if the table still has `key` there as a plain value.
2048    ///
2049    /// This is the read half of an inline cache: the caller remembers *where* a property was
2050    /// found on a particular object, and this re-checks the two things that could have
2051    /// changed — the entry moving (the table is a `Vec`, so a delete shifts it) and the
2052    /// property becoming an accessor. Re-checking is what makes the cache safe without
2053    /// shape/hidden-class machinery: there is no pointer arithmetic on a remembered index,
2054    /// only a bounds-checked lookup followed by an equality test.
2055    /// The value at `index` if the table still has the shape the entry recorded.
2056    ///
2057    /// One borrow for what [`Self::props_len`] followed by [`Self::cached_data_property`]
2058    /// does with two, and it answers from a single lookup instead of two. That pair is the
2059    /// whole body of a monomorphic cache hit, so the extra `RefCell` borrow was per
2060    /// property read in every loop there is.
2061    pub fn cached_property_at(
2062        &self,
2063        index: usize,
2064        key: &PropertyKey,
2065        expected_len: usize,
2066    ) -> Option<Value> {
2067        let data = self.data.borrow();
2068        if data.props.len() != expected_len {
2069            return None;
2070        }
2071        let (existing, property) = data.props.get(index)?;
2072        if existing != key || property.is_accessor() {
2073            return None;
2074        }
2075        property.value.clone()
2076    }
2077
2078    /// The data property at `index`, if the table still has `key` there as a plain value.
2079    ///
2080    /// The two-check form, for callers that have not already validated the table length.
2081    /// A cache hit on level 0 should use [`Self::cached_property_at`], which folds the
2082    /// length check into the same borrow.
2083    pub fn cached_data_property(&self, index: usize, key: &PropertyKey) -> Option<Value> {
2084        let data = self.data.borrow();
2085        let (existing, property) = data.props.get(index)?;
2086        if existing != key || property.is_accessor() {
2087            return None;
2088        }
2089        property.value.clone()
2090    }
2091
2092    /// The own data property at `index`, if the key there is still `name`.
2093    ///
2094    /// The global-variable cache's validation. It takes a `&str` rather than a
2095    /// `PropertyKey` on purpose: building a key allocates, and a cache that allocates on
2096    /// every hit is not a cache. The index and the name together are enough — the caller
2097    /// has already compared the name to the one it recorded.
2098    /// The own data property at `index`, if the key there is still `name`.
2099    ///
2100    /// The global-variable cache's validation. The caller passes the name it is looking
2101    /// for and this compares it against *the table's* entry — catching both the property
2102    /// being replaced by an accessor and the entry moving when a delete shifted the `Vec`.
2103    ///
2104    /// It takes a `&str` rather than a `PropertyKey` on purpose: building a key allocates,
2105    /// and a cache that allocates on every hit is not a cache.
2106    pub fn data_property_at(&self, index: usize, name: &str) -> Option<Value> {
2107        let data = self.data.borrow();
2108        let (existing, property) = data.props.get(index)?;
2109        if existing.as_str() != Some(name) || property.is_accessor() {
2110            return None;
2111        }
2112        property.value.clone()
2113    }
2114
2115    /// The number of own properties, for an inline cache's invalidation guard.
2116    ///
2117    /// A prototype-hit cache records this for every link of the chain it walked: adding or
2118    /// deleting *any* property moves it, which is what makes a stale entry a miss rather
2119    /// than a wrong answer.
2120    pub fn props_len(&self) -> usize {
2121        self.data.borrow().props.len()
2122    }
2123
2124    /// The index of the own **data** property `name`, for filling a cache.
2125    ///
2126    /// An accessor answers `None` — it must never be cached, because running its getter
2127    /// is the whole point of not caching it.
2128    pub fn own_data_index(&self, name: &str) -> Option<usize> {
2129        let data = self.data.borrow();
2130        let index = data
2131            .props
2132            .iter()
2133            .position(|(existing, _)| existing.as_str() == Some(name))?;
2134        let (_, property) = &data.props[index];
2135        if property.is_accessor() || property.value.is_none() {
2136            return None;
2137        }
2138        Some(index)
2139    }
2140
2141    /// Where `key` sits in this object's own property table, for caching.
2142    pub fn own_property_index(&self, key: &PropertyKey) -> Option<(usize, Value)> {
2143        let data = self.data.borrow();
2144        let index = data
2145            .props
2146            .iter()
2147            .position(|(existing, _)| existing == key)?;
2148        let (_, property) = &data.props[index];
2149        if property.is_accessor() {
2150            return None;
2151        }
2152        Some((index, property.value.clone()?))
2153    }
2154
2155    /// The own data property `name`, if there is one.
2156    pub fn own_property(&self, name: &str) -> Option<Property> {
2157        self.own_property_key(&PropertyKey::from(name))
2158    }
2159
2160    /// Whether the object has an own property `key`.
2161    pub fn has_own_key(&self, key: &PropertyKey) -> bool {
2162        let data = self.data.borrow();
2163        data.props.iter().any(|(existing, _)| existing == key)
2164    }
2165
2166    /// Whether the object has an own property `name`.
2167    pub fn has_own(&self, name: &str) -> bool {
2168        self.has_own_key(&PropertyKey::from(name))
2169    }
2170
2171    /// Define or replace an own property, keeping the original position when the
2172    /// key already exists.
2173    pub fn define_key(&self, key: &PropertyKey, property: Property) {
2174        let mut data = self.data.borrow_mut();
2175        match data.props.iter_mut().find(|(existing, _)| existing == key) {
2176            Some((_, slot)) => *slot = property,
2177            None => data.props.push((key.clone(), property)),
2178        }
2179    }
2180
2181    /// Define or replace an own property under a string key.
2182    pub fn define(&self, name: &str, property: Property) {
2183        self.define_key(&PropertyKey::from(name), property);
2184    }
2185
2186    /// Define an own data property, with the default attributes.
2187    ///
2188    /// This *creates*: on an existing property it overwrites the attributes too, so
2189    /// it is the wrong call for a plain assignment. Use [`Self::write_value`] for that.
2190    pub fn define_data(&self, name: &str, value: Value) {
2191        self.define(name, Property::data(value));
2192    }
2193
2194    /// Define an own data property under `key`.
2195    pub fn define_data_key(&self, key: &PropertyKey, value: Value) {
2196        self.define_key(key, Property::data(value));
2197    }
2198
2199    /// Store a value into an existing own data property, keeping its attributes.
2200    ///
2201    /// Returns `false` when the property is absent, is an accessor, or is not
2202    /// writable. An assignment has to go through this rather than
2203    /// [`Self::define_data`], because redefining is how a non-configurable global
2204    /// silently became configurable again and started answering `delete` with `true`.
2205    pub fn write_value(&self, name: &str, value: Value) -> bool {
2206        self.write_value_key(&PropertyKey::from(name), value)
2207    }
2208
2209    /// Store a value into an existing own data property under `key`.
2210    pub fn write_value_key(&self, key: &PropertyKey, value: Value) -> bool {
2211        let mut data = self.data.borrow_mut();
2212        let Some((_, property)) = data.props.iter_mut().find(|(existing, _)| existing == key)
2213        else {
2214            return false;
2215        };
2216        if property.is_accessor() || !property.writable {
2217            return false;
2218        }
2219        property.value = Some(value);
2220        true
2221    }
2222
2223    /// Delete an own property, reporting whether it was there and removable.
2224    pub fn delete(&self, name: &str) -> bool {
2225        self.delete_key(&PropertyKey::from(name))
2226    }
2227
2228    /// Delete an own property under `key`.
2229    pub fn delete_key(&self, key: &PropertyKey) -> bool {
2230        let mut data = self.data.borrow_mut();
2231        match data.props.iter().position(|(existing, _)| existing == key) {
2232            Some(index) => {
2233                if data.props[index].1.configurable {
2234                    data.props.remove(index);
2235                    true
2236                } else {
2237                    false
2238                }
2239            }
2240            None => true,
2241        }
2242    }
2243
2244    /// Whether new properties may be added.
2245    pub fn is_extensible(&self) -> bool {
2246        self.data.borrow().extensible
2247    }
2248
2249    /// Make the object non-extensible.
2250    pub fn set_extensible(&self, extensible: bool) {
2251        self.data.borrow_mut().extensible = extensible;
2252    }
2253
2254    /// Whether array elements may be replaced.
2255    pub fn elements_writable(&self) -> bool {
2256        self.data.borrow().elements_writable
2257    }
2258
2259    /// Whether an array's `length` may be changed.
2260    pub fn length_writable(&self) -> bool {
2261        self.data.borrow().length_writable
2262    }
2263
2264    /// Record whether `length` may be changed.
2265    pub fn set_length_writable(&self, writable: bool) {
2266        self.data.borrow_mut().length_writable = writable;
2267    }
2268
2269    /// Make array elements read-only, as `Object.freeze` does.
2270    pub fn set_elements_writable(&self, writable: bool) {
2271        self.data.borrow_mut().elements_writable = writable;
2272    }
2273
2274    /// The attributes recorded for an array index, if `defineProperty` set any.
2275    pub fn element_attributes(&self, index: u32) -> Option<Property> {
2276        self.own_property(&index.to_string())
2277    }
2278
2279    /// Whether `delete` at `index` would be rejected.
2280    ///
2281    /// Separate from [`JsObject::element_is_locked`]: a store needs the element to be
2282    /// non-writable, but a *delete* — which is what truncating an array does — only needs
2283    /// it to be non-configurable. `Object.defineProperty(a, "3", {configurable: false})`
2284    /// leaves `a[3]` writable and yet undeletable, so `a.length = 2` must fail.
2285    pub fn element_is_undeletable(&self, index: u32) -> bool {
2286        if !self.elements_writable() {
2287            return true;
2288        }
2289        self.element_attributes(index)
2290            .is_some_and(|property| !property.configurable)
2291    }
2292
2293    /// The lowest index at or above `from` whose element cannot be deleted.
2294    ///
2295    /// Callers use this to refuse a shrinking `length` (§10.4.2.4 deletes every index at or
2296    /// above the new length, and a non-configurable one makes that impossible). Scanning
2297    /// `from..length` instead is what a *sparse* array turns into an hour-long loop: after
2298    /// `x[2**32 - 2] = 1`, `x.length = 2` would ask `element_is_undeletable` four billion
2299    /// times. Only two things can be undeletable — a frozen object (every element) and an
2300    /// index with a recorded descriptor (a handful) — so this looks at exactly those.
2301    pub fn first_undeletable_at_or_above(&self, from: usize) -> Option<usize> {
2302        if !self.elements_writable() {
2303            return Some(from);
2304        }
2305        let data = self.data.borrow();
2306        data.props
2307            .iter()
2308            .filter_map(|(key, property)| {
2309                let index = key.as_str().and_then(array_index)? as usize;
2310                (index >= from && !property.configurable).then_some(index)
2311            })
2312            .min()
2313    }
2314
2315    /// The highest index in `from..below` whose element cannot be deleted.
2316    ///
2317    /// The spec's `ArraySetLength` walks *down* from the current length and stops at the
2318    /// first element it cannot delete, so the answer it needs is the last one.
2319    pub fn last_undeletable_at_or_above(&self, from: usize, below: usize) -> Option<usize> {
2320        if below <= from {
2321            return None;
2322        }
2323        if !self.elements_writable() {
2324            return Some(below - 1);
2325        }
2326        let data = self.data.borrow();
2327        data.props
2328            .iter()
2329            .filter_map(|(key, property)| {
2330                let index = key.as_str().and_then(array_index)? as usize;
2331                (index >= from && index < below && !property.configurable).then_some(index)
2332            })
2333            .max()
2334    }
2335
2336    /// Whether a store at `index` would be rejected.
2337    ///
2338    /// An element is locked either by `Object.freeze` on the whole object or by a
2339    /// non-configurable, non-writable descriptor recorded for that one index.
2340    pub fn element_is_locked(&self, index: u32) -> bool {
2341        if !self.elements_writable() {
2342            return true;
2343        }
2344        self.element_attributes(index)
2345            .is_some_and(|property| !property.writable && !property.configurable)
2346    }
2347
2348    /// The own property *names*, in definition order. Symbol keys are excluded:
2349    /// `Object.keys` and `for…in` cannot see them.
2350    pub fn own_keys(&self) -> Vec<crate::value::Wtf8> {
2351        self.data
2352            .borrow()
2353            .props
2354            .iter()
2355            .filter_map(|(key, _)| key.as_wtf8().cloned())
2356            .collect()
2357    }
2358
2359    /// The own *enumerable* property names, in definition order.
2360    pub fn own_enumerable_keys(&self) -> Vec<crate::value::Wtf8> {
2361        self.data
2362            .borrow()
2363            .props
2364            .iter()
2365            .filter(|(_, property)| property.enumerable)
2366            .filter_map(|(key, _)| key.as_wtf8().cloned())
2367            .collect()
2368    }
2369
2370    /// The own symbol keys, in definition order, for `Object.getOwnPropertySymbols`.
2371    pub fn own_symbol_keys(&self) -> Vec<Gc<JsSymbol>> {
2372        self.data
2373            .borrow()
2374            .props
2375            .iter()
2376            .filter_map(|(key, _)| match key {
2377                // Private names are invisible to enumeration; see `JsSymbol::is_private`.
2378                PropertyKey::Symbol(symbol) if !symbol.is_private() => Some(symbol.clone()),
2379                PropertyKey::Symbol(_) | PropertyKey::String(_) => None,
2380            })
2381            .collect()
2382    }
2383
2384    /// Every own key, strings first then symbols — the order `Reflect.ownKeys` and
2385    /// `Object.getOwnPropertyDescriptors` report, and the order `JSON.stringify`
2386    /// walks before it skips the symbols.
2387    pub fn own_property_keys(&self) -> Vec<PropertyKey> {
2388        let data = self.data.borrow();
2389        let mut strings: Vec<PropertyKey> = Vec::new();
2390        let mut symbols: Vec<PropertyKey> = Vec::new();
2391        for (key, _) in &data.props {
2392            if let PropertyKey::Symbol(symbol) = key {
2393                // A class-private name is not an own key for any observable purpose.
2394                if !symbol.is_private() {
2395                    symbols.push(key.clone());
2396                }
2397            } else {
2398                strings.push(key.clone());
2399            }
2400        }
2401        strings.extend(symbols);
2402        strings
2403    }
2404
2405    /// Own property keys in **definition order**, with symbols interleaved.
2406    ///
2407    /// [`JsObject::own_property_keys`] answers in the spec's order — integer-like keys
2408    /// ascending, then strings, then symbols — because that is what `Reflect.ownKeys` and
2409    /// `for...in` must do. A dumper has the opposite requirement: quickjs's
2410    /// `JS_PrintValue` walks the shape, so `{[Symbol("t")]: 1, y: 2}` prints the symbol
2411    /// first. That is not observable from a script except through such a dump, which is
2412    /// why this is a separate accessor rather than a change to `own_property_keys`.
2413    pub fn own_property_keys_in_definition_order(&self) -> Vec<PropertyKey> {
2414        self.data
2415            .borrow()
2416            .props
2417            .iter()
2418            .map(|(key, _)| key.clone())
2419            .collect()
2420    }
2421
2422    /// The prototype chain, starting with the prototypes of this object.
2423    pub fn chain(&self) -> Vec<Gc<JsObject>> {
2424        let mut out = Vec::new();
2425        let mut proto = self.proto();
2426        while let Some(object) = proto {
2427            proto = object.proto();
2428            out.push(object);
2429        }
2430        out
2431    }
2432}
2433
2434/// Whether two prototypes are the same one, `None` included.
2435///
2436/// A proxy's prototype invariants have to compare "no prototype" against "no
2437/// prototype" without unwrapping either side first.
2438pub(crate) fn same_proto(a: Option<&Gc<JsObject>>, b: Option<&Gc<JsObject>>) -> bool {
2439    match (a, b) {
2440        (None, None) => true,
2441        (Some(a), Some(b)) => a.ptr_eq(b),
2442        _ => false,
2443    }
2444}
2445
2446/// Walk the prototype chain from `object` looking for `name`.
2447///
2448/// Returns the object that owns the property along with the property itself. The
2449/// owner matters for a store: an inherited accessor is invoked on the receiver,
2450/// while an inherited *data* property is shadowed by a new own property.
2451/// The own property `key` names on `object`, arrays included.
2452///
2453/// An array keeps its elements in an element vector and derives its `length`, so its
2454/// property table knows about neither: a hole is a slot in the vector, not a missing
2455/// property, and `length` is not stored at all. `Array.prototype` is itself an array, so
2456/// every walk down the chain needs this same care — without it `1 in [1,,3]` stayed false
2457/// with `Array.prototype[1]` defined, `"length" in []` was false outright, and a hole did
2458/// not read an inherited element.
2459pub fn own_property_including_array(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2460    if let Some(property) = object.own_property_key(key) {
2461        return Some(property);
2462    }
2463    // A typed array's indices are its elements in the buffer, which the property table
2464    // does not hold either. Checked before the `is_array` return below, because a typed
2465    // array is not one.
2466    if object.typed_array_parts().is_some() {
2467        // A detached view exposes no indices at all: `Reflect.has(detached, "0")` is false
2468        // even though index 0 was in range before the buffer went away.
2469        let index = key.as_str().and_then(array_index)?;
2470        let in_range = (index as usize) < object.typed_array_length()?;
2471        return match object.typed_array_element(index as usize) {
2472            Some(value) if in_range => Some(Property::data(value)),
2473            _ => None,
2474        };
2475    }
2476    if !object.is_array() {
2477        return None;
2478    }
2479    let text = key.as_str()?;
2480    // `length` is non-enumerable and non-configurable; `writable` unless a definition
2481    // turned it off.
2482    if text == "length" {
2483        return Some(Property {
2484            value: Some(length_value(object.array_length()?)),
2485            writable: object.length_writable(),
2486            enumerable: false,
2487            configurable: false,
2488            getter: None,
2489            setter: None,
2490        });
2491    }
2492    // An element is a plain writable/enumerable/configurable data property, and a hole is
2493    // not one at all.
2494    let index = array_index(text)?;
2495    match object.array_get(index as usize) {
2496        Some(Value::Hole) | None => None,
2497        Some(value) => Some(Property::data(value)),
2498    }
2499}
2500
2501/// Whether `object` has `key` as an *own* property, arrays included.
2502pub fn has_own(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
2503    own_property_including_array(object, key).is_some()
2504}
2505
2506/// `key` on `object` or anywhere up its prototype chain, with the owner.
2507///
2508/// Array-aware at every step: an array's elements and its derived `length` are not in the
2509/// property table, and `Array.prototype` is itself an array.
2510pub fn lookup_key(object: &Gc<JsObject>, key: &PropertyKey) -> Option<(Gc<JsObject>, Property)> {
2511    if let Some(property) = own_property_including_array(object, key) {
2512        return Some((object.clone(), property));
2513    }
2514    for ancestor in object.chain() {
2515        if let Some(property) = own_property_including_array(&ancestor, key) {
2516            return Some((ancestor, property));
2517        }
2518    }
2519    None
2520}
2521
2522/// [`lookup_key`] for a string key.
2523pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
2524    lookup_key(object, &PropertyKey::from(name))
2525}
2526
2527/// The largest array index that may be *stored*, i.e. the largest dense vector this engine
2528/// will grow to an index for.
2529///
2530/// The spec's `length` limit is `2^32-1`, but the elements are a dense `Vec<Value>` here,
2531/// so a store at index `2^32-2` is a 68 GB reservation. The reference (which keeps
2532/// elements in a hash map) answers instantly. Refusing past this bound keeps the process
2533/// alive; the conformance tests that really do store near `2^32` are recorded in
2534/// `docs/test262-status.md` as a limitation rather than quietly answered wrong.
2535pub const ARRAY_ELEMENT_LIMIT: usize = 1 << 26;
2536
2537/// An array's `length` as a JavaScript number.
2538///
2539/// `Value::Int` only holds an `i32`, and an array's length may legitimately reach
2540/// `2^32-1`, so a plain cast is not enough: `a[2**32-2] = 1; a.length` came back as `-1`,
2541/// and `Object.getOwnPropertyDescriptor(a, "length").value` with it. Every
2542/// `LengthOfArrayLike` over such an array then ran to `-1`, and the paths without their
2543/// own `RangeError` check turned into `memory allocation of 68719476720 bytes failed`.
2544pub fn length_value(length: usize) -> Value {
2545    if length <= i32::MAX as usize {
2546        Value::Int(length as i32)
2547    } else {
2548        Value::Float(length as f64)
2549    }
2550}
2551
2552/// An array *index* as a JavaScript number.
2553///
2554/// Same problem as [`length_value`] and the same fix: an index may be as large as
2555/// `2^32-2`, which `Value::Int` cannot hold. `a[2**32-2] = 1; a.indexOf(1)` was answering
2556/// `-2` because the index was truncated on the way out.
2557pub fn index_value(index: usize) -> Value {
2558    length_value(index)
2559}
2560
2561/// The array index a property key names, if it names one.
2562///
2563/// A key is an index when it is the canonical decimal spelling of an integer below
2564/// `2^32 - 1` — the same rule the atom table uses to decide whether a key is a
2565/// tagged index. `"01"` and `"-1"` are ordinary string keys.
2566pub fn array_index(key: &str) -> Option<u32> {
2567    if key.is_empty() || key.len() > 10 {
2568        return None;
2569    }
2570    let bytes = key.as_bytes();
2571    if !bytes.iter().all(u8::is_ascii_digit) {
2572        return None;
2573    }
2574    if bytes[0] == b'0' && bytes.len() != 1 {
2575        return None;
2576    }
2577    let value: u32 = key.parse().ok()?;
2578    // `2^32 - 1` is reserved for the array length, so it is not an index.
2579    (value < u32::MAX).then_some(value)
2580}
2581
2582impl Trace for JsObject {
2583    fn trace(&self, tracer: &mut Tracer) {
2584        self.data.borrow().trace(tracer);
2585    }
2586
2587    /// Everything this object holds that is not its own box: element slots, the property
2588    /// table, `Map`/`Set` entries, an `ArrayBuffer`'s bytes.
2589    ///
2590    /// Counted by **capacity**, not length, because that is what the allocator actually
2591    /// holds — a 1000-element array with a 1024-slot vector costs 1024 slots, and reporting
2592    /// 1000 would make the limit wrong by whatever the vectors over-allocate (up to 2×).
2593    ///
2594    /// Growth in place is reported to the heap as it happens (see `JsObject::array_push`
2595    /// and friends) and this same number is subtracted when the object is freed, which is
2596    /// why the two have to agree.
2597    ///
2598    /// `try_borrow` because this can be called from inside the collector, where a mutation
2599    /// elsewhere in the engine may hold the borrow; a container that is being mutated at
2600    /// this instant is a container we cannot measure, and answering 0 for it is better than
2601    /// panicking mid-allocation.
2602    fn external_bytes(&self) -> usize {
2603        let Ok(data) = self.data.try_borrow() else {
2604            return 0;
2605        };
2606        // The property table is *not* counted. Every payload reported here is subtracted
2607        // when the box is freed, so a payload that nothing reports on growth would be
2608        // taken away twice — that abort is exactly what this comment replaced
2609        // (`attempt to subtract with overflow` in `Heap::deregister`). Property growth is
2610        // bounded by distinct keys, each of which is at least one string box that *is*
2611        // counted, so leaving the table out costs a constant factor rather than the limit.
2612        let mut total = 0;
2613        match &data.kind {
2614            ObjectKind::Array { elements, .. } => {
2615                total += elements.capacity() * std::mem::size_of::<Value>();
2616            }
2617            ObjectKind::Collection { entries, .. } => {
2618                total += entries.capacity() * std::mem::size_of::<(Value, Value)>();
2619            }
2620            ObjectKind::ArrayBuffer(storage) => {
2621                if let Ok(storage) = storage.try_borrow() {
2622                    total += storage.bytes.capacity();
2623                }
2624            }
2625            _ => {}
2626        }
2627        total
2628    }
2629}
2630
2631/// Drop the property-table entries whose key is an array index at or above `length`.
2632///
2633/// An index past the dense limit is kept as an ordinary property, so shrinking `length` has
2634/// to look there as well as in the element vector — the spec deletes every index at or above
2635/// the new length, wherever it was stored.
2636fn drop_sparse_indices(props: &mut Vec<(PropertyKey, Property)>, length: usize) {
2637    props.retain(|(key, _)| match key.as_str().and_then(array_index) {
2638        Some(index) => (index as usize) < length,
2639        None => true,
2640    });
2641}
2642
2643/// Tell the heap that a container's payload changed in place.
2644///
2645/// Reported as a **capacity** delta, the same quantity [`Trace::external_bytes`] reports, so
2646/// that the subtraction at free time takes back exactly what was added. Reporting length
2647/// instead would leave the vector's over-allocation — up to 2× — counted for ever.
2648fn charge_capacity<T>(heap: &js_gc::Heap, before: usize, after: usize) {
2649    if before == after {
2650        return;
2651    }
2652    let slot = std::mem::size_of::<T>() as isize;
2653    heap.adjust_payload((after as isize - before as isize) * slot);
2654}