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