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};
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 /// `(buffer, element, offset, length)`, when this object is a typed-array view.
70 pub fn typed_array_parts(
71 &self,
72 ) -> Option<(
73 Gc<JsObject>,
74 crate::builtins::typedarray::ElementType,
75 usize,
76 usize,
77 )> {
78 match &self.data.borrow().kind {
79 ObjectKind::TypedArray {
80 buffer,
81 element,
82 offset,
83 length,
84 } => Some((buffer.clone(), *element, *offset, *length)),
85 _ => None,
86 }
87 }
88
89 /// Make this object a typed-array view.
90 pub fn set_typed_array(
91 &self,
92 buffer: Gc<JsObject>,
93 element: crate::builtins::typedarray::ElementType,
94 offset: usize,
95 length: usize,
96 ) {
97 self.data.borrow_mut().kind = ObjectKind::TypedArray {
98 buffer,
99 element,
100 offset,
101 length,
102 };
103 }
104
105 /// The element type, when this object is a typed-array view.
106 pub fn typed_array_element_type(&self) -> Option<crate::builtins::typedarray::ElementType> {
107 self.typed_array_parts().map(|(_, element, _, _)| element)
108 }
109
110 /// How many elements the view exposes, or `None` when this is not a view.
111 ///
112 /// A detached buffer reports `0`: the storage is gone, so there is nothing to index.
113 pub fn typed_array_length(&self) -> Option<usize> {
114 let (buffer, _, _, length) = self.typed_array_parts()?;
115 let storage = buffer.array_buffer_storage()?;
116 if storage.borrow().detached {
117 return Some(0);
118 }
119 Some(length)
120 }
121
122 /// Read one view element.
123 ///
124 /// Out-of-range and detached reads are `undefined` rather than an error, which is what
125 /// makes `a[999]` and a detached `a[0]` behave the way the language says.
126 pub fn typed_array_element(&self, index: usize) -> Option<Value> {
127 let (buffer, element, offset, length) = self.typed_array_parts()?;
128 let storage = buffer.array_buffer_storage()?;
129 let storage = storage.borrow();
130 if storage.detached || index >= length {
131 return Some(Value::Undefined);
132 }
133 Some(element.read(&storage.bytes, offset + index * element.size()))
134 }
135
136 /// Store one view element, applying the type's wrap or clamp.
137 pub fn typed_array_set(&self, index: usize, value: Value) -> Option<()> {
138 let (buffer, element, offset, length) = self.typed_array_parts()?;
139 if index >= length {
140 return Some(());
141 }
142 let storage = buffer.array_buffer_storage()?;
143 let mut storage = storage.borrow_mut();
144 if storage.detached {
145 return Some(());
146 }
147 element.write(&mut storage.bytes, offset + index * element.size(), value);
148 Some(())
149 }
150}
151
152/// A property of an object.
153#[derive(Clone, Default)]
154pub struct Property {
155 /// The value of a data property.
156 pub value: Option<Value>,
157 /// The getter of an accessor property.
158 pub getter: Option<Value>,
159 /// The setter of an accessor property.
160 pub setter: Option<Value>,
161 /// Whether the value can be replaced.
162 pub writable: bool,
163 /// Whether `for`/`Object.keys` sees the property.
164 pub enumerable: bool,
165 /// Whether the property can be deleted or redefined.
166 pub configurable: bool,
167}
168
169impl Property {
170 /// A writable, enumerable, configurable data property.
171 ///
172 /// This is what a plain assignment or an object literal creates, and the
173 /// attributes only differ for built-ins and `Object.defineProperty`.
174 pub fn data(value: Value) -> Property {
175 Property {
176 value: Some(value),
177 writable: true,
178 enumerable: true,
179 configurable: true,
180 ..Property::default()
181 }
182 }
183
184 /// A data property with explicit attributes.
185 pub fn with_attributes(value: Value, writable: bool, enumerable: bool) -> Property {
186 Property {
187 value: Some(value),
188 writable,
189 enumerable,
190 configurable: writable,
191 ..Property::default()
192 }
193 }
194
195 /// An accessor property.
196 /// An accessor property with explicit `enumerable`/`configurable` flags, which is
197 /// what `Symbol.prototype.description` needs: it is enumerable: false in the spec.
198 pub fn accessor_with(
199 getter: Option<Value>,
200 setter: Option<Value>,
201 enumerable: bool,
202 ) -> Property {
203 Property {
204 getter,
205 setter,
206 enumerable,
207 configurable: true,
208 ..Property::default()
209 }
210 }
211
212 /// An accessor property with the default `enumerable`/`configurable` flags.
213 pub fn accessor(getter: Option<Value>, setter: Option<Value>) -> Property {
214 Property {
215 getter,
216 setter,
217 enumerable: true,
218 configurable: true,
219 ..Property::default()
220 }
221 }
222
223 /// Whether this is an accessor rather than a data property.
224 pub fn is_accessor(&self) -> bool {
225 self.getter.is_some() || self.setter.is_some()
226 }
227}
228
229impl Trace for Property {
230 fn trace(&self, tracer: &mut Tracer) {
231 self.value.trace(tracer);
232 self.getter.trace(tracer);
233 self.setter.trace(tracer);
234 }
235}
236
237/// A native (Rust) function reachable from JavaScript.
238///
239/// It receives the interpreter so a builtin can allocate (which needs the heap),
240/// call back into JavaScript (which needs the frame stack) and raise exceptions.
241pub type NativeFn =
242 fn(&mut crate::interp::Interp<'_>, Value, &[Value]) -> crate::interp::JsResult<Value>;
243
244/// The body of a callable object.
245pub enum Callable {
246 /// A function compiled from JavaScript source.
247 Bytecode {
248 /// The bytecode and slot mapping.
249 code: Gc<CompiledCode>,
250 /// The captured environment.
251 env: Gc<ClosureEnv>,
252 },
253 /// A function produced by `Function.prototype.bind`.
254 ///
255 /// This is a variant rather than a native function carrying the state in
256 /// properties because the state is not observable: `bind` has to remember its
257 /// target, `this` and leading arguments, and a native trampoline cannot capture
258 /// them.
259 Bound {
260 /// The function being called.
261 target: Value,
262 /// The `this` every call uses.
263 this: Value,
264 /// Arguments prepended to every call's own.
265 args: Vec<Value>,
266 },
267 /// A built-in implemented in Rust.
268 ///
269 /// The `name` and `length` a script observes are ordinary properties on the
270 /// function object, not fields here: they are writable (`f.name = "x"` works)
271 /// and would otherwise be two sources of truth.
272 Native {
273 /// The implementation.
274 func: NativeFn,
275 },
276 /// The `revoke` function `Proxy.revocable` hands back.
277 ///
278 /// It is a variant rather than a `Native` with the slots in a property because a
279 /// `NativeFn` is a plain function pointer: it cannot capture, and the slots are
280 /// precisely what this function exists to hold. Keeping them here also means the
281 /// collector sees them, so a proxy stays alive while only its `revoke` is reachable.
282 Revoker(crate::object::ProxyRef),
283 /// The `resolve` a `Promise` executor receives.
284 ///
285 /// Like [`Callable::Revoker`], this cannot be a plain `Native` with the state in a
286 /// property: a `NativeFn` is a function pointer and cannot capture, and the promise
287 /// it settles is exactly what it has to remember. Both are one-shot per §27.2.1.3.1 —
288 /// the second call is a no-op rather than a second settlement.
289 ///
290 /// The promise object is held directly rather than the state behind its `Rc`, because
291 /// settling has to run *that object's* reactions.
292 PromiseResolve(Gc<JsObject>),
293 /// The `reject` half of that pair.
294 PromiseReject(Gc<JsObject>),
295 /// One of the two continuations an `await` parks on.
296 ///
297 /// Reached through the ordinary reaction machinery, which is why it has to be a
298 /// callable object rather than a queue entry: `await x` is specified as
299 /// `PerformPromiseThen(x, resume, rethrow)`.
300 AwaitResume {
301 /// The body to continue.
302 coroutine: Gc<JsObject>,
303 /// The promise the async function returned.
304 promise: Gc<JsObject>,
305 /// Whether this continuation delivers the value or raises the reason.
306 kind: crate::interp::ResumeKind,
307 },
308 /// One element of `Promise.all`/`allSettled`/`any`/`race` settling.
309 CombinatorSettle {
310 /// The hidden object holding the results array, the remaining count and the
311 /// combinator's own resolve/reject pair.
312 state: Gc<JsObject>,
313 /// Which element this callback belongs to.
314 index: usize,
315 /// Whether the element fulfilled or rejected.
316 fulfilled: bool,
317 },
318 /// Settle a promise with a fixed outcome when called.
319 ///
320 /// `finally` needs "wait for this promise, then re-deliver that value", and a
321 /// `NativeFn` cannot carry the value to re-deliver.
322 SettlePromise {
323 /// The promise to settle.
324 promise: Gc<JsObject>,
325 /// The outcome to settle it with, which is the *original* one.
326 value: Value,
327 /// Whether that outcome is a rejection.
328 rejected: bool,
329 },
330 /// One continuation of an `await` inside an async generator.
331 GeneratorResume {
332 /// The async generator to continue.
333 generator: Gc<JsObject>,
334 /// The promise the pending `next`/`return`/`throw` returned.
335 promise: Gc<JsObject>,
336 /// Whether this delivers the value or raises the reason.
337 kind: crate::interp::ResumeKind,
338 },
339 /// Answer a pending async-generator method with `{value, done: false}`.
340 ///
341 /// `yield v` in an async generator awaits `v` first, so the value can arrive after
342 /// the body has already parked; this is what turns it into the result object.
343 YieldResult {
344 /// The promise the pending method returned.
345 promise: Gc<JsObject>,
346 /// Whether this answers a completed generator rather than a `yield`.
347 done: bool,
348 },
349 /// One step of `AsyncDisposableStack.disposeAsync`.
350 ///
351 /// The remaining resources ride along as a JS array so the collector can see them:
352 /// `disposeAsync` awaits each disposer in turn, which means the list has to survive
353 /// across microtasks rather than living on the Rust stack.
354 DisposeStep {
355 /// Pairs of `[resource, disposeMethod]`, consumed from the end.
356 remaining: Gc<JsObject>,
357 /// The promise `disposeAsync` returned.
358 promise: Gc<JsObject>,
359 /// The `SuppressedError` chain built so far, or `Uninitialized` for none.
360 error: Value,
361 /// Whether this continuation is being called with a rejection reason.
362 rejected: bool,
363 },
364 /// One of the two shims `Promise.prototype.finally` installs.
365 FinallyShim {
366 /// The script's callback, or `None` to pass the outcome straight through.
367 callback: Option<Value>,
368 /// Whether this is the fulfil side.
369 fulfilled: bool,
370 },
371}
372
373impl Trace for Callable {
374 fn trace(&self, tracer: &mut Tracer) {
375 match self {
376 Callable::Bytecode { code, env } => {
377 tracer.visit(code);
378 tracer.visit(env);
379 }
380 Callable::Bound { target, this, args } => {
381 target.trace(tracer);
382 this.trace(tracer);
383 for argument in args {
384 argument.trace(tracer);
385 }
386 }
387 Callable::Native { .. } => {}
388 Callable::Revoker(slots) => slots.borrow().trace(tracer),
389 Callable::PromiseResolve(promise) | Callable::PromiseReject(promise) => {
390 tracer.visit(promise)
391 }
392 Callable::AwaitResume {
393 coroutine, promise, ..
394 } => {
395 tracer.visit(coroutine);
396 tracer.visit(promise);
397 }
398 Callable::CombinatorSettle { state, .. } => tracer.visit(state),
399 Callable::GeneratorResume {
400 generator, promise, ..
401 } => {
402 tracer.visit(generator);
403 tracer.visit(promise);
404 }
405 Callable::YieldResult { promise, .. } => tracer.visit(promise),
406 Callable::DisposeStep {
407 remaining,
408 promise,
409 error,
410 ..
411 } => {
412 tracer.visit(remaining);
413 tracer.visit(promise);
414 error.trace(tracer);
415 }
416 Callable::SettlePromise { promise, value, .. } => {
417 tracer.visit(promise);
418 value.trace(tracer);
419 }
420 Callable::FinallyShim { callback, .. } => {
421 if let Some(callback) = callback {
422 callback.trace(tracer);
423 }
424 }
425 }
426 }
427}
428
429/// The bytecode of one function, plus the slot-to-cell mapping.
430///
431/// This is a separate GC object from the closure so that a frame can hold a handle
432/// to it and read it while the function object itself is free to be borrowed.
433/// Holding a `RefCell` borrow across a call would deadlock the moment a function
434/// referred to itself.
435pub struct CompiledCode {
436 /// The resolved bytecode.
437 pub code: CompiledFunction,
438 /// For each argument slot, the index of its reference cell, or `-1` when the
439 /// slot holds its value directly.
440 ///
441 /// A captured binding lives in a cell so that closures outlive the frame; every
442 /// other slot is a plain value. Precomputing the mapping keeps the hot
443 /// `get_arg`/`put_arg` paths to one array read instead of a lookup.
444 pub arg_cell: Vec<i32>,
445 /// The same, for local slots.
446 pub loc_cell: Vec<i32>,
447}
448
449impl CompiledCode {
450 /// Build the slot-to-cell mapping for `code`.
451 ///
452 /// Cells are numbered the way [`CompiledFunction::var_ref_count`] counts them:
453 /// the captured arguments first, then the captured locals, each in slot order.
454 pub fn new(code: CompiledFunction) -> CompiledCode {
455 let mut next = 0i32;
456 let mut arg_cell = vec![-1; code.args.len()];
457 for (slot, arg) in code.args.iter().enumerate() {
458 if arg.is_captured {
459 arg_cell[slot] = next;
460 next += 1;
461 }
462 }
463 let mut loc_cell = vec![-1; code.vars.len()];
464 for (slot, local) in code.vars.iter().enumerate() {
465 if local.is_captured {
466 loc_cell[slot] = next;
467 next += 1;
468 }
469 }
470 CompiledCode {
471 code,
472 arg_cell,
473 loc_cell,
474 }
475 }
476}
477
478impl Trace for CompiledCode {
479 fn trace(&self, _tracer: &mut Tracer) {}
480}
481
482/// The reference cells a closure captured from enclosing scopes.
483pub struct ClosureEnv {
484 /// Indexed the way the bytecode's closure-variable table indexes them.
485 pub cells: Vec<Gc<Cell>>,
486 /// The `eval` scope this closure was created in, if any.
487 ///
488 /// A function built by `eval` has to keep seeing the caller's bindings after the
489 /// eval has returned — `for (let i …) eval("push(() => i)")` collects closures that
490 /// read `i` later. Those bindings live in the *caller's* frame, which is long gone
491 /// by then, so the environment carries them by name instead. Ordinary closures leave
492 /// this `None` and resolve globals exactly as before.
493 pub eval_scope: Option<Gc<EvalScope>>,
494 /// Variables a direct `eval` declared in the frame this closure was created in, and
495 /// how much of that frame it may see.
496 ///
497 /// A closure is created at a *place* in a function, and a direct `eval` can add
498 /// variables after that point. Those variables belong to the variable environment
499 /// that was current at the closure's creation — the parameter list or the body — which
500 /// is what `local_phase` records.
501 pub local_vars: Option<Gc<LocalVars>>,
502 /// `0` for a closure created in a parameter list, `1` for one in a body. A parameter
503 /// list's closure must not see variables a later `eval` in the body declared:
504 /// `function f(a, p = () => c) { eval("var c = 1") }` has `p()` resolve `c` outside
505 /// the function entirely.
506 pub local_phase: u8,
507}
508
509/// Variables a direct `eval` declared in one function call.
510///
511/// A sloppy `eval` declares its `var`s in the caller's variable environment, not on the
512/// global object: `function f() { eval("var x = 1") } f(); x` is a `ReferenceError`, and
513/// two calls to `f` get two `x`s. Each entry therefore records the phase it was declared
514/// in, so a lookup from the parameter list cannot see a body declaration.
515pub struct LocalVars {
516 names: std::cell::RefCell<Vec<(String, Gc<Cell>, u8)>>,
517}
518
519impl Default for LocalVars {
520 fn default() -> LocalVars {
521 LocalVars::new()
522 }
523}
524
525impl LocalVars {
526 /// An empty set.
527 pub fn new() -> LocalVars {
528 LocalVars {
529 names: std::cell::RefCell::new(Vec::new()),
530 }
531 }
532
533 /// The cell `name` resolves to, when it was declared in `phase` or earlier.
534 pub fn get(&self, name: &str, phase: u8) -> Option<Gc<Cell>> {
535 self.names
536 .borrow()
537 .iter()
538 .find(|(bound, _, at)| bound == name && *at <= phase)
539 .map(|(_, cell, _)| cell.clone())
540 }
541
542 /// The cell for `name`, declaring it if this is the first time.
543 pub fn declare(&self, name: &str, phase: u8, cell: Gc<Cell>) -> Gc<Cell> {
544 let mut names = self.names.borrow_mut();
545 if let Some((_, cell, _)) = names.iter().find(|(bound, _, _)| bound == name) {
546 return cell.clone();
547 }
548 names.push((name.to_string(), cell.clone(), phase));
549 cell
550 }
551
552 /// Whether `name` has been declared at all.
553 pub fn contains(&self, name: &str) -> bool {
554 self.names
555 .borrow()
556 .iter()
557 .any(|(bound, _, _)| bound == name)
558 }
559}
560
561impl Trace for LocalVars {
562 fn trace(&self, tracer: &mut Tracer) {
563 for (_, cell, _) in self.names.borrow().iter() {
564 tracer.visit(cell);
565 }
566 }
567}
568
569impl Trace for ClosureEnv {
570 fn trace(&self, tracer: &mut Tracer) {
571 for cell in &self.cells {
572 tracer.visit(cell);
573 }
574 if let Some(scope) = &self.eval_scope {
575 tracer.visit(scope);
576 }
577 if let Some(local_vars) = &self.local_vars {
578 tracer.visit(local_vars);
579 }
580 }
581}
582
583/// The bindings a direct `eval` made visible, as name → cell.
584///
585/// Only bindings that already live in a cell appear here, because sharing their
586/// identity is the point: a closure created by the eval must observe later writes to
587/// the same variable, and a copy would not. The compiler puts every binding of a
588/// function that contains a direct `eval` into a cell, so in practice that is all of
589/// them.
590pub struct EvalScope {
591 /// In lookup order: the innermost binding for a name first.
592 pub names: Vec<(String, Gc<Cell>)>,
593}
594
595impl EvalScope {
596 /// The cell `name` resolves to, if this scope binds it.
597 pub fn get(&self, name: &str) -> Option<&Gc<Cell>> {
598 self.names
599 .iter()
600 .find(|(bound, _)| bound == name)
601 .map(|(_, cell)| cell)
602 }
603}
604
605impl Trace for EvalScope {
606 fn trace(&self, tracer: &mut Tracer) {
607 for (_, cell) in &self.names {
608 tracer.visit(cell);
609 }
610 }
611}
612
613/// What kind of object this is.
614pub enum ObjectKind {
615 /// An ordinary object: only its property table.
616 Ordinary,
617 /// An array: dense elements plus a property table for everything else.
618 Array {
619 /// The dense prefix of the array.
620 elements: Vec<Value>,
621 },
622 /// A function or a class constructor.
623 Function(Callable),
624 /// A regular expression: the compiled pattern, plus `lastIndex` as a property.
625 RegExp(crate::builtins::regexp::RegExpData),
626 /// A `DisposableStack` or `AsyncDisposableStack`: the resources it holds.
627 DisposableStack(crate::builtins::disposable::StackState),
628 /// An `ArrayBuffer`: a byte range that typed-array views share.
629 ///
630 /// The bytes sit behind an `Rc<RefCell<…>>` rather than in the object so that every view
631 /// of the buffer sees the same storage; the *views* hold the `Gc<JsObject>` of this
632 /// buffer, which is what keeps it alive and what the collector traces.
633 ArrayBuffer(std::rc::Rc<std::cell::RefCell<BufferStorage>>),
634 /// A `Map` or a `Set`: insertion-ordered entries with `SameValueZero` key equality.
635 ///
636 /// One variant for both, because a `Set` is exactly a `Map` whose value is unused — the
637 /// difference is a flag, and `is_set` is what makes `entries` yield `[v, v]` pairs.
638 Collection {
639 /// The entries, in insertion order.
640 entries: Vec<(Value, Value)>,
641 /// Whether this is a `Set` rather than a `Map`.
642 is_set: bool,
643 },
644 /// A typed-array view: a window onto an `ArrayBuffer`.
645 TypedArray {
646 /// The buffer whose bytes this view reads.
647 buffer: Gc<JsObject>,
648 /// What one element is.
649 element: crate::builtins::typedarray::ElementType,
650 /// Byte offset of element zero.
651 offset: usize,
652 /// How many elements the view exposes.
653 length: usize,
654 },
655 /// A generator object: a detached frame plus how far it got.
656 ///
657 /// The frame lives here rather than in the interpreter because a suspended generator
658 /// has to keep its locals and operand stack alive for as long as the script can reach
659 /// the generator object — and the collector has to see them, which it only does for
660 /// things hanging off a `Gc`.
661 Generator(Box<crate::interp::GeneratorState>),
662 /// A `Proxy`: a stand-in that forwards every internal method to a target through a
663 /// handler's traps.
664 ///
665 /// The state sits behind an `Rc` because `Proxy.revocable` hands the script a
666 /// `revoke` function that has to reach *this* proxy's two slots later, from a call
667 /// site that has no pointer to the object. Revoking clears them, which also drops
668 /// the collector's references to the target and the handler.
669 Proxy(ProxyRef),
670 /// A `Promise`.
671 ///
672 /// The state sits behind an `Rc` for the same reason a proxy's slots do: the
673 /// `resolve`/`reject` pair handed to an executor has to settle *this* promise later,
674 /// and those are function objects with no pointer back to it otherwise.
675 Promise(PromiseRef),
676}
677
678/// The two slots of a proxy, shared with its `revoke` function.
679///
680/// `None` in both slots means revoked: every operation then throws a `TypeError`, and
681/// the target and handler are no longer reachable — which is the whole point of
682/// `Proxy.revocable`.
683#[derive(Default)]
684pub struct ProxyState {
685 /// The object the traps receive, or `None` once revoked.
686 pub target: Option<Gc<JsObject>>,
687 /// The trap table, or `None` once revoked.
688 pub handler: Option<Value>,
689}
690
691/// A `Promise`'s state, shared between the promise object and its resolve/reject
692/// functions.
693///
694/// Behind an `Rc` for the same reason a proxy's slots are: the `resolve` and `reject`
695/// functions handed to an executor have to settle *this* promise later, from a call site
696/// that only has the function.
697pub struct PromiseState {
698 /// Pending, or the value it settled with.
699 pub status: PromiseStatus,
700 /// The `then` reactions waiting on it, in registration order.
701 pub reactions: Vec<PromiseReaction>,
702 /// Whether a rejection has been seen by a handler.
703 ///
704 /// A rejection that never is becomes an unhandled-rejection report, which the
705 /// reference makes fatal at the end of the job queue.
706 pub handled: bool,
707}
708
709impl Default for PromiseState {
710 fn default() -> Self {
711 PromiseState {
712 status: PromiseStatus::Pending,
713 reactions: Vec::new(),
714 handled: false,
715 }
716 }
717}
718
719/// What a `Promise` combinator does when its elements settle.
720#[derive(Debug, Clone, Copy, PartialEq, Eq)]
721pub enum CombinatorKind {
722 /// The first rejection wins, otherwise an array in input order.
723 All,
724 /// Never rejects; each entry is `{status, value}` or `{status, reason}`.
725 AllSettled,
726 /// The first fulfilment wins, otherwise an `AggregateError`.
727 Any,
728 /// Whichever element settles first.
729 Race,
730}
731
732/// Which of §27.2.1.2's three states a promise is in.
733#[derive(Clone, Default)]
734pub enum PromiseStatus {
735 /// Neither settled: reactions queue up.
736 #[default]
737 Pending,
738 /// Settled with a value, which no further settle may change.
739 Fulfilled(Value),
740 /// Settled with a reason.
741 Rejected(Value),
742}
743
744/// One `then` registration.
745#[derive(Clone)]
746pub struct PromiseReaction {
747 /// Called with the value if the promise fulfils.
748 pub on_fulfilled: Option<Value>,
749 /// Called with the reason if it rejects.
750 pub on_rejected: Option<Value>,
751 /// The promise to settle with whatever the handler returns.
752 pub promise: Gc<JsObject>,
753}
754
755impl Trace for PromiseState {
756 fn trace(&self, tracer: &mut Tracer) {
757 match &self.status {
758 PromiseStatus::Pending => {}
759 PromiseStatus::Fulfilled(value) | PromiseStatus::Rejected(value) => value.trace(tracer),
760 }
761 for reaction in &self.reactions {
762 if let Some(on_fulfilled) = &reaction.on_fulfilled {
763 on_fulfilled.trace(tracer);
764 }
765 if let Some(on_rejected) = &reaction.on_rejected {
766 on_rejected.trace(tracer);
767 }
768 tracer.visit(&reaction.promise);
769 }
770 }
771}
772
773/// A promise's shareable state.
774pub type PromiseRef = std::rc::Rc<std::cell::RefCell<PromiseState>>;
775
776/// A proxy's mutable state, shared between the proxy object and its `revoke`.
777pub type ProxyRef = std::rc::Rc<std::cell::RefCell<ProxyState>>;
778
779impl Trace for ProxyState {
780 fn trace(&self, tracer: &mut Tracer) {
781 if let Some(target) = &self.target {
782 tracer.visit(target);
783 }
784 if let Some(handler) = &self.handler {
785 handler.trace(tracer);
786 }
787 }
788}
789
790impl Trace for ObjectKind {
791 fn trace(&self, tracer: &mut Tracer) {
792 match self {
793 // Nothing in a compiled pattern is a GC value: it holds characters and
794 // integers only.
795 ObjectKind::RegExp(_) => {}
796 ObjectKind::DisposableStack(state) => state.trace(tracer),
797 // A buffer's bytes are plain bytes and hold no GC values; a view keeps its
798 // buffer alive through the `Gc` it carries.
799 ObjectKind::ArrayBuffer(_) => {}
800 ObjectKind::TypedArray { buffer, .. } => tracer.visit(buffer),
801 ObjectKind::Collection { entries, .. } => {
802 for (key, value) in entries {
803 key.trace(tracer);
804 value.trace(tracer);
805 }
806 }
807 ObjectKind::Ordinary => {}
808 ObjectKind::Array { elements } => {
809 for element in elements {
810 element.trace(tracer);
811 }
812 }
813 ObjectKind::Function(callable) => callable.trace(tracer),
814 ObjectKind::Generator(state) => state.trace(tracer),
815 ObjectKind::Proxy(state) => state.borrow().trace(tracer),
816 ObjectKind::Promise(state) => state.borrow().trace(tracer),
817 }
818 }
819}
820
821/// The mutable half of an object.
822/// What a property is keyed by.
823///
824/// A string and a symbol are separate key spaces even when they look alike: `o["a"]`
825/// and `o[Symbol("a")]` are two properties, and `o[Symbol("a")]` is not reachable by
826/// any string. Symbols are also invisible to `for`/`Object.keys`/`JSON.stringify`,
827/// which is the whole point of them, so the distinction has to survive into the
828/// property table rather than being flattened into a name.
829#[derive(Clone)]
830pub enum PropertyKey {
831 /// An ordinary string key, held as WTF-8 so a key containing an unpaired surrogate
832 /// addresses one property rather than colliding with its `U+FFFD` replacement.
833 String(crate::value::Wtf8),
834 /// A symbol key.
835 Symbol(Gc<JsSymbol>),
836}
837
838impl PropertyKey {
839 /// The key as a string, for the operations that only accept one.
840 ///
841 /// A symbol has no string form that would address it, so this answers `None` —
842 /// which is what makes `get_field` on a symbol key fall through to the general
843 /// path instead of silently reading a same-named string property.
844 pub fn as_str(&self) -> Option<&str> {
845 match self {
846 PropertyKey::String(text) => text.as_str(),
847 PropertyKey::Symbol(_) => None,
848 }
849 }
850
851 /// The key's bytes, which a string key always has and a symbol never does.
852 pub fn as_wtf8(&self) -> Option<&crate::value::Wtf8> {
853 match self {
854 PropertyKey::String(text) => Some(text),
855 PropertyKey::Symbol(_) => None,
856 }
857 }
858
859 /// Whether this is an ordinary string key.
860 pub fn is_symbol(&self) -> bool {
861 matches!(self, PropertyKey::Symbol(_))
862 }
863}
864
865impl fmt::Display for PropertyKey {
866 /// How a key reads inside an error message: strings bare, symbols in their
867 /// `Symbol(description)` form.
868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
869 match self {
870 PropertyKey::String(text) => write!(f, "{}", text.to_string_lossy()),
871 PropertyKey::Symbol(symbol) => write!(f, "{}", symbol.to_display_string()),
872 }
873 }
874}
875
876impl PartialEq for PropertyKey {
877 fn eq(&self, other: &Self) -> bool {
878 match (self, other) {
879 (PropertyKey::String(a), PropertyKey::String(b)) => a == b,
880 // Symbols compare by identity, never by description.
881 (PropertyKey::Symbol(a), PropertyKey::Symbol(b)) => a.ptr_eq(b),
882 _ => false,
883 }
884 }
885}
886
887impl From<&str> for PropertyKey {
888 fn from(text: &str) -> PropertyKey {
889 PropertyKey::String(crate::value::Wtf8::new(text))
890 }
891}
892
893impl From<String> for PropertyKey {
894 fn from(text: String) -> PropertyKey {
895 PropertyKey::String(crate::value::Wtf8::new(text))
896 }
897}
898
899impl From<crate::value::Wtf8> for PropertyKey {
900 fn from(text: crate::value::Wtf8) -> PropertyKey {
901 PropertyKey::String(text)
902 }
903}
904
905impl Trace for PropertyKey {
906 fn trace(&self, tracer: &mut Tracer) {
907 if let PropertyKey::Symbol(symbol) = self {
908 tracer.visit(symbol);
909 }
910 }
911}
912
913/// An object's mutable state: its prototype, property table and internal slots.
914pub struct ObjectData {
915 /// The prototype, or `None` for `Object.prototype` and for a null-prototype
916 /// object created with `Object.create(null)`.
917 pub proto: Option<Gc<JsObject>>,
918 /// Properties in definition order, string and symbol keys interleaved.
919 pub props: Vec<(PropertyKey, Property)>,
920 /// What kind of object this is.
921 pub kind: ObjectKind,
922 /// Whether new properties may be added. `Object.preventExtensions`, `seal` and
923 /// `freeze` clear it, and nothing clears it back.
924 pub extensible: bool,
925 /// Whether array elements may be replaced.
926 ///
927 /// Elements are not in the property table, so their attributes need somewhere to
928 /// live; `Object.freeze` clears this and `Object.isFrozen` reads it. A *single*
929 /// non-writable element is recorded in the property table instead, which is what
930 /// `Object.defineProperty(a, "3", {configurable: false})` does.
931 pub elements_writable: bool,
932 /// The object a method was defined on, which is what `super` resolves against.
933 ///
934 /// Kept here rather than as a property because it is not observable: the spec calls
935 /// it `[[HomeObject]]` and no script can read it, so putting it in the property
936 /// table would leak it to `Object.getOwnPropertyNames` and `JSON.stringify`.
937 pub home_object: Option<Gc<JsObject>>,
938 /// Whether this function is a class constructor, which may not be called without
939 /// `new`.
940 pub class_constructor: bool,
941}
942
943impl Trace for ObjectData {
944 fn trace(&self, tracer: &mut Tracer) {
945 if let Some(proto) = &self.proto {
946 tracer.visit(proto);
947 }
948 if let Some(home) = &self.home_object {
949 tracer.visit(home);
950 }
951 for (key, property) in &self.props {
952 key.trace(tracer);
953 property.trace(tracer);
954 }
955 self.kind.trace(tracer);
956 }
957}
958
959/// A JavaScript object.
960///
961/// The interior mutability is what makes `const o = {}; o.x = 1` work: the handle
962/// is immutable, the object it points at is not.
963pub struct JsObject {
964 data: RefCell<ObjectData>,
965}
966
967impl JsObject {
968 fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
969 JsObject {
970 data: RefCell::new(ObjectData {
971 proto,
972 props: Vec::new(),
973 kind,
974 extensible: true,
975 elements_writable: true,
976 home_object: None,
977 class_constructor: false,
978 }),
979 }
980 }
981
982 /// An ordinary object with the given prototype.
983 pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
984 Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
985 }
986
987 /// An array with the given prototype and initial capacity.
988 pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
989 Gc::new(
990 heap,
991 JsObject::new(
992 ObjectKind::Array {
993 elements: Vec::with_capacity(capacity),
994 },
995 proto,
996 ),
997 )
998 }
999
1000 /// A callable object.
1001 pub fn function(
1002 heap: &js_gc::Heap,
1003 proto: Option<Gc<JsObject>>,
1004 callable: Callable,
1005 ) -> Gc<JsObject> {
1006 Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
1007 }
1008
1009 /// Run `f` with the object's data borrowed.
1010 pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
1011 f(&self.data.borrow())
1012 }
1013
1014 /// Run `f` with the object's data mutably borrowed.
1015 pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
1016 f(&mut self.data.borrow_mut())
1017 }
1018
1019 /// Whether this object can be called.
1020 ///
1021 /// Covers every [`Callable`] variant, `Bound` included: `typeof bound ===
1022 /// "function"` and `bound()` works, so from a script's point of view a bound
1023 /// function is a function.
1024 pub fn is_callable(&self) -> bool {
1025 match &self.data.borrow().kind {
1026 ObjectKind::Function(_) => true,
1027 // A proxy is callable exactly when its target is: the `apply` trap is what a
1028 // call to it runs, and a target that cannot be called has nothing to forward
1029 // to. This is what makes `typeof proxyOfFunction === "function"`.
1030 ObjectKind::Proxy(state) => state
1031 .borrow()
1032 .target
1033 .as_ref()
1034 .is_some_and(|target| target.is_callable()),
1035 _ => false,
1036 }
1037 }
1038
1039 /// Whether the target of this proxy can be constructed.
1040 pub fn is_constructor(&self) -> bool {
1041 match &self.data.borrow().kind {
1042 ObjectKind::Function(_) => true,
1043 ObjectKind::Proxy(state) => state
1044 .borrow()
1045 .target
1046 .as_ref()
1047 .is_some_and(|target| target.is_callable()),
1048 _ => false,
1049 }
1050 }
1051
1052 /// This object's proxy slots, when it is one (revoked or not).
1053 pub fn proxy_state(&self) -> Option<ProxyRef> {
1054 match &self.data.borrow().kind {
1055 ObjectKind::Proxy(state) => Some(state.clone()),
1056 _ => None,
1057 }
1058 }
1059
1060 /// A proxy over `target` reading its traps from `handler`.
1061 ///
1062 /// The prototype stays empty on purpose: `[[GetPrototypeOf]]` on a proxy forwards to
1063 /// the target through the `getPrototypeOf` trap, so copying the target's prototype
1064 /// here would be a second, disagreeing source of truth.
1065 pub fn proxy(heap: &js_gc::Heap, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
1066 Gc::new(
1067 heap,
1068 JsObject::new(
1069 ObjectKind::Proxy(std::rc::Rc::new(std::cell::RefCell::new(ProxyState {
1070 target: Some(target),
1071 handler: Some(handler),
1072 }))),
1073 None,
1074 ),
1075 )
1076 }
1077
1078 /// The prototype.
1079 pub fn proto(&self) -> Option<Gc<JsObject>> {
1080 self.data.borrow().proto.clone()
1081 }
1082
1083 /// Replace the prototype.
1084 pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
1085 self.data.borrow_mut().proto = proto;
1086 }
1087
1088 /// The object a method was defined on, for `super` to resolve against.
1089 pub fn home_object(&self) -> Option<Gc<JsObject>> {
1090 self.data.borrow().home_object.clone()
1091 }
1092
1093 /// Record the object a method was defined on.
1094 pub fn set_home_object(&self, home: Option<Gc<JsObject>>) {
1095 self.data.borrow_mut().home_object = home;
1096 }
1097
1098 /// Whether this is a class constructor.
1099 pub fn is_class_constructor(&self) -> bool {
1100 self.data.borrow().class_constructor
1101 }
1102
1103 /// Mark this function as a class constructor.
1104 pub fn set_class_constructor(&self, yes: bool) {
1105 self.data.borrow_mut().class_constructor = yes;
1106 }
1107
1108 /// The elements of an array object, if this is one.
1109 pub fn array_elements(&self) -> Option<Vec<Value>> {
1110 match &self.data.borrow().kind {
1111 ObjectKind::Array { elements } => Some(elements.clone()),
1112 _ => None,
1113 }
1114 }
1115
1116 /// Every own key with its descriptor, array indices included.
1117 ///
1118 /// [`JsObject::own_property_keys`] answers the same question without the
1119 /// descriptors; a proxy invariant needs both at once, because it has to check the
1120 /// *value* of a key it is told about and the presence of a key it is not.
1121 pub fn property_entries(&self) -> Vec<(PropertyKey, Property)> {
1122 let data = self.data.borrow();
1123 let mut out: Vec<(PropertyKey, Property)> = data.props.to_vec();
1124 // An array's elements live in their own vector rather than the property table, so
1125 // they have to be synthesized — with the attributes an ordinary element has.
1126 if let ObjectKind::Array { elements } = &data.kind {
1127 for (index, element) in elements.iter().enumerate() {
1128 if matches!(element, Value::Hole) {
1129 continue;
1130 }
1131 let key = PropertyKey::from(index.to_string());
1132 if !out.iter().any(|(existing, _)| *existing == key) {
1133 out.push((key, Property::data(element.clone())));
1134 }
1135 }
1136 }
1137 // `length` is own on an array without being in the property table either. It is
1138 // writable, non-enumerable and — the part proxy invariants care about —
1139 // non-configurable, so leaving it out let a handler hide or redefine it.
1140 if matches!(data.kind, ObjectKind::Array { .. })
1141 && let Some(length) = self.array_length()
1142 {
1143 let key = PropertyKey::from("length");
1144 if !out.iter().any(|(existing, _)| *existing == key) {
1145 out.push((
1146 key,
1147 Property {
1148 value: Some(Value::Int(length as i32)),
1149 writable: true,
1150 enumerable: false,
1151 configurable: false,
1152 getter: None,
1153 setter: None,
1154 },
1155 ));
1156 }
1157 }
1158 out
1159 }
1160
1161 /// Whether this object has array elements at all.
1162 pub fn is_array(&self) -> bool {
1163 match &self.data.borrow().kind {
1164 ObjectKind::Array { .. } => true,
1165 // `Array.isArray` is specified to see *through* a proxy: it forwards
1166 // `[[Get]]`/prototype checks to the target, and the answer for a proxy of an
1167 // array is yes.
1168 ObjectKind::Proxy(state) => state
1169 .borrow()
1170 .target
1171 .as_ref()
1172 .is_some_and(|target| target.is_array()),
1173 _ => false,
1174 }
1175 }
1176
1177 /// `length` for an array, reading it out of the element vector.
1178 /// The compiled pattern, when this object is a `RegExp`.
1179 pub fn regexp(&self) -> Option<crate::builtins::regexp::RegExpData> {
1180 match &self.data.borrow().kind {
1181 ObjectKind::RegExp(data) => Some(data.clone()),
1182 _ => None,
1183 }
1184 }
1185
1186 /// The held resources, when this object is a `DisposableStack`.
1187 pub fn disposable_stack(&self) -> Option<crate::builtins::disposable::StackState> {
1188 match &self.data.borrow().kind {
1189 ObjectKind::DisposableStack(state) => Some(state.clone()),
1190 _ => None,
1191 }
1192 }
1193
1194 /// Make this object a `DisposableStack` holding `state`.
1195 pub fn set_disposable_stack(&self, state: crate::builtins::disposable::StackState) {
1196 self.data.borrow_mut().kind = ObjectKind::DisposableStack(state);
1197 }
1198
1199 /// Make this object a `RegExp` carrying `data`.
1200 pub fn set_regexp(&self, data: crate::builtins::regexp::RegExpData) {
1201 self.data.borrow_mut().kind = ObjectKind::RegExp(data);
1202 }
1203
1204 /// Whether this object is a `RegExp`.
1205 pub fn is_regexp(&self) -> bool {
1206 matches!(self.data.borrow().kind, ObjectKind::RegExp(_))
1207 }
1208
1209 /// An array's element count, when this object is an array.
1210 pub fn array_length(&self) -> Option<usize> {
1211 match &self.data.borrow().kind {
1212 ObjectKind::Array { elements } => Some(elements.len()),
1213 _ => None,
1214 }
1215 }
1216
1217 /// Read one array element.
1218 pub fn array_get(&self, index: usize) -> Option<Value> {
1219 match &self.data.borrow().kind {
1220 ObjectKind::Array { elements } => elements.get(index).cloned(),
1221 _ => None,
1222 }
1223 }
1224
1225 /// Append to an array and return the new length.
1226 pub fn array_push(&self, value: Value) -> usize {
1227 match &mut self.data.borrow_mut().kind {
1228 ObjectKind::Array { elements } => {
1229 elements.push(value);
1230 elements.len()
1231 }
1232 _ => 0,
1233 }
1234 }
1235
1236 /// Store into an array, and return whether the write happened.
1237 ///
1238 /// The gap an out-of-range store leaves behind is filled with [`Value::Hole`], not
1239 /// `undefined`: `a = [1]; a[3] = 4` has holes at 1 and 2, which `forEach` skips
1240 /// and the debug printer reports. A store *of* `undefined` is a real element.
1241 pub fn array_set(&self, index: usize, value: Value) -> bool {
1242 match &mut self.data.borrow_mut().kind {
1243 ObjectKind::Array { elements } => {
1244 if index >= elements.len() {
1245 elements.resize(index + 1, Value::Hole);
1246 }
1247 elements[index] = value;
1248 true
1249 }
1250 _ => false,
1251 }
1252 }
1253
1254 /// Store an element, honouring its attributes, reporting whether it happened.
1255 ///
1256 /// Array methods that write back (`sort`, `reverse`, `splice`, …) use this rather
1257 /// than [`Self::array_set`]: the spec has them go through `[[Set]]`, so a frozen
1258 /// element makes them throw instead of being quietly overwritten.
1259 pub fn array_store(&self, index: usize, value: Value) -> bool {
1260 if self.elements_writable() {
1261 return self.array_set(index, value);
1262 }
1263 if self.element_attributes(index as u32).is_some() {
1264 // A recorded descriptor decides on its own.
1265 return !self.element_is_locked(index as u32) && self.array_set(index, value);
1266 }
1267 false
1268 }
1269
1270 /// Store `value` as a plain element without creating holes, used by `push`.
1271 pub fn array_push_hole(&self) -> bool {
1272 match &mut self.data.borrow_mut().kind {
1273 ObjectKind::Array { elements } => {
1274 elements.push(Value::Hole);
1275 true
1276 }
1277 _ => false,
1278 }
1279 }
1280
1281 /// Set the length of an array, truncating or extending with holes.
1282 ///
1283 /// `a.length = 5` on a two-element array leaves three holes, so the fill value is
1284 /// [`Value::Hole`] rather than `undefined`.
1285 pub fn array_set_length(&self, length: usize) -> bool {
1286 match &mut self.data.borrow_mut().kind {
1287 ObjectKind::Array { elements } => {
1288 elements.resize(length, Value::Hole);
1289 true
1290 }
1291 _ => false,
1292 }
1293 }
1294
1295 /// Truncate an array to `length` elements without extending it.
1296 ///
1297 /// This is what `arr.length = n` does for `n` smaller than the current length;
1298 /// it is separate from [`Self::array_set_length`] because growing an array by
1299 /// assignment produces holes, which are indistinguishable from `undefined`
1300 /// here.
1301 pub fn array_truncate(&self, length: usize) -> bool {
1302 match &mut self.data.borrow_mut().kind {
1303 ObjectKind::Array { elements } => {
1304 if length < elements.len() {
1305 elements.truncate(length);
1306 }
1307 true
1308 }
1309 _ => false,
1310 }
1311 }
1312
1313 /// The own data property `key`, if there is one.
1314 pub fn own_property_key(&self, key: &PropertyKey) -> Option<Property> {
1315 let data = self.data.borrow();
1316 data.props
1317 .iter()
1318 .find(|(existing, _)| existing == key)
1319 .map(|(_, property)| property.clone())
1320 }
1321
1322 /// The own data property `name`, if there is one.
1323 pub fn own_property(&self, name: &str) -> Option<Property> {
1324 self.own_property_key(&PropertyKey::from(name))
1325 }
1326
1327 /// Whether the object has an own property `key`.
1328 pub fn has_own_key(&self, key: &PropertyKey) -> bool {
1329 let data = self.data.borrow();
1330 data.props.iter().any(|(existing, _)| existing == key)
1331 }
1332
1333 /// Whether the object has an own property `name`.
1334 pub fn has_own(&self, name: &str) -> bool {
1335 self.has_own_key(&PropertyKey::from(name))
1336 }
1337
1338 /// Define or replace an own property, keeping the original position when the
1339 /// key already exists.
1340 pub fn define_key(&self, key: &PropertyKey, property: Property) {
1341 let mut data = self.data.borrow_mut();
1342 match data.props.iter_mut().find(|(existing, _)| existing == key) {
1343 Some((_, slot)) => *slot = property,
1344 None => data.props.push((key.clone(), property)),
1345 }
1346 }
1347
1348 /// Define or replace an own property under a string key.
1349 pub fn define(&self, name: &str, property: Property) {
1350 self.define_key(&PropertyKey::from(name), property);
1351 }
1352
1353 /// Define an own data property, with the default attributes.
1354 ///
1355 /// This *creates*: on an existing property it overwrites the attributes too, so
1356 /// it is the wrong call for a plain assignment. Use [`Self::write_value`] for that.
1357 pub fn define_data(&self, name: &str, value: Value) {
1358 self.define(name, Property::data(value));
1359 }
1360
1361 /// Define an own data property under `key`.
1362 pub fn define_data_key(&self, key: &PropertyKey, value: Value) {
1363 self.define_key(key, Property::data(value));
1364 }
1365
1366 /// Store a value into an existing own data property, keeping its attributes.
1367 ///
1368 /// Returns `false` when the property is absent, is an accessor, or is not
1369 /// writable. An assignment has to go through this rather than
1370 /// [`Self::define_data`], because redefining is how a non-configurable global
1371 /// silently became configurable again and started answering `delete` with `true`.
1372 pub fn write_value(&self, name: &str, value: Value) -> bool {
1373 self.write_value_key(&PropertyKey::from(name), value)
1374 }
1375
1376 /// Store a value into an existing own data property under `key`.
1377 pub fn write_value_key(&self, key: &PropertyKey, value: Value) -> bool {
1378 let mut data = self.data.borrow_mut();
1379 let Some((_, property)) = data.props.iter_mut().find(|(existing, _)| existing == key)
1380 else {
1381 return false;
1382 };
1383 if property.is_accessor() || !property.writable {
1384 return false;
1385 }
1386 property.value = Some(value);
1387 true
1388 }
1389
1390 /// Delete an own property, reporting whether it was there and removable.
1391 pub fn delete(&self, name: &str) -> bool {
1392 self.delete_key(&PropertyKey::from(name))
1393 }
1394
1395 /// Delete an own property under `key`.
1396 pub fn delete_key(&self, key: &PropertyKey) -> bool {
1397 let mut data = self.data.borrow_mut();
1398 match data.props.iter().position(|(existing, _)| existing == key) {
1399 Some(index) => {
1400 if data.props[index].1.configurable {
1401 data.props.remove(index);
1402 true
1403 } else {
1404 false
1405 }
1406 }
1407 None => true,
1408 }
1409 }
1410
1411 /// Whether new properties may be added.
1412 pub fn is_extensible(&self) -> bool {
1413 self.data.borrow().extensible
1414 }
1415
1416 /// Make the object non-extensible.
1417 pub fn set_extensible(&self, extensible: bool) {
1418 self.data.borrow_mut().extensible = extensible;
1419 }
1420
1421 /// Whether array elements may be replaced.
1422 pub fn elements_writable(&self) -> bool {
1423 self.data.borrow().elements_writable
1424 }
1425
1426 /// Make array elements read-only, as `Object.freeze` does.
1427 pub fn set_elements_writable(&self, writable: bool) {
1428 self.data.borrow_mut().elements_writable = writable;
1429 }
1430
1431 /// The attributes recorded for an array index, if `defineProperty` set any.
1432 pub fn element_attributes(&self, index: u32) -> Option<Property> {
1433 self.own_property(&index.to_string())
1434 }
1435
1436 /// Whether a store at `index` would be rejected.
1437 ///
1438 /// An element is locked either by `Object.freeze` on the whole object or by a
1439 /// non-configurable, non-writable descriptor recorded for that one index.
1440 pub fn element_is_locked(&self, index: u32) -> bool {
1441 if !self.elements_writable() {
1442 return true;
1443 }
1444 self.element_attributes(index)
1445 .is_some_and(|property| !property.writable && !property.configurable)
1446 }
1447
1448 /// The own property *names*, in definition order. Symbol keys are excluded:
1449 /// `Object.keys` and `for…in` cannot see them.
1450 pub fn own_keys(&self) -> Vec<crate::value::Wtf8> {
1451 self.data
1452 .borrow()
1453 .props
1454 .iter()
1455 .filter_map(|(key, _)| key.as_wtf8().cloned())
1456 .collect()
1457 }
1458
1459 /// The own *enumerable* property names, in definition order.
1460 pub fn own_enumerable_keys(&self) -> Vec<crate::value::Wtf8> {
1461 self.data
1462 .borrow()
1463 .props
1464 .iter()
1465 .filter(|(_, property)| property.enumerable)
1466 .filter_map(|(key, _)| key.as_wtf8().cloned())
1467 .collect()
1468 }
1469
1470 /// The own symbol keys, in definition order, for `Object.getOwnPropertySymbols`.
1471 pub fn own_symbol_keys(&self) -> Vec<Gc<JsSymbol>> {
1472 self.data
1473 .borrow()
1474 .props
1475 .iter()
1476 .filter_map(|(key, _)| match key {
1477 PropertyKey::Symbol(symbol) => Some(symbol.clone()),
1478 PropertyKey::String(_) => None,
1479 })
1480 .collect()
1481 }
1482
1483 /// Every own key, strings first then symbols — the order `Reflect.ownKeys` and
1484 /// `Object.getOwnPropertyDescriptors` report, and the order `JSON.stringify`
1485 /// walks before it skips the symbols.
1486 pub fn own_property_keys(&self) -> Vec<PropertyKey> {
1487 let data = self.data.borrow();
1488 let mut strings: Vec<PropertyKey> = Vec::new();
1489 let mut symbols: Vec<PropertyKey> = Vec::new();
1490 for (key, _) in &data.props {
1491 if key.is_symbol() {
1492 symbols.push(key.clone());
1493 } else {
1494 strings.push(key.clone());
1495 }
1496 }
1497 strings.extend(symbols);
1498 strings
1499 }
1500
1501 /// The prototype chain, starting with the prototypes of this object.
1502 pub fn chain(&self) -> Vec<Gc<JsObject>> {
1503 let mut out = Vec::new();
1504 let mut proto = self.proto();
1505 while let Some(object) = proto {
1506 proto = object.proto();
1507 out.push(object);
1508 }
1509 out
1510 }
1511}
1512
1513/// Whether two prototypes are the same one, `None` included.
1514///
1515/// A proxy's prototype invariants have to compare "no prototype" against "no
1516/// prototype" without unwrapping either side first.
1517pub(crate) fn same_proto(a: Option<&Gc<JsObject>>, b: Option<&Gc<JsObject>>) -> bool {
1518 match (a, b) {
1519 (None, None) => true,
1520 (Some(a), Some(b)) => a.ptr_eq(b),
1521 _ => false,
1522 }
1523}
1524
1525/// Walk the prototype chain from `object` looking for `name`.
1526///
1527/// Returns the object that owns the property along with the property itself. The
1528/// owner matters for a store: an inherited accessor is invoked on the receiver,
1529/// while an inherited *data* property is shadowed by a new own property.
1530pub fn lookup_key(object: &Gc<JsObject>, key: &PropertyKey) -> Option<(Gc<JsObject>, Property)> {
1531 if let Some(property) = object.own_property_key(key) {
1532 return Some((object.clone(), property));
1533 }
1534 for ancestor in object.chain() {
1535 if let Some(property) = ancestor.own_property_key(key) {
1536 return Some((ancestor, property));
1537 }
1538 }
1539 None
1540}
1541
1542/// [`lookup_key`] for a string key.
1543pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
1544 lookup_key(object, &PropertyKey::from(name))
1545}
1546
1547/// The array index a property key names, if it names one.
1548///
1549/// A key is an index when it is the canonical decimal spelling of an integer below
1550/// `2^32 - 1` — the same rule the atom table uses to decide whether a key is a
1551/// tagged index. `"01"` and `"-1"` are ordinary string keys.
1552pub fn array_index(key: &str) -> Option<u32> {
1553 if key.is_empty() || key.len() > 10 {
1554 return None;
1555 }
1556 let bytes = key.as_bytes();
1557 if !bytes.iter().all(u8::is_ascii_digit) {
1558 return None;
1559 }
1560 if bytes[0] == b'0' && bytes.len() != 1 {
1561 return None;
1562 }
1563 let value: u32 = key.parse().ok()?;
1564 // `2^32 - 1` is reserved for the array length, so it is not an index.
1565 (value < u32::MAX).then_some(value)
1566}
1567
1568impl Trace for JsObject {
1569 fn trace(&self, tracer: &mut Tracer) {
1570 self.data.borrow().trace(tracer);
1571 }
1572}