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