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