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