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