Skip to main content

quickjs/
object.rs

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