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