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