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