1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! The performance-era object: a [`Shape`] (hidden class) paired with a flat
//! vector of [`NanBox`] value slots (`ROADMAP.md` §3).
//!
//! This composes the three object-model pillars. An object holds:
//! - a shared, immutable [`Shape`] describing *where* each property lives, and
//! - a dense `Vec<NanBox>` holding the property *values* by slot index.
//!
//! Reading a property is a shape lookup (cacheable on the shape pointer) plus a
//! slot load; adding one transitions the shape and pushes a slot. Objects of the
//! same structure share a shape, so the per-object cost is just the value
//! vector — and a handle into a [`Heap`] is how other values point at it.
//!
//! [`Shape`]: crate::shape::Shape
//! [`NanBox`]: crate::nanbox::NanBox
//! [`Heap`]: crate::heap::Heap
//!
//! Pure, safe `alloc`-only Rust; this is the representation the bytecode VM will
//! migrate onto once the GC that manages the heap lands.
use crate::nanbox::NanBox;
use crate::shape::Shape;
use alloc::rc::Rc;
use alloc::string::ToString;
use alloc::vec::Vec;
/// The numeric value of `k` if it is a canonical array-index key (a non-negative
/// integer `< 2^32 - 1` whose decimal form is exactly `k`), else `None`.
fn array_index(k: &str) -> Option<u32> {
k.parse::<u32>()
.ok()
.filter(|n| *n < u32::MAX && n.to_string() == k)
}
/// A property-bearing object: a hidden-class shape plus its value slots, with an
/// optional side list of accessor (getter/setter) properties.
pub struct Object {
shape: Rc<Shape>,
slots: Vec<NanBox>,
/// Accessor properties: `(name, getter, setter)`, both held as value
/// handles (`undefined` when absent). Kept out of the shape's slot layout.
accessors: Vec<(alloc::boxed::Box<str>, NanBox, NanBox)>,
/// Own keys that are **non-enumerable** (e.g. class methods): present in the
/// slots and readable, but hidden from `Object.keys`/spread/`for-in`/JSON.
hidden: Vec<alloc::boxed::Box<str>>,
/// Own keys that are **non-writable** (`defineProperty` with
/// `writable: false`): writes are silently ignored.
readonly: Vec<alloc::boxed::Box<str>>,
/// Own keys that are **non-configurable** (`defineProperty` with
/// `configurable: false`): they cannot be deleted.
non_configurable: Vec<alloc::boxed::Box<str>>,
/// Whether the object is frozen (`Object.freeze`): no new properties and no
/// writes to existing ones.
frozen: bool,
/// Whether new properties may be added (`Object.preventExtensions` clears it).
extensible: bool,
/// Whether the object is sealed (`Object.seal`): no new properties and no
/// deletions, but existing writable properties may still change.
sealed: bool,
/// The class this object was instantiated from (for `instanceof`), if any.
class_tag: Option<u32>,
/// The `[[Prototype]]` link (`Object.create`/`getPrototypeOf`), if any. A
/// property miss walks this chain.
proto: Option<crate::heap::Handle>,
}
impl Object {
/// Creates an empty object whose layout starts at `root` (the shared root
/// shape of the owning realm/heap, so identically-structured objects share
/// shapes).
#[must_use]
pub fn new(root: Rc<Shape>) -> Self {
Self {
shape: root,
slots: Vec::new(),
accessors: Vec::new(),
hidden: Vec::new(),
readonly: Vec::new(),
non_configurable: Vec::new(),
frozen: false,
extensible: true,
sealed: false,
class_tag: None,
proto: None,
}
}
/// The `[[Prototype]]` handle, if any.
#[must_use]
pub fn proto(&self) -> Option<crate::heap::Handle> {
self.proto
}
/// Sets the `[[Prototype]]` link (`None` clears it to a null prototype).
pub fn set_proto(&mut self, proto: Option<crate::heap::Handle>) {
self.proto = proto;
}
/// Tags this object with the class it was constructed from.
pub fn set_class_tag(&mut self, class_id: u32) {
self.class_tag = Some(class_id);
}
/// The class this object was constructed from, if any.
#[must_use]
pub fn class_tag(&self) -> Option<u32> {
self.class_tag
}
/// Defines an accessor property `name` with `getter`/`setter` (either may be
/// `undefined`). Replaces an existing accessor of the same name.
pub fn define_accessor(&mut self, name: &str, getter: NanBox, setter: NanBox) {
if let Some(a) = self
.accessors
.iter_mut()
.find(|(k, _, _)| k.as_ref() == name)
{
if !matches!(getter.unpack(), crate::nanbox::Unpacked::Undefined) {
a.1 = getter;
}
if !matches!(setter.unpack(), crate::nanbox::Unpacked::Undefined) {
a.2 = setter;
}
} else {
self.accessors
.push((alloc::boxed::Box::from(name), getter, setter));
}
}
/// The names of this object's accessor (getter/setter) properties.
#[must_use]
pub fn accessor_keys(&self) -> Vec<&str> {
self.accessors.iter().map(|(k, _, _)| k.as_ref()).collect()
}
/// The `(getter, setter)` of accessor `name`, if defined.
#[must_use]
pub fn accessor(&self, name: &str) -> Option<(NanBox, NanBox)> {
self.accessors
.iter()
.find(|(k, _, _)| k.as_ref() == name)
.map(|(_, g, s)| (*g, *s))
}
/// The object's current shape (its hidden class).
#[must_use]
pub fn shape(&self) -> &Rc<Shape> {
&self.shape
}
/// The number of own properties.
#[must_use]
pub fn len(&self) -> u32 {
self.shape.len()
}
/// Whether the object has no own properties.
#[must_use]
pub fn is_empty(&self) -> bool {
self.shape.is_empty()
}
/// The value of own property `key`, or `None` if absent.
#[must_use]
pub fn get(&self, key: &str) -> Option<NanBox> {
let slot = self.shape.lookup(key)?;
self.slots.get(slot as usize).copied()
}
/// Whether the object has own property `key`.
#[must_use]
pub fn contains(&self, key: &str) -> bool {
self.shape.contains(key)
}
/// Sets own property `key` to `value`: updates the slot in place if the
/// property exists, otherwise transitions the shape and appends a slot. A
/// no-op on a frozen object (matching `Object.freeze` semantics in
/// non-strict code).
pub fn set(&mut self, key: &str, value: NanBox) {
if self.frozen || self.is_readonly(key) {
return;
}
if let Some(slot) = self.shape.lookup(key) {
self.slots[slot as usize] = value;
} else if self.extensible {
self.shape = self.shape.transition(key);
self.slots.push(value);
}
// A non-extensible object silently ignores new keys.
}
/// The own property names, in insertion (slot) order.
#[must_use]
pub fn keys(&self) -> Vec<&str> {
self.shape.keys()
}
/// All own property names — data and accessor, including non-enumerable — in
/// insertion order. For reflection that ignores enumerability (e.g.
/// `Object.getOwnPropertySymbols`).
#[must_use]
pub fn all_keys(&self) -> Vec<&str> {
let mut keys = self.shape.keys();
keys.extend(self.accessors.iter().map(|(k, _, _)| k.as_ref()));
keys
}
/// All own property names (data + accessor, **including** non-enumerable) in spec
/// `[[OwnPropertyKeys]]` order: integer-index keys ascending, then the rest in
/// insertion order. Used by `getOwnPropertyNames` / `Reflect.ownKeys`.
#[must_use]
pub fn ordered_keys(&self) -> Vec<&str> {
let keys = self.shape.keys();
let mut ints: Vec<&str> = keys
.iter()
.copied()
.filter(|k| array_index(k).is_some())
.collect();
ints.sort_by_key(|k| array_index(k).unwrap());
let strs = keys.iter().copied().filter(|k| array_index(k).is_none());
let acc = self.accessors.iter().map(|(k, _, _)| k.as_ref());
ints.into_iter().chain(strs).chain(acc).collect()
}
/// The own **enumerable** property names (excludes keys marked hidden), in
/// spec order: integer-index keys ascending, then the rest in insertion order.
#[must_use]
pub fn enumerable_keys(&self) -> Vec<&str> {
let keys: Vec<&str> = self
.shape
.keys()
.into_iter()
.filter(|k| !self.is_hidden(k))
.collect();
let mut ints: Vec<&str> = keys
.iter()
.copied()
.filter(|k| array_index(k).is_some())
.collect();
ints.sort_by_key(|k| array_index(k).unwrap());
let strs = keys.into_iter().filter(|k| array_index(k).is_none());
// Enumerable accessor (getter/setter) properties live outside the shape;
// include those not marked hidden, after the data keys.
let acc = self
.accessors
.iter()
.map(|(k, _, _)| k.as_ref())
.filter(|k| !self.is_hidden(k));
ints.into_iter().chain(strs).chain(acc).collect()
}
/// Marks own property `key` non-enumerable (idempotent).
pub fn set_hidden(&mut self, key: &str) {
if !self.is_hidden(key) {
self.hidden.push(alloc::boxed::Box::from(key));
}
}
/// Whether own property `key` is non-enumerable.
#[must_use]
pub fn is_hidden(&self, key: &str) -> bool {
self.hidden.iter().any(|k| k.as_ref() == key)
}
/// Marks own property `key` non-writable (idempotent).
pub fn set_readonly(&mut self, key: &str) {
if !self.is_readonly(key) {
self.readonly.push(alloc::boxed::Box::from(key));
}
}
/// Whether own property `key` is non-writable.
#[must_use]
pub fn is_readonly(&self, key: &str) -> bool {
self.readonly.iter().any(|k| k.as_ref() == key)
}
/// Clears the non-writable mark for `key` (a `defineProperty` redefines
/// attributes from scratch, so the prior `writable: false` is dropped first).
pub fn clear_readonly(&mut self, key: &str) {
self.readonly.retain(|k| k.as_ref() != key);
}
/// Marks own property `key` non-configurable (idempotent).
pub fn set_non_configurable(&mut self, key: &str) {
if !self.is_non_configurable(key) {
self.non_configurable.push(alloc::boxed::Box::from(key));
}
}
/// Whether own property `key` is non-configurable (cannot be deleted).
#[must_use]
pub fn is_non_configurable(&self, key: &str) -> bool {
self.non_configurable.iter().any(|k| k.as_ref() == key)
}
/// Whether `key` is an own property (data slot or accessor).
#[must_use]
pub fn has_own_key(&self, key: &str) -> bool {
self.shape.contains(key) || self.accessors.iter().any(|(k, _, _)| k.as_ref() == key)
}
/// Marks the object frozen (`Object.freeze`) — implies sealed + non-extensible.
pub fn freeze(&mut self) {
self.frozen = true;
self.sealed = true;
self.extensible = false;
}
/// Prevents new properties (`Object.preventExtensions`).
pub fn prevent_extensions(&mut self) {
self.extensible = false;
}
/// Seals the object (`Object.seal`): no new props, no deletions.
pub fn seal(&mut self) {
self.sealed = true;
self.extensible = false;
}
/// Whether new properties may be added.
#[must_use]
pub fn is_extensible(&self) -> bool {
self.extensible
}
/// Whether the object is sealed (or frozen).
#[must_use]
pub fn is_sealed(&self) -> bool {
self.sealed || self.frozen
}
/// Whether the object is frozen.
#[must_use]
pub fn is_frozen(&self) -> bool {
self.frozen
}
/// Removes any accessor (getter/setter) for `key`, leaving data properties
/// intact — used when a `defineProperty` replaces an accessor with data.
pub fn clear_accessor(&mut self, key: &str) {
self.accessors.retain(|(k, _, _)| k.as_ref() != key);
}
/// Deletes own property `key`, rebuilding the shape/slots from `root` without
/// it (also drops a same-named accessor). Returns whether anything was
/// removed.
pub fn delete(&mut self, root: Rc<Shape>, key: &str) -> bool {
let had_accessor = self.accessors.iter().any(|(k, _, _)| k.as_ref() == key);
self.accessors.retain(|(k, _, _)| k.as_ref() != key);
if !self.shape.contains(key) {
return had_accessor;
}
let kept: Vec<(alloc::string::String, NanBox)> = self
.shape
.keys()
.into_iter()
.filter(|k| *k != key)
.map(|k| (alloc::string::String::from(k), self.get(k).unwrap()))
.collect();
self.shape = root;
self.slots.clear();
for (k, v) in kept {
self.set(&k, v);
}
true
}
/// Rewrites every outgoing handle through `forward` — the mutating mirror of
/// [`trace_handles`](Object::trace_handles), used by a moving collector to
/// fix up references after relocation.
pub fn relocate_handles(
&mut self,
forward: &dyn Fn(crate::heap::Handle) -> crate::heap::Handle,
) {
let fwd = |v: &mut NanBox| {
if let Some(raw) = v.as_handle() {
*v = NanBox::handle(forward(crate::heap::Handle::from_raw(raw)).to_raw());
}
};
for slot in &mut self.slots {
fwd(slot);
}
for (_, g, s) in &mut self.accessors {
fwd(g);
fwd(s);
}
if let Some(p) = self.proto {
self.proto = Some(forward(p));
}
}
/// Calls `visit` for every heap [`Handle`](crate::heap::Handle) this object
/// references through a slot — the outgoing edges a tracing collector
/// follows.
pub fn trace_handles(&self, mut visit: impl FnMut(crate::heap::Handle)) {
for slot in &self.slots {
if let Some(raw) = slot.as_handle() {
visit(crate::heap::Handle::from_raw(raw));
}
}
for (_, g, s) in &self.accessors {
for v in [g, s] {
if let Some(raw) = v.as_handle() {
visit(crate::heap::Handle::from_raw(raw));
}
}
}
if let Some(p) = self.proto {
visit(p);
}
}
}
impl crate::gc::Trace for Object {
fn trace(&self, visit: &mut dyn FnMut(crate::heap::Handle)) {
self.trace_handles(visit);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::heap::Heap;
use crate::nanbox::Unpacked;
fn n(x: f64) -> NanBox {
NanBox::number(x)
}
#[test]
fn set_get_and_update() {
let mut o = Object::new(Shape::root());
assert!(o.is_empty());
o.set("x", n(1.0));
o.set("y", n(2.0));
assert_eq!(o.len(), 2);
assert_eq!(o.get("x").unwrap().unpack(), Unpacked::Number(1.0));
assert_eq!(o.get("y").unwrap().unpack(), Unpacked::Number(2.0));
assert_eq!(o.get("z"), None);
// Updating an existing property keeps the shape and reuses the slot.
let shape_before = Rc::clone(o.shape());
o.set("x", n(9.0));
assert!(Rc::ptr_eq(o.shape(), &shape_before));
assert_eq!(o.get("x").unwrap().unpack(), Unpacked::Number(9.0));
assert_eq!(o.len(), 2);
assert_eq!(o.keys(), ["x", "y"]);
}
#[test]
fn same_structure_objects_share_a_shape() {
let root = Shape::root();
let mut a = Object::new(Rc::clone(&root));
let mut b = Object::new(Rc::clone(&root));
a.set("p", n(1.0));
a.set("q", n(2.0));
b.set("p", n(10.0));
b.set("q", n(20.0));
// Distinct values, one shared hidden class.
assert!(Rc::ptr_eq(a.shape(), b.shape()));
assert_eq!(a.get("p").unwrap().unpack(), Unpacked::Number(1.0));
assert_eq!(b.get("p").unwrap().unpack(), Unpacked::Number(10.0));
}
#[test]
fn mixed_value_kinds_in_slots() {
let mut o = Object::new(Shape::root());
o.set("a", NanBox::number(3.5));
o.set("b", NanBox::boolean(true));
o.set("c", NanBox::null());
o.set("d", NanBox::handle(42));
assert_eq!(o.get("a").unwrap().unpack(), Unpacked::Number(3.5));
assert_eq!(o.get("b").unwrap().unpack(), Unpacked::Bool(true));
assert_eq!(o.get("c").unwrap().unpack(), Unpacked::Null);
assert_eq!(o.get("d").unwrap().unpack(), Unpacked::Handle(42));
}
#[test]
fn objects_live_in_the_heap_and_reference_each_other() {
// An object graph: `parent.child` holds a handle to another object in
// the same heap — the value representation the GC will manage.
let root = Shape::root();
let mut heap: Heap<Object> = Heap::new();
let mut child = Object::new(Rc::clone(&root));
child.set("value", n(7.0));
let child_handle = heap.alloc(child);
let mut parent = Object::new(Rc::clone(&root));
parent.set("child", NanBox::handle(child_handle.to_raw()));
let parent_handle = heap.alloc(parent);
// Walk parent -> child by resolving the handle stored in the slot.
let parent_ref = heap.get(parent_handle).unwrap();
let raw = parent_ref.get("child").unwrap().as_handle().unwrap();
let resolved = crate::heap::Handle::from_raw(raw);
let child_ref = heap.get(resolved).unwrap();
assert_eq!(
child_ref.get("value").unwrap().unpack(),
Unpacked::Number(7.0)
);
}
}