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 pub bytes: Vec<u8>,
30 /// Whether `transfer()` has taken the bytes away.
31 pub detached: bool,
32}
33
34impl JsObject {
35 /// The storage of this object, when it is an `ArrayBuffer`.
36 pub fn array_buffer_storage(&self) -> Option<Rc<RefCell<BufferStorage>>> {
37 match &self.data.borrow().kind {
38 ObjectKind::ArrayBuffer(storage) => Some(storage.clone()),
39 _ => None,
40 }
41 }
42
43 /// Make this object an `ArrayBuffer` owning `storage`.
44 pub fn set_array_buffer(&self, storage: Rc<RefCell<BufferStorage>>) {
45 self.data.borrow_mut().kind = ObjectKind::ArrayBuffer(storage);
46 }
47
48 /// The entries of this object, when it is a `Map` or a `Set`.
49 pub fn collection_entries(&self) -> Option<Vec<(Value, Value)>> {
50 match &self.data.borrow().kind {
51 ObjectKind::Collection { entries, .. } => Some(entries.clone()),
52 _ => None,
53 }
54 }
55
56 /// Whether this object is a `Set` rather than a `Map`.
57 pub fn collection_is_set(&self) -> Option<bool> {
58 match &self.data.borrow().kind {
59 ObjectKind::Collection { is_set, .. } => Some(*is_set),
60 _ => None,
61 }
62 }
63
64 /// Make this object a `Map` or `Set` holding `entries`.
65 pub fn set_collection(&self, entries: Vec<(Value, Value)>, is_set: bool) {
66 self.data.borrow_mut().kind = ObjectKind::Collection { entries, is_set };
67 }
68
69 /// This object's weak entries, when it is a `WeakMap` or `WeakSet`.
70 ///
71 /// Expired handles are filtered out here rather than at the call site, so every reader
72 /// sees the same live view of the map and a dead key can never be observed.
73 pub fn weak_entries(&self) -> Option<Vec<(Value, Value)>> {
74 match &self.data.borrow().kind {
75 ObjectKind::WeakCollection { entries, .. } => Some(
76 entries
77 .iter()
78 .filter_map(|(key, value)| key.upgrade().map(|key| (key, value.clone())))
79 .collect(),
80 ),
81 _ => None,
82 }
83 }
84
85 /// Whether this object is a `WeakSet` rather than a `WeakMap`.
86 pub fn weak_is_set(&self) -> Option<bool> {
87 match &self.data.borrow().kind {
88 ObjectKind::WeakCollection { is_set, .. } => Some(*is_set),
89 _ => None,
90 }
91 }
92
93 /// Make this object a `WeakMap` or `WeakSet`, replacing any entries it had.
94 pub fn set_weak_collection(&self, entries: Vec<(WeakKey, Value)>, is_set: bool) {
95 self.data.borrow_mut().kind = ObjectKind::WeakCollection { entries, is_set };
96 }
97
98 /// Store one entry in a weak collection, replacing the value for a live equal key.
99 ///
100 /// The comparison is pointer identity: a weak key has to be an object, and two objects
101 /// are the same key exactly when they are the same object. Expired entries are dropped
102 /// on the way through, which keeps the vector from growing without bound in a program
103 /// that churns keys.
104 pub fn weak_set(&self, key: WeakKey, value: Value) {
105 let mut data = self.data.borrow_mut();
106 let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
107 return;
108 };
109 entries.retain(|(existing, _)| !existing.is_expired());
110 for (existing, slot) in entries.iter_mut() {
111 if existing.same(&key) {
112 *slot = value;
113 return;
114 }
115 }
116 entries.push((key, value));
117 }
118
119 /// Remove `key` from a weak collection, answering whether it was there.
120 pub fn weak_delete(&self, key: &Value) -> bool {
121 let mut data = self.data.borrow_mut();
122 let ObjectKind::WeakCollection { entries, .. } = &mut data.kind else {
123 return false;
124 };
125 let before = entries.len();
126 entries.retain(|(existing, _)| !existing.is_expired() && !existing.matches(key));
127 entries.len() != before
128 }
129
130 /// The target of a `WeakRef`, when this object is one.
131 pub fn weak_ref_target(&self) -> Option<WeakKey> {
132 match &self.data.borrow().kind {
133 ObjectKind::WeakRef { target } => Some(target.clone()),
134 _ => None,
135 }
136 }
137
138 /// Make this object a `WeakRef` to `target`.
139 pub fn set_weak_ref(&self, target: WeakKey) {
140 self.data.borrow_mut().kind = ObjectKind::WeakRef { target };
141 }
142
143 /// The registry state, when this object is a `FinalizationRegistry`.
144 pub fn finalization_state(&self) -> Option<Box<FinalizationState>> {
145 match &self.data.borrow().kind {
146 ObjectKind::Finalization(state) => Some(Box::new(FinalizationState {
147 registrations: state
148 .registrations
149 .iter()
150 .map(|registration| Registration {
151 target: registration.target.clone(),
152 held_value: registration.held_value.clone(),
153 token: registration.token.clone(),
154 })
155 .collect(),
156 cleanup: state.cleanup.clone(),
157 })),
158 _ => None,
159 }
160 }
161
162 /// Replace a registry's state.
163 pub fn set_finalization_state(&self, state: FinalizationState) {
164 self.data.borrow_mut().kind = ObjectKind::Finalization(Box::new(state));
165 }
166
167 /// `(buffer, element, offset, length)`, when this object is a typed-array view.
168 pub fn typed_array_parts(
169 &self,
170 ) -> Option<(
171 Gc<JsObject>,
172 crate::builtins::typedarray::ElementType,
173 usize,
174 usize,
175 )> {
176 match &self.data.borrow().kind {
177 ObjectKind::TypedArray {
178 buffer,
179 element,
180 offset,
181 length,
182 } => Some((buffer.clone(), *element, *offset, *length)),
183 _ => None,
184 }
185 }
186
187 /// Whether this callable is a native function rather than compiled JavaScript.
188 ///
189 /// `construct` uses it to decide who builds the instance: a native constructor creates
190 /// its own, after validating its arguments.
191 pub fn is_native_function(&self) -> bool {
192 matches!(
193 &self.data.borrow().kind,
194 ObjectKind::Function(Callable::Native { .. })
195 )
196 }
197
198 /// Whether this native constructor builds its own instance, so `new` must not pass one.
199 pub fn native_creates_own_instance(&self) -> bool {
200 matches!(
201 &self.data.borrow().kind,
202 ObjectKind::Function(Callable::Native {
203 own_instance: true,
204 ..
205 })
206 )
207 }
208
209 /// Make this object a `DataView` over `buffer`.
210 pub fn set_data_view(&self, buffer: Gc<JsObject>, offset: usize, length: usize) {
211 self.data.borrow_mut().kind = ObjectKind::DataView {
212 buffer,
213 offset,
214 length,
215 };
216 }
217
218 /// The `(buffer, offset, length)` of a `DataView`, or `None` when this is not one.
219 pub fn data_view_parts(&self) -> Option<(Gc<JsObject>, usize, usize)> {
220 match &self.data.borrow().kind {
221 ObjectKind::DataView {
222 buffer,
223 offset,
224 length,
225 } => Some((buffer.clone(), *offset, *length)),
226 _ => None,
227 }
228 }
229
230 /// Make this object a typed-array view of `length` elements.
231 pub fn set_typed_array(
232 &self,
233 buffer: Gc<JsObject>,
234 element: crate::builtins::typedarray::ElementType,
235 offset: usize,
236 length: usize,
237 ) {
238 self.data.borrow_mut().kind = ObjectKind::TypedArray {
239 buffer,
240 element,
241 offset,
242 length,
243 };
244 }
245
246 /// The element type, when this object is a typed-array view.
247 pub fn typed_array_element_type(&self) -> Option<crate::builtins::typedarray::ElementType> {
248 self.typed_array_parts().map(|(_, element, _, _)| element)
249 }
250
251 /// How many elements the view exposes, or `None` when this is not a view.
252 ///
253 /// A detached buffer reports `0`: the storage is gone, so there is nothing to index.
254 pub fn typed_array_length(&self) -> Option<usize> {
255 let (buffer, _, _, length) = self.typed_array_parts()?;
256 let storage = buffer.array_buffer_storage()?;
257 if storage.borrow().detached {
258 return Some(0);
259 }
260 Some(length)
261 }
262
263 /// Read one view element.
264 ///
265 /// Out-of-range and detached reads are `undefined` rather than an error, which is what
266 /// makes `a[999]` and a detached `a[0]` behave the way the language says.
267 pub fn typed_array_element(&self, index: usize) -> Option<Value> {
268 let (buffer, element, offset, length) = self.typed_array_parts()?;
269 let storage = buffer.array_buffer_storage()?;
270 let storage = storage.borrow();
271 if storage.detached || index >= length {
272 return Some(Value::Undefined);
273 }
274 // The buffer's own handle is where the heap comes from, so a BigInt element can be
275 // allocated without every caller having to thread one through.
276 Some(element.read(
277 buffer.heap(),
278 &storage.bytes,
279 offset + index * element.size(),
280 ))
281 }
282
283 /// Store one view element, applying the type's wrap or clamp.
284 ///
285 /// `Some(Ok(()))` stored, `Some(Err(()))` refused the *value* — a Number into a BigInt
286 /// view, which the caller turns into a `TypeError` — and `None` when this is not a
287 /// view at all or the index is out of range, which is a silent no-op.
288 pub fn typed_array_set(&self, index: usize, value: Value) -> Option<Result<(), &'static str>> {
289 let (buffer, element, offset, length) = self.typed_array_parts()?;
290 if index >= length {
291 return Some(Ok(()));
292 }
293 let storage = buffer.array_buffer_storage()?;
294 let mut storage = storage.borrow_mut();
295 if storage.detached {
296 return Some(Ok(()));
297 }
298 let stored = element.write(&mut storage.bytes, offset + index * element.size(), &value);
299 Some(stored)
300 }
301}
302
303/// A property of an object.
304#[derive(Clone, Default)]
305pub struct Property {
306 /// The value of a data property.
307 pub value: Option<Value>,
308 /// The getter of an accessor property.
309 pub getter: Option<Value>,
310 /// The setter of an accessor property.
311 pub setter: Option<Value>,
312 /// Whether the value can be replaced.
313 pub writable: bool,
314 /// Whether `for`/`Object.keys` sees the property.
315 pub enumerable: bool,
316 /// Whether the property can be deleted or redefined.
317 pub configurable: bool,
318}
319
320impl Property {
321 /// A writable, enumerable, configurable data property.
322 ///
323 /// This is what a plain assignment or an object literal creates, and the
324 /// attributes only differ for built-ins and `Object.defineProperty`.
325 pub fn data(value: Value) -> Property {
326 Property {
327 value: Some(value),
328 writable: true,
329 enumerable: true,
330 configurable: true,
331 ..Property::default()
332 }
333 }
334
335 /// A data property with explicit attributes.
336 ///
337 /// `configurable` is derived from `writable`, because that derivation is right for the
338 /// case this is overwhelmingly used for: a built-in method or constructor, which the
339 /// spec gives `{writable: true, enumerable: false, configurable: true}`.
340 ///
341 /// It is *not* right for the two other shapes the spec uses on functions, and both were
342 /// wrong here for a long time — `name`/`length` are `{writable: false, enumerable:
343 /// false, configurable: true}`, and a function's `prototype` is `{writable: true,
344 /// enumerable: false, configurable: false}`. Use [`Property::name_or_length`] and
345 /// [`Property::prototype_of`] for those rather than spelling them out, so that the two
346 /// exceptions to the rule stay in one place.
347 pub fn with_attributes(value: Value, writable: bool, enumerable: bool) -> Property {
348 Property {
349 value: Some(value),
350 writable,
351 enumerable,
352 configurable: writable,
353 ..Property::default()
354 }
355 }
356
357 /// A `name` or `length` property: writable and enumerable are false, configurable true.
358 ///
359 /// Every function has both, and the spec makes them configurable so that a definition
360 /// can replace them (`Object.defineProperty(f, "length", {value: 0})`, and
361 /// `Function.prototype.bind` renaming its result). With them non-configurable, those
362 /// definitions throw and about five hundred conformance tests fail.
363 pub fn name_or_length(value: Value) -> Property {
364 Property {
365 value: Some(value),
366 writable: false,
367 enumerable: false,
368 configurable: true,
369 ..Property::default()
370 }
371 }
372
373 /// A function's `prototype`: not configurable, and writable only for user functions.
374 ///
375 /// A built-in constructor's `prototype` is read-only — assigning to `Object.prototype`
376 /// must not stick — while a user function's is writable, since that is how
377 /// `Ctor.prototype.method = f` sets up inheritance. Neither is configurable, so
378 /// `delete Ctor.prototype` fails in both cases.
379 pub fn prototype_of(value: Value, writable: bool) -> Property {
380 Property {
381 value: Some(value),
382 writable,
383 enumerable: false,
384 configurable: false,
385 ..Property::default()
386 }
387 }
388
389 /// An accessor property.
390 /// An accessor property with explicit `enumerable`/`configurable` flags, which is
391 /// what `Symbol.prototype.description` needs: it is enumerable: false in the spec.
392 pub fn accessor_with(
393 getter: Option<Value>,
394 setter: Option<Value>,
395 enumerable: bool,
396 ) -> Property {
397 Property {
398 getter,
399 setter,
400 enumerable,
401 configurable: true,
402 ..Property::default()
403 }
404 }
405
406 /// An accessor property with the default `enumerable`/`configurable` flags.
407 pub fn accessor(getter: Option<Value>, setter: Option<Value>) -> Property {
408 Property {
409 getter,
410 setter,
411 enumerable: true,
412 configurable: true,
413 ..Property::default()
414 }
415 }
416
417 /// Whether this is an accessor rather than a data property.
418 pub fn is_accessor(&self) -> bool {
419 self.getter.is_some() || self.setter.is_some()
420 }
421}
422
423impl Trace for Property {
424 fn trace(&self, tracer: &mut Tracer) {
425 self.value.trace(tracer);
426 self.getter.trace(tracer);
427 self.setter.trace(tracer);
428 }
429}
430
431/// A host function: a native function plus the state it captured.
432///
433/// `NativeFn` is a bare `fn` pointer, so a builtin that needs state (an open-file table,
434/// a timer queue, a sink to write to) has nowhere to put it. `HostFn` boxes the closure
435/// instead, and [`Callable::Host`] keeps it on the function object.
436///
437/// # Why the closure must not capture a `Gc`
438///
439/// The collector finds live objects by walking the object graph through [`Trace`]. A
440/// closure is opaque Rust, so nothing inside it is walked: a `Gc<JsObject>` captured here
441/// would be invisible to the collector and could be freed while the closure still holds
442/// it — a use-after-free.
443///
444/// Keep Rust-side state (file descriptors, timer ids, deadlines) in the closure, and keep
445/// every JavaScript value somewhere the collector already scans: a property of a real JS
446/// object, or a table hanging off [`Interp`]. `os.setTimeout(fn, ms)` stores `fn` in the
447/// interpreter's timer table for exactly this reason.
448///
449/// [`Trace`]: js_gc::Trace
450/// [`Interp`]: crate::interp::Interp
451pub type HostFn = Box<
452 dyn for<'i> FnMut(
453 &mut crate::interp::Interp<'i>,
454 Value,
455 &[Value],
456 ) -> crate::interp::JsResult<Value>,
457>;
458
459/// A native (Rust) function reachable from JavaScript.
460///
461/// It receives the interpreter so a builtin can allocate (which needs the heap),
462/// call back into JavaScript (which needs the frame stack) and raise exceptions.
463pub type NativeFn =
464 fn(&mut crate::interp::Interp<'_>, Value, &[Value]) -> crate::interp::JsResult<Value>;
465
466/// The body of a callable object.
467pub enum Callable {
468 /// A function compiled from JavaScript source.
469 Bytecode {
470 /// The bytecode and slot mapping.
471 code: Gc<CompiledCode>,
472 /// The captured environment.
473 env: Gc<ClosureEnv>,
474 },
475 /// A function produced by `Function.prototype.bind`.
476 ///
477 /// This is a variant rather than a native function carrying the state in
478 /// properties because the state is not observable: `bind` has to remember its
479 /// target, `this` and leading arguments, and a native trampoline cannot capture
480 /// them.
481 Bound {
482 /// The function being called.
483 target: Value,
484 /// The `this` every call uses.
485 this: Value,
486 /// Arguments prepended to every call's own.
487 args: Vec<Value>,
488 },
489 /// A built-in implemented in Rust.
490 ///
491 /// The `name` and `length` a script observes are ordinary properties on the
492 /// function object, not fields here: they are writable (`f.name = "x"` works)
493 /// and would otherwise be two sources of truth.
494 Native {
495 /// The implementation.
496 func: NativeFn,
497 /// Whether this constructor builds its own instance instead of being handed one.
498 ///
499 /// The spec has a constructor validate its arguments *before*
500 /// `OrdinaryCreateFromConstructor` reads `new.target.prototype`, and only the ones
501 /// with real validation need to: `new Promise(nonCallable)` and `new DataView(…)`
502 /// must refuse the argument before a throwing `prototype` getter can run. The rest
503 /// keep the simpler shape where `new` has already made the object.
504 own_instance: bool,
505 },
506 /// A host function: a native closure that carries its own state.
507 ///
508 /// Behind an `Rc<RefCell<…>>` because the closure has to be *called* with
509 /// `&mut Interp`, and the call site would otherwise still be holding a borrow of this
510 /// object's data — the closure itself may reach the same object. Cloning the `Rc` out
511 /// and dropping the borrow first is what keeps that from panicking.
512 Host {
513 /// The body, with whatever it captured.
514 func: std::rc::Rc<std::cell::RefCell<HostFn>>,
515 /// Whether this constructor builds its own instance; see [`Callable::Native`].
516 own_instance: bool,
517 },
518 /// The `revoke` function `Proxy.revocable` hands back.
519 ///
520 /// It is a variant rather than a `Native` with the slots in a property because a
521 /// `NativeFn` is a plain function pointer: it cannot capture, and the slots are
522 /// precisely what this function exists to hold. Keeping them here also means the
523 /// collector sees them, so a proxy stays alive while only its `revoke` is reachable.
524 Revoker(crate::object::ProxyRef),
525 /// The `resolve` a `Promise` executor receives.
526 ///
527 /// Like [`Callable::Revoker`], this cannot be a plain `Native` with the state in a
528 /// property: a `NativeFn` is a function pointer and cannot capture, and the promise
529 /// it settles is exactly what it has to remember. Both are one-shot per §27.2.1.3.1 —
530 /// the second call is a no-op rather than a second settlement.
531 ///
532 /// The promise object is held directly rather than the state behind its `Rc`, because
533 /// settling has to run *that object's* reactions.
534 PromiseResolve(Gc<JsObject>),
535 /// The `reject` half of that pair.
536 PromiseReject(Gc<JsObject>),
537 /// One of the two continuations an `await` parks on.
538 ///
539 /// Reached through the ordinary reaction machinery, which is why it has to be a
540 /// callable object rather than a queue entry: `await x` is specified as
541 /// `PerformPromiseThen(x, resume, rethrow)`.
542 AwaitResume {
543 /// The body to continue.
544 coroutine: Gc<JsObject>,
545 /// The promise the async function returned.
546 promise: Gc<JsObject>,
547 /// Whether this continuation delivers the value or raises the reason.
548 kind: crate::interp::ResumeKind,
549 },
550 /// One element of `Promise.all`/`allSettled`/`any`/`race` settling.
551 CombinatorSettle {
552 /// The hidden object holding the results array, the remaining count and the
553 /// combinator's own resolve/reject pair.
554 state: Gc<JsObject>,
555 /// Which element this callback belongs to.
556 index: usize,
557 /// Whether the element fulfilled or rejected.
558 fulfilled: bool,
559 },
560 /// Settle a promise with a fixed outcome when called.
561 ///
562 /// `finally` needs "wait for this promise, then re-deliver that value", and a
563 /// `NativeFn` cannot carry the value to re-deliver.
564 SettlePromise {
565 /// The promise to settle.
566 promise: Gc<JsObject>,
567 /// The outcome to settle it with, which is the *original* one.
568 value: Value,
569 /// Whether that outcome is a rejection.
570 rejected: bool,
571 },
572 /// One continuation of an `await` inside an async generator.
573 GeneratorResume {
574 /// The async generator to continue.
575 generator: Gc<JsObject>,
576 /// The promise the pending `next`/`return`/`throw` returned.
577 promise: Gc<JsObject>,
578 /// Whether this delivers the value or raises the reason.
579 kind: crate::interp::ResumeKind,
580 },
581 /// Reads a module namespace's binding out of the cell it is stored in.
582 ///
583 /// A namespace object is an ordinary object whose exports are getters, so a getter
584 /// is what `ns.x` calls — and it has to be a callable object carrying the cell, for
585 /// the same reason `PromiseResolve` carries its promise.
586 ModuleBinding {
587 /// The binding's cell, shared with the exporting module.
588 cell: Gc<Cell>,
589 },
590 /// Answer a pending async-generator method with `{value, done: false}`.
591 ///
592 /// `yield v` in an async generator awaits `v` first, so the value can arrive after
593 /// the body has already parked; this is what turns it into the result object.
594 YieldResult {
595 /// The promise the pending method returned.
596 promise: Gc<JsObject>,
597 /// Whether this answers a completed generator rather than a `yield`.
598 done: bool,
599 },
600 /// One step of `AsyncDisposableStack.disposeAsync`.
601 ///
602 /// The remaining resources ride along as a JS array so the collector can see them:
603 /// `disposeAsync` awaits each disposer in turn, which means the list has to survive
604 /// across microtasks rather than living on the Rust stack.
605 DisposeStep {
606 /// Pairs of `[resource, disposeMethod]`, consumed from the end.
607 remaining: Gc<JsObject>,
608 /// The promise `disposeAsync` returned.
609 promise: Gc<JsObject>,
610 /// The `SuppressedError` chain built so far, or `Uninitialized` for none.
611 error: Value,
612 /// Whether this continuation is being called with a rejection reason.
613 rejected: bool,
614 },
615 /// One of the two shims `Promise.prototype.finally` installs.
616 FinallyShim {
617 /// The script's callback, or `None` to pass the outcome straight through.
618 callback: Option<Value>,
619 /// Whether this is the fulfil side.
620 fulfilled: bool,
621 },
622}
623
624impl Trace for Callable {
625 fn trace(&self, tracer: &mut Tracer) {
626 match self {
627 Callable::Bytecode { code, env } => {
628 tracer.visit(code);
629 tracer.visit(env);
630 }
631 Callable::Bound { target, this, args } => {
632 target.trace(tracer);
633 this.trace(tracer);
634 for argument in args {
635 argument.trace(tracer);
636 }
637 }
638 Callable::Native { .. } => {}
639 // Nothing to trace, by construction: the closure must not hold a `Gc`. See
640 // `HostFn`'s documentation.
641 Callable::Host { .. } => {}
642 Callable::Revoker(slots) => slots.borrow().trace(tracer),
643 Callable::PromiseResolve(promise) | Callable::PromiseReject(promise) => {
644 tracer.visit(promise)
645 }
646 Callable::AwaitResume {
647 coroutine, promise, ..
648 } => {
649 tracer.visit(coroutine);
650 tracer.visit(promise);
651 }
652 Callable::CombinatorSettle { state, .. } => tracer.visit(state),
653 Callable::GeneratorResume {
654 generator, promise, ..
655 } => {
656 tracer.visit(generator);
657 tracer.visit(promise);
658 }
659 Callable::YieldResult { promise, .. } => tracer.visit(promise),
660 Callable::ModuleBinding { cell } => tracer.visit(cell),
661 Callable::DisposeStep {
662 remaining,
663 promise,
664 error,
665 ..
666 } => {
667 tracer.visit(remaining);
668 tracer.visit(promise);
669 error.trace(tracer);
670 }
671 Callable::SettlePromise { promise, value, .. } => {
672 tracer.visit(promise);
673 value.trace(tracer);
674 }
675 Callable::FinallyShim { callback, .. } => {
676 if let Some(callback) = callback {
677 callback.trace(tracer);
678 }
679 }
680 }
681 }
682}
683
684/// The bytecode of one function, plus the slot-to-cell mapping.
685///
686/// This is a separate GC object from the closure so that a frame can hold a handle
687/// to it and read it while the function object itself is free to be borrowed.
688/// Holding a `RefCell` borrow across a call would deadlock the moment a function
689/// referred to itself.
690pub struct CompiledCode {
691 /// The resolved bytecode.
692 pub code: CompiledFunction,
693 /// For each argument slot, the index of its reference cell, or `-1` when the
694 /// slot holds its value directly.
695 ///
696 /// A captured binding lives in a cell so that closures outlive the frame; every
697 /// other slot is a plain value. Precomputing the mapping keeps the hot
698 /// `get_arg`/`put_arg` paths to one array read instead of a lookup.
699 pub arg_cell: Vec<i32>,
700 /// The same, for local slots.
701 pub loc_cell: Vec<i32>,
702}
703
704impl CompiledCode {
705 /// Build the slot-to-cell mapping for `code`.
706 ///
707 /// Cells are numbered the way [`CompiledFunction::var_ref_count`] counts them:
708 /// the captured arguments first, then the captured locals, each in slot order.
709 pub fn new(code: CompiledFunction) -> CompiledCode {
710 let mut next = 0i32;
711 let mut arg_cell = vec![-1; code.args.len()];
712 for (slot, arg) in code.args.iter().enumerate() {
713 if arg.is_captured {
714 arg_cell[slot] = next;
715 next += 1;
716 }
717 }
718 let mut loc_cell = vec![-1; code.vars.len()];
719 for (slot, local) in code.vars.iter().enumerate() {
720 if local.is_captured {
721 loc_cell[slot] = next;
722 next += 1;
723 }
724 }
725 CompiledCode {
726 code,
727 arg_cell,
728 loc_cell,
729 }
730 }
731}
732
733impl Trace for CompiledCode {
734 fn trace(&self, _tracer: &mut Tracer) {}
735}
736
737/// The reference cells a closure captured from enclosing scopes.
738pub struct ClosureEnv {
739 /// Indexed the way the bytecode's closure-variable table indexes them.
740 pub cells: Vec<Gc<Cell>>,
741 /// The `eval` scope this closure was created in, if any.
742 ///
743 /// A function built by `eval` has to keep seeing the caller's bindings after the
744 /// eval has returned — `for (let i …) eval("push(() => i)")` collects closures that
745 /// read `i` later. Those bindings live in the *caller's* frame, which is long gone
746 /// by then, so the environment carries them by name instead. Ordinary closures leave
747 /// this `None` and resolve globals exactly as before.
748 pub eval_scope: Option<Gc<EvalScope>>,
749 /// Variables a direct `eval` declared in the frame this closure was created in, and
750 /// how much of that frame it may see.
751 ///
752 /// A closure is created at a *place* in a function, and a direct `eval` can add
753 /// variables after that point. Those variables belong to the variable environment
754 /// that was current at the closure's creation — the parameter list or the body — which
755 /// is what `local_phase` records.
756 pub local_vars: Option<Gc<LocalVars>>,
757 /// `0` for a closure created in a parameter list, `1` for one in a body. A parameter
758 /// list's closure must not see variables a later `eval` in the body declared:
759 /// `function f(a, p = () => c) { eval("var c = 1") }` has `p()` resolve `c` outside
760 /// the function entirely.
761 pub local_phase: u8,
762}
763
764/// Variables a direct `eval` declared in one function call.
765///
766/// A sloppy `eval` declares its `var`s in the caller's variable environment, not on the
767/// global object: `function f() { eval("var x = 1") } f(); x` is a `ReferenceError`, and
768/// two calls to `f` get two `x`s. Each entry therefore records the phase it was declared
769/// in, so a lookup from the parameter list cannot see a body declaration.
770pub struct LocalVars {
771 names: std::cell::RefCell<Vec<(String, Gc<Cell>, u8)>>,
772}
773
774impl Default for LocalVars {
775 fn default() -> LocalVars {
776 LocalVars::new()
777 }
778}
779
780impl LocalVars {
781 /// An empty set.
782 pub fn new() -> LocalVars {
783 LocalVars {
784 names: std::cell::RefCell::new(Vec::new()),
785 }
786 }
787
788 /// The cell `name` resolves to, when it was declared in `phase` or earlier.
789 pub fn get(&self, name: &str, phase: u8) -> Option<Gc<Cell>> {
790 self.names
791 .borrow()
792 .iter()
793 .find(|(bound, _, at)| bound == name && *at <= phase)
794 .map(|(_, cell, _)| cell.clone())
795 }
796
797 /// The cell for `name`, declaring it if this is the first time.
798 pub fn declare(&self, name: &str, phase: u8, cell: Gc<Cell>) -> Gc<Cell> {
799 let mut names = self.names.borrow_mut();
800 if let Some((_, cell, _)) = names.iter().find(|(bound, _, _)| bound == name) {
801 return cell.clone();
802 }
803 names.push((name.to_string(), cell.clone(), phase));
804 cell
805 }
806
807 /// Whether `name` has been declared at all.
808 pub fn contains(&self, name: &str) -> bool {
809 self.names
810 .borrow()
811 .iter()
812 .any(|(bound, _, _)| bound == name)
813 }
814}
815
816impl Trace for LocalVars {
817 fn trace(&self, tracer: &mut Tracer) {
818 for (_, cell, _) in self.names.borrow().iter() {
819 tracer.visit(cell);
820 }
821 }
822}
823
824impl Trace for ClosureEnv {
825 fn trace(&self, tracer: &mut Tracer) {
826 for cell in &self.cells {
827 tracer.visit(cell);
828 }
829 if let Some(scope) = &self.eval_scope {
830 tracer.visit(scope);
831 }
832 if let Some(local_vars) = &self.local_vars {
833 tracer.visit(local_vars);
834 }
835 }
836}
837
838/// The bindings a direct `eval` made visible, as name → cell.
839///
840/// Only bindings that already live in a cell appear here, because sharing their
841/// identity is the point: a closure created by the eval must observe later writes to
842/// the same variable, and a copy would not. The compiler puts every binding of a
843/// function that contains a direct `eval` into a cell, so in practice that is all of
844/// them.
845pub struct EvalScope {
846 /// In lookup order: the innermost binding for a name first.
847 pub names: Vec<(String, Gc<Cell>)>,
848}
849
850impl EvalScope {
851 /// The cell `name` resolves to, if this scope binds it.
852 pub fn get(&self, name: &str) -> Option<&Gc<Cell>> {
853 self.names
854 .iter()
855 .find(|(bound, _)| bound == name)
856 .map(|(_, cell)| cell)
857 }
858}
859
860impl Trace for EvalScope {
861 fn trace(&self, tracer: &mut Tracer) {
862 for (_, cell) in &self.names {
863 tracer.visit(cell);
864 }
865 }
866}
867
868/// What kind of object this is.
869pub enum ObjectKind {
870 /// An ordinary object: only its property table.
871 Ordinary,
872 /// An array: a dense element vector plus a property table for everything else.
873 ///
874 /// `length` is stored **separately** rather than derived from `elements.len()`, so a
875 /// sparse array costs nothing to poke at a far index: the reference answers
876 /// `a = []; a.length = 4294967295` instantly, while deriving the length from a dense
877 /// vector meant allocating one `Value` per slot — 62 GB and 24 seconds for that one
878 /// statement. An index past the vector is a hole, and `length` alone records how many
879 /// holes there are at the end.
880 ///
881 /// Invariant: `elements.len() <= length`. A truncation drops both, so the reverse
882 /// (`length < elements.len()`) never holds.
883 Array {
884 /// The dense prefix: everything before the first trailing hole.
885 elements: Vec<Value>,
886 /// The logical length, which may exceed `elements.len()`.
887 length: usize,
888 },
889 /// A function or a class constructor.
890 Function(Callable),
891 /// A regular expression: the compiled pattern, plus `lastIndex` as a property.
892 RegExp(crate::builtins::regexp::RegExpData),
893 /// A `DisposableStack` or `AsyncDisposableStack`: the resources it holds.
894 DisposableStack(crate::builtins::disposable::StackState),
895 /// An `ArrayBuffer`: a byte range that typed-array views share.
896 ///
897 /// The bytes sit behind an `Rc<RefCell<…>>` rather than in the object so that every view
898 /// of the buffer sees the same storage; the *views* hold the `Gc<JsObject>` of this
899 /// buffer, which is what keeps it alive and what the collector traces.
900 ArrayBuffer(std::rc::Rc<std::cell::RefCell<BufferStorage>>),
901 /// A `Map` or a `Set`: insertion-ordered entries with `SameValueZero` key equality.
902 ///
903 /// One variant for both, because a `Set` is exactly a `Map` whose value is unused — the
904 /// difference is a flag, and `is_set` is what makes `entries` yield `[v, v]` pairs.
905 Collection {
906 /// The entries, in insertion order.
907 entries: Vec<(Value, Value)>,
908 /// Whether this is a `Set` rather than a `Map`.
909 is_set: bool,
910 },
911 /// A `DataView`: a byte-oriented window onto an `ArrayBuffer`.
912 ///
913 /// Separate from `TypedArray` because the two index differently: a typed array has an
914 /// element type and counts *elements*, while a `DataView` is untyped and every accessor
915 /// names its own width and byte offset. Sharing one variant would mean carrying an
916 /// element type that is always "bytes" and a length that means something else.
917 DataView {
918 /// The buffer whose bytes this view reads.
919 buffer: Gc<JsObject>,
920 /// Byte offset of the view's first byte.
921 offset: usize,
922 /// How many bytes the view exposes.
923 length: usize,
924 },
925 /// A typed-array view: a window onto an `ArrayBuffer`.
926 TypedArray {
927 /// The buffer whose bytes this view reads.
928 buffer: Gc<JsObject>,
929 /// What one element is.
930 element: crate::builtins::typedarray::ElementType,
931 /// Byte offset of element zero.
932 offset: usize,
933 /// How many elements the view exposes.
934 length: usize,
935 },
936 /// A generator object: a detached frame plus how far it got.
937 ///
938 /// The frame lives here rather than in the interpreter because a suspended generator
939 /// has to keep its locals and operand stack alive for as long as the script can reach
940 /// the generator object — and the collector has to see them, which it only does for
941 /// things hanging off a `Gc`.
942 Generator(Box<crate::interp::GeneratorState>),
943 /// A `Proxy`: a stand-in that forwards every internal method to a target through a
944 /// handler's traps.
945 ///
946 /// The state sits behind an `Rc` because `Proxy.revocable` hands the script a
947 /// `revoke` function that has to reach *this* proxy's two slots later, from a call
948 /// site that has no pointer to the object. Revoking clears them, which also drops
949 /// the collector's references to the target and the handler.
950 Proxy(ProxyRef),
951 /// A `Promise`.
952 ///
953 /// The state sits behind an `Rc` for the same reason a proxy's slots do: the
954 /// `resolve`/`reject` pair handed to an executor has to settle *this* promise later,
955 /// and those are function objects with no pointer back to it otherwise.
956 Promise(PromiseRef),
957 /// A `WeakMap` or `WeakSet`: like a collection, but the *keys* are weak.
958 ///
959 /// The distinction lives entirely in [`Trace`]: a `Collection` traces its keys, a
960 /// `WeakCollection` does not. An entry keyed by an otherwise-unreachable object is
961 /// therefore reclaimed together with that object instead of keeping it alive, and the
962 /// entry simply stops being found — `upgrade` fails and a liveness sweep drops the
963 /// pair. That is the "ephemeron" behaviour `WeakMap` promises, and it falls out of
964 /// reference counting rather than needing a second collection pass.
965 WeakCollection {
966 /// The entries, in insertion order, keyed by a non-owning handle.
967 entries: Vec<(WeakKey, Value)>,
968 /// Whether this is a `WeakSet` rather than a `WeakMap`.
969 is_set: bool,
970 },
971 /// A `WeakRef`: one non-owning handle to a target object.
972 WeakRef {
973 /// The target. Once `upgrade` fails the reference is dead for good, because a box
974 /// whose strong count reached zero never comes back.
975 ///
976 /// A `WeakKey` rather than a `WeakGc<JsObject>`, because a symbol is a valid target
977 /// too — `new WeakRef(Symbol())` works and `deref` has to answer it back.
978 target: WeakKey,
979 },
980 /// A `FinalizationRegistry`: the cleanup callback and its live registrations.
981 Finalization(Box<FinalizationState>),
982}
983
984/// The mutable half of a `FinalizationRegistry`.
985///
986/// Boxed inside the [`ObjectKind`] variant because it holds a vector plus a value, and every
987/// `ObjectKind` is stored inline in the object header — an unboxed field this wide would
988/// make *every* object in the realm that much larger.
989pub struct FinalizationState {
990 /// One entry per successful `register` call.
991 pub registrations: Vec<Registration>,
992 /// The cleanup callback, validated as callable when the registry was built.
993 pub cleanup: Value,
994}
995
996/// A key that can be held weakly: an object, or a symbol.
997///
998/// Both are heap allocations in this engine (`Value::Symbol` carries a `Gc<JsSymbol>`), so a
999/// `WeakGc` holds either one just as well. Symbols became valid keys with the
1000/// `symbols-as-weakmap-keys` proposal, which is what test262 already tests.
1001#[derive(Clone)]
1002pub enum WeakKey {
1003 /// An object target.
1004 Object(WeakGc<JsObject>),
1005 /// A symbol target.
1006 Symbol(WeakGc<JsSymbol>),
1007}
1008
1009impl WeakKey {
1010 /// Whether the allocation behind this key has been released.
1011 pub fn is_expired(&self) -> bool {
1012 match self {
1013 WeakKey::Object(handle) => handle.is_expired(),
1014 WeakKey::Symbol(handle) => handle.is_expired(),
1015 }
1016 }
1017
1018 /// Whether two weak keys are the same allocation.
1019 pub fn same(&self, other: &WeakKey) -> bool {
1020 match (self, other) {
1021 (WeakKey::Object(left), WeakKey::Object(right)) => left.ptr_eq(right),
1022 (WeakKey::Symbol(left), WeakKey::Symbol(right)) => left.ptr_eq(right),
1023 _ => false,
1024 }
1025 }
1026
1027 /// Whether this key is the same allocation as `value`, without upgrading it.
1028 ///
1029 /// Upgrading would resurrect the key, which for a `WeakMap` lookup is exactly what must
1030 /// not happen — a dead key has to compare equal to nothing.
1031 pub fn matches(&self, value: &Value) -> bool {
1032 match (self, value) {
1033 (WeakKey::Object(handle), Value::Object(object)) => object.upgrades_to(handle),
1034 (WeakKey::Symbol(handle), Value::Symbol(symbol)) => symbol.upgrades_to(handle),
1035 _ => false,
1036 }
1037 }
1038
1039 /// The key as a strong value, when it is still alive.
1040 pub fn upgrade(&self) -> Option<Value> {
1041 match self {
1042 WeakKey::Object(handle) => handle.upgrade().map(Value::Object),
1043 WeakKey::Symbol(handle) => handle.upgrade().map(Value::Symbol),
1044 }
1045 }
1046}
1047
1048impl Trace for WeakKey {
1049 fn trace(&self, _tracer: &mut Tracer) {}
1050}
1051
1052/// Turn a script value into a weak key, if `CanBeHeldWeakly` allows it.
1053///
1054/// The rule is "an object, or a symbol that is not in the registry". A registered symbol —
1055/// one from `Symbol.for` — is refused on purpose: it lives in the realm's registry for the
1056/// lifetime of the realm, so it never dies, and a weak entry keyed by it could never be
1057/// observed to be collected. A plain `Symbol()` is a fresh allocation each time and so has
1058/// a lifetime worth observing.
1059pub fn weak_key(value: &Value) -> Option<WeakKey> {
1060 match value {
1061 Value::Object(object) => Some(WeakKey::Object(object.downgrade())),
1062 Value::Symbol(symbol) if symbol.registry_key().is_none() => {
1063 Some(WeakKey::Symbol(symbol.downgrade()))
1064 }
1065 _ => None,
1066 }
1067}
1068
1069/// One `FinalizationRegistry.register` call.
1070///
1071/// `token` is compared with `SameValue`, not `SameValueZero`, which is why it is kept as
1072/// the original `Value` rather than normalised into a key.
1073pub struct Registration {
1074 /// The handle whose death fires the callback.
1075 pub target: WeakKey,
1076 /// What the callback receives: the script's held value, kept alive until it fires.
1077 pub held_value: Value,
1078 /// The cancellation token, if one was given.
1079 pub token: Option<Value>,
1080}
1081
1082/// The two slots of a proxy, shared with its `revoke` function.
1083///
1084/// `None` in both slots means revoked: every operation then throws a `TypeError`, and
1085/// the target and handler are no longer reachable — which is the whole point of
1086/// `Proxy.revocable`.
1087#[derive(Default)]
1088pub struct ProxyState {
1089 /// The object the traps receive, or `None` once revoked.
1090 pub target: Option<Gc<JsObject>>,
1091 /// The trap table, or `None` once revoked.
1092 pub handler: Option<Value>,
1093 /// Whether this proxy has a `[[Call]]`, decided once when it is created.
1094 ///
1095 /// Revoking drops the target but does not take `[[Call]]` away, so this cannot be
1096 /// re-derived from `target` being `Some`: `typeof p.proxy` has to stay `"function"`
1097 /// after `Proxy.revocable(function(){}, {}).revoke()`, and the reference agrees.
1098 pub callable: bool,
1099 /// Whether this proxy has a `[[Construct]]`, decided once when it is created.
1100 ///
1101 /// Same reasoning as [`ProxyState::callable`], and the two are genuinely independent:
1102 /// `Proxy.revocable(function(){}, {})` is both callable and constructible, while a
1103 /// proxy over an arrow function is callable and not constructible.
1104 pub constructible: bool,
1105}
1106
1107/// A `Promise`'s state, shared between the promise object and its resolve/reject
1108/// functions.
1109///
1110/// Behind an `Rc` for the same reason a proxy's slots are: the `resolve` and `reject`
1111/// functions handed to an executor have to settle *this* promise later, from a call site
1112/// that only has the function.
1113pub struct PromiseState {
1114 /// Pending, or the value it settled with.
1115 pub status: PromiseStatus,
1116 /// The `then` reactions waiting on it, in registration order.
1117 pub reactions: Vec<PromiseReaction>,
1118 /// Whether a rejection has been seen by a handler.
1119 ///
1120 /// A rejection that never is becomes an unhandled-rejection report, which the
1121 /// reference makes fatal at the end of the job queue.
1122 pub handled: bool,
1123}
1124
1125impl Default for PromiseState {
1126 fn default() -> Self {
1127 PromiseState {
1128 status: PromiseStatus::Pending,
1129 reactions: Vec::new(),
1130 handled: false,
1131 }
1132 }
1133}
1134
1135/// What a `Promise` combinator does when its elements settle.
1136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1137pub enum CombinatorKind {
1138 /// The first rejection wins, otherwise an array in input order.
1139 All,
1140 /// Never rejects; each entry is `{status, value}` or `{status, reason}`.
1141 AllSettled,
1142 /// The first fulfilment wins, otherwise an `AggregateError`.
1143 Any,
1144 /// Whichever element settles first.
1145 Race,
1146}
1147
1148/// Which of §27.2.1.2's three states a promise is in.
1149#[derive(Clone, Default)]
1150pub enum PromiseStatus {
1151 /// Neither settled: reactions queue up.
1152 #[default]
1153 Pending,
1154 /// Settled with a value, which no further settle may change.
1155 Fulfilled(Value),
1156 /// Settled with a reason.
1157 Rejected(Value),
1158}
1159
1160/// One `then` registration.
1161#[derive(Clone)]
1162pub struct PromiseReaction {
1163 /// Called with the value if the promise fulfils.
1164 pub on_fulfilled: Option<Value>,
1165 /// Called with the reason if it rejects.
1166 pub on_rejected: Option<Value>,
1167 /// The promise to settle with whatever the handler returns.
1168 pub promise: Gc<JsObject>,
1169}
1170
1171impl Trace for PromiseState {
1172 fn trace(&self, tracer: &mut Tracer) {
1173 match &self.status {
1174 PromiseStatus::Pending => {}
1175 PromiseStatus::Fulfilled(value) | PromiseStatus::Rejected(value) => value.trace(tracer),
1176 }
1177 for reaction in &self.reactions {
1178 if let Some(on_fulfilled) = &reaction.on_fulfilled {
1179 on_fulfilled.trace(tracer);
1180 }
1181 if let Some(on_rejected) = &reaction.on_rejected {
1182 on_rejected.trace(tracer);
1183 }
1184 tracer.visit(&reaction.promise);
1185 }
1186 }
1187}
1188
1189/// A promise's shareable state.
1190pub type PromiseRef = std::rc::Rc<std::cell::RefCell<PromiseState>>;
1191
1192/// A proxy's mutable state, shared between the proxy object and its `revoke`.
1193pub type ProxyRef = std::rc::Rc<std::cell::RefCell<ProxyState>>;
1194
1195impl Trace for ProxyState {
1196 fn trace(&self, tracer: &mut Tracer) {
1197 if let Some(target) = &self.target {
1198 tracer.visit(target);
1199 }
1200 if let Some(handler) = &self.handler {
1201 handler.trace(tracer);
1202 }
1203 }
1204}
1205
1206impl Trace for ObjectKind {
1207 fn trace(&self, tracer: &mut Tracer) {
1208 match self {
1209 // Nothing in a compiled pattern is a GC value: it holds characters and
1210 // integers only.
1211 ObjectKind::RegExp(_) => {}
1212 ObjectKind::DisposableStack(state) => state.trace(tracer),
1213 // A buffer's bytes are plain bytes and hold no GC values; a view keeps its
1214 // buffer alive through the `Gc` it carries.
1215 ObjectKind::ArrayBuffer(_) => {}
1216 ObjectKind::TypedArray { buffer, .. } | ObjectKind::DataView { buffer, .. } => {
1217 tracer.visit(buffer)
1218 }
1219 ObjectKind::Collection { entries, .. } => {
1220 for (key, value) in entries {
1221 key.trace(tracer);
1222 value.trace(tracer);
1223 }
1224 }
1225 ObjectKind::Ordinary => {}
1226 ObjectKind::Array { elements, .. } => {
1227 for element in elements {
1228 element.trace(tracer);
1229 }
1230 }
1231 ObjectKind::Function(callable) => callable.trace(tracer),
1232 ObjectKind::Generator(state) => state.trace(tracer),
1233 ObjectKind::Proxy(state) => state.borrow().trace(tracer),
1234 ObjectKind::Promise(state) => state.borrow().trace(tracer),
1235 // The *keys* are deliberately not visited: that absence is what makes the
1236 // collection weak, and it is also why a `WeakMap` cannot keep its key alive
1237 // through a cycle that only the map closes. The values are traced, so
1238 // `wm.set(k, v)` keeping `v` alive while `k` is reachable is the right half of
1239 // the ephemeron rule to get right here — the other half (dropping the pair once
1240 // the key dies) needs no liveness test, because `upgrade` on a dead key fails.
1241 ObjectKind::WeakCollection { entries, .. } => {
1242 for (_, value) in entries {
1243 value.trace(tracer);
1244 }
1245 }
1246 // A `WeakRef` owns nothing at all: that is its whole purpose.
1247 ObjectKind::WeakRef { .. } => {}
1248 // A registry keeps its held values and its callback alive — the held value has
1249 // to survive until the callback can run — but not the targets, which is the
1250 // handle type's job rather than the tracer's.
1251 ObjectKind::Finalization(state) => {
1252 state.cleanup.trace(tracer);
1253 for registration in &state.registrations {
1254 registration.held_value.trace(tracer);
1255 registration.token.trace(tracer);
1256 }
1257 }
1258 }
1259 }
1260}
1261
1262/// The mutable half of an object.
1263/// What a property is keyed by.
1264///
1265/// A string and a symbol are separate key spaces even when they look alike: `o["a"]`
1266/// and `o[Symbol("a")]` are two properties, and `o[Symbol("a")]` is not reachable by
1267/// any string. Symbols are also invisible to `for`/`Object.keys`/`JSON.stringify`,
1268/// which is the whole point of them, so the distinction has to survive into the
1269/// property table rather than being flattened into a name.
1270#[derive(Clone)]
1271pub enum PropertyKey {
1272 /// An ordinary string key, held as WTF-8 so a key containing an unpaired surrogate
1273 /// addresses one property rather than colliding with its `U+FFFD` replacement.
1274 String(crate::value::Wtf8),
1275 /// A symbol key.
1276 Symbol(Gc<JsSymbol>),
1277}
1278
1279impl PropertyKey {
1280 /// The key as a string, for the operations that only accept one.
1281 ///
1282 /// A symbol has no string form that would address it, so this answers `None` —
1283 /// which is what makes `get_field` on a symbol key fall through to the general
1284 /// path instead of silently reading a same-named string property.
1285 pub fn as_str(&self) -> Option<&str> {
1286 match self {
1287 PropertyKey::String(text) => text.as_str(),
1288 PropertyKey::Symbol(_) => None,
1289 }
1290 }
1291
1292 /// The key's bytes, which a string key always has and a symbol never does.
1293 pub fn as_wtf8(&self) -> Option<&crate::value::Wtf8> {
1294 match self {
1295 PropertyKey::String(text) => Some(text),
1296 PropertyKey::Symbol(_) => None,
1297 }
1298 }
1299
1300 /// Whether this is an ordinary string key.
1301 pub fn is_symbol(&self) -> bool {
1302 matches!(self, PropertyKey::Symbol(_))
1303 }
1304}
1305
1306impl fmt::Display for PropertyKey {
1307 /// How a key reads inside an error message: strings bare, symbols in their
1308 /// `Symbol(description)` form.
1309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1310 match self {
1311 PropertyKey::String(text) => write!(f, "{}", text.to_string_lossy()),
1312 PropertyKey::Symbol(symbol) => write!(f, "{}", symbol.to_display_string()),
1313 }
1314 }
1315}
1316
1317impl PartialEq for PropertyKey {
1318 fn eq(&self, other: &Self) -> bool {
1319 match (self, other) {
1320 (PropertyKey::String(a), PropertyKey::String(b)) => a == b,
1321 // Symbols compare by identity, never by description.
1322 (PropertyKey::Symbol(a), PropertyKey::Symbol(b)) => a.ptr_eq(b),
1323 _ => false,
1324 }
1325 }
1326}
1327
1328impl From<&str> for PropertyKey {
1329 fn from(text: &str) -> PropertyKey {
1330 PropertyKey::String(crate::value::Wtf8::new(text))
1331 }
1332}
1333
1334impl From<String> for PropertyKey {
1335 fn from(text: String) -> PropertyKey {
1336 PropertyKey::String(crate::value::Wtf8::new(text))
1337 }
1338}
1339
1340impl From<crate::value::Wtf8> for PropertyKey {
1341 fn from(text: crate::value::Wtf8) -> PropertyKey {
1342 PropertyKey::String(text)
1343 }
1344}
1345
1346impl Trace for PropertyKey {
1347 fn trace(&self, tracer: &mut Tracer) {
1348 if let PropertyKey::Symbol(symbol) = self {
1349 tracer.visit(symbol);
1350 }
1351 }
1352}
1353
1354/// An object's mutable state: its prototype, property table and internal slots.
1355pub struct ObjectData {
1356 /// The prototype, or `None` for `Object.prototype` and for a null-prototype
1357 /// object created with `Object.create(null)`.
1358 pub proto: Option<Gc<JsObject>>,
1359 /// Properties in definition order, string and symbol keys interleaved.
1360 pub props: Vec<(PropertyKey, Property)>,
1361 /// What kind of object this is.
1362 pub kind: ObjectKind,
1363 /// Whether new properties may be added. `Object.preventExtensions`, `seal` and
1364 /// `freeze` clear it, and nothing clears it back.
1365 pub extensible: bool,
1366 /// Whether array elements may be replaced.
1367 ///
1368 /// Elements are not in the property table, so their attributes need somewhere to
1369 /// live; `Object.freeze` clears this and `Object.isFrozen` reads it. A *single*
1370 /// non-writable element is recorded in the property table instead, which is what
1371 /// `Object.defineProperty(a, "3", {configurable: false})` does.
1372 pub elements_writable: bool,
1373 /// Whether an array's `length` may be changed.
1374 ///
1375 /// `Object.defineProperty(a, "length", {writable: false})` makes it read-only without
1376 /// touching the elements, so it cannot share `elements_writable`: the two mean
1377 /// different things and `Object.freeze` sets both.
1378 pub length_writable: bool,
1379 /// The object a method was defined on, which is what `super` resolves against.
1380 ///
1381 /// Kept here rather than as a property because it is not observable: the spec calls
1382 /// it `[[HomeObject]]` and no script can read it, so putting it in the property
1383 /// table would leak it to `Object.getOwnPropertyNames` and `JSON.stringify`.
1384 pub home_object: Option<Gc<JsObject>>,
1385 /// Whether this function is a class constructor, which may not be called without
1386 /// `new`.
1387 pub class_constructor: bool,
1388 /// Whether this function has a `[[Construct]]`, i.e. may appear as the target of
1389 /// `new` or `Reflect.construct`.
1390 ///
1391 /// Not derivable from being callable, and that is the whole point: an ordinary
1392 /// method, an arrow function, a generator, an async function and most built-in
1393 /// methods are all callable and none of them may be constructed (§10.2.1,
1394 /// §15.3.1). Deriving it from `is_callable` made `new (Array.prototype.map)` succeed,
1395 /// which test262 checks for every built-in (`not-a-constructor.js`, 515 files).
1396 pub constructible: bool,
1397}
1398
1399impl Trace for ObjectData {
1400 fn trace(&self, tracer: &mut Tracer) {
1401 if let Some(proto) = &self.proto {
1402 tracer.visit(proto);
1403 }
1404 if let Some(home) = &self.home_object {
1405 tracer.visit(home);
1406 }
1407 for (key, property) in &self.props {
1408 key.trace(tracer);
1409 property.trace(tracer);
1410 }
1411 self.kind.trace(tracer);
1412 }
1413}
1414
1415/// A JavaScript object.
1416///
1417/// The interior mutability is what makes `const o = {}; o.x = 1` work: the handle
1418/// is immutable, the object it points at is not.
1419pub struct JsObject {
1420 data: RefCell<ObjectData>,
1421}
1422
1423impl JsObject {
1424 fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
1425 JsObject {
1426 data: RefCell::new(ObjectData {
1427 proto,
1428 props: Vec::new(),
1429 kind,
1430 extensible: true,
1431 elements_writable: true,
1432 length_writable: true,
1433 home_object: None,
1434 class_constructor: false,
1435 constructible: false,
1436 }),
1437 }
1438 }
1439
1440 /// An ordinary object with the given prototype.
1441 pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1442 Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
1443 }
1444
1445 /// An array with the given prototype and initial capacity.
1446 /// An empty array with room for `capacity` elements.
1447 ///
1448 /// The length starts at 0: `capacity` is a `Vec` hint, not a length. Callers that want
1449 /// holes use [`Self::array_set_length`], which no longer allocates them.
1450 pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
1451 Gc::new(
1452 heap,
1453 JsObject::new(
1454 ObjectKind::Array {
1455 elements: Vec::with_capacity(capacity),
1456 length: 0,
1457 },
1458 proto,
1459 ),
1460 )
1461 }
1462
1463 /// A callable object.
1464 pub fn function(
1465 heap: &js_gc::Heap,
1466 proto: Option<Gc<JsObject>>,
1467 callable: Callable,
1468 ) -> Gc<JsObject> {
1469 Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
1470 }
1471
1472 /// Run `f` with the object's data borrowed.
1473 pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
1474 f(&self.data.borrow())
1475 }
1476
1477 /// Run `f` with the object's data mutably borrowed.
1478 pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
1479 f(&mut self.data.borrow_mut())
1480 }
1481
1482 /// Whether this object can be called.
1483 ///
1484 /// Covers every [`Callable`] variant, `Bound` included: `typeof bound ===
1485 /// "function"` and `bound()` works, so from a script's point of view a bound
1486 /// function is a function.
1487 pub fn is_callable(&self) -> bool {
1488 match &self.data.borrow().kind {
1489 ObjectKind::Function(_) => true,
1490 // A proxy is callable exactly when its target was when the proxy was built.
1491 // Not "when its target still is": revoking drops the target but leaves
1492 // `[[Call]]` in place, so a revoked proxy over a function stays a function.
1493 // This is what makes `typeof proxyOfFunction === "function"` survive revoke.
1494 ObjectKind::Proxy(state) => state.borrow().callable,
1495 _ => false,
1496 }
1497 }
1498
1499 /// Whether this object has a `[[Construct]]`, i.e. may be the target of `new` or
1500 /// `Reflect.construct`.
1501 pub fn is_constructor(&self) -> bool {
1502 let data = self.data.borrow();
1503 match &data.kind {
1504 // The flag, not "is a function": a plain method is a function and is not a
1505 // constructor. Set at creation by whoever knows what was built.
1506 ObjectKind::Function(_) => data.constructible,
1507 // Recorded at creation for the same reason as callability: revoking drops the
1508 // target without taking `[[Construct]]` away.
1509 ObjectKind::Proxy(state) => state.borrow().constructible,
1510 _ => false,
1511 }
1512 }
1513
1514 /// Give this function a `[[Construct]]`.
1515 ///
1516 /// Only for callables that are constructors by definition: ordinary functions, class
1517 /// constructors, and the built-in constructors. Everything else — methods, arrows,
1518 /// generators, async functions — keeps the default `false`.
1519 pub fn set_constructible(&self, yes: bool) {
1520 self.data.borrow_mut().constructible = yes;
1521 }
1522
1523 /// This object's proxy slots, when it is one (revoked or not).
1524 pub fn proxy_state(&self) -> Option<ProxyRef> {
1525 match &self.data.borrow().kind {
1526 ObjectKind::Proxy(state) => Some(state.clone()),
1527 _ => None,
1528 }
1529 }
1530
1531 /// A proxy over `target` reading its traps from `handler`.
1532 ///
1533 /// The prototype stays empty on purpose: `[[GetPrototypeOf]]` on a proxy forwards to
1534 /// the target through the `getPrototypeOf` trap, so copying the target's prototype
1535 /// here would be a second, disagreeing source of truth.
1536 pub fn proxy(heap: &js_gc::Heap, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
1537 // Read callability from the target *now*: it is the one moment the answer is
1538 // available, and it outlives revocation.
1539 let callable = target.is_callable();
1540 let constructible = target.is_constructor();
1541 Gc::new(
1542 heap,
1543 JsObject::new(
1544 ObjectKind::Proxy(std::rc::Rc::new(std::cell::RefCell::new(ProxyState {
1545 callable,
1546 constructible,
1547 target: Some(target),
1548 handler: Some(handler),
1549 }))),
1550 None,
1551 ),
1552 )
1553 }
1554
1555 /// The prototype.
1556 pub fn proto(&self) -> Option<Gc<JsObject>> {
1557 self.data.borrow().proto.clone()
1558 }
1559
1560 /// Replace the prototype.
1561 pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
1562 self.data.borrow_mut().proto = proto;
1563 }
1564
1565 /// The object a method was defined on, for `super` to resolve against.
1566 pub fn home_object(&self) -> Option<Gc<JsObject>> {
1567 self.data.borrow().home_object.clone()
1568 }
1569
1570 /// Record the object a method was defined on.
1571 ///
1572 /// A method has no `[[Construct]]` (§10.2.1): `new (o.m)` is a `TypeError` even
1573 /// though `o.m` is a function. Acquiring a home object is exactly the moment a
1574 /// function becomes a method, so the flag is cleared here rather than left to every
1575 /// method-defining call site to remember.
1576 pub fn set_home_object(&self, home: Option<Gc<JsObject>>) {
1577 let mut data = self.data.borrow_mut();
1578 data.home_object = home.clone();
1579 if home.is_some() {
1580 data.constructible = false;
1581 }
1582 }
1583
1584 /// Whether this is a class constructor.
1585 pub fn is_class_constructor(&self) -> bool {
1586 self.data.borrow().class_constructor
1587 }
1588
1589 /// Mark this function as a class constructor.
1590 pub fn set_class_constructor(&self, yes: bool) {
1591 self.data.borrow_mut().class_constructor = yes;
1592 }
1593
1594 /// The elements of an array object, if this is one.
1595 pub fn array_elements(&self) -> Option<Vec<Value>> {
1596 match &self.data.borrow().kind {
1597 ObjectKind::Array { elements, .. } => Some(elements.clone()),
1598 _ => None,
1599 }
1600 }
1601
1602 /// Every own key with its descriptor, array indices included.
1603 ///
1604 /// [`JsObject::own_property_keys`] answers the same question without the
1605 /// descriptors; a proxy invariant needs both at once, because it has to check the
1606 /// *value* of a key it is told about and the presence of a key it is not.
1607 pub fn property_entries(&self) -> Vec<(PropertyKey, Property)> {
1608 let data = self.data.borrow();
1609 let mut out: Vec<(PropertyKey, Property)> = data.props.to_vec();
1610 // An array's elements live in their own vector rather than the property table, so
1611 // they have to be synthesized — with the attributes an ordinary element has.
1612 if let ObjectKind::Array { elements, .. } = &data.kind {
1613 for (index, element) in elements.iter().enumerate() {
1614 if matches!(element, Value::Hole) {
1615 continue;
1616 }
1617 let key = PropertyKey::from(index.to_string());
1618 if !out.iter().any(|(existing, _)| *existing == key) {
1619 out.push((key, Property::data(element.clone())));
1620 }
1621 }
1622 }
1623 // `length` is own on an array without being in the property table either. It is
1624 // writable, non-enumerable and — the part proxy invariants care about —
1625 // non-configurable, so leaving it out let a handler hide or redefine it.
1626 if matches!(data.kind, ObjectKind::Array { .. })
1627 && let Some(length) = self.array_length()
1628 {
1629 let key = PropertyKey::from("length");
1630 if !out.iter().any(|(existing, _)| *existing == key) {
1631 out.push((
1632 key,
1633 Property {
1634 value: Some(length_value(length)),
1635 writable: self.length_writable(),
1636 enumerable: false,
1637 configurable: false,
1638 getter: None,
1639 setter: None,
1640 },
1641 ));
1642 }
1643 }
1644 out
1645 }
1646
1647 /// Whether this object has array elements at all.
1648 pub fn is_array(&self) -> bool {
1649 match &self.data.borrow().kind {
1650 ObjectKind::Array { .. } => true,
1651 // `Array.isArray` is specified to see *through* a proxy: it forwards
1652 // `[[Get]]`/prototype checks to the target, and the answer for a proxy of an
1653 // array is yes.
1654 ObjectKind::Proxy(state) => state
1655 .borrow()
1656 .target
1657 .as_ref()
1658 .is_some_and(|target| target.is_array()),
1659 _ => false,
1660 }
1661 }
1662
1663 /// `length` for an array, reading it out of the element vector.
1664 /// The compiled pattern, when this object is a `RegExp`.
1665 pub fn regexp(&self) -> Option<crate::builtins::regexp::RegExpData> {
1666 match &self.data.borrow().kind {
1667 ObjectKind::RegExp(data) => Some(data.clone()),
1668 _ => None,
1669 }
1670 }
1671
1672 /// The held resources, when this object is a `DisposableStack`.
1673 pub fn disposable_stack(&self) -> Option<crate::builtins::disposable::StackState> {
1674 match &self.data.borrow().kind {
1675 ObjectKind::DisposableStack(state) => Some(state.clone()),
1676 _ => None,
1677 }
1678 }
1679
1680 /// Make this object a `DisposableStack` holding `state`.
1681 pub fn set_disposable_stack(&self, state: crate::builtins::disposable::StackState) {
1682 self.data.borrow_mut().kind = ObjectKind::DisposableStack(state);
1683 }
1684
1685 /// Make this object a `RegExp` carrying `data`.
1686 pub fn set_regexp(&self, data: crate::builtins::regexp::RegExpData) {
1687 self.data.borrow_mut().kind = ObjectKind::RegExp(data);
1688 }
1689
1690 /// Whether this object is a `RegExp`.
1691 pub fn is_regexp(&self) -> bool {
1692 matches!(self.data.borrow().kind, ObjectKind::RegExp(_))
1693 }
1694
1695 /// An array's element count, when this object is an array.
1696 pub fn array_length(&self) -> Option<usize> {
1697 match &self.data.borrow().kind {
1698 ObjectKind::Array { length, .. } => Some(*length),
1699 _ => None,
1700 }
1701 }
1702
1703 /// Read one array element.
1704 pub fn array_get(&self, index: usize) -> Option<Value> {
1705 match &self.data.borrow().kind {
1706 ObjectKind::Array { elements, .. } => elements.get(index).cloned(),
1707 _ => None,
1708 }
1709 }
1710
1711 /// Append to an array and return the new length.
1712 pub fn array_push(&self, value: Value) -> usize {
1713 match &mut self.data.borrow_mut().kind {
1714 ObjectKind::Array { elements, length } => {
1715 elements.push(value);
1716 *length = elements.len();
1717 *length
1718 }
1719 _ => 0,
1720 }
1721 }
1722
1723 /// Store into an array, and return whether the write happened.
1724 ///
1725 /// The gap an out-of-range store leaves behind is filled with [`Value::Hole`], not
1726 /// `undefined`: `a = [1]; a[3] = 4` has holes at 1 and 2, which `forEach` skips
1727 /// and the debug printer reports. A store *of* `undefined` is a real element.
1728 pub fn array_set(&self, index: usize, value: Value) -> bool {
1729 match &mut self.data.borrow_mut().kind {
1730 ObjectKind::Array { elements, length } => {
1731 if index >= *length {
1732 // Growing has to fill the gap, and filling it means the vector really
1733 // does hold `index + 1` slots — a store at `2^32-2` is 68 GB whatever
1734 // the length field says. Refuse instead of aborting the process: the
1735 // reference throws `RangeError` from the allocation. A caller that
1736 // cares converts this `false` into the spec's answer.
1737 if index + 1 > ARRAY_ELEMENT_LIMIT {
1738 return false;
1739 }
1740 elements.resize(index + 1, Value::Hole);
1741 *length = elements.len();
1742 } else if index >= elements.len() {
1743 // Inside the logical length but past the dense prefix: a hole that is
1744 // being filled, so the vector has to catch up first.
1745 elements.resize(index + 1, Value::Hole);
1746 }
1747 elements[index] = value;
1748 true
1749 }
1750 _ => false,
1751 }
1752 }
1753
1754 /// Store an element, honouring its attributes, reporting whether it happened.
1755 ///
1756 /// Array methods that write back (`sort`, `reverse`, `splice`, …) use this rather
1757 /// than [`Self::array_set`]: the spec has them go through `[[Set]]`, so a frozen
1758 /// element makes them throw instead of being quietly overwritten.
1759 pub fn array_store(&self, index: usize, value: Value) -> bool {
1760 if self.elements_writable() {
1761 return self.array_set(index, value);
1762 }
1763 if self.element_attributes(index as u32).is_some() {
1764 // A recorded descriptor decides on its own.
1765 return !self.element_is_locked(index as u32) && self.array_set(index, value);
1766 }
1767 false
1768 }
1769
1770 /// Store `value` as a plain element without creating holes, used by `push`.
1771 pub fn array_push_hole(&self) -> bool {
1772 match &mut self.data.borrow_mut().kind {
1773 ObjectKind::Array { elements, length } => {
1774 elements.push(Value::Hole);
1775 *length = elements.len();
1776 true
1777 }
1778 _ => false,
1779 }
1780 }
1781
1782 /// Set the length of an array, truncating or extending with holes.
1783 ///
1784 /// `a.length = 5` on a two-element array leaves three holes, so the fill value is
1785 /// [`Value::Hole`] rather than `undefined`.
1786 /// Growing only records the new length: the extra slots are holes, and a hole needs
1787 /// no storage. That is what makes `a = []; a.length = 4294967295` an O(1) operation
1788 /// instead of a 62 GB allocation.
1789 pub fn array_set_length(&self, new_length: usize) -> bool {
1790 match &mut self.data.borrow_mut().kind {
1791 ObjectKind::Array { elements, length } => {
1792 if new_length < *length {
1793 // Shrinking really does drop the trailing elements.
1794 elements.truncate(new_length);
1795 }
1796 *length = new_length;
1797 true
1798 }
1799 _ => false,
1800 }
1801 }
1802
1803 /// Truncate an array to `length` elements without extending it.
1804 ///
1805 /// This is what `arr.length = n` does for `n` smaller than the current length;
1806 /// it is separate from [`Self::array_set_length`] because growing an array by
1807 /// assignment produces holes, which are indistinguishable from `undefined`
1808 /// here.
1809 pub fn array_truncate(&self, new_length: usize) -> bool {
1810 match &mut self.data.borrow_mut().kind {
1811 ObjectKind::Array { elements, length } => {
1812 if new_length < elements.len() {
1813 elements.truncate(new_length);
1814 }
1815 if new_length < *length {
1816 *length = new_length;
1817 }
1818 true
1819 }
1820 _ => false,
1821 }
1822 }
1823
1824 /// The own data property `key`, if there is one.
1825 pub fn own_property_key(&self, key: &PropertyKey) -> Option<Property> {
1826 let data = self.data.borrow();
1827 data.props
1828 .iter()
1829 .find(|(existing, _)| existing == key)
1830 .map(|(_, property)| property.clone())
1831 }
1832
1833 /// The own data property `name`, if there is one.
1834 pub fn own_property(&self, name: &str) -> Option<Property> {
1835 self.own_property_key(&PropertyKey::from(name))
1836 }
1837
1838 /// Whether the object has an own property `key`.
1839 pub fn has_own_key(&self, key: &PropertyKey) -> bool {
1840 let data = self.data.borrow();
1841 data.props.iter().any(|(existing, _)| existing == key)
1842 }
1843
1844 /// Whether the object has an own property `name`.
1845 pub fn has_own(&self, name: &str) -> bool {
1846 self.has_own_key(&PropertyKey::from(name))
1847 }
1848
1849 /// Define or replace an own property, keeping the original position when the
1850 /// key already exists.
1851 pub fn define_key(&self, key: &PropertyKey, property: Property) {
1852 let mut data = self.data.borrow_mut();
1853 match data.props.iter_mut().find(|(existing, _)| existing == key) {
1854 Some((_, slot)) => *slot = property,
1855 None => data.props.push((key.clone(), property)),
1856 }
1857 }
1858
1859 /// Define or replace an own property under a string key.
1860 pub fn define(&self, name: &str, property: Property) {
1861 self.define_key(&PropertyKey::from(name), property);
1862 }
1863
1864 /// Define an own data property, with the default attributes.
1865 ///
1866 /// This *creates*: on an existing property it overwrites the attributes too, so
1867 /// it is the wrong call for a plain assignment. Use [`Self::write_value`] for that.
1868 pub fn define_data(&self, name: &str, value: Value) {
1869 self.define(name, Property::data(value));
1870 }
1871
1872 /// Define an own data property under `key`.
1873 pub fn define_data_key(&self, key: &PropertyKey, value: Value) {
1874 self.define_key(key, Property::data(value));
1875 }
1876
1877 /// Store a value into an existing own data property, keeping its attributes.
1878 ///
1879 /// Returns `false` when the property is absent, is an accessor, or is not
1880 /// writable. An assignment has to go through this rather than
1881 /// [`Self::define_data`], because redefining is how a non-configurable global
1882 /// silently became configurable again and started answering `delete` with `true`.
1883 pub fn write_value(&self, name: &str, value: Value) -> bool {
1884 self.write_value_key(&PropertyKey::from(name), value)
1885 }
1886
1887 /// Store a value into an existing own data property under `key`.
1888 pub fn write_value_key(&self, key: &PropertyKey, value: Value) -> bool {
1889 let mut data = self.data.borrow_mut();
1890 let Some((_, property)) = data.props.iter_mut().find(|(existing, _)| existing == key)
1891 else {
1892 return false;
1893 };
1894 if property.is_accessor() || !property.writable {
1895 return false;
1896 }
1897 property.value = Some(value);
1898 true
1899 }
1900
1901 /// Delete an own property, reporting whether it was there and removable.
1902 pub fn delete(&self, name: &str) -> bool {
1903 self.delete_key(&PropertyKey::from(name))
1904 }
1905
1906 /// Delete an own property under `key`.
1907 pub fn delete_key(&self, key: &PropertyKey) -> bool {
1908 let mut data = self.data.borrow_mut();
1909 match data.props.iter().position(|(existing, _)| existing == key) {
1910 Some(index) => {
1911 if data.props[index].1.configurable {
1912 data.props.remove(index);
1913 true
1914 } else {
1915 false
1916 }
1917 }
1918 None => true,
1919 }
1920 }
1921
1922 /// Whether new properties may be added.
1923 pub fn is_extensible(&self) -> bool {
1924 self.data.borrow().extensible
1925 }
1926
1927 /// Make the object non-extensible.
1928 pub fn set_extensible(&self, extensible: bool) {
1929 self.data.borrow_mut().extensible = extensible;
1930 }
1931
1932 /// Whether array elements may be replaced.
1933 pub fn elements_writable(&self) -> bool {
1934 self.data.borrow().elements_writable
1935 }
1936
1937 /// Whether an array's `length` may be changed.
1938 pub fn length_writable(&self) -> bool {
1939 self.data.borrow().length_writable
1940 }
1941
1942 /// Record whether `length` may be changed.
1943 pub fn set_length_writable(&self, writable: bool) {
1944 self.data.borrow_mut().length_writable = writable;
1945 }
1946
1947 /// Make array elements read-only, as `Object.freeze` does.
1948 pub fn set_elements_writable(&self, writable: bool) {
1949 self.data.borrow_mut().elements_writable = writable;
1950 }
1951
1952 /// The attributes recorded for an array index, if `defineProperty` set any.
1953 pub fn element_attributes(&self, index: u32) -> Option<Property> {
1954 self.own_property(&index.to_string())
1955 }
1956
1957 /// Whether `delete` at `index` would be rejected.
1958 ///
1959 /// Separate from [`JsObject::element_is_locked`]: a store needs the element to be
1960 /// non-writable, but a *delete* — which is what truncating an array does — only needs
1961 /// it to be non-configurable. `Object.defineProperty(a, "3", {configurable: false})`
1962 /// leaves `a[3]` writable and yet undeletable, so `a.length = 2` must fail.
1963 pub fn element_is_undeletable(&self, index: u32) -> bool {
1964 if !self.elements_writable() {
1965 return true;
1966 }
1967 self.element_attributes(index)
1968 .is_some_and(|property| !property.configurable)
1969 }
1970
1971 /// Whether a store at `index` would be rejected.
1972 ///
1973 /// An element is locked either by `Object.freeze` on the whole object or by a
1974 /// non-configurable, non-writable descriptor recorded for that one index.
1975 pub fn element_is_locked(&self, index: u32) -> bool {
1976 if !self.elements_writable() {
1977 return true;
1978 }
1979 self.element_attributes(index)
1980 .is_some_and(|property| !property.writable && !property.configurable)
1981 }
1982
1983 /// The own property *names*, in definition order. Symbol keys are excluded:
1984 /// `Object.keys` and `for…in` cannot see them.
1985 pub fn own_keys(&self) -> Vec<crate::value::Wtf8> {
1986 self.data
1987 .borrow()
1988 .props
1989 .iter()
1990 .filter_map(|(key, _)| key.as_wtf8().cloned())
1991 .collect()
1992 }
1993
1994 /// The own *enumerable* property names, in definition order.
1995 pub fn own_enumerable_keys(&self) -> Vec<crate::value::Wtf8> {
1996 self.data
1997 .borrow()
1998 .props
1999 .iter()
2000 .filter(|(_, property)| property.enumerable)
2001 .filter_map(|(key, _)| key.as_wtf8().cloned())
2002 .collect()
2003 }
2004
2005 /// The own symbol keys, in definition order, for `Object.getOwnPropertySymbols`.
2006 pub fn own_symbol_keys(&self) -> Vec<Gc<JsSymbol>> {
2007 self.data
2008 .borrow()
2009 .props
2010 .iter()
2011 .filter_map(|(key, _)| match key {
2012 PropertyKey::Symbol(symbol) => Some(symbol.clone()),
2013 PropertyKey::String(_) => None,
2014 })
2015 .collect()
2016 }
2017
2018 /// Every own key, strings first then symbols — the order `Reflect.ownKeys` and
2019 /// `Object.getOwnPropertyDescriptors` report, and the order `JSON.stringify`
2020 /// walks before it skips the symbols.
2021 pub fn own_property_keys(&self) -> Vec<PropertyKey> {
2022 let data = self.data.borrow();
2023 let mut strings: Vec<PropertyKey> = Vec::new();
2024 let mut symbols: Vec<PropertyKey> = Vec::new();
2025 for (key, _) in &data.props {
2026 if key.is_symbol() {
2027 symbols.push(key.clone());
2028 } else {
2029 strings.push(key.clone());
2030 }
2031 }
2032 strings.extend(symbols);
2033 strings
2034 }
2035
2036 /// Own property keys in **definition order**, with symbols interleaved.
2037 ///
2038 /// [`JsObject::own_property_keys`] answers in the spec's order — integer-like keys
2039 /// ascending, then strings, then symbols — because that is what `Reflect.ownKeys` and
2040 /// `for...in` must do. A dumper has the opposite requirement: quickjs's
2041 /// `JS_PrintValue` walks the shape, so `{[Symbol("t")]: 1, y: 2}` prints the symbol
2042 /// first. That is not observable from a script except through such a dump, which is
2043 /// why this is a separate accessor rather than a change to `own_property_keys`.
2044 pub fn own_property_keys_in_definition_order(&self) -> Vec<PropertyKey> {
2045 self.data
2046 .borrow()
2047 .props
2048 .iter()
2049 .map(|(key, _)| key.clone())
2050 .collect()
2051 }
2052
2053 /// The prototype chain, starting with the prototypes of this object.
2054 pub fn chain(&self) -> Vec<Gc<JsObject>> {
2055 let mut out = Vec::new();
2056 let mut proto = self.proto();
2057 while let Some(object) = proto {
2058 proto = object.proto();
2059 out.push(object);
2060 }
2061 out
2062 }
2063}
2064
2065/// Whether two prototypes are the same one, `None` included.
2066///
2067/// A proxy's prototype invariants have to compare "no prototype" against "no
2068/// prototype" without unwrapping either side first.
2069pub(crate) fn same_proto(a: Option<&Gc<JsObject>>, b: Option<&Gc<JsObject>>) -> bool {
2070 match (a, b) {
2071 (None, None) => true,
2072 (Some(a), Some(b)) => a.ptr_eq(b),
2073 _ => false,
2074 }
2075}
2076
2077/// Walk the prototype chain from `object` looking for `name`.
2078///
2079/// Returns the object that owns the property along with the property itself. The
2080/// owner matters for a store: an inherited accessor is invoked on the receiver,
2081/// while an inherited *data* property is shadowed by a new own property.
2082/// The own property `key` names on `object`, arrays included.
2083///
2084/// An array keeps its elements in an element vector and derives its `length`, so its
2085/// property table knows about neither: a hole is a slot in the vector, not a missing
2086/// property, and `length` is not stored at all. `Array.prototype` is itself an array, so
2087/// every walk down the chain needs this same care — without it `1 in [1,,3]` stayed false
2088/// with `Array.prototype[1]` defined, `"length" in []` was false outright, and a hole did
2089/// not read an inherited element.
2090pub fn own_property_including_array(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2091 if let Some(property) = object.own_property_key(key) {
2092 return Some(property);
2093 }
2094 // A typed array's indices are its elements in the buffer, which the property table
2095 // does not hold either. Checked before the `is_array` return below, because a typed
2096 // array is not one.
2097 if object.typed_array_parts().is_some() {
2098 // A detached view exposes no indices at all: `Reflect.has(detached, "0")` is false
2099 // even though index 0 was in range before the buffer went away.
2100 let index = key.as_str().and_then(array_index)?;
2101 let in_range = (index as usize) < object.typed_array_length()?;
2102 return match object.typed_array_element(index as usize) {
2103 Some(value) if in_range => Some(Property::data(value)),
2104 _ => None,
2105 };
2106 }
2107 if !object.is_array() {
2108 return None;
2109 }
2110 let text = key.as_str()?;
2111 // `length` is non-enumerable and non-configurable; `writable` unless a definition
2112 // turned it off.
2113 if text == "length" {
2114 return Some(Property {
2115 value: Some(length_value(object.array_length()?)),
2116 writable: object.length_writable(),
2117 enumerable: false,
2118 configurable: false,
2119 getter: None,
2120 setter: None,
2121 });
2122 }
2123 // An element is a plain writable/enumerable/configurable data property, and a hole is
2124 // not one at all.
2125 let index = array_index(text)?;
2126 match object.array_get(index as usize) {
2127 Some(Value::Hole) | None => None,
2128 Some(value) => Some(Property::data(value)),
2129 }
2130}
2131
2132/// Whether `object` has `key` as an *own* property, arrays included.
2133pub fn has_own(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
2134 own_property_including_array(object, key).is_some()
2135}
2136
2137/// `key` on `object` or anywhere up its prototype chain, with the owner.
2138///
2139/// Array-aware at every step: an array's elements and its derived `length` are not in the
2140/// property table, and `Array.prototype` is itself an array.
2141pub fn lookup_key(object: &Gc<JsObject>, key: &PropertyKey) -> Option<(Gc<JsObject>, Property)> {
2142 if let Some(property) = own_property_including_array(object, key) {
2143 return Some((object.clone(), property));
2144 }
2145 for ancestor in object.chain() {
2146 if let Some(property) = own_property_including_array(&ancestor, key) {
2147 return Some((ancestor, property));
2148 }
2149 }
2150 None
2151}
2152
2153/// [`lookup_key`] for a string key.
2154pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
2155 lookup_key(object, &PropertyKey::from(name))
2156}
2157
2158/// The largest array index that may be *stored*, i.e. the largest dense vector this engine
2159/// will grow to an index for.
2160///
2161/// The spec's `length` limit is `2^32-1`, but the elements are a dense `Vec<Value>` here,
2162/// so a store at index `2^32-2` is a 68 GB reservation. The reference (which keeps
2163/// elements in a hash map) answers instantly. Refusing past this bound keeps the process
2164/// alive; the conformance tests that really do store near `2^32` are recorded in
2165/// `docs/test262-status.md` as a limitation rather than quietly answered wrong.
2166pub const ARRAY_ELEMENT_LIMIT: usize = 1 << 26;
2167
2168/// An array's `length` as a JavaScript number.
2169///
2170/// `Value::Int` only holds an `i32`, and an array's length may legitimately reach
2171/// `2^32-1`, so a plain cast is not enough: `a[2**32-2] = 1; a.length` came back as `-1`,
2172/// and `Object.getOwnPropertyDescriptor(a, "length").value` with it. Every
2173/// `LengthOfArrayLike` over such an array then ran to `-1`, and the paths without their
2174/// own `RangeError` check turned into `memory allocation of 68719476720 bytes failed`.
2175pub fn length_value(length: usize) -> Value {
2176 if length <= i32::MAX as usize {
2177 Value::Int(length as i32)
2178 } else {
2179 Value::Float(length as f64)
2180 }
2181}
2182
2183/// An array *index* as a JavaScript number.
2184///
2185/// Same problem as [`length_value`] and the same fix: an index may be as large as
2186/// `2^32-2`, which `Value::Int` cannot hold. `a[2**32-2] = 1; a.indexOf(1)` was answering
2187/// `-2` because the index was truncated on the way out.
2188pub fn index_value(index: usize) -> Value {
2189 length_value(index)
2190}
2191
2192/// The array index a property key names, if it names one.
2193///
2194/// A key is an index when it is the canonical decimal spelling of an integer below
2195/// `2^32 - 1` — the same rule the atom table uses to decide whether a key is a
2196/// tagged index. `"01"` and `"-1"` are ordinary string keys.
2197pub fn array_index(key: &str) -> Option<u32> {
2198 if key.is_empty() || key.len() > 10 {
2199 return None;
2200 }
2201 let bytes = key.as_bytes();
2202 if !bytes.iter().all(u8::is_ascii_digit) {
2203 return None;
2204 }
2205 if bytes[0] == b'0' && bytes.len() != 1 {
2206 return None;
2207 }
2208 let value: u32 = key.parse().ok()?;
2209 // `2^32 - 1` is reserved for the array length, so it is not an index.
2210 (value < u32::MAX).then_some(value)
2211}
2212
2213impl Trace for JsObject {
2214 fn trace(&self, tracer: &mut Tracer) {
2215 self.data.borrow().trace(tracer);
2216 }
2217}