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