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