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