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    ///
30    /// `bytes.len()` *is* the byte length: resizing is `Vec::resize`, which is what keeps the
31    /// length, the capacity and the pointer from ever disagreeing.
32    pub bytes: Vec<u8>,
33    /// Whether `transfer()` has taken the bytes away.
34    pub detached: bool,
35    /// The most bytes this buffer may grow to, or `None` when it cannot grow at all.
36    ///
37    /// `Some(max)` is what `new ArrayBuffer(n, {maxByteLength: max})` asks for: `resizable`
38    /// answers `true`, `maxByteLength` answers `max`, and `resize` may move the length
39    /// anywhere up to it. A fixed-length buffer answers `false`/the byte length.
40    pub max_byte_length: Option<usize>,
41    /// A host's "release this block" callback, run when the storage dies.
42    ///
43    /// This is what lets the C API's `JS_NewArrayBuffer` honour its `free_func` contract: the
44    /// header says the block is released when the buffer is collected, not when it is built,
45    /// and a host that counts allocations sees the difference. The bytes themselves are
46    /// *copied* — this engine's storage is a `Vec<u8>` and cannot alias a foreign pointer
47    /// without a second representation of every typed-array operation — so the callback
48    /// releases the host's original block while the storage keeps its own copy. Writes the
49    /// host makes to its block after the call are therefore not visible to script, which is
50    /// the one documented difference.
51    pub release: Option<Box<dyn FnOnce()>>,
52}
53
54impl BufferStorage {
55    /// Storage for a fixed-length buffer, which is what every caller but a resizable
56    /// constructor wants.
57    pub fn fixed(bytes: Vec<u8>) -> BufferStorage {
58        BufferStorage {
59            bytes,
60            detached: false,
61            max_byte_length: None,
62            release: None,
63        }
64    }
65
66    /// Storage for a fixed-length buffer whose origin block has to be released at collection.
67    ///
68    /// The C API's `JS_NewArrayBuffer(ctx, buf, len, free_func, opaque, …)`: the bytes are a
69    /// copy, and `release` is the closure that calls `free_func(opaque, buf)` when this
70    /// storage is dropped. Keeping the closure here rather than calling it at construction is
71    /// the whole difference between honouring the header and approximating it.
72    pub fn fixed_with_release(bytes: Vec<u8>, release: Box<dyn FnOnce()>) -> BufferStorage {
73        BufferStorage {
74            bytes,
75            detached: false,
76            max_byte_length: None,
77            release: Some(release),
78        }
79    }
80
81    /// Storage for a resizable buffer of `bytes` bytes that may grow to `max`.
82    pub fn resizable(bytes: Vec<u8>, max: usize) -> BufferStorage {
83        BufferStorage {
84            bytes,
85            detached: false,
86            max_byte_length: Some(max),
87            release: None,
88        }
89    }
90
91    /// Whether `resize` can change this buffer's length.
92    pub fn is_resizable(&self) -> bool {
93        self.max_byte_length.is_some()
94    }
95
96    /// What `maxByteLength` reports: the ceiling for a resizable buffer, and the current
97    /// length for a fixed one — which is what the getter's `IsDetachedBuffer`/`IsFixedLength`
98    /// split in the spec amounts to once the length stops changing.
99    pub fn max_byte_length(&self) -> usize {
100        match self.max_byte_length {
101            Some(max) => max,
102            None => self.bytes.len(),
103        }
104    }
105}
106
107impl Drop for BufferStorage {
108    fn drop(&mut self) {
109        // The host's callback runs here rather than in the constructor: that is the contract
110        // `JS_NewArrayBuffer`'s `free_func` states, and the difference is observable to a
111        // host that counts how many blocks it owns at any moment.
112        if let Some(release) = self.release.take() {
113            release();
114        }
115    }
116}
117
118/// How long a view is, which for a resizable buffer is not a constant.
119///
120/// `new Uint8Array(resizableBuffer)` with no length argument is **length-tracking**
121/// (§23.2.5.1 step 8: the length comes out `auto`): the view has no length of its own, it
122/// has a rule for computing one from the buffer's *current* byte length. Growing the
123/// buffer therefore grows the view, and shrinking it to nothing empties the view without
124/// detaching anything. An explicit length — or a view of a fixed-length buffer — is the
125/// other case, and its length stays put while the buffer may not fit it any more.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum ViewLength {
128    /// The length the view was created with, in its own units.
129    Fixed(usize),
130    /// Recomputed from the buffer's byte length on every access.
131    Tracking,
132}
133
134impl ViewLength {
135    /// The length as an integer, for the paths that know the view is in bounds.
136    pub fn stored(self) -> usize {
137        match self {
138            ViewLength::Fixed(length) => length,
139            // Only reachable for a view whose length was just computed; `geometry` is the
140            // one place that knows what a tracking view currently measures.
141            ViewLength::Tracking => 0,
142        }
143    }
144
145    /// Whether the length follows the buffer rather than being fixed at construction.
146    pub fn is_tracking(self) -> bool {
147        matches!(self, ViewLength::Tracking)
148    }
149}
150
151/// A view's geometry at this instant: its byte offset, its length in its own units, and
152/// whether it is out of bounds.
153///
154/// This is the whole of §10.4.5.12 (`IsTypedArrayOutOfBounds`, `TypedArrayLength`,
155/// `TypedArrayByteOffset`) shared between typed arrays and `DataView`, which differ only in
156/// what one unit is. Nothing is cached on the view: the same view goes out of bounds when
157/// its buffer shrinks and back in bounds when it grows again, and every read has to ask.
158///
159/// Out of bounds answers `(0, 0, true)` rather than the last good numbers, because that is
160/// what the spec's accessors report — `ta.byteOffset` is `0`, not the offset it was built
161/// with, once the buffer can no longer hold the view.
162fn view_geometry(
163    offset: usize,
164    length: ViewLength,
165    unit: usize,
166    buffer_bytes: usize,
167    detached: bool,
168) -> (usize, usize, bool) {
169    if detached {
170        return (0, 0, true);
171    }
172    match length {
173        // A tracking view only falls out of bounds when its *offset* alone is past the end;
174        // otherwise a partial element is simply not an element.
175        ViewLength::Tracking => {
176            if offset > buffer_bytes {
177                (0, 0, true)
178            } else {
179                (offset, (buffer_bytes - offset) / unit, false)
180            }
181        }
182        ViewLength::Fixed(count) => {
183            if offset.saturating_add(count.saturating_mul(unit)) > buffer_bytes {
184                (0, 0, true)
185            } else {
186                (offset, count, false)
187            }
188        }
189    }
190}
191
192impl JsObject {
193    /// The storage of this object, when it is an `ArrayBuffer`.
194    pub fn array_buffer_storage(&self) -> Option<Rc<RefCell<BufferStorage>>> {
195        match &self.data.borrow().kind {
196            ObjectKind::ArrayBuffer(storage) => Some(storage.clone()),
197            _ => None,
198        }
199    }
200
201    /// Make this object an `ArrayBuffer` owning `storage`.
202    pub fn set_array_buffer(&self, storage: Rc<RefCell<BufferStorage>>) {
203        self.data.borrow_mut().kind = ObjectKind::ArrayBuffer(storage);
204    }
205
206    /// The live entries of this object, when it is a `Map` or a `Set`.
207    ///
208    /// Tombstones are skipped, so this is what every *reader* wants. A live iterator must
209    /// not use it — see [`JsObject::collection_slots`].
210    pub fn collection_entries(&self) -> Option<Vec<(Value, Value)>> {
211        match &self.data.borrow().kind {
212            ObjectKind::Collection { entries, .. } => {
213                Some(entries.iter().flatten().cloned().collect())
214            }
215            _ => None,
216        }
217    }
218
219    /// The entries **with their positions**, tombstones included.
220    ///
221    /// This is `[[MapData]]`, and the reason a `Map`/`Set` iterator can be live: the spec
222    /// deletes by emptying a slot rather than by shifting the list, so an index a running
223    /// iterator holds keeps pointing at the same entry. With `retain`-style deletion,
224    /// `new Set([a,b,c])` walked by `forEach` skipped `b` as soon as the callback removed
225    /// `a` (`Map/prototype/forEach/deleted-values-during-foreach`).
226    pub fn collection_slots(&self) -> Option<Vec<Option<(Value, Value)>>> {
227        match &self.data.borrow().kind {
228            ObjectKind::Collection { entries, .. } => Some(entries.clone()),
229            _ => None,
230        }
231    }
232
233    /// Whether this object is a `Set` rather than a `Map`.
234    pub fn collection_is_set(&self) -> Option<bool> {
235        match &self.data.borrow().kind {
236            ObjectKind::Collection { is_set, .. } => Some(*is_set),
237            _ => None,
238        }
239    }
240
241    /// Make this object a `Map` or `Set` holding `entries`, with no tombstones.
242    ///
243    /// The whole-list form: for the callers that rebuild the collection (species results,
244    /// `Set` operations). A method that must *preserve* the positions a running iterator
245    /// depends on uses [`JsObject::set_collection_slots`].
246    pub fn set_collection(&self, heap: &js_gc::Heap, entries: Vec<(Value, Value)>, is_set: bool) {
247        let slots: Vec<Option<(Value, Value)>> = entries.into_iter().map(Some).collect();
248        self.set_collection_slots(heap, slots, is_set);
249    }
250
251    /// [`JsObject::set_collection`] with explicit positions, tombstones included.
252    pub fn set_collection_slots(
253        &self,
254        heap: &js_gc::Heap,
255        entries: Vec<Option<(Value, Value)>>,
256        is_set: bool,
257    ) {
258        let mut data = self.data.borrow_mut();
259        let before = match &data.kind {
260            ObjectKind::Collection { entries, .. } => entries.capacity(),
261            _ => 0,
262        };
263        let after = entries.capacity();
264        data.kind = ObjectKind::Collection { entries, is_set };
265        charge_capacity::<Option<(Value, Value)>>(heap, before, after);
266    }
267
268    /// This object's weak entries, when it is a `WeakMap` or `WeakSet`.
269    ///
270    /// Expired handles are filtered out here rather than at the call site, so every reader
271    /// sees the same live view of the map and a dead key can never be observed.
272    pub fn weak_entries(&self) -> Option<Vec<(Value, Value)>> {
273        match &self.data.borrow().kind {
274            ObjectKind::WeakCollection { entries, .. } => Some(
275                entries
276                    .iter()
277                    .filter_map(|(key, value)| key.upgrade().map(|key| (key, value.clone())))
278                    .collect(),
279            ),
280            _ => None,
281        }
282    }
283
284    /// Whether this object is a `WeakSet` rather than a `WeakMap`.
285    pub fn weak_is_set(&self) -> Option<bool> {
286        match &self.data.borrow().kind {
287            ObjectKind::WeakCollection { is_set, .. } => Some(*is_set),
288            _ => None,
289        }
290    }
291
292    /// Make this object a `WeakMap` or `WeakSet`, replacing any entries it had.
293    pub fn set_weak_collection(
294        &self,
295        heap: &js_gc::Heap,
296        entries: Vec<(WeakKey, Value)>,
297        is_set: bool,
298    ) {
299        let mut data = self.data.borrow_mut();
300        let before = match &data.kind {
301            ObjectKind::WeakCollection { entries, .. } => entries.capacity(),
302            _ => 0,
303        };
304        let after = entries.capacity();
305        data.kind = ObjectKind::WeakCollection { entries, is_set };
306        charge_capacity::<(WeakKey, Value)>(heap, before, after);
307    }
308
309    /// Store one entry in a weak collection, replacing the value for a live equal key.
310    ///
311    /// The comparison is pointer identity: a weak key has to be an object, and two objects
312    /// are the same key exactly when they are the same object. Expired entries are dropped
313    /// on the way through, which keeps the vector from growing without bound in a program
314    /// that churns keys.
315    pub fn weak_set(&self, key: WeakKey, value: Value) {
316        let mut data = self.data.borrow_mut();
317        let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
318            return;
319        };
320        entries.retain(|(existing, _)| !existing.is_expired());
321        for (existing, slot) in entries.iter_mut() {
322            if existing.same(&key) {
323                *slot = value;
324                return;
325            }
326        }
327        entries.push((key, value));
328    }
329
330    /// Remove `key` from a weak collection, answering whether it was there.
331    pub fn weak_delete(&self, key: &Value) -> bool {
332        let mut data = self.data.borrow_mut();
333        let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
334            return false;
335        };
336        let before = entries.len();
337        entries.retain(|(existing, _)| !existing.is_expired() && !existing.matches(key));
338        entries.len() != before
339    }
340
341    /// The target of a `WeakRef`, when this object is one.
342    pub fn weak_ref_target(&self) -> Option<WeakKey> {
343        match &self.data.borrow().kind {
344            ObjectKind::WeakRef { target } => Some(target.clone()),
345            _ => None,
346        }
347    }
348
349    /// Make this object a `WeakRef` to `target`.
350    pub fn set_weak_ref(&self, target: WeakKey) {
351        self.data.borrow_mut().kind = ObjectKind::WeakRef { target };
352    }
353
354    /// The registry state, when this object is a `FinalizationRegistry`.
355    pub fn finalization_state(&self) -> Option<Box<FinalizationState>> {
356        match &self.data.borrow().kind {
357            ObjectKind::Finalization(state) => Some(Box::new(FinalizationState {
358                registrations: state
359                    .registrations
360                    .iter()
361                    .map(|registration| Registration {
362                        target: registration.target.clone(),
363                        held_value: registration.held_value.clone(),
364                        token: registration.token.clone(),
365                    })
366                    .collect(),
367                cleanup: state.cleanup.clone(),
368            })),
369            _ => None,
370        }
371    }
372
373    /// Replace a registry's state.
374    pub fn set_finalization_state(&self, state: FinalizationState) {
375        self.data.borrow_mut().kind = ObjectKind::Finalization(Box::new(state));
376    }
377
378    /// `(buffer, element, offset, length)`, when this object is a typed-array view.
379    ///
380    /// The offset and length are **effective**: a view whose buffer has been resized out
381    /// from under it answers `(0, 0)`, and a length-tracking view answers what the buffer
382    /// measures now — see [`view_geometry`].
383    pub fn typed_array_parts(
384        &self,
385    ) -> Option<(
386        Gc<JsObject>,
387        crate::builtins::typedarray::ElementType,
388        usize,
389        usize,
390    )> {
391        self.typed_array_geometry()
392            .map(|(buffer, element, offset, length, _)| (buffer, element, offset, length))
393    }
394
395    /// As [`JsObject::typed_array_parts`], plus whether the view is out of bounds.
396    ///
397    /// The extra flag cannot be recovered from the length: an empty view that legitimately
398    /// sits at the end of its buffer is in bounds and answers `0`, while a view that shrank
399    /// away is out of bounds and *also* answers `0`. Every method that runs
400    /// `ValidateTypedArray` has to tell them apart, since one is allowed to return and the
401    /// other has to throw.
402    pub fn typed_array_geometry(
403        &self,
404    ) -> Option<(
405        Gc<JsObject>,
406        crate::builtins::typedarray::ElementType,
407        usize,
408        usize,
409        bool,
410    )> {
411        let (buffer, element, offset, length) = match &self.data.borrow().kind {
412            ObjectKind::TypedArray {
413                buffer,
414                element,
415                offset,
416                length,
417            } => (buffer.clone(), *element, *offset, *length),
418            _ => return None,
419        };
420        let storage = buffer.array_buffer_storage()?;
421        let storage = storage.borrow();
422        let (offset, length, oob) = view_geometry(
423            offset,
424            length,
425            element.size(),
426            storage.bytes.len(),
427            storage.detached,
428        );
429        Some((buffer, element, offset, length, oob))
430    }
431
432    /// The view's **stored** geometry: `(buffer, element, offset, length)` as it was built,
433    /// with no collapse for an out-of-bounds buffer.
434    ///
435    /// Apart from [`JsObject::typed_array_geometry`], which reports what a script sees, this
436    /// is what `subarray` needs: §23.2.3.30 computes `beginByteOffset` from
437    /// `O.[[ByteOffset]]`, and that slot keeps its value when the buffer shrinks — so
438    /// `oobView.subarray(1)` still starts at the original offset once the buffer grows back
439    /// (`subarray/result-byteOffset-from-out-of-bounds`).
440    pub fn typed_array_stored(
441        &self,
442    ) -> Option<(
443        Gc<JsObject>,
444        crate::builtins::typedarray::ElementType,
445        usize,
446        ViewLength,
447    )> {
448        match &self.data.borrow().kind {
449            ObjectKind::TypedArray {
450                buffer,
451                element,
452                offset,
453                length,
454            } => Some((buffer.clone(), *element, *offset, *length)),
455            _ => None,
456        }
457    }
458
459    /// Whether this view's length follows its buffer rather than being fixed.
460    pub fn typed_array_tracks_length(&self) -> bool {
461        matches!(
462            &self.data.borrow().kind,
463            ObjectKind::TypedArray {
464                length: ViewLength::Tracking,
465                ..
466            }
467        )
468    }
469
470    /// Whether this callable is a native function rather than compiled JavaScript.
471    ///
472    /// `construct` uses it to decide who builds the instance: a native constructor creates
473    /// its own, after validating its arguments.
474    pub fn is_native_function(&self) -> bool {
475        matches!(
476            &self.data.borrow().kind,
477            ObjectKind::Function(Callable::Native { .. })
478        )
479    }
480
481    /// Whether this native constructor builds its own instance, so `new` must not pass one.
482    pub fn native_creates_own_instance(&self) -> bool {
483        matches!(
484            &self.data.borrow().kind,
485            ObjectKind::Function(Callable::Native {
486                own_instance: true,
487                ..
488            })
489        )
490    }
491
492    /// Make this object a `DataView` over `buffer`.
493    pub fn set_data_view(&self, buffer: Gc<JsObject>, offset: usize, length: ViewLength) {
494        self.data.borrow_mut().kind = ObjectKind::DataView {
495            buffer,
496            offset,
497            length,
498        };
499    }
500
501    /// Whether this object has a `[[ViewedArrayBuffer]]` internal slot.
502    ///
503    /// Deliberately *not* `typed_array_parts().is_some() || data_view_parts().is_some()`
504    /// written at each call site: `ArrayBuffer.isView` must answer `false` for a Proxy
505    /// whose target is a view, because a Proxy has no such slot and `[[Get]]` is never
506    /// reached. Keeping the predicate here means the "no proxy, no prototype" rule lives
507    /// in one place.
508    pub fn is_array_buffer_view(&self) -> bool {
509        matches!(
510            &self.data.borrow().kind,
511            ObjectKind::TypedArray { .. } | ObjectKind::DataView { .. }
512        )
513    }
514
515    /// The `(buffer, offset, length)` of a `DataView`, or `None` when this is not one.
516    ///
517    /// Like [`JsObject::typed_array_parts`], the offset and length are effective: a
518    /// `DataView` whose buffer shrank under it answers `(0, 0)`.
519    pub fn data_view_parts(&self) -> Option<(Gc<JsObject>, usize, usize)> {
520        self.data_view_geometry()
521            .map(|(buffer, offset, length, _)| (buffer, offset, length))
522    }
523
524    /// As [`JsObject::data_view_parts`], plus whether the view is out of bounds.
525    pub fn data_view_geometry(&self) -> Option<(Gc<JsObject>, usize, usize, bool)> {
526        let (buffer, offset, length) = match &self.data.borrow().kind {
527            ObjectKind::DataView {
528                buffer,
529                offset,
530                length,
531            } => (buffer.clone(), *offset, *length),
532            _ => return None,
533        };
534        let storage = buffer.array_buffer_storage()?;
535        let storage = storage.borrow();
536        // A `DataView`'s unit is the byte, so the typed-array rule applies unchanged.
537        let (offset, length, oob) =
538            view_geometry(offset, length, 1, storage.bytes.len(), storage.detached);
539        Some((buffer, offset, length, oob))
540    }
541
542    /// Whether this `DataView`'s length follows its buffer.
543    pub fn data_view_tracks_length(&self) -> bool {
544        matches!(
545            &self.data.borrow().kind,
546            ObjectKind::DataView {
547                length: ViewLength::Tracking,
548                ..
549            }
550        )
551    }
552
553    /// Make this object a typed-array view of `length` elements.
554    pub fn set_typed_array(
555        &self,
556        buffer: Gc<JsObject>,
557        element: crate::builtins::typedarray::ElementType,
558        offset: usize,
559        length: ViewLength,
560    ) {
561        self.data.borrow_mut().kind = ObjectKind::TypedArray {
562            buffer,
563            element,
564            offset,
565            length,
566        };
567    }
568
569    /// The element type, when this object is a typed-array view.
570    pub fn typed_array_element_type(&self) -> Option<crate::builtins::typedarray::ElementType> {
571        self.typed_array_parts().map(|(_, element, _, _)| element)
572    }
573
574    /// How many elements the view exposes, or `None` when this is not a view.
575    ///
576    /// A detached or resized-away buffer reports `0`: there is nothing to index. A
577    /// length-tracking view reports what its buffer measures *now*, which is why this is
578    /// computed rather than read.
579    pub fn typed_array_length(&self) -> Option<usize> {
580        self.typed_array_geometry()
581            .map(|(_, _, _, length, _)| length)
582    }
583
584    /// Read one view element.
585    ///
586    /// Out-of-range and out-of-bounds reads are `undefined` rather than an error, which is
587    /// what makes `a[999]`, `a[0]` after the buffer shrank, and every read of a detached
588    /// view behave the way the language says.
589    pub fn typed_array_element(&self, index: usize) -> Option<Value> {
590        let (buffer, element, offset, length) = self.typed_array_parts()?;
591        let storage = buffer.array_buffer_storage()?;
592        let storage = storage.borrow();
593        if storage.detached || index >= length {
594            return Some(Value::Undefined);
595        }
596        // The buffer's own handle is where the heap comes from, so a BigInt element can be
597        // allocated without every caller having to thread one through.
598        Some(element.read(
599            buffer.heap(),
600            &storage.bytes,
601            offset + index * element.size(),
602        ))
603    }
604
605    /// Store one view element, applying the type's wrap or clamp.
606    ///
607    /// `Some(Ok(()))` stored, `Some(Err(()))` refused the *value* — a Number into a BigInt
608    /// view, which the caller turns into a `TypeError` — and `None` when this is not a
609    /// view at all or the index is out of range, which is a silent no-op.
610    pub fn typed_array_set(&self, index: usize, value: Value) -> Option<Result<(), &'static str>> {
611        let (buffer, element, offset, length) = self.typed_array_parts()?;
612        if index >= length {
613            return Some(Ok(()));
614        }
615        let storage = buffer.array_buffer_storage()?;
616        let mut storage = storage.borrow_mut();
617        if storage.detached {
618            return Some(Ok(()));
619        }
620        let stored = element.write(&mut storage.bytes, offset + index * element.size(), &value);
621        Some(stored)
622    }
623}
624
625/// A property of an object.
626#[derive(Clone, Default)]
627pub struct Property {
628    /// The value of a data property.
629    pub value: Option<Value>,
630    /// The getter of an accessor property.
631    pub getter: Option<Value>,
632    /// The setter of an accessor property.
633    pub setter: Option<Value>,
634    /// Whether the value can be replaced.
635    pub writable: bool,
636    /// Whether `for`/`Object.keys` sees the property.
637    pub enumerable: bool,
638    /// Whether the property can be deleted or redefined.
639    pub configurable: bool,
640    /// Which of the four fields a *descriptor* names, when it is not all of them.
641    ///
642    /// `None` means "all of them", which is what a whole property looks like and what
643    /// every existing caller hands over. The one producer of the partial shape is
644    /// `SetIntegrityLevel`: §7.3.3 step 3.a builds `{ [[Configurable]]: false }`, plus
645    /// `{ [[Writable]]: false }` at `Frozen`, and a proxy's `defineProperty` trap has to
646    /// see *exactly* those fields — `proxy-with-defineProperty-handler` asserts
647    /// `descriptor.value === undefined` and `descriptor.enumerable === undefined`.
648    ///
649    /// It rides on `Property` rather than becoming a second descriptor type because
650    /// `[[DefineOwnProperty]]` already takes a `Property` and threads it through six
651    /// internal methods; splitting the type would touch every one of them for a single
652    /// caller. `None` is the default, so nothing else changes.
653    pub descriptor_fields: Option<DescriptorFields>,
654}
655
656/// Which fields of a [`Property`] a descriptor names.
657#[derive(Clone, Copy, Default, PartialEq, Eq)]
658pub struct DescriptorFields {
659    /// `[[Value]]` is named.
660    pub value: bool,
661    /// `[[Writable]]` is named.
662    pub writable: bool,
663    /// `[[Enumerable]]` is named.
664    pub enumerable: bool,
665    /// `[[Configurable]]` is named.
666    pub configurable: bool,
667    /// `[[Get]]` is named.
668    ///
669    /// Needed to know that the descriptor is an *accessor* one. Without it, forwarding a
670    /// partial `{set: f}` to a target that owns a data property merged the generic fields
671    /// and dropped the accessor half entirely, so `Object.defineProperty(new
672    /// Proxy(function(){}, {}), "prototype", {set: f})` reported success where the same
673    /// call on the function itself refuses — and the proxy is required to refuse too.
674    pub get: bool,
675    /// `[[Set]]` is named. See [`DescriptorFields::get`].
676    pub set: bool,
677}
678
679impl Property {
680    /// A writable, enumerable, configurable data property.
681    ///
682    /// This is what a plain assignment or an object literal creates, and the
683    /// attributes only differ for built-ins and `Object.defineProperty`.
684    pub fn data(value: Value) -> Property {
685        Property {
686            value: Some(value),
687            writable: true,
688            enumerable: true,
689            configurable: true,
690            ..Property::default()
691        }
692    }
693
694    /// A data property with explicit attributes.
695    ///
696    /// `configurable` is derived from `writable`, because that derivation is right for the
697    /// case this is overwhelmingly used for: a built-in method or constructor, which the
698    /// spec gives `{writable: true, enumerable: false, configurable: true}`.
699    ///
700    /// It is *not* right for the two other shapes the spec uses on functions, and both were
701    /// wrong here for a long time — `name`/`length` are `{writable: false, enumerable:
702    /// false, configurable: true}`, and a function's `prototype` is `{writable: true,
703    /// enumerable: false, configurable: false}`. Use [`Property::name_or_length`] and
704    /// [`Property::prototype_of`] for those rather than spelling them out, so that the two
705    /// exceptions to the rule stay in one place.
706    pub fn with_attributes(value: Value, writable: bool, enumerable: bool) -> Property {
707        Property {
708            value: Some(value),
709            writable,
710            enumerable,
711            configurable: writable,
712            ..Property::default()
713        }
714    }
715
716    /// `{ value, writable: false, enumerable: false, configurable: true }`.
717    ///
718    /// [`Self::with_attributes`] ties `configurable` to `writable`, which is right for the
719    /// `@@` methods (writable *and* configurable) but wrong for `@@toStringTag`, which is
720    /// configurable and **not** writable — `RegExpStringIteratorPrototype/Symbol.toStringTag`
721    /// checks exactly that pair.
722    pub fn configurable_only(value: Value) -> Property {
723        Property {
724            value: Some(value),
725            writable: false,
726            enumerable: false,
727            configurable: true,
728            ..Property::default()
729        }
730    }
731
732    /// `{ value, writable: false, enumerable: false, configurable: false }`.
733    ///
734    /// The fully locked-down data property. `%ThrowTypeError%`'s `length` and `name` are
735    /// the reason it exists: every other shape the spec uses leaves at least one attribute
736    /// `true`, and `Object.isFrozen` on that function is what notices.
737    pub fn frozen(value: Value) -> Property {
738        Property {
739            value: Some(value),
740            writable: false,
741            enumerable: false,
742            configurable: false,
743            ..Property::default()
744        }
745    }
746
747    /// A `name` or `length` property: writable and enumerable are false, configurable true.
748    ///
749    /// Every function has both, and the spec makes them configurable so that a definition
750    /// can replace them (`Object.defineProperty(f, "length", {value: 0})`, and
751    /// `Function.prototype.bind` renaming its result). With them non-configurable, those
752    /// definitions throw and about five hundred conformance tests fail.
753    pub fn name_or_length(value: Value) -> Property {
754        Property {
755            value: Some(value),
756            writable: false,
757            enumerable: false,
758            configurable: true,
759            ..Property::default()
760        }
761    }
762
763    /// A function's `prototype`: not configurable, and writable only for user functions.
764    ///
765    /// A built-in constructor's `prototype` is read-only — assigning to `Object.prototype`
766    /// must not stick — while a user function's is writable, since that is how
767    /// `Ctor.prototype.method = f` sets up inheritance. Neither is configurable, so
768    /// `delete Ctor.prototype` fails in both cases.
769    pub fn prototype_of(value: Value, writable: bool) -> Property {
770        Property {
771            value: Some(value),
772            writable,
773            enumerable: false,
774            configurable: false,
775            ..Property::default()
776        }
777    }
778
779    /// An accessor property.
780    /// An accessor property with explicit `enumerable`/`configurable` flags, which is
781    /// what `Symbol.prototype.description` needs: it is enumerable: false in the spec.
782    pub fn accessor_with(
783        getter: Option<Value>,
784        setter: Option<Value>,
785        enumerable: bool,
786    ) -> Property {
787        Property {
788            getter,
789            setter,
790            enumerable,
791            configurable: true,
792            ..Property::default()
793        }
794    }
795
796    /// An accessor property with the default `enumerable`/`configurable` flags.
797    pub fn accessor(getter: Option<Value>, setter: Option<Value>) -> Property {
798        Property {
799            getter,
800            setter,
801            enumerable: true,
802            configurable: true,
803            ..Property::default()
804        }
805    }
806
807    /// Whether this is an accessor rather than a data property.
808    pub fn is_accessor(&self) -> bool {
809        self.getter.is_some() || self.setter.is_some()
810    }
811}
812
813impl Trace for Property {
814    fn trace(&self, tracer: &mut Tracer) {
815        self.value.trace(tracer);
816        self.getter.trace(tracer);
817        self.setter.trace(tracer);
818    }
819}
820
821// ---------------------------------------------------------------------------
822// Host classes
823// ---------------------------------------------------------------------------
824
825/// The id a host class is registered under: what `JS_NewClassID` hands out.
826///
827/// Zero means "no class" (`JS_INVALID_CLASS_ID`), which is why allocation starts at one:
828/// `JS_GetOpaque(val, 0)` has to match nothing, or every object in the realm would answer
829/// for a class that was never registered.
830#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
831pub struct ClassId(u32);
832
833impl ClassId {
834    /// The id that matches no object (`JS_INVALID_CLASS_ID`).
835    pub const INVALID: ClassId = ClassId(0);
836
837    /// The id as the integer the C API speaks.
838    pub fn get(self) -> u32 {
839        self.0
840    }
841
842    /// Whether this id could name a registered class.
843    pub fn is_valid(self) -> bool {
844        self.0 != ClassId::INVALID.0
845    }
846
847    /// Build one from the integer a host kept on its side.
848    pub fn from_raw(raw: u32) -> ClassId {
849        ClassId(raw)
850    }
851}
852
853impl fmt::Display for ClassId {
854    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
855        write!(f, "{}", self.0)
856    }
857}
858
859/// A pointer the engine never dereferences.
860///
861/// This is the payload of `JS_SetOpaque`: the host owns whatever it points at, and the
862/// engine's whole involvement is handing it back unchanged, showing it to `gc_mark`, and
863/// passing it to the finalizer. Storing, copying and comparing a raw pointer are safe
864/// operations in Rust — only the host's own code ever dereferences it — which is what lets
865/// this live in `quickjs-pure` without the crate growing an `unsafe` block.
866#[derive(Clone, Copy, PartialEq, Eq)]
867pub struct Opaque(*mut ());
868
869impl Opaque {
870    /// The "nothing is set" pointer: what `JS_GetOpaque` answers for a host object whose
871    /// `JS_SetOpaque` never ran.
872    pub const NULL: Opaque = Opaque(std::ptr::null_mut());
873
874    /// Wrap a pointer the host owns.
875    pub fn new(pointer: *mut ()) -> Opaque {
876        Opaque(pointer)
877    }
878
879    /// The pointer back, for the host to dereference.
880    pub fn as_ptr(self) -> *mut () {
881        self.0
882    }
883
884    /// Whether nothing has been stored.
885    pub fn is_null(self) -> bool {
886        self.0.is_null()
887    }
888}
889
890impl fmt::Debug for Opaque {
891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892        write!(f, "Opaque({:p})", self.0)
893    }
894}
895
896/// The property behaviour a host class may override: the exotic half of `JSClassDef`.
897///
898/// Every method's default is "no opinion", so an implementation names only the traps it
899/// actually wants and everything else keeps the ordinary algorithm. That is what makes
900/// `point.c`'s class — which has no exotic methods at all — work with an empty impl.
901///
902/// The `Option` in each answer is the same two-level question `JSClassExoticMethods` asks:
903///
904/// * outer `None` — not my business, run the ordinary algorithm;
905/// * outer `Some(None)` — this object has no such property;
906/// * outer `Some(Some(x))` — here is the answer.
907///
908/// # Re-entrancy
909///
910/// A trap receives the interpreter and may call back into it, because a host property can
911/// be a JavaScript getter or a function on another object. It must not re-enter the *same*
912/// operation on the *same* object (`get_property` calling `interp.get_property(object, …)`
913/// for the key it was asked about), which recurses until the stack ends. The C API has the
914/// identical hazard.
915pub trait Exotic: 'static {
916    /// `[[GetOwnProperty]]` (`JSClassExoticMethods::get_own_property`).
917    fn get_own_property(
918        &self,
919        _interp: &mut crate::interp::Interp<'_>,
920        _object: &Gc<JsObject>,
921        _key: &PropertyKey,
922    ) -> crate::interp::JsResult<Option<Option<Property>>> {
923        Ok(None)
924    }
925
926    /// `[[DefineOwnProperty]]` (`JSClassExoticMethods::define_own_property`).
927    fn define_own_property(
928        &self,
929        _interp: &mut crate::interp::Interp<'_>,
930        _object: &Gc<JsObject>,
931        _key: &PropertyKey,
932        _property: &Property,
933    ) -> crate::interp::JsResult<Option<bool>> {
934        Ok(None)
935    }
936
937    /// `[[HasProperty]]` (`JSClassExoticMethods::has_property`).
938    fn has_property(
939        &self,
940        _interp: &mut crate::interp::Interp<'_>,
941        _object: &Gc<JsObject>,
942        _key: &PropertyKey,
943    ) -> crate::interp::JsResult<Option<bool>> {
944        Ok(None)
945    }
946
947    /// `[[Delete]]` (`JSClassExoticMethods::delete_property`).
948    fn delete_property(
949        &self,
950        _interp: &mut crate::interp::Interp<'_>,
951        _object: &Gc<JsObject>,
952        _key: &PropertyKey,
953    ) -> crate::interp::JsResult<Option<bool>> {
954        Ok(None)
955    }
956
957    /// `[[Get]]` (`JSClassExoticMethods::get_property`).
958    ///
959    /// Answers the *value*, and does its own prototype walk if it wants one; returning
960    /// `None` leaves the read to the ordinary algorithm.
961    fn get_property(
962        &self,
963        _interp: &mut crate::interp::Interp<'_>,
964        _object: &Gc<JsObject>,
965        _key: &PropertyKey,
966        _receiver: &Value,
967    ) -> crate::interp::JsResult<Option<Value>> {
968        Ok(None)
969    }
970
971    /// `[[Set]]` (`JSClassExoticMethods::set_property`).
972    ///
973    /// `Some(false)` is a refusal, which the caller turns into a `TypeError` in strict code
974    /// and silence in sloppy code — exactly like a proxy's `set` trap.
975    fn set_property(
976        &self,
977        _interp: &mut crate::interp::Interp<'_>,
978        _object: &Gc<JsObject>,
979        _key: &PropertyKey,
980        _value: &Value,
981        _receiver: &Value,
982    ) -> crate::interp::JsResult<Option<bool>> {
983        Ok(None)
984    }
985
986    /// `[[GetPrototypeOf]]` (`JSClassExoticMethods::get_prototype`).
987    fn get_prototype(
988        &self,
989        _interp: &mut crate::interp::Interp<'_>,
990        _object: &Gc<JsObject>,
991    ) -> crate::interp::JsResult<Option<Option<Gc<JsObject>>>> {
992        Ok(None)
993    }
994
995    /// `[[SetPrototypeOf]]` (`JSClassExoticMethods::set_prototype`).
996    fn set_prototype(
997        &self,
998        _interp: &mut crate::interp::Interp<'_>,
999        _object: &Gc<JsObject>,
1000        _proto: Option<Gc<JsObject>>,
1001    ) -> crate::interp::JsResult<Option<bool>> {
1002        Ok(None)
1003    }
1004
1005    /// `[[IsExtensible]]` (`JSClassExoticMethods::is_extensible`).
1006    fn is_extensible(
1007        &self,
1008        _interp: &mut crate::interp::Interp<'_>,
1009        _object: &Gc<JsObject>,
1010    ) -> crate::interp::JsResult<Option<bool>> {
1011        Ok(None)
1012    }
1013
1014    /// `[[PreventExtensions]]` (`JSClassExoticMethods::prevent_extensions`).
1015    fn prevent_extensions(
1016        &self,
1017        _interp: &mut crate::interp::Interp<'_>,
1018        _object: &Gc<JsObject>,
1019    ) -> crate::interp::JsResult<Option<bool>> {
1020        Ok(None)
1021    }
1022}
1023
1024/// A host class's finalizer: `JSClassDef::finalizer`.
1025///
1026/// Receives the class id and the payload, and nothing else — no interpreter, no context —
1027/// because it runs from [`Drop`], at which point there may be neither.
1028pub type HostFinalizer = Box<dyn Fn(ClassId, Opaque)>;
1029
1030/// A host class's `gc_mark` callback: `JSClassDef::gc_mark`.
1031pub type HostGcMark = Box<dyn Fn(Opaque, &mut Tracer)>;
1032
1033/// What every instance of one host class shares: the engine's half of `JSClassDef`.
1034///
1035/// Shared by `Rc` with each instance rather than looked up in a table when needed, because
1036/// the finalizer runs from `Drop` — at which point there is no interpreter, and often no
1037/// `Context`, left to look anything up in.
1038pub struct ClassDef {
1039    /// The class name (`JSClassDef::class_name`). Used in diagnostics.
1040    ///
1041    /// It is deliberately *not* the `Object.prototype.toString` tag: the reference answers
1042    /// `[object Object]` for a host object named `Point`, and only names its own built-in
1043    /// class ids. Making this the tag would be a visible difference.
1044    pub name: String,
1045    /// Run once when an instance is released (`JSClassDef::finalizer`).
1046    ///
1047    /// Called from `Drop`, so it must not touch the object being destroyed and must not
1048    /// allocate JavaScript values — it is not given an interpreter, which is what makes
1049    /// both mistakes impossible rather than merely discouraged.
1050    pub finalizer: Option<HostFinalizer>,
1051    /// Report the JavaScript values an instance's opaque state points at
1052    /// (`JSClassDef::gc_mark`).
1053    ///
1054    /// An instance whose Rust state holds a [`Gc`] has to say so here. The collector cannot
1055    /// see inside an opaque pointer, so a hidden handle counts as a reference from *outside*
1056    /// the heap — which makes the object it holds look like a root, and every garbage cycle
1057    /// closed through it immortal. It is a leak rather than a use-after-free (an invisible
1058    /// reference is still a reference), but it is a leak a host class creates without
1059    /// noticing, which is why the C API makes the callback part of the class definition.
1060    ///
1061    /// The callback must only report edges: it runs from [`Trace::trace`], which the
1062    /// collector calls while it holds a snapshot of the heap.
1063    pub gc_mark: Option<HostGcMark>,
1064    /// Property behaviour (`JSClassDef::exotic`).
1065    pub exotic: Option<Rc<dyn Exotic>>,
1066}
1067
1068impl ClassDef {
1069    /// A class with no behaviour beyond being its own class id.
1070    pub fn new(name: impl Into<String>) -> ClassDef {
1071        ClassDef {
1072            name: name.into(),
1073            finalizer: None,
1074            gc_mark: None,
1075            exotic: None,
1076        }
1077    }
1078
1079    /// Attach the finalizer `JSClassDef::finalizer` would carry.
1080    pub fn with_finalizer(mut self, finalizer: impl Fn(ClassId, Opaque) + 'static) -> ClassDef {
1081        self.finalizer = Some(Box::new(finalizer));
1082        self
1083    }
1084
1085    /// Attach the `gc_mark` callback.
1086    pub fn with_gc_mark(mut self, mark: impl Fn(Opaque, &mut Tracer) + 'static) -> ClassDef {
1087        self.gc_mark = Some(Box::new(mark));
1088        self
1089    }
1090
1091    /// Attach the exotic methods.
1092    pub fn with_exotic(mut self, exotic: Rc<dyn Exotic>) -> ClassDef {
1093        self.exotic = Some(exotic);
1094        self
1095    }
1096}
1097
1098impl fmt::Debug for ClassDef {
1099    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1100        f.debug_struct("ClassDef")
1101            .field("name", &self.name)
1102            .field("finalizer", &self.finalizer.is_some())
1103            .field("gc_mark", &self.gc_mark.is_some())
1104            .field("exotic", &self.exotic.is_some())
1105            .finish()
1106    }
1107}
1108
1109/// One instance of a host class: the class id, the class, and the host's payload.
1110///
1111/// Boxed inside [`ObjectKind`] because every `ObjectKind` is stored inline in the object
1112/// header: an unboxed `Rc` plus a pointer plus an id would widen *every* object in the
1113/// realm to no purpose.
1114pub struct HostData {
1115    /// Which class this is an instance of.
1116    pub class_id: ClassId,
1117    /// The class's shared behaviour.
1118    pub class: Rc<ClassDef>,
1119    /// The host's payload. See [`Opaque`].
1120    pub opaque: Opaque,
1121}
1122
1123impl Drop for HostData {
1124    /// The finalizer's one and only call site.
1125    ///
1126    /// `HostData` is owned by exactly one `ObjectKind`, which is owned by exactly one
1127    /// `ObjectData`, so this runs exactly once — when the last strong reference goes away
1128    /// or when the cycle collector reclaims an unreachable object, which is the same two
1129    /// moments the reference implementation runs `JSClassDef::finalizer`.
1130    fn drop(&mut self) {
1131        if let Some(finalizer) = &self.class.finalizer {
1132            finalizer(self.class_id, self.opaque);
1133        }
1134    }
1135}
1136
1137impl Trace for HostData {
1138    fn trace(&self, tracer: &mut Tracer) {
1139        // Nothing in the opaque state is visible to the collector unless the class says
1140        // so: `gc_mark` is the host's declaration that its Rust state holds `Gc` handles.
1141        if let Some(mark) = &self.class.gc_mark {
1142            mark(self.opaque, tracer);
1143        }
1144    }
1145}
1146
1147/// A host function: a native function plus the state it captured.
1148///
1149/// `NativeFn` is a bare `fn` pointer, so a builtin that needs state (an open-file table,
1150/// a timer queue, a sink to write to) has nowhere to put it. `HostFn` boxes the closure
1151/// instead, and [`Callable::Host`] keeps it on the function object.
1152///
1153/// # Why the closure must not capture a `Gc`
1154///
1155/// The collector finds live objects by walking the object graph through [`Trace`]. A
1156/// closure is opaque Rust, so nothing inside it is walked: a `Gc<JsObject>` captured here
1157/// would be invisible to the collector and could be freed while the closure still holds
1158/// it — a use-after-free.
1159///
1160/// Keep Rust-side state (file descriptors, timer ids, deadlines) in the closure, and keep
1161/// every JavaScript value somewhere the collector already scans: a property of a real JS
1162/// object, or a table hanging off [`Interp`]. `os.setTimeout(fn, ms)` stores `fn` in the
1163/// interpreter's timer table for exactly this reason.
1164///
1165/// [`Trace`]: js_gc::Trace
1166/// [`Interp`]: crate::interp::Interp
1167pub type HostFn = Box<
1168    dyn for<'i> FnMut(
1169        &mut crate::interp::Interp<'i>,
1170        Value,
1171        &[Value],
1172    ) -> crate::interp::JsResult<Value>,
1173>;
1174
1175/// A native (Rust) function reachable from JavaScript.
1176///
1177/// It receives the interpreter so a builtin can allocate (which needs the heap),
1178/// call back into JavaScript (which needs the frame stack) and raise exceptions.
1179pub type NativeFn =
1180    fn(&mut crate::interp::Interp<'_>, Value, &[Value]) -> crate::interp::JsResult<Value>;
1181
1182/// The body of a callable object.
1183pub enum Callable {
1184    /// A function compiled from JavaScript source.
1185    Bytecode {
1186        /// The bytecode and slot mapping.
1187        code: Gc<CompiledCode>,
1188        /// The captured environment.
1189        env: Gc<ClosureEnv>,
1190    },
1191    /// A function produced by `Function.prototype.bind`.
1192    ///
1193    /// This is a variant rather than a native function carrying the state in
1194    /// properties because the state is not observable: `bind` has to remember its
1195    /// target, `this` and leading arguments, and a native trampoline cannot capture
1196    /// them.
1197    Bound {
1198        /// The function being called.
1199        target: Value,
1200        /// The `this` every call uses.
1201        this: Value,
1202        /// Arguments prepended to every call's own.
1203        args: Vec<Value>,
1204    },
1205    /// A built-in implemented in Rust.
1206    ///
1207    /// The `name` and `length` a script observes are ordinary properties on the
1208    /// function object, not fields here: they are writable (`f.name = "x"` works)
1209    /// and would otherwise be two sources of truth.
1210    Native {
1211        /// The implementation.
1212        func: NativeFn,
1213        /// Whether this constructor builds its own instance instead of being handed one.
1214        ///
1215        /// The spec has a constructor validate its arguments *before*
1216        /// `OrdinaryCreateFromConstructor` reads `new.target.prototype`, and only the ones
1217        /// with real validation need to: `new Promise(nonCallable)` and `new DataView(…)`
1218        /// must refuse the argument before a throwing `prototype` getter can run. The rest
1219        /// keep the simpler shape where `new` has already made the object.
1220        own_instance: bool,
1221    },
1222    /// A host function: a native closure that carries its own state.
1223    ///
1224    /// Behind an `Rc<RefCell<…>>` because the closure has to be *called* with
1225    /// `&mut Interp`, and the call site would otherwise still be holding a borrow of this
1226    /// object's data — the closure itself may reach the same object. Cloning the `Rc` out
1227    /// and dropping the borrow first is what keeps that from panicking.
1228    Host {
1229        /// The body, with whatever it captured.
1230        func: std::rc::Rc<std::cell::RefCell<HostFn>>,
1231        /// Whether this constructor builds its own instance; see [`Callable::Native`].
1232        own_instance: bool,
1233    },
1234    /// The `revoke` function `Proxy.revocable` hands back.
1235    ///
1236    /// It is a variant rather than a `Native` with the slots in a property because a
1237    /// `NativeFn` is a plain function pointer: it cannot capture, and the slots are
1238    /// precisely what this function exists to hold. Keeping them here also means the
1239    /// collector sees them, so a proxy stays alive while only its `revoke` is reachable.
1240    Revoker(crate::object::ProxyRef),
1241    /// The `resolve` a `Promise` executor receives.
1242    ///
1243    /// Like [`Callable::Revoker`], this cannot be a plain `Native` with the state in a
1244    /// property: a `NativeFn` is a function pointer and cannot capture, and the promise
1245    /// it settles is exactly what it has to remember. Both are one-shot per §27.2.1.3.1 —
1246    /// the second call is a no-op rather than a second settlement.
1247    ///
1248    /// The promise object is held directly rather than the state behind its `Rc`, because
1249    /// settling has to run *that object's* reactions.
1250    PromiseResolve(Gc<JsObject>),
1251    /// The `reject` half of that pair.
1252    PromiseReject(Gc<JsObject>),
1253    /// The executor handed to a *user* promise constructor by `NewPromiseCapability(C)`.
1254    ///
1255    /// `Promise.all.call(MyPromise, …)` has to let `MyPromise` decide what a capability is,
1256    /// so the executor cannot be a Rust closure: it has to be a function object the script
1257    /// can call, and it records whatever `resolve`/`reject` it is given into `state` so the
1258    /// combinator can read them back after the constructor returns.
1259    CapabilityExecutor {
1260        /// The hidden object the pair is recorded on.
1261        state: Gc<JsObject>,
1262    },
1263    /// One of the two continuations an `await` parks on.
1264    ///
1265    /// Reached through the ordinary reaction machinery, which is why it has to be a
1266    /// callable object rather than a queue entry: `await x` is specified as
1267    /// `PerformPromiseThen(x, resume, rethrow)`.
1268    AwaitResume {
1269        /// The body to continue.
1270        coroutine: Gc<JsObject>,
1271        /// The promise the async function returned.
1272        promise: Gc<JsObject>,
1273        /// Whether this continuation delivers the value or raises the reason.
1274        kind: crate::interp::ResumeKind,
1275    },
1276    /// One element of `Promise.all`/`allSettled`/`any`/`race` settling.
1277    CombinatorSettle {
1278        /// The hidden object holding the results array, the remaining count and the
1279        /// combinator's own resolve/reject pair.
1280        state: Gc<JsObject>,
1281        /// Which element this callback belongs to.
1282        index: usize,
1283        /// Whether the element fulfilled or rejected.
1284        fulfilled: bool,
1285    },
1286    /// One leg of a `then` that answers through a *user* capability.
1287    ///
1288    /// `promise.then(f, g)` builds its result from `SpeciesConstructor(promise)`, so the
1289    /// settlement has to go through whatever `resolve`/`reject` that constructor produced.
1290    /// The user's handler therefore cannot be attached to `perform_then` directly — that
1291    /// would settle the engine's own derived promise — so it rides here and the shim calls
1292    /// it, then hands the result (or the throw) to the capability.
1293    ThenShim {
1294        /// The script's `onFulfilled`/`onRejected`, or `None` for a pass-through.
1295        handler: Option<Value>,
1296        /// `capability.[[Resolve]]`.
1297        resolve: Value,
1298        /// `capability.[[Reject]]`.
1299        reject: Value,
1300        /// Whether this leg delivers the value or the reason.
1301        fulfilled: bool,
1302    },
1303    /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
1304    ///
1305    /// `finally` has to hand `Promise.prototype.then` a function that re-delivers the
1306    /// original outcome, and a `NativeFn` is a bare pointer that cannot carry it.
1307    ReturnValue(Value),
1308    /// A thunk that throws a fixed value, for `finally`'s `thrower`.
1309    ThrowValue(Value),
1310    /// Settle a promise with a fixed outcome when called.
1311    SettlePromise {
1312        /// The promise to settle.
1313        promise: Gc<JsObject>,
1314        /// The outcome to settle it with, which is the *original* one.
1315        value: Value,
1316        /// Whether that outcome is a rejection.
1317        rejected: bool,
1318    },
1319    /// One continuation of an `await` inside an async generator.
1320    GeneratorResume {
1321        /// The async generator to continue.
1322        generator: Gc<JsObject>,
1323        /// The promise the pending `next`/`return`/`throw` returned.
1324        promise: Gc<JsObject>,
1325        /// Whether this delivers the value or raises the reason.
1326        kind: crate::interp::ResumeKind,
1327    },
1328    /// Reads a module namespace's binding out of the cell it is stored in.
1329    ///
1330    /// A namespace object is an ordinary object whose exports are getters, so a getter
1331    /// is what `ns.x` calls — and it has to be a callable object carrying the cell, for
1332    /// the same reason `PromiseResolve` carries its promise.
1333    ModuleBinding {
1334        /// The binding's cell, shared with the exporting module.
1335        cell: Gc<Cell>,
1336    },
1337    /// Finish a completed async generator's `return(v)` once `v` has settled.
1338    CompletedReturn {
1339        /// The generator, so settling this request can start the next one.
1340        generator: Gc<JsObject>,
1341        /// The promise the `return` answered.
1342        promise: Gc<JsObject>,
1343        /// Whether the value rejected instead of settling.
1344        rejected: bool,
1345    },
1346    /// Answer a pending async-generator method with `{value, done: false}`.
1347    ///
1348    /// `yield v` in an async generator awaits `v` first, so the value can arrive after
1349    /// the body has already parked; this is what turns it into the result object.
1350    YieldResult {
1351        /// The generator, so settling this request can start the next one.
1352        generator: Gc<JsObject>,
1353        /// The promise the pending method returned.
1354        promise: Gc<JsObject>,
1355        /// Whether this answers a completed generator rather than a `yield`.
1356        done: bool,
1357    },
1358    /// One step of `AsyncDisposableStack.disposeAsync`.
1359    ///
1360    /// The remaining resources ride along as a JS array so the collector can see them:
1361    /// `disposeAsync` awaits each disposer in turn, which means the list has to survive
1362    /// across microtasks rather than living on the Rust stack.
1363    DisposeStep {
1364        /// Pairs of `[resource, disposeMethod]`, consumed from the end.
1365        remaining: Gc<JsObject>,
1366        /// The promise `disposeAsync` returned.
1367        promise: Gc<JsObject>,
1368        /// The `SuppressedError` chain built so far, or `Uninitialized` for none.
1369        error: Value,
1370        /// Whether this continuation is being called with a rejection reason.
1371        rejected: bool,
1372    },
1373    /// One of the two shims `Promise.prototype.finally` installs.
1374    FinallyShim {
1375        /// The script's callback, or `None` to pass the outcome straight through.
1376        callback: Option<Value>,
1377        /// Whether this is the fulfil side.
1378        fulfilled: bool,
1379        /// `C` from §27.2.5.3: the constructor whose `PromiseResolve` the callback's
1380        /// result goes through, so `mp1.finally(() => mp2)` reuses `mp2` rather than
1381        /// wrapping it in another capability.
1382        constructor: Value,
1383    },
1384}
1385
1386impl Trace for Callable {
1387    fn trace(&self, tracer: &mut Tracer) {
1388        match self {
1389            Callable::Bytecode { code, env } => {
1390                tracer.visit(code);
1391                tracer.visit(env);
1392            }
1393            Callable::Bound { target, this, args } => {
1394                target.trace(tracer);
1395                this.trace(tracer);
1396                for argument in args {
1397                    argument.trace(tracer);
1398                }
1399            }
1400            Callable::Native { .. } => {}
1401            // Nothing to trace, by construction: the closure must not hold a `Gc`. See
1402            // `HostFn`'s documentation.
1403            Callable::Host { .. } => {}
1404            Callable::Revoker(slots) => slots.borrow().trace(tracer),
1405            Callable::CapabilityExecutor { state } => tracer.visit(state),
1406            Callable::ThenShim {
1407                handler,
1408                resolve,
1409                reject,
1410                fulfilled: _,
1411            } => {
1412                if let Some(handler) = handler {
1413                    handler.trace(tracer);
1414                }
1415                resolve.trace(tracer);
1416                reject.trace(tracer);
1417            }
1418            Callable::PromiseResolve(promise) | Callable::PromiseReject(promise) => {
1419                tracer.visit(promise)
1420            }
1421            Callable::AwaitResume {
1422                coroutine, promise, ..
1423            } => {
1424                tracer.visit(coroutine);
1425                tracer.visit(promise);
1426            }
1427            Callable::CombinatorSettle { state, .. } => tracer.visit(state),
1428            Callable::GeneratorResume {
1429                generator, promise, ..
1430            } => {
1431                tracer.visit(generator);
1432                tracer.visit(promise);
1433            }
1434            Callable::CompletedReturn {
1435                generator, promise, ..
1436            }
1437            | Callable::YieldResult {
1438                generator, promise, ..
1439            } => {
1440                tracer.visit(generator);
1441                tracer.visit(promise);
1442            }
1443            Callable::ModuleBinding { cell } => tracer.visit(cell),
1444            Callable::DisposeStep {
1445                remaining,
1446                promise,
1447                error,
1448                ..
1449            } => {
1450                tracer.visit(remaining);
1451                tracer.visit(promise);
1452                error.trace(tracer);
1453            }
1454            Callable::ReturnValue(value) => value.trace(tracer),
1455            Callable::ThrowValue(value) => value.trace(tracer),
1456            Callable::SettlePromise { promise, value, .. } => {
1457                tracer.visit(promise);
1458                value.trace(tracer);
1459            }
1460            Callable::FinallyShim {
1461                callback,
1462                constructor,
1463                ..
1464            } => {
1465                if let Some(callback) = callback {
1466                    callback.trace(tracer);
1467                }
1468                constructor.trace(tracer);
1469            }
1470        }
1471    }
1472}
1473
1474/// The bytecode of one function, plus the slot-to-cell mapping.
1475///
1476/// This is a separate GC object from the closure so that a frame can hold a handle
1477/// to it and read it while the function object itself is free to be borrowed.
1478/// Holding a `RefCell` borrow across a call would deadlock the moment a function
1479/// referred to itself.
1480pub struct CompiledCode {
1481    /// The resolved bytecode.
1482    pub code: CompiledFunction,
1483    /// For each argument slot, the index of its reference cell, or `-1` when the
1484    /// slot holds its value directly.
1485    ///
1486    /// A captured binding lives in a cell so that closures outlive the frame; every
1487    /// other slot is a plain value. Precomputing the mapping keeps the hot
1488    /// `get_arg`/`put_arg` paths to one array read instead of a lookup.
1489    pub arg_cell: Vec<i32>,
1490    /// The same, for local slots.
1491    pub loc_cell: Vec<i32>,
1492    /// The bytecode decoded once, into fixed-width records.
1493    ///
1494    /// Decoding is per instruction and never changes its answer — the bytecode is
1495    /// immutable once compiled — so doing it at compile time is free and doing it on
1496    /// every dispatch is not. See [`crate::insn`].
1497    pub insns: Vec<crate::insn::Insn>,
1498    /// The atom table as property keys, built once.
1499    ///
1500    /// `get_field x` needs `x` as a [`PropertyKey`], and building one per access meant
1501    /// `Wtf8::from_rc_str`, which allocates a fresh `Rc<[u8]>` and copies the bytes —
1502    /// despite its name, it does not share the atom's storage. That put a `malloc` on
1503    /// every property read: 5.3% of `property:monomorphic`, plus 1.6% in the `memmove`
1504    /// inside it.
1505    ///
1506    /// Built here instead, so a lookup clones an `Rc` — a pointer bump — rather than
1507    /// allocating. Same trick, and the same reason, as `arg_cell` and `insns`.
1508    pub atom_keys: Vec<PropertyKey>,
1509}
1510
1511impl CompiledCode {
1512    /// Build the slot-to-cell mapping for `code`.
1513    ///
1514    /// Cells are numbered the way [`CompiledFunction::var_ref_count`] counts them:
1515    /// the captured arguments first, then the captured locals, each in slot order.
1516    pub fn new(code: CompiledFunction) -> CompiledCode {
1517        let mut next = 0i32;
1518        let mut arg_cell = vec![-1; code.args.len()];
1519        for (slot, arg) in code.args.iter().enumerate() {
1520            if arg.is_captured {
1521                arg_cell[slot] = next;
1522                next += 1;
1523            }
1524        }
1525        let mut loc_cell = vec![-1; code.vars.len()];
1526        for (slot, local) in code.vars.iter().enumerate() {
1527            if local.is_captured {
1528                loc_cell[slot] = next;
1529                next += 1;
1530            }
1531        }
1532        let insns = crate::insn::predecode(&code.code);
1533        let atom_keys = code.atoms.iter().map(atom_key_of).collect();
1534        CompiledCode {
1535            code,
1536            arg_cell,
1537            loc_cell,
1538            insns,
1539            atom_keys,
1540        }
1541    }
1542}
1543
1544impl Trace for CompiledCode {
1545    fn trace(&self, _tracer: &mut Tracer) {}
1546
1547    /// The decoded instruction array, which is the one thing here that is not shared
1548    /// with the compiler's own table.
1549    ///
1550    /// Counted because `--memory-limit` has to see it: twenty bytes per instruction
1551    /// for every function in the program, and a program with ten thousand small
1552    /// functions is a few megabytes that used to be invisible.
1553    fn external_bytes(&self) -> usize {
1554        self.insns.len() * std::mem::size_of::<crate::insn::Insn>()
1555            + self.atom_keys.len() * std::mem::size_of::<PropertyKey>()
1556    }
1557}
1558
1559/// One atom of a compiled function's atom table, as the property key a lookup needs.
1560///
1561/// Kept beside [`CompiledCode::new`] rather than inline in it so the three `Atom`
1562/// variants are matched in one place: `Str` shares its bytes through the `Rc` in
1563/// [`Wtf8::from_rc_str`], and `Index` formats the number once instead of once per read.
1564fn atom_key_of(atom: &js_compile::bytecode::Atom) -> PropertyKey {
1565    use js_compile::bytecode::Atom;
1566    PropertyKey::String(match atom {
1567        // Already a `Wtf8`, and cloning one is a refcount bump, so the atom's bytes are
1568        // shared rather than re-scanned the way `from_rc_str` would.
1569        Atom::Str(text) => text.clone(),
1570        Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
1571        // `JS_ATOM_NULL`: no name. The opcodes that take one never read it.
1572        Atom::Null => crate::value::Wtf8::new(String::new()),
1573    })
1574}
1575
1576/// The reference cells a closure captured from enclosing scopes.
1577pub struct ClosureEnv {
1578    /// Indexed the way the bytecode's closure-variable table indexes them.
1579    pub cells: Vec<Gc<Cell>>,
1580    /// The `eval` scope this closure was created in, if any.
1581    ///
1582    /// A function built by `eval` has to keep seeing the caller's bindings after the
1583    /// eval has returned — `for (let i …) eval("push(() => i)")` collects closures that
1584    /// read `i` later. Those bindings live in the *caller's* frame, which is long gone
1585    /// by then, so the environment carries them by name instead. Ordinary closures leave
1586    /// this `None` and resolve globals exactly as before.
1587    pub eval_scope: Option<Gc<EvalScope>>,
1588    /// Variables a direct `eval` declared in the frame this closure was created in, and
1589    /// how much of that frame it may see.
1590    ///
1591    /// A closure is created at a *place* in a function, and a direct `eval` can add
1592    /// variables after that point. Those variables belong to the variable environment
1593    /// that was current at the closure's creation — the parameter list or the body — which
1594    /// is what `local_phase` records.
1595    pub local_vars: Option<Gc<LocalVars>>,
1596    /// `0` for a closure created in a parameter list, `1` for one in a body. A parameter
1597    /// list's closure must not see variables a later `eval` in the body declared:
1598    /// `function f(a, p = () => c) { eval("var c = 1") }` has `p()` resolve `c` outside
1599    /// the function entirely.
1600    pub local_phase: u8,
1601}
1602
1603/// Variables a direct `eval` declared in one function call.
1604///
1605/// A sloppy `eval` declares its `var`s in the caller's variable environment, not on the
1606/// global object: `function f() { eval("var x = 1") } f(); x` is a `ReferenceError`, and
1607/// two calls to `f` get two `x`s. Each entry therefore records the phase it was declared
1608/// in, so a lookup from the parameter list cannot see a body declaration.
1609pub struct LocalVars {
1610    names: std::cell::RefCell<Vec<(String, Gc<Cell>, u8)>>,
1611}
1612
1613impl Default for LocalVars {
1614    fn default() -> LocalVars {
1615        LocalVars::new()
1616    }
1617}
1618
1619impl LocalVars {
1620    /// An empty set.
1621    pub fn new() -> LocalVars {
1622        LocalVars {
1623            names: std::cell::RefCell::new(Vec::new()),
1624        }
1625    }
1626
1627    /// The cell `name` resolves to, when it was declared in `phase` or earlier.
1628    pub fn get(&self, name: &str, phase: u8) -> Option<Gc<Cell>> {
1629        self.names
1630            .borrow()
1631            .iter()
1632            .find(|(bound, _, at)| bound == name && *at <= phase)
1633            .map(|(_, cell, _)| cell.clone())
1634    }
1635
1636    /// The cell for `name`, declaring it if this is the first time.
1637    pub fn declare(&self, name: &str, phase: u8, cell: Gc<Cell>) -> Gc<Cell> {
1638        let mut names = self.names.borrow_mut();
1639        if let Some((_, cell, _)) = names.iter().find(|(bound, _, _)| bound == name) {
1640            return cell.clone();
1641        }
1642        names.push((name.to_string(), cell.clone(), phase));
1643        cell
1644    }
1645
1646    /// Whether `name` has been declared at all.
1647    pub fn contains(&self, name: &str) -> bool {
1648        self.names
1649            .borrow()
1650            .iter()
1651            .any(|(bound, _, _)| bound == name)
1652    }
1653}
1654
1655impl Trace for LocalVars {
1656    fn trace(&self, tracer: &mut Tracer) {
1657        for (_, cell, _) in self.names.borrow().iter() {
1658            tracer.visit(cell);
1659        }
1660    }
1661}
1662
1663impl Trace for ClosureEnv {
1664    fn trace(&self, tracer: &mut Tracer) {
1665        for cell in &self.cells {
1666            tracer.visit(cell);
1667        }
1668        if let Some(scope) = &self.eval_scope {
1669            tracer.visit(scope);
1670        }
1671        if let Some(local_vars) = &self.local_vars {
1672            tracer.visit(local_vars);
1673        }
1674    }
1675}
1676
1677/// The bindings a direct `eval` made visible, as name → cell.
1678///
1679/// Only bindings that already live in a cell appear here, because sharing their
1680/// identity is the point: a closure created by the eval must observe later writes to
1681/// the same variable, and a copy would not. The compiler puts every binding of a
1682/// function that contains a direct `eval` into a cell, so in practice that is all of
1683/// them.
1684pub struct EvalScope {
1685    /// In lookup order: the innermost binding for a name first.
1686    pub names: Vec<(String, Gc<Cell>)>,
1687}
1688
1689impl EvalScope {
1690    /// The cell `name` resolves to, if this scope binds it.
1691    pub fn get(&self, name: &str) -> Option<&Gc<Cell>> {
1692        self.names
1693            .iter()
1694            .find(|(bound, _)| bound == name)
1695            .map(|(_, cell)| cell)
1696    }
1697}
1698
1699impl Trace for EvalScope {
1700    fn trace(&self, tracer: &mut Tracer) {
1701        for (_, cell) in &self.names {
1702            tracer.visit(cell);
1703        }
1704    }
1705}
1706
1707/// What kind of object this is.
1708pub enum ObjectKind {
1709    /// An ordinary object: only its property table.
1710    Ordinary,
1711    /// An array: a dense element vector plus a property table for everything else.
1712    ///
1713    /// `length` is stored **separately** rather than derived from `elements.len()`, so a
1714    /// sparse array costs nothing to poke at a far index: the reference answers
1715    /// `a = []; a.length = 4294967295` instantly, while deriving the length from a dense
1716    /// vector meant allocating one `Value` per slot — 62 GB and 24 seconds for that one
1717    /// statement. An index past the vector is a hole, and `length` alone records how many
1718    /// holes there are at the end.
1719    ///
1720    /// Invariant: `elements.len() <= length`. A truncation drops both, so the reverse
1721    /// (`length < elements.len()`) never holds.
1722    Array {
1723        /// The dense prefix: everything before the first trailing hole.
1724        elements: Vec<Value>,
1725        /// The logical length, which may exceed `elements.len()`.
1726        length: usize,
1727    },
1728    /// A function or a class constructor.
1729    Function(Callable),
1730    /// A regular expression: the compiled pattern, plus `lastIndex` as a property.
1731    RegExp(crate::builtins::regexp::RegExpData),
1732    /// A `DisposableStack` or `AsyncDisposableStack`: the resources it holds.
1733    DisposableStack(crate::builtins::disposable::StackState),
1734    /// An `ArrayBuffer`: a byte range that typed-array views share.
1735    ///
1736    /// The bytes sit behind an `Rc<RefCell<…>>` rather than in the object so that every view
1737    /// of the buffer sees the same storage; the *views* hold the `Gc<JsObject>` of this
1738    /// buffer, which is what keeps it alive and what the collector traces.
1739    ArrayBuffer(std::rc::Rc<std::cell::RefCell<BufferStorage>>),
1740    /// A `Map` or a `Set`: insertion-ordered entries with `SameValueZero` key equality.
1741    ///
1742    /// One variant for both, because a `Set` is exactly a `Map` whose value is unused — the
1743    /// difference is a flag, and `is_set` is what makes `entries` yield `[v, v]` pairs.
1744    Collection {
1745        /// The entries, in insertion order.
1746        ///
1747        /// A deleted entry leaves `None` behind instead of shifting its neighbours down.
1748        /// That is the specification's own model (`[[MapData]]` is a list whose deletions
1749        /// write an *empty* marker), and it is load-bearing: a live iterator holds an
1750        /// index into this list, so compacting it would make the iterator revisit one entry
1751        /// and skip another. `None` slots are reclaimed only when the whole list is
1752        /// rebuilt by `clear` or by a `Set` operation.
1753        entries: Vec<Option<(Value, Value)>>,
1754        /// Whether this is a `Set` rather than a `Map`.
1755        is_set: bool,
1756    },
1757    /// A `DataView`: a byte-oriented window onto an `ArrayBuffer`.
1758    ///
1759    /// Separate from `TypedArray` because the two index differently: a typed array has an
1760    /// element type and counts *elements*, while a `DataView` is untyped and every accessor
1761    /// names its own width and byte offset. Sharing one variant would mean carrying an
1762    /// element type that is always "bytes" and a length that means something else.
1763    DataView {
1764        /// The buffer whose bytes this view reads.
1765        buffer: Gc<JsObject>,
1766        /// Byte offset of the view's first byte.
1767        offset: usize,
1768        /// How many bytes the view exposes, or that it follows the buffer.
1769        length: ViewLength,
1770    },
1771    /// A typed-array view: a window onto an `ArrayBuffer`.
1772    TypedArray {
1773        /// The buffer whose bytes this view reads.
1774        buffer: Gc<JsObject>,
1775        /// What one element is.
1776        element: crate::builtins::typedarray::ElementType,
1777        /// Byte offset of element zero.
1778        offset: usize,
1779        /// How many elements the view exposes, or that it follows the buffer.
1780        length: ViewLength,
1781    },
1782    /// A generator object: a detached frame plus how far it got.
1783    ///
1784    /// The frame lives here rather than in the interpreter because a suspended generator
1785    /// has to keep its locals and operand stack alive for as long as the script can reach
1786    /// the generator object — and the collector has to see them, which it only does for
1787    /// things hanging off a `Gc`.
1788    Generator(Box<crate::interp::GeneratorState>),
1789    /// A `Proxy`: a stand-in that forwards every internal method to a target through a
1790    /// handler's traps.
1791    ///
1792    /// The state sits behind an `Rc` because `Proxy.revocable` hands the script a
1793    /// `revoke` function that has to reach *this* proxy's two slots later, from a call
1794    /// site that has no pointer to the object. Revoking clears them, which also drops
1795    /// the collector's references to the target and the handler.
1796    Proxy(ProxyRef),
1797    /// A `Promise`.
1798    ///
1799    /// The state sits behind an `Rc` for the same reason a proxy's slots do: the
1800    /// `resolve`/`reject` pair handed to an executor has to settle *this* promise later,
1801    /// and those are function objects with no pointer back to it otherwise.
1802    Promise(PromiseRef),
1803    /// A `WeakMap` or `WeakSet`: like a collection, but the *keys* are weak.
1804    ///
1805    /// The distinction lives entirely in [`Trace`]: a `Collection` traces its keys, a
1806    /// `WeakCollection` does not. An entry keyed by an otherwise-unreachable object is
1807    /// therefore reclaimed together with that object instead of keeping it alive, and the
1808    /// entry simply stops being found — `upgrade` fails and a liveness sweep drops the
1809    /// pair. That is the "ephemeron" behaviour `WeakMap` promises, and it falls out of
1810    /// reference counting rather than needing a second collection pass.
1811    WeakCollection {
1812        /// The entries, in insertion order, keyed by a non-owning handle.
1813        entries: Vec<(WeakKey, Value)>,
1814        /// Whether this is a `WeakSet` rather than a `WeakMap`.
1815        is_set: bool,
1816    },
1817    /// A `WeakRef`: one non-owning handle to a target object.
1818    WeakRef {
1819        /// The target. Once `upgrade` fails the reference is dead for good, because a box
1820        /// whose strong count reached zero never comes back.
1821        ///
1822        /// A `WeakKey` rather than a `WeakGc<JsObject>`, because a symbol is a valid target
1823        /// too — `new WeakRef(Symbol())` works and `deref` has to answer it back.
1824        target: WeakKey,
1825    },
1826    /// A `FinalizationRegistry`: the cleanup callback and its live registrations.
1827    Finalization(Box<FinalizationState>),
1828    /// An instance of a class the host registered (`JS_NewObjectProtoClass`).
1829    ///
1830    /// Deliberately not folded into `Ordinary` with the payload in a private property:
1831    /// `JS_GetOpaque` has to be a class check as well as a pointer read, so that handing a
1832    /// `Date` to a method expecting a `Point` is a `TypeError` rather than a reinterpreted
1833    /// pointer.
1834    HostClass(Box<HostData>),
1835}
1836
1837impl ObjectKind {
1838    /// This variant's name, for the memory report's per-class census.
1839    ///
1840    /// Not `Debug`: the census groups and sorts by these strings, so they have to be stable
1841    /// and human-readable, and several variants carry payloads that `Debug` would print.
1842    pub fn variant_name(&self) -> &'static str {
1843        match self {
1844            ObjectKind::Ordinary => "Object",
1845            ObjectKind::Array { .. } => "Array",
1846            ObjectKind::Function(_) => "Function",
1847            ObjectKind::RegExp(_) => "RegExp",
1848            ObjectKind::DisposableStack(_) => "DisposableStack",
1849            ObjectKind::ArrayBuffer(_) => "ArrayBuffer",
1850            ObjectKind::Collection { is_set, .. } => {
1851                if *is_set {
1852                    "Set"
1853                } else {
1854                    "Map"
1855                }
1856            }
1857            ObjectKind::DataView { .. } => "DataView",
1858            ObjectKind::TypedArray { .. } => "TypedArray",
1859            ObjectKind::Generator(_) => "Generator",
1860            ObjectKind::Proxy(_) => "Proxy",
1861            ObjectKind::Promise(_) => "Promise",
1862            ObjectKind::WeakCollection { .. } => "WeakCollection",
1863            ObjectKind::WeakRef { .. } => "WeakRef",
1864            ObjectKind::Finalization(_) => "Finalization",
1865            ObjectKind::HostClass(_) => "HostClass",
1866        }
1867    }
1868}
1869
1870/// The mutable half of a `FinalizationRegistry`.
1871///
1872/// Boxed inside the [`ObjectKind`] variant because it holds a vector plus a value, and every
1873/// `ObjectKind` is stored inline in the object header — an unboxed field this wide would
1874/// make *every* object in the realm that much larger.
1875pub struct FinalizationState {
1876    /// One entry per successful `register` call.
1877    pub registrations: Vec<Registration>,
1878    /// The cleanup callback, validated as callable when the registry was built.
1879    pub cleanup: Value,
1880}
1881
1882/// A key that can be held weakly: an object, or a symbol.
1883///
1884/// Both are heap allocations in this engine (`Value::Symbol` carries a `Gc<JsSymbol>`), so a
1885/// `WeakGc` holds either one just as well. Symbols became valid keys with the
1886/// `symbols-as-weakmap-keys` proposal, which is what test262 already tests.
1887#[derive(Clone)]
1888pub enum WeakKey {
1889    /// An object target.
1890    Object(WeakGc<JsObject>),
1891    /// A symbol target.
1892    Symbol(WeakGc<JsSymbol>),
1893}
1894
1895impl WeakKey {
1896    /// Whether the allocation behind this key has been released.
1897    pub fn is_expired(&self) -> bool {
1898        match self {
1899            WeakKey::Object(handle) => handle.is_expired(),
1900            WeakKey::Symbol(handle) => handle.is_expired(),
1901        }
1902    }
1903
1904    /// Whether two weak keys are the same allocation.
1905    pub fn same(&self, other: &WeakKey) -> bool {
1906        match (self, other) {
1907            (WeakKey::Object(left), WeakKey::Object(right)) => left.ptr_eq(right),
1908            (WeakKey::Symbol(left), WeakKey::Symbol(right)) => left.ptr_eq(right),
1909            _ => false,
1910        }
1911    }
1912
1913    /// Whether this key is the same allocation as `value`, without upgrading it.
1914    ///
1915    /// Upgrading would resurrect the key, which for a `WeakMap` lookup is exactly what must
1916    /// not happen — a dead key has to compare equal to nothing.
1917    pub fn matches(&self, value: &Value) -> bool {
1918        match (self, value) {
1919            (WeakKey::Object(handle), Value::Object(object)) => object.upgrades_to(handle),
1920            (WeakKey::Symbol(handle), Value::Symbol(symbol)) => symbol.upgrades_to(handle),
1921            _ => false,
1922        }
1923    }
1924
1925    /// The key as a strong value, when it is still alive.
1926    pub fn upgrade(&self) -> Option<Value> {
1927        match self {
1928            WeakKey::Object(handle) => handle.upgrade().map(Value::Object),
1929            WeakKey::Symbol(handle) => handle.upgrade().map(Value::Symbol),
1930        }
1931    }
1932}
1933
1934impl Trace for WeakKey {
1935    fn trace(&self, _tracer: &mut Tracer) {}
1936}
1937
1938/// Turn a script value into a weak key, if `CanBeHeldWeakly` allows it.
1939///
1940/// The rule is "an object, or a symbol that is not in the registry". A registered symbol —
1941/// one from `Symbol.for` — is refused on purpose: it lives in the realm's registry for the
1942/// lifetime of the realm, so it never dies, and a weak entry keyed by it could never be
1943/// observed to be collected. A plain `Symbol()` is a fresh allocation each time and so has
1944/// a lifetime worth observing.
1945pub fn weak_key(value: &Value) -> Option<WeakKey> {
1946    match value {
1947        Value::Object(object) => Some(WeakKey::Object(object.downgrade())),
1948        Value::Symbol(symbol) if symbol.registry_key().is_none() => {
1949            Some(WeakKey::Symbol(symbol.downgrade()))
1950        }
1951        _ => None,
1952    }
1953}
1954
1955/// One `FinalizationRegistry.register` call.
1956///
1957/// `token` is compared with `SameValue`, not `SameValueZero`, which is why it is kept as
1958/// the original `Value` rather than normalised into a key.
1959pub struct Registration {
1960    /// The handle whose death fires the callback.
1961    pub target: WeakKey,
1962    /// What the callback receives: the script's held value, kept alive until it fires.
1963    pub held_value: Value,
1964    /// The cancellation token, if one was given.
1965    pub token: Option<Value>,
1966}
1967
1968/// The two slots of a proxy, shared with its `revoke` function.
1969///
1970/// `None` in both slots means revoked: every operation then throws a `TypeError`, and
1971/// the target and handler are no longer reachable — which is the whole point of
1972/// `Proxy.revocable`.
1973#[derive(Default)]
1974pub struct ProxyState {
1975    /// The object the traps receive, or `None` once revoked.
1976    pub target: Option<Gc<JsObject>>,
1977    /// The trap table, or `None` once revoked.
1978    pub handler: Option<Value>,
1979    /// Whether this proxy has a `[[Call]]`, decided once when it is created.
1980    ///
1981    /// Revoking drops the target but does not take `[[Call]]` away, so this cannot be
1982    /// re-derived from `target` being `Some`: `typeof p.proxy` has to stay `"function"`
1983    /// after `Proxy.revocable(function(){}, {}).revoke()`, and the reference agrees.
1984    pub callable: bool,
1985    /// Whether this proxy has a `[[Construct]]`, decided once when it is created.
1986    ///
1987    /// Same reasoning as [`ProxyState::callable`], and the two are genuinely independent:
1988    /// `Proxy.revocable(function(){}, {})` is both callable and constructible, while a
1989    /// proxy over an arrow function is callable and not constructible.
1990    pub constructible: bool,
1991}
1992
1993/// A `Promise`'s state, shared between the promise object and its resolve/reject
1994/// functions.
1995///
1996/// Behind an `Rc` for the same reason a proxy's slots are: the `resolve` and `reject`
1997/// functions handed to an executor have to settle *this* promise later, from a call site
1998/// that only has the function.
1999pub struct PromiseState {
2000    /// Pending, or the value it settled with.
2001    pub status: PromiseStatus,
2002    /// The `then` reactions waiting on it, in registration order.
2003    pub reactions: Vec<PromiseReaction>,
2004    /// Whether a rejection has been seen by a handler.
2005    ///
2006    /// A rejection that never is becomes an unhandled-rejection report, which the
2007    /// reference makes fatal at the end of the job queue.
2008    pub handled: bool,
2009}
2010
2011impl Default for PromiseState {
2012    fn default() -> Self {
2013        PromiseState {
2014            status: PromiseStatus::Pending,
2015            reactions: Vec::new(),
2016            handled: false,
2017        }
2018    }
2019}
2020
2021/// What a `Promise` combinator does when its elements settle.
2022#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2023pub enum CombinatorKind {
2024    /// The first rejection wins, otherwise an array in input order.
2025    All,
2026    /// Never rejects; each entry is `{status, value}` or `{status, reason}`.
2027    AllSettled,
2028    /// The first fulfilment wins, otherwise an `AggregateError`.
2029    Any,
2030    /// Whichever element settles first.
2031    Race,
2032    /// `Promise.allKeyed`: the first rejection wins, otherwise a null-prototype object
2033    /// keyed like the input. Identical to [`Self::All`] except for the result's shape.
2034    AllKeyed,
2035    /// `Promise.allSettledKeyed`: never rejects, and each entry records what happened —
2036    /// [`Self::AllSettled`] with the keyed result object.
2037    AllSettledKeyed,
2038}
2039
2040/// Which of §27.2.1.2's three states a promise is in.
2041#[derive(Clone, Default)]
2042pub enum PromiseStatus {
2043    /// Neither settled: reactions queue up.
2044    #[default]
2045    Pending,
2046    /// Settled with a value, which no further settle may change.
2047    Fulfilled(Value),
2048    /// Settled with a reason.
2049    Rejected(Value),
2050}
2051
2052/// One `then` registration.
2053#[derive(Clone)]
2054pub struct PromiseReaction {
2055    /// Called with the value if the promise fulfils.
2056    pub on_fulfilled: Option<Value>,
2057    /// Called with the reason if it rejects.
2058    pub on_rejected: Option<Value>,
2059    /// The promise to settle with whatever the handler returns.
2060    pub promise: Gc<JsObject>,
2061}
2062
2063impl Trace for PromiseState {
2064    fn trace(&self, tracer: &mut Tracer) {
2065        match &self.status {
2066            PromiseStatus::Pending => {}
2067            PromiseStatus::Fulfilled(value) | PromiseStatus::Rejected(value) => value.trace(tracer),
2068        }
2069        for reaction in &self.reactions {
2070            if let Some(on_fulfilled) = &reaction.on_fulfilled {
2071                on_fulfilled.trace(tracer);
2072            }
2073            if let Some(on_rejected) = &reaction.on_rejected {
2074                on_rejected.trace(tracer);
2075            }
2076            tracer.visit(&reaction.promise);
2077        }
2078    }
2079}
2080
2081/// A promise's shareable state.
2082pub type PromiseRef = std::rc::Rc<std::cell::RefCell<PromiseState>>;
2083
2084/// A proxy's mutable state, shared between the proxy object and its `revoke`.
2085pub type ProxyRef = std::rc::Rc<std::cell::RefCell<ProxyState>>;
2086
2087impl Trace for ProxyState {
2088    fn trace(&self, tracer: &mut Tracer) {
2089        if let Some(target) = &self.target {
2090            tracer.visit(target);
2091        }
2092        if let Some(handler) = &self.handler {
2093            handler.trace(tracer);
2094        }
2095    }
2096}
2097
2098impl Trace for ObjectKind {
2099    fn trace(&self, tracer: &mut Tracer) {
2100        match self {
2101            // Nothing in a compiled pattern is a GC value: it holds characters and
2102            // integers only.
2103            ObjectKind::RegExp(_) => {}
2104            ObjectKind::DisposableStack(state) => state.trace(tracer),
2105            // A buffer's bytes are plain bytes and hold no GC values; a view keeps its
2106            // buffer alive through the `Gc` it carries.
2107            ObjectKind::ArrayBuffer(_) => {}
2108            ObjectKind::TypedArray { buffer, .. } | ObjectKind::DataView { buffer, .. } => {
2109                tracer.visit(buffer)
2110            }
2111            ObjectKind::Collection { entries, .. } => {
2112                for slot in entries.iter().flatten() {
2113                    slot.0.trace(tracer);
2114                    slot.1.trace(tracer);
2115                }
2116            }
2117            ObjectKind::Ordinary => {}
2118            ObjectKind::Array { elements, .. } => {
2119                for element in elements {
2120                    element.trace(tracer);
2121                }
2122            }
2123            ObjectKind::Function(callable) => callable.trace(tracer),
2124            ObjectKind::Generator(state) => state.trace(tracer),
2125            ObjectKind::Proxy(state) => state.borrow().trace(tracer),
2126            ObjectKind::Promise(state) => state.borrow().trace(tracer),
2127            // The *keys* are deliberately not visited: that absence is what makes the
2128            // collection weak, and it is also why a `WeakMap` cannot keep its key alive
2129            // through a cycle that only the map closes. The values are traced, so
2130            // `wm.set(k, v)` keeping `v` alive while `k` is reachable is the right half of
2131            // the ephemeron rule to get right here — the other half (dropping the pair once
2132            // the key dies) needs no liveness test, because `upgrade` on a dead key fails.
2133            ObjectKind::WeakCollection { entries, .. } => {
2134                for (_, value) in entries {
2135                    value.trace(tracer);
2136                }
2137            }
2138            // A `WeakRef` owns nothing at all: that is its whole purpose.
2139            ObjectKind::WeakRef { .. } => {}
2140            // A registry keeps its held values and its callback alive — the held value has
2141            // to survive until the callback can run — but not the targets, which is the
2142            // handle type's job rather than the tracer's.
2143            ObjectKind::Finalization(state) => {
2144                state.cleanup.trace(tracer);
2145                for registration in &state.registrations {
2146                    registration.held_value.trace(tracer);
2147                    registration.token.trace(tracer);
2148                }
2149            }
2150            // An instance's own state is invisible unless the class declared a `gc_mark`.
2151            ObjectKind::HostClass(data) => data.trace(tracer),
2152        }
2153    }
2154}
2155
2156/// The mutable half of an object.
2157/// What a property is keyed by.
2158///
2159/// A string and a symbol are separate key spaces even when they look alike: `o["a"]`
2160/// and `o[Symbol("a")]` are two properties, and `o[Symbol("a")]` is not reachable by
2161/// any string. Symbols are also invisible to `for`/`Object.keys`/`JSON.stringify`,
2162/// which is the whole point of them, so the distinction has to survive into the
2163/// property table rather than being flattened into a name.
2164#[derive(Clone)]
2165pub enum PropertyKey {
2166    /// An ordinary string key, held as WTF-8 so a key containing an unpaired surrogate
2167    /// addresses one property rather than colliding with its `U+FFFD` replacement.
2168    String(crate::value::Wtf8),
2169    /// A symbol key.
2170    Symbol(Gc<JsSymbol>),
2171}
2172
2173impl PropertyKey {
2174    /// A cheap hash of this key, for an inline cache's slot choice.
2175    ///
2176    /// Not a hash of the whole string: a long property name would make the cache slower than
2177    /// the lookup it is caching. Mixing the length with the first and last byte is enough to
2178    /// separate the names that appear on one object (`x`/`y`, `value`/`add`), and a
2179    /// collision only costs a miss.
2180    pub fn hash_code(&self) -> usize {
2181        match self {
2182            PropertyKey::String(text) => {
2183                let bytes = text.as_bytes();
2184                let mut hash = bytes.len();
2185                for &byte in bytes.iter().take(4).chain(bytes.iter().rev().take(2)) {
2186                    hash = hash.wrapping_mul(31).wrapping_add(byte as usize);
2187                }
2188                hash
2189            }
2190            // A symbol's identity is its allocation, which is exactly what the cache needs —
2191            // two symbols with the same description are two keys.
2192            PropertyKey::Symbol(symbol) => symbol.identity(),
2193        }
2194    }
2195}
2196
2197impl PropertyKey {
2198    /// The key as a string, for the operations that only accept one.
2199    ///
2200    /// A symbol has no string form that would address it, so this answers `None` —
2201    /// which is what makes `get_field` on a symbol key fall through to the general
2202    /// path instead of silently reading a same-named string property.
2203    pub fn as_str(&self) -> Option<&str> {
2204        match self {
2205            PropertyKey::String(text) => text.as_str(),
2206            PropertyKey::Symbol(_) => None,
2207        }
2208    }
2209
2210    /// The key's bytes, which a string key always has and a symbol never does.
2211    pub fn as_wtf8(&self) -> Option<&crate::value::Wtf8> {
2212        match self {
2213            PropertyKey::String(text) => Some(text),
2214            PropertyKey::Symbol(_) => None,
2215        }
2216    }
2217
2218    /// Whether this is an ordinary string key.
2219    pub fn is_symbol(&self) -> bool {
2220        matches!(self, PropertyKey::Symbol(_))
2221    }
2222}
2223
2224impl fmt::Display for PropertyKey {
2225    /// How a key reads inside an error message: strings bare, symbols in their
2226    /// `Symbol(description)` form.
2227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2228        match self {
2229            PropertyKey::String(text) => write!(f, "{}", text.to_string_lossy()),
2230            PropertyKey::Symbol(symbol) => write!(f, "{}", symbol.to_display_string()),
2231        }
2232    }
2233}
2234
2235impl PartialEq for PropertyKey {
2236    fn eq(&self, other: &Self) -> bool {
2237        match (self, other) {
2238            (PropertyKey::String(a), PropertyKey::String(b)) => a == b,
2239            // Symbols compare by identity, never by description.
2240            (PropertyKey::Symbol(a), PropertyKey::Symbol(b)) => a.ptr_eq(b),
2241            _ => false,
2242        }
2243    }
2244}
2245
2246impl From<&str> for PropertyKey {
2247    fn from(text: &str) -> PropertyKey {
2248        PropertyKey::String(crate::value::Wtf8::new(text))
2249    }
2250}
2251
2252impl From<String> for PropertyKey {
2253    fn from(text: String) -> PropertyKey {
2254        PropertyKey::String(crate::value::Wtf8::new(text))
2255    }
2256}
2257
2258impl From<crate::value::Wtf8> for PropertyKey {
2259    fn from(text: crate::value::Wtf8) -> PropertyKey {
2260        PropertyKey::String(text)
2261    }
2262}
2263
2264impl Trace for PropertyKey {
2265    fn trace(&self, tracer: &mut Tracer) {
2266        if let PropertyKey::Symbol(symbol) = self {
2267            tracer.visit(symbol);
2268        }
2269    }
2270}
2271
2272/// An object's mutable state: its prototype, property table and internal slots.
2273pub struct ObjectData {
2274    /// The prototype, or `None` for `Object.prototype` and for a null-prototype
2275    /// object created with `Object.create(null)`.
2276    pub proto: Option<Gc<JsObject>>,
2277    /// Properties in definition order, string and symbol keys interleaved.
2278    pub props: Vec<(PropertyKey, Property)>,
2279    /// What kind of object this is.
2280    pub kind: ObjectKind,
2281    /// Whether new properties may be added. `Object.preventExtensions`, `seal` and
2282    /// `freeze` clear it, and nothing clears it back.
2283    pub extensible: bool,
2284    /// Whether array elements may be replaced.
2285    ///
2286    /// Elements are not in the property table, so their attributes need somewhere to
2287    /// live; `Object.freeze` clears this and `Object.isFrozen` reads it. A *single*
2288    /// non-writable element is recorded in the property table instead, which is what
2289    /// `Object.defineProperty(a, "3", {configurable: false})` does.
2290    pub elements_writable: bool,
2291    /// Whether any element of this array has a descriptor of its own — an accessor, or a
2292    /// `writable`/`enumerable`/`configurable` that is not the default.
2293    ///
2294    /// An array with none has nothing in its property table that a direct slot write could
2295    /// shadow, which is what makes the dense store path safe. Set once and never cleared:
2296    /// `delete` leaves a hole but not the attributes, and a flag that went back to `false`
2297    /// would have to prove the table is clean again.
2298    pub element_descriptors: bool,
2299    /// Whether an array's `length` may be changed.
2300    ///
2301    /// `Object.defineProperty(a, "length", {writable: false})` makes it read-only without
2302    /// touching the elements, so it cannot share `elements_writable`: the two mean
2303    /// different things and `Object.freeze` sets both.
2304    pub length_writable: bool,
2305    /// The object a method was defined on, which is what `super` resolves against.
2306    ///
2307    /// Kept here rather than as a property because it is not observable: the spec calls
2308    /// it `[[HomeObject]]` and no script can read it, so putting it in the property
2309    /// table would leak it to `Object.getOwnPropertyNames` and `JSON.stringify`.
2310    pub home_object: Option<Gc<JsObject>>,
2311    /// The brand symbol this object *owns*, when it is the home object of a class.
2312    ///
2313    /// The reference keeps two separate things under private names it never exposes. The
2314    /// first is `[[PrivateBrand]]`: one symbol per class, stored on the home object — the
2315    /// prototype for the instance brand, the constructor for the static one. Creating it the
2316    /// first time and reusing it after is what ties a prototype, its instances and the class
2317    /// itself to one identity.
2318    ///
2319    /// Kept off the property table for the same reason as `home_object`: a property would be
2320    /// reachable from `Object.getOwnPropertyNames`.
2321    pub private_brand: Option<Gc<crate::value::JsSymbol>>,
2322    /// The brand symbols this object *carries*, as an instance of one or more classes.
2323    ///
2324    /// A list rather than one symbol because brands accumulate down an inheritance chain:
2325    /// `class D extends C` with a private method in each means a `D` instance carries both,
2326    /// since `C`'s field initialiser runs on it and so does `D`'s. Membership is what
2327    /// `check_brand` — and so `#m()` and `#a` — tests before it runs.
2328    pub brands: Vec<Gc<crate::value::JsSymbol>>,
2329    /// Whether this function is a class constructor, which may not be called without
2330    /// `new`.
2331    pub class_constructor: bool,
2332    /// For a sloppy-mode `arguments` object, the reference cell behind each mapped
2333    /// index, or `None` where the index is an ordinary data property.
2334    ///
2335    /// ES §10.4.4 makes a mapped index behave as a data property that happens to
2336    /// alias the parameter. The aliasing is implemented with an accessor, because
2337    /// that is the only way to write through to the cell; this table is what lets the
2338    /// object report the index back as the *data* property the spec describes, so
2339    /// `Object.getOwnPropertyDescriptor` does not expose the plumbing.
2340    pub mapped_arguments: Option<Vec<Option<Gc<crate::value::Cell>>>>,
2341    /// Whether this function has a `[[Construct]]`, i.e. may appear as the target of
2342    /// `new` or `Reflect.construct`.
2343    ///
2344    /// Not derivable from being callable, and that is the whole point: an ordinary
2345    /// method, an arrow function, a generator, an async function and most built-in
2346    /// methods are all callable and none of them may be constructed (§10.2.1,
2347    /// §15.3.1). Deriving it from `is_callable` made `new (Array.prototype.map)` succeed,
2348    /// which test262 checks for every built-in (`not-a-constructor.js`, 515 files).
2349    pub constructible: bool,
2350}
2351
2352impl Trace for ObjectData {
2353    fn trace(&self, tracer: &mut Tracer) {
2354        if let Some(proto) = &self.proto {
2355            tracer.visit(proto);
2356        }
2357        if let Some(home) = &self.home_object {
2358            tracer.visit(home);
2359        }
2360        if let Some(brand) = &self.private_brand {
2361            tracer.visit(brand);
2362        }
2363        for brand in &self.brands {
2364            tracer.visit(brand);
2365        }
2366        for (key, property) in &self.props {
2367            key.trace(tracer);
2368            property.trace(tracer);
2369        }
2370        // A mapped `arguments` index writes through to its cell, so the cell is
2371        // reachable from here and has to be kept alive with the object.
2372        if let Some(mapped) = &self.mapped_arguments {
2373            for cell in mapped.iter().flatten() {
2374                tracer.visit(cell);
2375            }
2376        }
2377        self.kind.trace(tracer);
2378    }
2379}
2380
2381/// A JavaScript object.
2382///
2383/// The interior mutability is what makes `const o = {}; o.x = 1` work: the handle
2384/// is immutable, the object it points at is not.
2385pub struct JsObject {
2386    data: RefCell<ObjectData>,
2387}
2388
2389impl JsObject {
2390    fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
2391        JsObject {
2392            data: RefCell::new(ObjectData {
2393                proto,
2394                props: Vec::new(),
2395                kind,
2396                extensible: true,
2397                elements_writable: true,
2398                element_descriptors: false,
2399                length_writable: true,
2400                home_object: None,
2401                private_brand: None,
2402                brands: Vec::new(),
2403                class_constructor: false,
2404                constructible: false,
2405                mapped_arguments: None,
2406            }),
2407        }
2408    }
2409
2410    /// An ordinary object with the given prototype.
2411    pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
2412        Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
2413    }
2414
2415    /// An array with the given prototype and initial capacity.
2416    /// An empty array with room for `capacity` elements.
2417    ///
2418    /// The length starts at 0: `capacity` is a `Vec` hint, not a length. Callers that want
2419    /// holes use [`Self::array_set_length`], which no longer allocates them.
2420    pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
2421        Gc::new(
2422            heap,
2423            JsObject::new(
2424                ObjectKind::Array {
2425                    elements: Vec::with_capacity(capacity),
2426                    length: 0,
2427                },
2428                proto,
2429            ),
2430        )
2431    }
2432
2433    /// An instance of a host class (`JS_NewObjectProtoClass`).
2434    ///
2435    /// The opaque starts null; the host fills it with [`JsObject::set_host_opaque`], which
2436    /// is the order `point.c` uses (create the object, then hand it the payload) and the
2437    /// order that makes a finalizer's "the opaqued may still be null" note true.
2438    pub fn host_object(
2439        heap: &js_gc::Heap,
2440        proto: Option<Gc<JsObject>>,
2441        class_id: ClassId,
2442        class: Rc<ClassDef>,
2443    ) -> Gc<JsObject> {
2444        Gc::new(
2445            heap,
2446            JsObject::new(
2447                ObjectKind::HostClass(Box::new(HostData {
2448                    class_id,
2449                    class,
2450                    opaque: Opaque::NULL,
2451                })),
2452                proto,
2453            ),
2454        )
2455    }
2456
2457    /// Whether this object is an instance of a host class.
2458    pub fn is_host_class(&self) -> bool {
2459        matches!(self.data.borrow().kind, ObjectKind::HostClass(_))
2460    }
2461
2462    /// This object's class id, when it is a host class instance.
2463    pub fn host_class_id(&self) -> Option<ClassId> {
2464        match &self.data.borrow().kind {
2465            ObjectKind::HostClass(data) => Some(data.class_id),
2466            _ => None,
2467        }
2468    }
2469
2470    /// The class definition this object belongs to, when it is a host class instance.
2471    pub fn host_class(&self) -> Option<Rc<ClassDef>> {
2472        match &self.data.borrow().kind {
2473            ObjectKind::HostClass(data) => Some(data.class.clone()),
2474            _ => None,
2475        }
2476    }
2477
2478    /// The exotic methods of this object's class, if it has a class and the class has any.
2479    ///
2480    /// Cloned out of the object's data rather than borrowed, because every caller is about
2481    /// to call back into the interpreter and the trap may reach this very object.
2482    pub fn exotic(&self) -> Option<Rc<dyn Exotic>> {
2483        match &self.data.borrow().kind {
2484            ObjectKind::HostClass(data) => data.class.exotic.clone(),
2485            _ => None,
2486        }
2487    }
2488
2489    /// The opaque payload, when this object is a host instance.
2490    ///
2491    /// `None` distinguishes "not a host instance" from an instance whose `JS_SetOpaque`
2492    /// never ran, which is the distinction `JS_GetOpaque` versus `JS_GetOpaque2` exists
2493    /// for: the first answers `NULL` for both, the second raises a `TypeError` for the
2494    /// class mismatch.
2495    pub fn host_opaque(&self) -> Option<Opaque> {
2496        match &self.data.borrow().kind {
2497            ObjectKind::HostClass(data) => Some(data.opaque),
2498            _ => None,
2499        }
2500    }
2501
2502    /// Store the opaque payload (`JS_SetOpaque`). Answers whether the object is a host
2503    /// instance at all.
2504    pub fn set_host_opaque(&self, opaque: Opaque) -> bool {
2505        match &mut self.data.borrow_mut().kind {
2506            ObjectKind::HostClass(data) => {
2507                data.opaque = opaque;
2508                true
2509            }
2510            _ => false,
2511        }
2512    }
2513
2514    /// A callable object.
2515    pub fn function(
2516        heap: &js_gc::Heap,
2517        proto: Option<Gc<JsObject>>,
2518        callable: Callable,
2519    ) -> Gc<JsObject> {
2520        Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
2521    }
2522
2523    /// Run `f` with the object's data borrowed.
2524    pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
2525        f(&self.data.borrow())
2526    }
2527
2528    /// Run `f` with the object's data mutably borrowed.
2529    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
2530        f(&mut self.data.borrow_mut())
2531    }
2532
2533    /// Whether this object can be called.
2534    ///
2535    /// Covers every [`Callable`] variant, `Bound` included: `typeof bound ===
2536    /// "function"` and `bound()` works, so from a script's point of view a bound
2537    /// function is a function.
2538    pub fn is_callable(&self) -> bool {
2539        match &self.data.borrow().kind {
2540            ObjectKind::Function(_) => true,
2541            // A proxy is callable exactly when its target was when the proxy was built.
2542            // Not "when its target still is": revoking drops the target but leaves
2543            // `[[Call]]` in place, so a revoked proxy over a function stays a function.
2544            // This is what makes `typeof proxyOfFunction === "function"` survive revoke.
2545            ObjectKind::Proxy(state) => state.borrow().callable,
2546            _ => false,
2547        }
2548    }
2549
2550    /// Whether this is a `bind`-produced function.
2551    ///
2552    /// Needed by the `caller`/`arguments` short-circuit, which applies to *ordinary*
2553    /// constructible functions only: a bound function over an ordinary function is itself
2554    /// constructible, so `is_constructor` alone cannot tell them apart, and a bound function
2555    /// must throw where the ordinary one answers `undefined`.
2556    pub fn is_bound_function(&self) -> bool {
2557        matches!(
2558            &self.data.borrow().kind,
2559            ObjectKind::Function(Callable::Bound { .. })
2560        )
2561    }
2562
2563    /// The `([[BoundTargetFunction]], [[BoundThis]])` pair, for `OrdinaryHasInstance`'s
2564    /// bound-function step (§10.3.1 step 3) — the only caller that needs to look *into* a
2565    /// bound function rather than just call it.
2566    ///
2567    /// `None` for anything that is not a bound function.
2568    pub fn bound_target_and_this(&self) -> Option<(Value, Value)> {
2569        match &self.data.borrow().kind {
2570            ObjectKind::Function(Callable::Bound { target, this, .. }) => {
2571                Some((target.clone(), this.clone()))
2572            }
2573            _ => None,
2574        }
2575    }
2576
2577    /// Whether this object has a `[[Construct]]`, i.e. may be the target of `new` or
2578    /// `Reflect.construct`.
2579    pub fn is_constructor(&self) -> bool {
2580        let data = self.data.borrow();
2581        match &data.kind {
2582            // The flag, not "is a function": a plain method is a function and is not a
2583            // constructor. Set at creation by whoever knows what was built.
2584            ObjectKind::Function(_) => data.constructible,
2585            // Recorded at creation for the same reason as callability: revoking drops the
2586            // target without taking `[[Construct]]` away.
2587            ObjectKind::Proxy(state) => state.borrow().constructible,
2588            _ => false,
2589        }
2590    }
2591
2592    /// Give this function a `[[Construct]]`.
2593    ///
2594    /// Only for callables that are constructors by definition: ordinary functions, class
2595    /// constructors, and the built-in constructors. Everything else — methods, arrows,
2596    /// generators, async functions — keeps the default `false`.
2597    pub fn set_constructible(&self, yes: bool) {
2598        self.data.borrow_mut().constructible = yes;
2599    }
2600
2601    /// This object's proxy slots, when it is one (revoked or not).
2602    pub fn proxy_state(&self) -> Option<ProxyRef> {
2603        match &self.data.borrow().kind {
2604            ObjectKind::Proxy(state) => Some(state.clone()),
2605            _ => None,
2606        }
2607    }
2608
2609    /// A proxy over `target` reading its traps from `handler`.
2610    ///
2611    /// The prototype stays empty on purpose: `[[GetPrototypeOf]]` on a proxy forwards to
2612    /// the target through the `getPrototypeOf` trap, so copying the target's prototype
2613    /// here would be a second, disagreeing source of truth.
2614    pub fn proxy(heap: &js_gc::Heap, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2615        // Read callability from the target *now*: it is the one moment the answer is
2616        // available, and it outlives revocation.
2617        let callable = target.is_callable();
2618        let constructible = target.is_constructor();
2619        Gc::new(
2620            heap,
2621            JsObject::new(
2622                ObjectKind::Proxy(std::rc::Rc::new(std::cell::RefCell::new(ProxyState {
2623                    callable,
2624                    constructible,
2625                    target: Some(target),
2626                    handler: Some(handler),
2627                }))),
2628                None,
2629            ),
2630        )
2631    }
2632
2633    /// The prototype.
2634    pub fn proto(&self) -> Option<Gc<JsObject>> {
2635        self.data.borrow().proto.clone()
2636    }
2637
2638    /// Replace the prototype.
2639    pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
2640        self.data.borrow_mut().proto = proto;
2641    }
2642
2643    /// The object a method was defined on, for `super` to resolve against.
2644    pub fn home_object(&self) -> Option<Gc<JsObject>> {
2645        self.data.borrow().home_object.clone()
2646    }
2647
2648    /// Record the object a method was defined on.
2649    ///
2650    /// A method has no `[[Construct]]` (§10.2.1): `new (o.m)` is a `TypeError` even
2651    /// though `o.m` is a function. Acquiring a home object is exactly the moment a
2652    /// function becomes a method, so the flag is cleared here rather than left to every
2653    /// method-defining call site to remember.
2654    pub fn set_home_object(&self, home: Option<Gc<JsObject>>) {
2655        let mut data = self.data.borrow_mut();
2656        data.home_object = home.clone();
2657        if home.is_some() {
2658            data.constructible = false;
2659            // §15.4 / §10.2.1: a method has **no own `prototype`** — it is created with
2660            // `OrdinaryFunctionCreate` and no `MakeConstructor` call. The function object is
2661            // built before it is known to be a method (that is what this call marks), so the
2662            // property installed back then has to come off here.
2663            //
2664            // Leaving it on made `{ m() {} }.m` report `length,name,prototype` where the
2665            // reference reports `length,name`, and — because the property is
2666            // non-configurable — made `Object.defineProperty(m, "prototype", …)` throw
2667            // "cannot redefine property", which is the first thing
2668            // `Function/prototype/Symbol.hasInstance/this-val-poisoned-prototype.js` does.
2669            data.props
2670                .retain(|(key, _)| key.as_str() != Some("prototype"));
2671        }
2672    }
2673
2674    /// The brand symbol this object owns as a class home object, if it is one.
2675    pub fn private_brand(&self) -> Option<Gc<crate::value::JsSymbol>> {
2676        self.data.borrow().private_brand.clone()
2677    }
2678
2679    /// Record `symbol` as the brand this object owns.
2680    pub fn set_private_brand(&self, symbol: Gc<crate::value::JsSymbol>) {
2681        self.data.borrow_mut().private_brand = Some(symbol);
2682    }
2683
2684    /// Whether this object carries `symbol` among its brands.
2685    ///
2686    /// This is the question `check_brand` asks of the receiver, and the one `add_brand`
2687    /// asks before adding — a second `add_brand` with the same symbol is the reference's
2688    /// "private method is already present".
2689    pub fn carries_brand(&self, symbol: &Gc<crate::value::JsSymbol>) -> bool {
2690        self.data
2691            .borrow()
2692            .brands
2693            .iter()
2694            .any(|own| Gc::ptr_eq(own, symbol))
2695    }
2696
2697    /// Give this object the brand `symbol`.
2698    pub fn add_brand(&self, symbol: Gc<crate::value::JsSymbol>) {
2699        self.data.borrow_mut().brands.push(symbol);
2700    }
2701
2702    /// Whether this is a class constructor.
2703    pub fn is_class_constructor(&self) -> bool {
2704        self.data.borrow().class_constructor
2705    }
2706
2707    /// Mark this function as a class constructor.
2708    pub fn set_class_constructor(&self, yes: bool) {
2709        self.data.borrow_mut().class_constructor = yes;
2710    }
2711
2712    /// The elements of an array object, if this is one.
2713    pub fn array_elements(&self) -> Option<Vec<Value>> {
2714        match &self.data.borrow().kind {
2715            ObjectKind::Array { elements, .. } => Some(elements.clone()),
2716            _ => None,
2717        }
2718    }
2719
2720    /// Every own key with its descriptor, array indices included.
2721    ///
2722    /// [`JsObject::own_property_keys`] answers the same question without the
2723    /// descriptors; a proxy invariant needs both at once, because it has to check the
2724    /// *value* of a key it is told about and the presence of a key it is not.
2725    pub fn property_entries(&self) -> Vec<(PropertyKey, Property)> {
2726        let data = self.data.borrow();
2727        let mut out: Vec<(PropertyKey, Property)> = data.props.to_vec();
2728        // An array's elements live in their own vector rather than the property table, so
2729        // they have to be synthesized — with the attributes an ordinary element has.
2730        if let ObjectKind::Array { elements, .. } = &data.kind {
2731            for (index, element) in elements.iter().enumerate() {
2732                if matches!(element, Value::Hole) {
2733                    continue;
2734                }
2735                let key = PropertyKey::from(index.to_string());
2736                if !out.iter().any(|(existing, _)| *existing == key) {
2737                    out.push((key, Property::data(element.clone())));
2738                }
2739            }
2740        }
2741        // `length` is own on an array without being in the property table either. It is
2742        // writable, non-enumerable and — the part proxy invariants care about —
2743        // non-configurable, so leaving it out let a handler hide or redefine it.
2744        if matches!(data.kind, ObjectKind::Array { .. })
2745            && let Some(length) = self.array_length()
2746        {
2747            let key = PropertyKey::from("length");
2748            if !out.iter().any(|(existing, _)| *existing == key) {
2749                out.push((
2750                    key,
2751                    Property {
2752                        value: Some(length_value(length)),
2753                        writable: self.length_writable(),
2754                        enumerable: false,
2755                        configurable: false,
2756                        getter: None,
2757                        setter: None,
2758                        descriptor_fields: None,
2759                    },
2760                ));
2761            }
2762        }
2763        out
2764    }
2765
2766    /// Whether this object has array elements at all.
2767    pub fn is_array(&self) -> bool {
2768        match &self.data.borrow().kind {
2769            ObjectKind::Array { .. } => true,
2770            // `Array.isArray` is specified to see *through* a proxy: it forwards
2771            // `[[Get]]`/prototype checks to the target, and the answer for a proxy of an
2772            // array is yes.
2773            ObjectKind::Proxy(state) => state
2774                .borrow()
2775                .target
2776                .as_ref()
2777                .is_some_and(|target| target.is_array()),
2778            _ => false,
2779        }
2780    }
2781
2782    /// `length` for an array, reading it out of the element vector.
2783    /// The compiled pattern, when this object is a `RegExp`.
2784    pub fn regexp(&self) -> Option<crate::builtins::regexp::RegExpData> {
2785        match &self.data.borrow().kind {
2786            ObjectKind::RegExp(data) => Some(data.clone()),
2787            _ => None,
2788        }
2789    }
2790
2791    /// The held resources, when this object is a `DisposableStack`.
2792    pub fn disposable_stack(&self) -> Option<crate::builtins::disposable::StackState> {
2793        match &self.data.borrow().kind {
2794            ObjectKind::DisposableStack(state) => Some(state.clone()),
2795            _ => None,
2796        }
2797    }
2798
2799    /// Make this object a `DisposableStack` holding `state`.
2800    pub fn set_disposable_stack(&self, state: crate::builtins::disposable::StackState) {
2801        self.data.borrow_mut().kind = ObjectKind::DisposableStack(state);
2802    }
2803
2804    /// Make this object a `RegExp` carrying `data`.
2805    pub fn set_regexp(&self, data: crate::builtins::regexp::RegExpData) {
2806        self.data.borrow_mut().kind = ObjectKind::RegExp(data);
2807    }
2808
2809    /// Whether this object is a `RegExp`.
2810    pub fn is_regexp(&self) -> bool {
2811        matches!(self.data.borrow().kind, ObjectKind::RegExp(_))
2812    }
2813
2814    /// An array's element count, when this object is an array.
2815    pub fn array_length(&self) -> Option<usize> {
2816        match &self.data.borrow().kind {
2817            ObjectKind::Array { length, .. } => Some(*length),
2818            _ => None,
2819        }
2820    }
2821
2822    /// How many elements are actually allocated, which is at most the length.
2823    ///
2824    /// Distinct from [`Self::array_length`] on purpose: `new Array(5)` has a length of 5
2825    /// and nothing allocated, and the difference is what tells a store that fills a hole
2826    /// (it has to grow the vector) from one that overwrites an existing element.
2827    pub fn array_allocated(&self) -> usize {
2828        match &self.data.borrow().kind {
2829            ObjectKind::Array { elements, .. } => elements.len(),
2830            _ => 0,
2831        }
2832    }
2833
2834    /// Read one array element.
2835    pub fn array_get(&self, index: usize) -> Option<Value> {
2836        match &self.data.borrow().kind {
2837            ObjectKind::Array { elements, .. } => elements.get(index).cloned(),
2838            _ => None,
2839        }
2840    }
2841
2842    /// Append to an array and return the new length.
2843    pub fn array_push(&self, heap: &js_gc::Heap, value: Value) -> usize {
2844        let mut data = self.data.borrow_mut();
2845        match &mut data.kind {
2846            ObjectKind::Array { elements, length } => {
2847                let before = elements.capacity();
2848                elements.push(value);
2849                *length = elements.len();
2850                charge_capacity::<Value>(heap, before, elements.capacity());
2851                *length
2852            }
2853            _ => 0,
2854        }
2855    }
2856
2857    /// Store into an array, and return whether the write happened.
2858    ///
2859    /// The gap an out-of-range store leaves behind is filled with [`Value::Hole`], not
2860    /// `undefined`: `a = [1]; a[3] = 4` has holes at 1 and 2, which `forEach` skips
2861    /// and the debug printer reports. A store *of* `undefined` is a real element.
2862    pub fn array_set(&self, heap: &js_gc::Heap, index: usize, value: Value) -> bool {
2863        let mut data = self.data.borrow_mut();
2864        match &mut data.kind {
2865            ObjectKind::Array { elements, length } => {
2866                let before = elements.capacity();
2867                // Growing has to fill the gap, and filling it means the vector really does
2868                // hold `index + 1` slots — a store at `2^32-2` is 68 GB whatever the length
2869                // field says, which is why the reference's allocation fails there. Refuse
2870                // instead of aborting the process, and let the caller take the sparse path
2871                // (an ordinary property plus a longer `length`).
2872                //
2873                // The bound is checked for *both* branches. It used to be checked only when
2874                // the index was past `length`, on the reasoning that an index inside the
2875                // length is at most `length` — true, and useless once `length` is 2^32-1:
2876                // `a.length` can be set to 4 billion without allocating anything, so the
2877                // very next store inside it asked for a 68 GB vector. That took eight
2878                // seconds and tens of gigabytes to discover.
2879                if index + 1 > ARRAY_ELEMENT_LIMIT {
2880                    return false;
2881                }
2882                if index >= *length {
2883                    elements.resize(index + 1, Value::Hole);
2884                    *length = elements.len();
2885                } else if index >= elements.len() {
2886                    // Inside the logical length but past the dense prefix: a hole that is
2887                    // being filled, so the vector has to catch up first.
2888                    elements.resize(index + 1, Value::Hole);
2889                }
2890                elements[index] = value;
2891                charge_capacity::<Value>(heap, before, elements.capacity());
2892                true
2893            }
2894            _ => false,
2895        }
2896    }
2897
2898    /// Store an element, honouring its attributes, reporting whether it happened.
2899    ///
2900    /// Array methods that write back (`sort`, `reverse`, `splice`, …) use this rather
2901    /// than [`Self::array_set`]: the spec has them go through `[[Set]]`, so a frozen
2902    /// element makes them throw instead of being quietly overwritten.
2903    pub fn array_store(&self, heap: &js_gc::Heap, index: usize, value: Value) -> bool {
2904        // The ordinary array — nothing in it has ever been given an attribute of its own —
2905        // has no table entry that a slot write could shadow, so the vector is the answer.
2906        if !self.has_element_descriptors() {
2907            return self.elements_writable() && self.array_set(heap, index, value);
2908        }
2909        // Otherwise this index may be an accessor (which is not a slot at all) or
2910        // read-only. `false` sends the caller down the slow path, which is the only one
2911        // that can call a setter or raise the strict-mode `TypeError`.
2912        if let Some(property) = self.element_attributes(index as u32)
2913            && (property.is_accessor() || !property.writable)
2914        {
2915            return false;
2916        }
2917        self.elements_writable() && self.array_set(heap, index, value)
2918    }
2919
2920    /// Store `value` as a plain element without creating holes, used by `push`.
2921    pub fn array_push_hole(&self, heap: &js_gc::Heap) -> bool {
2922        let mut data = self.data.borrow_mut();
2923        match &mut data.kind {
2924            ObjectKind::Array { elements, length } => {
2925                let before = elements.capacity();
2926                elements.push(Value::Hole);
2927                *length = elements.len();
2928                charge_capacity::<Value>(heap, before, elements.capacity());
2929                true
2930            }
2931            _ => false,
2932        }
2933    }
2934
2935    /// Set the length of an array, truncating or extending with holes.
2936    ///
2937    /// `a.length = 5` on a two-element array leaves three holes, so the fill value is
2938    /// [`Value::Hole`] rather than `undefined`.
2939    /// Growing only records the new length: the extra slots are holes, and a hole needs
2940    /// no storage. That is what makes `a = []; a.length = 4294967295` an O(1) operation
2941    /// instead of a 62 GB allocation.
2942    pub fn array_set_length(&self, heap: &js_gc::Heap, new_length: usize) -> bool {
2943        let mut data = self.data.borrow_mut();
2944        let ObjectData { kind, props, .. } = &mut *data;
2945        match kind {
2946            ObjectKind::Array { elements, length } => {
2947                let before = elements.capacity();
2948                if new_length < *length {
2949                    // Shrinking really does drop the trailing elements.
2950                    elements.truncate(new_length);
2951                    // …and the sparse ones, which live in the property table: §10.4.2.4
2952                    // deletes *every* index at or above the new length, not only the dense
2953                    // prefix. An index past the dense limit is an ordinary property (see
2954                    // [`Self::array_set`]), so without this `x[4294967294] = 1; x.length = 2`
2955                    // left the value readable — `S15.4.5.2_A3_T4` is that case.
2956                    drop_sparse_indices(props, new_length);
2957                }
2958                *length = new_length;
2959                charge_capacity::<Value>(heap, before, elements.capacity());
2960                true
2961            }
2962            _ => false,
2963        }
2964    }
2965
2966    /// Truncate an array to `length` elements without extending it.
2967    ///
2968    /// This is what `arr.length = n` does for `n` smaller than the current length;
2969    /// it is separate from [`Self::array_set_length`] because growing an array by
2970    /// assignment produces holes, which are indistinguishable from `undefined`
2971    /// here.
2972    pub fn array_truncate(&self, heap: &js_gc::Heap, new_length: usize) -> bool {
2973        let mut data = self.data.borrow_mut();
2974        let ObjectData { kind, props, .. } = &mut *data;
2975        match kind {
2976            ObjectKind::Array { elements, length } => {
2977                let before = elements.capacity();
2978                if new_length < elements.len() {
2979                    elements.truncate(new_length);
2980                }
2981                if new_length < *length {
2982                    *length = new_length;
2983                    drop_sparse_indices(props, new_length);
2984                }
2985                charge_capacity::<Value>(heap, before, elements.capacity());
2986                true
2987            }
2988            _ => false,
2989        }
2990    }
2991
2992    /// The own data property `key`, if there is one.
2993    pub fn own_property_key(&self, key: &PropertyKey) -> Option<Property> {
2994        let data = self.data.borrow();
2995        data.props
2996            .iter()
2997            .find(|(existing, _)| existing == key)
2998            .map(|(_, property)| property.clone())
2999    }
3000
3001    /// The reference cell behind a mapped `arguments` index, if there is one.
3002    ///
3003    /// `None` for every other object, and for an index that is not mapped (a strict
3004    /// `arguments`, or an index past the parameter list).
3005    pub fn mapped_argument_cell(&self, index: usize) -> Option<Gc<crate::value::Cell>> {
3006        self.data
3007            .borrow()
3008            .mapped_arguments
3009            .as_ref()
3010            .and_then(|mapped| mapped.get(index).cloned().flatten())
3011    }
3012
3013    /// Stop treating `index` as a mapped `arguments` index, leaving the value it had.
3014    ///
3015    /// §10.4.4.2 drops the parameter alias once the property stops being a writable
3016    /// data property; the index then holds whatever was last mapped into it.
3017    pub fn drop_mapped_argument(&self, index: usize) {
3018        if let Some(mapped) = self.data.borrow_mut().mapped_arguments.as_mut()
3019            && let Some(slot) = mapped.get_mut(index)
3020        {
3021            *slot = None;
3022        }
3023    }
3024
3025    /// Record the mapped cells of a sloppy-mode `arguments` object.
3026    pub fn set_mapped_arguments(&self, mapped: Vec<Option<Gc<crate::value::Cell>>>) {
3027        self.data.borrow_mut().mapped_arguments = Some(mapped);
3028    }
3029
3030    /// The address of this object, for an inline cache's hash.
3031    ///
3032    /// Only ever hashed, never dereferenced — and a hash collision is caught by the
3033    /// re-validation, never trusted. Compare a cached handle instead when identity matters.
3034    pub fn address(&self) -> usize {
3035        self as *const JsObject as usize
3036    }
3037
3038    /// The data property at `index`, if the table still has `key` there as a plain value.
3039    ///
3040    /// This is the read half of an inline cache: the caller remembers *where* a property was
3041    /// found on a particular object, and this re-checks the two things that could have
3042    /// changed — the entry moving (the table is a `Vec`, so a delete shifts it) and the
3043    /// property becoming an accessor. Re-checking is what makes the cache safe without
3044    /// shape/hidden-class machinery: there is no pointer arithmetic on a remembered index,
3045    /// only a bounds-checked lookup followed by an equality test.
3046    /// The value at `index` if the table still has the shape the entry recorded.
3047    ///
3048    /// One borrow for what [`Self::props_len`] followed by [`Self::cached_data_property`]
3049    /// does with two, and it answers from a single lookup instead of two. That pair is the
3050    /// whole body of a monomorphic cache hit, so the extra `RefCell` borrow was per
3051    /// property read in every loop there is.
3052    pub fn cached_property_at(
3053        &self,
3054        index: usize,
3055        key: &PropertyKey,
3056        expected_len: usize,
3057    ) -> Option<Value> {
3058        let data = self.data.borrow();
3059        if data.props.len() != expected_len {
3060            return None;
3061        }
3062        let (existing, property) = data.props.get(index)?;
3063        if existing != key || property.is_accessor() {
3064            return None;
3065        }
3066        property.value.clone()
3067    }
3068
3069    /// The data property at `index`, if the table still has `key` there as a plain value.
3070    ///
3071    /// The two-check form, for callers that have not already validated the table length.
3072    /// A cache hit on level 0 should use [`Self::cached_property_at`], which folds the
3073    /// length check into the same borrow.
3074    pub fn cached_data_property(&self, index: usize, key: &PropertyKey) -> Option<Value> {
3075        let data = self.data.borrow();
3076        let (existing, property) = data.props.get(index)?;
3077        if existing != key || property.is_accessor() {
3078            return None;
3079        }
3080        property.value.clone()
3081    }
3082
3083    /// The own data property at `index`, if the key there is still `name`.
3084    ///
3085    /// The global-variable cache's validation. The caller passes the name it is looking
3086    /// for and this compares it against *the table's* entry — catching both the property
3087    /// being replaced by an accessor and the entry moving when a delete shifted the `Vec`.
3088    ///
3089    /// It takes a `&str` rather than a `PropertyKey` on purpose: building a key allocates,
3090    /// and a cache that allocates on every hit is not a cache.
3091    pub fn data_property_at(&self, index: usize, name: &str) -> Option<Value> {
3092        let data = self.data.borrow();
3093        let (existing, property) = data.props.get(index)?;
3094        if existing.as_str() != Some(name) || property.is_accessor() {
3095            return None;
3096        }
3097        property.value.clone()
3098    }
3099
3100    /// Store `value` at the own data property `index`, if the table still has `name`
3101    /// there as a writable data property.
3102    ///
3103    /// The write half of [`Self::data_property_at`], and it exists for the same reason the
3104    /// read half does: assigning to a global `var` went through `set_property_with`, which
3105    /// converts the name to a `PropertyKey` (two allocations) and then linearly scans the
3106    /// global object's table — which holds every builtin. A loop body like `s += 1` paid
3107    /// that on every iteration: measured with a counter, a 5-million-iteration loop
3108    /// assigning to a global made 20,000,036 `own_property_key` calls where the same loop
3109    /// over a local made 32.
3110    ///
3111    /// Re-validation is the same pair the read half checks — the entry has not moved and
3112    /// is still a data property — plus `writable`, because a store has one more way to
3113    /// fail than a load.
3114    pub fn write_data_at(&self, index: usize, name: &str, value: Value) -> bool {
3115        let mut data = self.data.borrow_mut();
3116        let Some((existing, property)) = data.props.get_mut(index) else {
3117            return false;
3118        };
3119        if existing.as_str() != Some(name) || property.is_accessor() || !property.writable {
3120            return false;
3121        }
3122        property.value = Some(value);
3123        true
3124    }
3125
3126    /// The number of own properties, for an inline cache's invalidation guard.
3127    ///
3128    /// A prototype-hit cache records this for every link of the chain it walked: adding or
3129    /// deleting *any* property moves it, which is what makes a stale entry a miss rather
3130    /// than a wrong answer.
3131    pub fn props_len(&self) -> usize {
3132        self.data.borrow().props.len()
3133    }
3134
3135    /// The property table's allocated slot count.
3136    ///
3137    /// The memory report wants capacity rather than length: the difference is memory the
3138    /// object is holding and nobody can see from `Object.keys`.
3139    pub fn props_capacity(&self) -> usize {
3140        self.data.borrow().props.capacity()
3141    }
3142
3143    /// Run `f` on this object's kind.
3144    ///
3145    /// A closure rather than `&ObjectKind`, for the same reason
3146    /// [`JsString::wtf8`](crate::value::JsString::wtf8) hands out a reference tied to
3147    /// `&self`: the kind lives behind a `RefCell`, so a borrow cannot outlive this call.
3148    /// Everything that needs to *inspect* rather than mutate goes through here.
3149    pub fn with_kind<R>(&self, f: impl FnOnce(&ObjectKind) -> R) -> R {
3150        f(&self.data.borrow().kind)
3151    }
3152
3153    /// The index of the own **data** property `name`, for filling a cache.
3154    ///
3155    /// An accessor answers `None` — it must never be cached, because running its getter
3156    /// is the whole point of not caching it.
3157    pub fn own_data_index(&self, name: &str) -> Option<usize> {
3158        let data = self.data.borrow();
3159        let index = data
3160            .props
3161            .iter()
3162            .position(|(existing, _)| existing.as_str() == Some(name))?;
3163        let (_, property) = &data.props[index];
3164        if property.is_accessor() || property.value.is_none() {
3165            return None;
3166        }
3167        Some(index)
3168    }
3169
3170    /// Where `key` sits in this object's own property table, for caching.
3171    pub fn own_property_index(&self, key: &PropertyKey) -> Option<(usize, Value)> {
3172        let data = self.data.borrow();
3173        let index = data
3174            .props
3175            .iter()
3176            .position(|(existing, _)| existing == key)?;
3177        let (_, property) = &data.props[index];
3178        if property.is_accessor() {
3179            return None;
3180        }
3181        Some((index, property.value.clone()?))
3182    }
3183
3184    /// The own data property `name`, if there is one.
3185    pub fn own_property(&self, name: &str) -> Option<Property> {
3186        self.own_property_key(&PropertyKey::from(name))
3187    }
3188
3189    /// Whether the object has an own property `key`.
3190    pub fn has_own_key(&self, key: &PropertyKey) -> bool {
3191        let data = self.data.borrow();
3192        data.props.iter().any(|(existing, _)| existing == key)
3193    }
3194
3195    /// Whether the object has an own property `name`.
3196    pub fn has_own(&self, name: &str) -> bool {
3197        self.has_own_key(&PropertyKey::from(name))
3198    }
3199
3200    /// Define or replace an own property, keeping the original position when the
3201    /// key already exists.
3202    pub fn define_key(&self, key: &PropertyKey, property: Property) {
3203        let mut data = self.data.borrow_mut();
3204        match data.props.iter_mut().find(|(existing, _)| existing == key) {
3205            Some((_, slot)) => *slot = property,
3206            None => data.props.push((key.clone(), property)),
3207        }
3208    }
3209
3210    /// Define or replace an own property under a string key.
3211    pub fn define(&self, name: &str, property: Property) {
3212        self.define_key(&PropertyKey::from(name), property);
3213    }
3214
3215    /// Define an own data property, with the default attributes.
3216    ///
3217    /// This *creates*: on an existing property it overwrites the attributes too, so
3218    /// it is the wrong call for a plain assignment. Use [`Self::write_value`] for that.
3219    pub fn define_data(&self, name: &str, value: Value) {
3220        self.define(name, Property::data(value));
3221    }
3222
3223    /// Define an own data property under `key`.
3224    pub fn define_data_key(&self, key: &PropertyKey, value: Value) {
3225        self.define_key(key, Property::data(value));
3226    }
3227
3228    /// Store a value into an existing own data property, keeping its attributes.
3229    ///
3230    /// Returns `false` when the property is absent, is an accessor, or is not
3231    /// writable. An assignment has to go through this rather than
3232    /// [`Self::define_data`], because redefining is how a non-configurable global
3233    /// silently became configurable again and started answering `delete` with `true`.
3234    pub fn write_value(&self, name: &str, value: Value) -> bool {
3235        self.write_value_key(&PropertyKey::from(name), value)
3236    }
3237
3238    /// Store a value into an existing own data property under `key`.
3239    pub fn write_value_key(&self, key: &PropertyKey, value: Value) -> bool {
3240        let mut data = self.data.borrow_mut();
3241        let Some((_, property)) = data.props.iter_mut().find(|(existing, _)| existing == key)
3242        else {
3243            return false;
3244        };
3245        if property.is_accessor() || !property.writable {
3246            return false;
3247        }
3248        property.value = Some(value);
3249        true
3250    }
3251
3252    /// Delete an own property, reporting whether it was there and removable.
3253    pub fn delete(&self, name: &str) -> bool {
3254        self.delete_key(&PropertyKey::from(name))
3255    }
3256
3257    /// Delete an own property under `key`.
3258    pub fn delete_key(&self, key: &PropertyKey) -> bool {
3259        let mut data = self.data.borrow_mut();
3260        match data.props.iter().position(|(existing, _)| existing == key) {
3261            Some(index) => {
3262                if data.props[index].1.configurable {
3263                    data.props.remove(index);
3264                    true
3265                } else {
3266                    false
3267                }
3268            }
3269            None => true,
3270        }
3271    }
3272
3273    /// Whether new properties may be added.
3274    pub fn is_extensible(&self) -> bool {
3275        self.data.borrow().extensible
3276    }
3277
3278    /// Make the object non-extensible.
3279    pub fn set_extensible(&self, extensible: bool) {
3280        self.data.borrow_mut().extensible = extensible;
3281    }
3282
3283    /// Whether array elements may be replaced.
3284    pub fn elements_writable(&self) -> bool {
3285        self.data.borrow().elements_writable
3286    }
3287
3288    /// Whether any element of this array has a descriptor of its own.
3289    ///
3290    /// Until something has, [`JsObject::array_store`] may write the element vector
3291    /// directly; after, every store has to consult the property table for that index.
3292    pub fn has_element_descriptors(&self) -> bool {
3293        self.data.borrow().element_descriptors
3294    }
3295
3296    /// Record that an element now has a descriptor of its own.
3297    pub fn note_element_descriptor(&self) {
3298        self.data.borrow_mut().element_descriptors = true;
3299    }
3300
3301    /// Whether an array's `length` may be changed.
3302    pub fn length_writable(&self) -> bool {
3303        self.data.borrow().length_writable
3304    }
3305
3306    /// Record whether `length` may be changed.
3307    pub fn set_length_writable(&self, writable: bool) {
3308        self.data.borrow_mut().length_writable = writable;
3309    }
3310
3311    /// Make array elements read-only, as `Object.freeze` does.
3312    pub fn set_elements_writable(&self, writable: bool) {
3313        self.data.borrow_mut().elements_writable = writable;
3314    }
3315
3316    /// The attributes recorded for an array index, if `defineProperty` set any.
3317    pub fn element_attributes(&self, index: u32) -> Option<Property> {
3318        self.own_property(&index.to_string())
3319    }
3320
3321    /// Whether `delete` at `index` would be rejected.
3322    ///
3323    /// Separate from [`JsObject::element_is_locked`]: a store needs the element to be
3324    /// non-writable, but a *delete* — which is what truncating an array does — only needs
3325    /// it to be non-configurable. `Object.defineProperty(a, "3", {configurable: false})`
3326    /// leaves `a[3]` writable and yet undeletable, so `a.length = 2` must fail.
3327    pub fn element_is_undeletable(&self, index: u32) -> bool {
3328        if !self.elements_writable() {
3329            return true;
3330        }
3331        self.element_attributes(index)
3332            .is_some_and(|property| !property.configurable)
3333    }
3334
3335    /// The lowest index at or above `from` whose element cannot be deleted.
3336    ///
3337    /// Callers use this to refuse a shrinking `length` (§10.4.2.4 deletes every index at or
3338    /// above the new length, and a non-configurable one makes that impossible). Scanning
3339    /// `from..length` instead is what a *sparse* array turns into an hour-long loop: after
3340    /// `x[2**32 - 2] = 1`, `x.length = 2` would ask `element_is_undeletable` four billion
3341    /// times. Only two things can be undeletable — a frozen object (every element) and an
3342    /// index with a recorded descriptor (a handful) — so this looks at exactly those.
3343    pub fn first_undeletable_at_or_above(&self, from: usize) -> Option<usize> {
3344        if !self.elements_writable() {
3345            return Some(from);
3346        }
3347        let data = self.data.borrow();
3348        data.props
3349            .iter()
3350            .filter_map(|(key, property)| {
3351                let index = key.as_str().and_then(array_index)? as usize;
3352                (index >= from && !property.configurable).then_some(index)
3353            })
3354            .min()
3355    }
3356
3357    /// The highest index in `from..below` whose element cannot be deleted.
3358    ///
3359    /// The spec's `ArraySetLength` walks *down* from the current length and stops at the
3360    /// first element it cannot delete, so the answer it needs is the last one.
3361    pub fn last_undeletable_at_or_above(&self, from: usize, below: usize) -> Option<usize> {
3362        if below <= from {
3363            return None;
3364        }
3365        if !self.elements_writable() {
3366            return Some(below - 1);
3367        }
3368        let data = self.data.borrow();
3369        data.props
3370            .iter()
3371            .filter_map(|(key, property)| {
3372                let index = key.as_str().and_then(array_index)? as usize;
3373                (index >= from && index < below && !property.configurable).then_some(index)
3374            })
3375            .max()
3376    }
3377
3378    /// Whether a store at `index` would be rejected.
3379    ///
3380    /// An element is locked either by `Object.freeze` on the whole object or by a
3381    /// non-configurable, non-writable descriptor recorded for that one index.
3382    pub fn element_is_locked(&self, index: u32) -> bool {
3383        if !self.elements_writable() {
3384            return true;
3385        }
3386        self.element_attributes(index)
3387            .is_some_and(|property| !property.writable && !property.configurable)
3388    }
3389
3390    /// The own property *names*, in definition order. Symbol keys are excluded:
3391    /// `Object.keys` and `for…in` cannot see them.
3392    pub fn own_keys(&self) -> Vec<crate::value::Wtf8> {
3393        self.data
3394            .borrow()
3395            .props
3396            .iter()
3397            .filter_map(|(key, _)| key.as_wtf8().cloned())
3398            .collect()
3399    }
3400
3401    /// The own *enumerable* property names, in definition order.
3402    pub fn own_enumerable_keys(&self) -> Vec<crate::value::Wtf8> {
3403        self.data
3404            .borrow()
3405            .props
3406            .iter()
3407            .filter(|(_, property)| property.enumerable)
3408            .filter_map(|(key, _)| key.as_wtf8().cloned())
3409            .collect()
3410    }
3411
3412    /// The own symbol keys, in definition order, for `Object.getOwnPropertySymbols`.
3413    pub fn own_symbol_keys(&self) -> Vec<Gc<JsSymbol>> {
3414        self.data
3415            .borrow()
3416            .props
3417            .iter()
3418            .filter_map(|(key, _)| match key {
3419                // Private names are invisible to enumeration; see `JsSymbol::is_private`.
3420                PropertyKey::Symbol(symbol) if !symbol.is_private() => Some(symbol.clone()),
3421                PropertyKey::Symbol(_) | PropertyKey::String(_) => None,
3422            })
3423            .collect()
3424    }
3425
3426    /// Every own key, strings first then symbols — the order `Reflect.ownKeys` and
3427    /// `Object.getOwnPropertyDescriptors` report, and the order `JSON.stringify`
3428    /// walks before it skips the symbols.
3429    pub fn own_property_keys(&self) -> Vec<PropertyKey> {
3430        let data = self.data.borrow();
3431        let mut strings: Vec<PropertyKey> = Vec::new();
3432        let mut symbols: Vec<PropertyKey> = Vec::new();
3433        for (key, _) in &data.props {
3434            if let PropertyKey::Symbol(symbol) = key {
3435                // A class-private name is not an own key for any observable purpose.
3436                if !symbol.is_private() {
3437                    symbols.push(key.clone());
3438                }
3439            } else {
3440                strings.push(key.clone());
3441            }
3442        }
3443        strings.extend(symbols);
3444        strings
3445    }
3446
3447    /// Own property keys in **definition order**, with symbols interleaved.
3448    ///
3449    /// [`JsObject::own_property_keys`] answers in the spec's order — integer-like keys
3450    /// ascending, then strings, then symbols — because that is what `Reflect.ownKeys` and
3451    /// `for...in` must do. A dumper has the opposite requirement: quickjs's
3452    /// `JS_PrintValue` walks the shape, so `{[Symbol("t")]: 1, y: 2}` prints the symbol
3453    /// first. That is not observable from a script except through such a dump, which is
3454    /// why this is a separate accessor rather than a change to `own_property_keys`.
3455    pub fn own_property_keys_in_definition_order(&self) -> Vec<PropertyKey> {
3456        self.data
3457            .borrow()
3458            .props
3459            .iter()
3460            .map(|(key, _)| key.clone())
3461            .collect()
3462    }
3463
3464    /// The prototype chain, starting with the prototypes of this object.
3465    pub fn chain(&self) -> Vec<Gc<JsObject>> {
3466        let mut out = Vec::new();
3467        let mut proto = self.proto();
3468        while let Some(object) = proto {
3469            proto = object.proto();
3470            out.push(object);
3471        }
3472        out
3473    }
3474}
3475
3476/// Whether two prototypes are the same one, `None` included.
3477///
3478/// A proxy's prototype invariants have to compare "no prototype" against "no
3479/// prototype" without unwrapping either side first.
3480pub(crate) fn same_proto(a: Option<&Gc<JsObject>>, b: Option<&Gc<JsObject>>) -> bool {
3481    match (a, b) {
3482        (None, None) => true,
3483        (Some(a), Some(b)) => a.ptr_eq(b),
3484        _ => false,
3485    }
3486}
3487
3488/// Walk the prototype chain from `object` looking for `name`.
3489///
3490/// Returns the object that owns the property along with the property itself. The
3491/// owner matters for a store: an inherited accessor is invoked on the receiver,
3492/// while an inherited *data* property is shadowed by a new own property.
3493/// The own property `key` names on `object`, arrays included.
3494///
3495/// An array keeps its elements in an element vector and derives its `length`, so its
3496/// property table knows about neither: a hole is a slot in the vector, not a missing
3497/// property, and `length` is not stored at all. `Array.prototype` is itself an array, so
3498/// every walk down the chain needs this same care — without it `1 in [1,,3]` stayed false
3499/// with `Array.prototype[1]` defined, `"length" in []` was false outright, and a hole did
3500/// not read an inherited element.
3501pub fn own_property_including_array(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3502    if let Some(property) = object.own_property_key(key) {
3503        return Some(property);
3504    }
3505    // A typed array's indices are its elements in the buffer, which the property table
3506    // does not hold either. Checked before the `is_array` return below, because a typed
3507    // array is not one.
3508    if object.typed_array_parts().is_some() {
3509        // A detached view exposes no indices at all: `Reflect.has(detached, "0")` is false
3510        // even though index 0 was in range before the buffer went away.
3511        let index = key.as_str().and_then(array_index)?;
3512        let in_range = (index as usize) < object.typed_array_length()?;
3513        return match object.typed_array_element(index as usize) {
3514            Some(value) if in_range => Some(Property::data(value)),
3515            _ => None,
3516        };
3517    }
3518    if !object.is_array() {
3519        return None;
3520    }
3521    let text = key.as_str()?;
3522    // `length` is non-enumerable and non-configurable; `writable` unless a definition
3523    // turned it off.
3524    if text == "length" {
3525        return Some(Property {
3526            value: Some(length_value(object.array_length()?)),
3527            writable: object.length_writable(),
3528            enumerable: false,
3529            configurable: false,
3530            getter: None,
3531            setter: None,
3532            descriptor_fields: None,
3533        });
3534    }
3535    // An element is a plain writable/enumerable/configurable data property, and a hole is
3536    // not one at all.
3537    let index = array_index(text)?;
3538    match object.array_get(index as usize) {
3539        Some(Value::Hole) | None => None,
3540        Some(value) => Some(Property::data(value)),
3541    }
3542}
3543
3544/// Whether `object` has `key` as an *own* property, arrays included.
3545pub fn has_own(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
3546    own_property_including_array(object, key).is_some()
3547}
3548
3549/// `key` on `object` or anywhere up its prototype chain, with the owner.
3550///
3551/// Array-aware at every step: an array's elements and its derived `length` are not in the
3552/// property table, and `Array.prototype` is itself an array.
3553pub fn lookup_key(object: &Gc<JsObject>, key: &PropertyKey) -> Option<(Gc<JsObject>, Property)> {
3554    if let Some(property) = own_property_including_array(object, key) {
3555        return Some((object.clone(), property));
3556    }
3557    lookup_key_above(object, key)
3558}
3559
3560/// [`lookup_key`] starting *above* `object`: its prototype and upwards.
3561///
3562/// Split out for the exotic `[[GetOwnProperty]]` hook, which can report a key as absent on
3563/// the object itself — after which the read still has to find it on the prototype.
3564pub fn lookup_key_above(
3565    object: &Gc<JsObject>,
3566    key: &PropertyKey,
3567) -> Option<(Gc<JsObject>, Property)> {
3568    for ancestor in object.chain() {
3569        if let Some(property) = own_property_including_array(&ancestor, key) {
3570            return Some((ancestor, property));
3571        }
3572    }
3573    None
3574}
3575
3576/// [`lookup_key`] for a string key.
3577pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
3578    lookup_key(object, &PropertyKey::from(name))
3579}
3580
3581/// The largest array index that may be *stored*, i.e. the largest dense vector this engine
3582/// will grow to an index for.
3583///
3584/// The spec's `length` limit is `2^32-1`, but the elements are a dense `Vec<Value>` here,
3585/// so a store at index `2^32-2` is a 68 GB reservation. The reference (which keeps
3586/// elements in a hash map) answers instantly. Refusing past this bound keeps the process
3587/// alive; the conformance tests that really do store near `2^32` are recorded in
3588/// `docs/test262-status.md` as a limitation rather than quietly answered wrong.
3589pub const ARRAY_ELEMENT_LIMIT: usize = 1 << 26;
3590
3591/// An array's `length` as a JavaScript number.
3592///
3593/// `Value::Int` only holds an `i32`, and an array's length may legitimately reach
3594/// `2^32-1`, so a plain cast is not enough: `a[2**32-2] = 1; a.length` came back as `-1`,
3595/// and `Object.getOwnPropertyDescriptor(a, "length").value` with it. Every
3596/// `LengthOfArrayLike` over such an array then ran to `-1`, and the paths without their
3597/// own `RangeError` check turned into `memory allocation of 68719476720 bytes failed`.
3598pub fn length_value(length: usize) -> Value {
3599    if length <= i32::MAX as usize {
3600        Value::Int(length as i32)
3601    } else {
3602        Value::Float(length as f64)
3603    }
3604}
3605
3606/// An array *index* as a JavaScript number.
3607///
3608/// Same problem as [`length_value`] and the same fix: an index may be as large as
3609/// `2^32-2`, which `Value::Int` cannot hold. `a[2**32-2] = 1; a.indexOf(1)` was answering
3610/// `-2` because the index was truncated on the way out.
3611pub fn index_value(index: usize) -> Value {
3612    length_value(index)
3613}
3614
3615/// The array index a property key names, if it names one.
3616///
3617/// A key is an index when it is the canonical decimal spelling of an integer below
3618/// `2^32 - 1` — the same rule the atom table uses to decide whether a key is a
3619/// tagged index. `"01"` and `"-1"` are ordinary string keys.
3620pub fn array_index(key: &str) -> Option<u32> {
3621    if key.is_empty() || key.len() > 10 {
3622        return None;
3623    }
3624    let bytes = key.as_bytes();
3625    if !bytes.iter().all(u8::is_ascii_digit) {
3626        return None;
3627    }
3628    if bytes[0] == b'0' && bytes.len() != 1 {
3629        return None;
3630    }
3631    let value: u32 = key.parse().ok()?;
3632    // `2^32 - 1` is reserved for the array length, so it is not an index.
3633    (value < u32::MAX).then_some(value)
3634}
3635
3636impl Trace for JsObject {
3637    fn trace(&self, tracer: &mut Tracer) {
3638        self.data.borrow().trace(tracer);
3639    }
3640
3641    /// Everything this object holds that is not its own box: element slots, the property
3642    /// table, `Map`/`Set` entries, an `ArrayBuffer`'s bytes.
3643    ///
3644    /// Counted by **capacity**, not length, because that is what the allocator actually
3645    /// holds — a 1000-element array with a 1024-slot vector costs 1024 slots, and reporting
3646    /// 1000 would make the limit wrong by whatever the vectors over-allocate (up to 2×).
3647    ///
3648    /// Growth in place is reported to the heap as it happens (see `JsObject::array_push`
3649    /// and friends) and this same number is subtracted when the object is freed, which is
3650    /// why the two have to agree.
3651    ///
3652    /// `try_borrow` because this can be called from inside the collector, where a mutation
3653    /// elsewhere in the engine may hold the borrow; a container that is being mutated at
3654    /// this instant is a container we cannot measure, and answering 0 for it is better than
3655    /// panicking mid-allocation.
3656    fn external_bytes(&self) -> usize {
3657        let Ok(data) = self.data.try_borrow() else {
3658            return 0;
3659        };
3660        // The property table is *not* counted. Every payload reported here is subtracted
3661        // when the box is freed, so a payload that nothing reports on growth would be
3662        // taken away twice — that abort is exactly what this comment replaced
3663        // (`attempt to subtract with overflow` in `Heap::deregister`). Property growth is
3664        // bounded by distinct keys, each of which is at least one string box that *is*
3665        // counted, so leaving the table out costs a constant factor rather than the limit.
3666        let mut total = 0;
3667        match &data.kind {
3668            ObjectKind::Array { elements, .. } => {
3669                total += elements.capacity() * std::mem::size_of::<Value>();
3670            }
3671            ObjectKind::Collection { entries, .. } => {
3672                total += entries.capacity() * std::mem::size_of::<Option<(Value, Value)>>();
3673            }
3674            ObjectKind::ArrayBuffer(storage) => {
3675                if let Ok(storage) = storage.try_borrow() {
3676                    total += storage.bytes.capacity();
3677                }
3678            }
3679            _ => {}
3680        }
3681        total
3682    }
3683}
3684
3685/// Drop the property-table entries whose key is an array index at or above `length`.
3686///
3687/// An index past the dense limit is kept as an ordinary property, so shrinking `length` has
3688/// to look there as well as in the element vector — the spec deletes every index at or above
3689/// the new length, wherever it was stored.
3690fn drop_sparse_indices(props: &mut Vec<(PropertyKey, Property)>, length: usize) {
3691    props.retain(|(key, _)| match key.as_str().and_then(array_index) {
3692        Some(index) => (index as usize) < length,
3693        None => true,
3694    });
3695}
3696
3697/// Tell the heap that a container's payload changed in place.
3698///
3699/// Reported as a **capacity** delta, the same quantity [`Trace::external_bytes`] reports, so
3700/// that the subtraction at free time takes back exactly what was added. Reporting length
3701/// instead would leave the vector's over-allocation — up to 2× — counted for ever.
3702fn charge_capacity<T>(heap: &js_gc::Heap, before: usize, after: usize) {
3703    if before == after {
3704        return;
3705    }
3706    let slot = std::mem::size_of::<T>() as isize;
3707    heap.adjust_payload((after as isize - before as isize) * slot);
3708}