Skip to main content

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 crate::value::{Cell, Value};
19
20/// A property of an object.
21#[derive(Clone, Default)]
22pub struct Property {
23    /// The value of a data property.
24    pub value: Option<Value>,
25    /// The getter of an accessor property.
26    pub getter: Option<Value>,
27    /// The setter of an accessor property.
28    pub setter: Option<Value>,
29    /// Whether the value can be replaced.
30    pub writable: bool,
31    /// Whether `for`/`Object.keys` sees the property.
32    pub enumerable: bool,
33    /// Whether the property can be deleted or redefined.
34    pub configurable: bool,
35}
36
37impl Property {
38    /// A writable, enumerable, configurable data property.
39    ///
40    /// This is what a plain assignment or an object literal creates, and the
41    /// attributes only differ for built-ins and `Object.defineProperty`.
42    pub fn data(value: Value) -> Property {
43        Property {
44            value: Some(value),
45            writable: true,
46            enumerable: true,
47            configurable: true,
48            ..Property::default()
49        }
50    }
51
52    /// A data property with explicit attributes.
53    pub fn with_attributes(value: Value, writable: bool, enumerable: bool) -> Property {
54        Property {
55            value: Some(value),
56            writable,
57            enumerable,
58            configurable: writable,
59            ..Property::default()
60        }
61    }
62
63    /// An accessor property.
64    pub fn accessor(getter: Option<Value>, setter: Option<Value>) -> Property {
65        Property {
66            getter,
67            setter,
68            enumerable: true,
69            configurable: true,
70            ..Property::default()
71        }
72    }
73
74    /// Whether this is an accessor rather than a data property.
75    pub fn is_accessor(&self) -> bool {
76        self.getter.is_some() || self.setter.is_some()
77    }
78}
79
80impl Trace for Property {
81    fn trace(&self, tracer: &mut Tracer) {
82        self.value.trace(tracer);
83        self.getter.trace(tracer);
84        self.setter.trace(tracer);
85    }
86}
87
88/// A native (Rust) function reachable from JavaScript.
89///
90/// It receives the interpreter so a builtin can allocate (which needs the heap),
91/// call back into JavaScript (which needs the frame stack) and raise exceptions.
92pub type NativeFn =
93    fn(&mut crate::interp::Interp<'_>, Value, &[Value]) -> crate::interp::JsResult<Value>;
94
95/// The body of a callable object.
96pub enum Callable {
97    /// A function compiled from JavaScript source.
98    Bytecode {
99        /// The bytecode and slot mapping.
100        code: Gc<CompiledCode>,
101        /// The captured environment.
102        env: Gc<ClosureEnv>,
103    },
104    /// A function produced by `Function.prototype.bind`.
105    ///
106    /// This is a variant rather than a native function carrying the state in
107    /// properties because the state is not observable: `bind` has to remember its
108    /// target, `this` and leading arguments, and a native trampoline cannot capture
109    /// them.
110    Bound {
111        /// The function being called.
112        target: Value,
113        /// The `this` every call uses.
114        this: Value,
115        /// Arguments prepended to every call's own.
116        args: Vec<Value>,
117    },
118    /// A built-in implemented in Rust.
119    ///
120    /// The `name` and `length` a script observes are ordinary properties on the
121    /// function object, not fields here: they are writable (`f.name = "x"` works)
122    /// and would otherwise be two sources of truth.
123    Native {
124        /// The implementation.
125        func: NativeFn,
126    },
127}
128
129impl Trace for Callable {
130    fn trace(&self, tracer: &mut Tracer) {
131        match self {
132            Callable::Bytecode { code, env } => {
133                tracer.visit(code);
134                tracer.visit(env);
135            }
136            Callable::Bound { target, this, args } => {
137                target.trace(tracer);
138                this.trace(tracer);
139                for argument in args {
140                    argument.trace(tracer);
141                }
142            }
143            Callable::Native { .. } => {}
144        }
145    }
146}
147
148/// The bytecode of one function, plus the slot-to-cell mapping.
149///
150/// This is a separate GC object from the closure so that a frame can hold a handle
151/// to it and read it while the function object itself is free to be borrowed.
152/// Holding a `RefCell` borrow across a call would deadlock the moment a function
153/// referred to itself.
154pub struct CompiledCode {
155    /// The resolved bytecode.
156    pub code: CompiledFunction,
157    /// For each argument slot, the index of its reference cell, or `-1` when the
158    /// slot holds its value directly.
159    ///
160    /// A captured binding lives in a cell so that closures outlive the frame; every
161    /// other slot is a plain value. Precomputing the mapping keeps the hot
162    /// `get_arg`/`put_arg` paths to one array read instead of a lookup.
163    pub arg_cell: Vec<i32>,
164    /// The same, for local slots.
165    pub loc_cell: Vec<i32>,
166}
167
168impl CompiledCode {
169    /// Build the slot-to-cell mapping for `code`.
170    ///
171    /// Cells are numbered the way [`CompiledFunction::var_ref_count`] counts them:
172    /// the captured arguments first, then the captured locals, each in slot order.
173    pub fn new(code: CompiledFunction) -> CompiledCode {
174        let mut next = 0i32;
175        let mut arg_cell = vec![-1; code.args.len()];
176        for (slot, arg) in code.args.iter().enumerate() {
177            if arg.is_captured {
178                arg_cell[slot] = next;
179                next += 1;
180            }
181        }
182        let mut loc_cell = vec![-1; code.vars.len()];
183        for (slot, local) in code.vars.iter().enumerate() {
184            if local.is_captured {
185                loc_cell[slot] = next;
186                next += 1;
187            }
188        }
189        CompiledCode {
190            code,
191            arg_cell,
192            loc_cell,
193        }
194    }
195}
196
197impl Trace for CompiledCode {
198    fn trace(&self, _tracer: &mut Tracer) {}
199}
200
201/// The reference cells a closure captured from enclosing scopes.
202pub struct ClosureEnv {
203    /// Indexed the way the bytecode's closure-variable table indexes them.
204    pub cells: Vec<Gc<Cell>>,
205}
206
207impl Trace for ClosureEnv {
208    fn trace(&self, tracer: &mut Tracer) {
209        for cell in &self.cells {
210            tracer.visit(cell);
211        }
212    }
213}
214
215/// What kind of object this is.
216pub enum ObjectKind {
217    /// An ordinary object: only its property table.
218    Ordinary,
219    /// An array: dense elements plus a property table for everything else.
220    Array {
221        /// The dense prefix of the array.
222        elements: Vec<Value>,
223    },
224    /// A function or a class constructor.
225    Function(Callable),
226}
227
228impl Trace for ObjectKind {
229    fn trace(&self, tracer: &mut Tracer) {
230        match self {
231            ObjectKind::Ordinary => {}
232            ObjectKind::Array { elements } => {
233                for element in elements {
234                    element.trace(tracer);
235                }
236            }
237            ObjectKind::Function(callable) => callable.trace(tracer),
238        }
239    }
240}
241
242/// The mutable half of an object.
243pub struct ObjectData {
244    /// The prototype, or `None` for `Object.prototype` and for a null-prototype
245    /// object created with `Object.create(null)`.
246    pub proto: Option<Gc<JsObject>>,
247    /// Properties in definition order.
248    pub props: Vec<(String, Property)>,
249    /// What kind of object this is.
250    pub kind: ObjectKind,
251    /// Whether new properties may be added. `Object.preventExtensions`, `seal` and
252    /// `freeze` clear it, and nothing clears it back.
253    pub extensible: bool,
254    /// Whether array elements may be replaced.
255    ///
256    /// Elements are not in the property table, so their attributes need somewhere to
257    /// live; `Object.freeze` clears this and `Object.isFrozen` reads it. A *single*
258    /// non-writable element is recorded in the property table instead, which is what
259    /// `Object.defineProperty(a, "3", {configurable: false})` does.
260    pub elements_writable: bool,
261}
262
263impl Trace for ObjectData {
264    fn trace(&self, tracer: &mut Tracer) {
265        if let Some(proto) = &self.proto {
266            tracer.visit(proto);
267        }
268        for (_, property) in &self.props {
269            property.trace(tracer);
270        }
271        self.kind.trace(tracer);
272    }
273}
274
275/// A JavaScript object.
276///
277/// The interior mutability is what makes `const o = {}; o.x = 1` work: the handle
278/// is immutable, the object it points at is not.
279pub struct JsObject {
280    data: RefCell<ObjectData>,
281}
282
283impl JsObject {
284    fn new(kind: ObjectKind, proto: Option<Gc<JsObject>>) -> JsObject {
285        JsObject {
286            data: RefCell::new(ObjectData {
287                proto,
288                props: Vec::new(),
289                kind,
290                extensible: true,
291                elements_writable: true,
292            }),
293        }
294    }
295
296    /// An ordinary object with the given prototype.
297    pub fn ordinary(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
298        Gc::new(heap, JsObject::new(ObjectKind::Ordinary, proto))
299    }
300
301    /// An array with the given prototype and initial capacity.
302    pub fn array(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>, capacity: usize) -> Gc<JsObject> {
303        Gc::new(
304            heap,
305            JsObject::new(
306                ObjectKind::Array {
307                    elements: Vec::with_capacity(capacity),
308                },
309                proto,
310            ),
311        )
312    }
313
314    /// A callable object.
315    pub fn function(
316        heap: &js_gc::Heap,
317        proto: Option<Gc<JsObject>>,
318        callable: Callable,
319    ) -> Gc<JsObject> {
320        Gc::new(heap, JsObject::new(ObjectKind::Function(callable), proto))
321    }
322
323    /// Run `f` with the object's data borrowed.
324    pub fn with<R>(&self, f: impl FnOnce(&ObjectData) -> R) -> R {
325        f(&self.data.borrow())
326    }
327
328    /// Run `f` with the object's data mutably borrowed.
329    pub fn with_mut<R>(&self, f: impl FnOnce(&mut ObjectData) -> R) -> R {
330        f(&mut self.data.borrow_mut())
331    }
332
333    /// Whether this object can be called.
334    ///
335    /// Covers every [`Callable`] variant, `Bound` included: `typeof bound ===
336    /// "function"` and `bound()` works, so from a script's point of view a bound
337    /// function is a function.
338    pub fn is_callable(&self) -> bool {
339        matches!(self.data.borrow().kind, ObjectKind::Function(_))
340    }
341
342    /// The prototype.
343    pub fn proto(&self) -> Option<Gc<JsObject>> {
344        self.data.borrow().proto.clone()
345    }
346
347    /// Replace the prototype.
348    pub fn set_proto(&self, proto: Option<Gc<JsObject>>) {
349        self.data.borrow_mut().proto = proto;
350    }
351
352    /// The elements of an array object, if this is one.
353    pub fn array_elements(&self) -> Option<Vec<Value>> {
354        match &self.data.borrow().kind {
355            ObjectKind::Array { elements } => Some(elements.clone()),
356            _ => None,
357        }
358    }
359
360    /// Whether this object has array elements at all.
361    pub fn is_array(&self) -> bool {
362        matches!(self.data.borrow().kind, ObjectKind::Array { .. })
363    }
364
365    /// `length` for an array, reading it out of the element vector.
366    pub fn array_length(&self) -> Option<usize> {
367        match &self.data.borrow().kind {
368            ObjectKind::Array { elements } => Some(elements.len()),
369            _ => None,
370        }
371    }
372
373    /// Read one array element.
374    pub fn array_get(&self, index: usize) -> Option<Value> {
375        match &self.data.borrow().kind {
376            ObjectKind::Array { elements } => elements.get(index).cloned(),
377            _ => None,
378        }
379    }
380
381    /// Append to an array and return the new length.
382    pub fn array_push(&self, value: Value) -> usize {
383        match &mut self.data.borrow_mut().kind {
384            ObjectKind::Array { elements } => {
385                elements.push(value);
386                elements.len()
387            }
388            _ => 0,
389        }
390    }
391
392    /// Store into an array, and return whether the write happened.
393    ///
394    /// The gap an out-of-range store leaves behind is filled with [`Value::Hole`], not
395    /// `undefined`: `a = [1]; a[3] = 4` has holes at 1 and 2, which `forEach` skips
396    /// and the debug printer reports. A store *of* `undefined` is a real element.
397    pub fn array_set(&self, index: usize, value: Value) -> bool {
398        match &mut self.data.borrow_mut().kind {
399            ObjectKind::Array { elements } => {
400                if index >= elements.len() {
401                    elements.resize(index + 1, Value::Hole);
402                }
403                elements[index] = value;
404                true
405            }
406            _ => false,
407        }
408    }
409
410    /// Store an element, honouring its attributes, reporting whether it happened.
411    ///
412    /// Array methods that write back (`sort`, `reverse`, `splice`, …) use this rather
413    /// than [`Self::array_set`]: the spec has them go through `[[Set]]`, so a frozen
414    /// element makes them throw instead of being quietly overwritten.
415    pub fn array_store(&self, index: usize, value: Value) -> bool {
416        if self.elements_writable() {
417            return self.array_set(index, value);
418        }
419        if self.element_attributes(index as u32).is_some() {
420            // A recorded descriptor decides on its own.
421            return !self.element_is_locked(index as u32) && self.array_set(index, value);
422        }
423        false
424    }
425
426    /// Store `value` as a plain element without creating holes, used by `push`.
427    pub fn array_push_hole(&self) -> bool {
428        match &mut self.data.borrow_mut().kind {
429            ObjectKind::Array { elements } => {
430                elements.push(Value::Hole);
431                true
432            }
433            _ => false,
434        }
435    }
436
437    /// Set the length of an array, truncating or extending with holes.
438    ///
439    /// `a.length = 5` on a two-element array leaves three holes, so the fill value is
440    /// [`Value::Hole`] rather than `undefined`.
441    pub fn array_set_length(&self, length: usize) -> bool {
442        match &mut self.data.borrow_mut().kind {
443            ObjectKind::Array { elements } => {
444                elements.resize(length, Value::Hole);
445                true
446            }
447            _ => false,
448        }
449    }
450
451    /// Truncate an array to `length` elements without extending it.
452    ///
453    /// This is what `arr.length = n` does for `n` smaller than the current length;
454    /// it is separate from [`Self::array_set_length`] because growing an array by
455    /// assignment produces holes, which are indistinguishable from `undefined`
456    /// here.
457    pub fn array_truncate(&self, length: usize) -> bool {
458        match &mut self.data.borrow_mut().kind {
459            ObjectKind::Array { elements } => {
460                if length < elements.len() {
461                    elements.truncate(length);
462                }
463                true
464            }
465            _ => false,
466        }
467    }
468
469    /// The own data property `name`, if there is one.
470    pub fn own_property(&self, name: &str) -> Option<Property> {
471        let data = self.data.borrow();
472        data.props
473            .iter()
474            .find(|(key, _)| key == name)
475            .map(|(_, property)| property.clone())
476    }
477
478    /// Whether the object has an own property `name`.
479    pub fn has_own(&self, name: &str) -> bool {
480        self.data.borrow().props.iter().any(|(key, _)| key == name)
481    }
482
483    /// Define or replace an own property, keeping the original position when the
484    /// name already exists.
485    pub fn define(&self, name: &str, property: Property) {
486        let mut data = self.data.borrow_mut();
487        match data.props.iter_mut().find(|(key, _)| key == name) {
488            Some((_, slot)) => *slot = property,
489            None => data.props.push((name.to_string(), property)),
490        }
491    }
492
493    /// Define an own data property, with the default attributes.
494    ///
495    /// This *creates*: on an existing property it overwrites the attributes too, so
496    /// it is the wrong call for a plain assignment. Use [`Self::write_value`] for that.
497    pub fn define_data(&self, name: &str, value: Value) {
498        self.define(name, Property::data(value));
499    }
500
501    /// Store a value into an existing own data property, keeping its attributes.
502    ///
503    /// Returns `false` when the property is absent, is an accessor, or is not
504    /// writable. An assignment has to go through this rather than
505    /// [`Self::define_data`], because redefining is how a non-configurable global
506    /// silently became configurable again and started answering `delete` with `true`.
507    pub fn write_value(&self, name: &str, value: Value) -> bool {
508        let mut data = self.data.borrow_mut();
509        let Some((_, property)) = data.props.iter_mut().find(|(key, _)| key == name) else {
510            return false;
511        };
512        if property.is_accessor() || !property.writable {
513            return false;
514        }
515        property.value = Some(value);
516        true
517    }
518
519    /// Delete an own property, reporting whether it was there and removable.
520    pub fn delete(&self, name: &str) -> bool {
521        let mut data = self.data.borrow_mut();
522        match data.props.iter().position(|(key, _)| key == name) {
523            Some(index) => {
524                if data.props[index].1.configurable {
525                    data.props.remove(index);
526                    true
527                } else {
528                    false
529                }
530            }
531            None => true,
532        }
533    }
534
535    /// Whether new properties may be added.
536    pub fn is_extensible(&self) -> bool {
537        self.data.borrow().extensible
538    }
539
540    /// Make the object non-extensible.
541    pub fn set_extensible(&self, extensible: bool) {
542        self.data.borrow_mut().extensible = extensible;
543    }
544
545    /// Whether array elements may be replaced.
546    pub fn elements_writable(&self) -> bool {
547        self.data.borrow().elements_writable
548    }
549
550    /// Make array elements read-only, as `Object.freeze` does.
551    pub fn set_elements_writable(&self, writable: bool) {
552        self.data.borrow_mut().elements_writable = writable;
553    }
554
555    /// The attributes recorded for an array index, if `defineProperty` set any.
556    pub fn element_attributes(&self, index: u32) -> Option<Property> {
557        self.own_property(&index.to_string())
558    }
559
560    /// Whether a store at `index` would be rejected.
561    ///
562    /// An element is locked either by `Object.freeze` on the whole object or by a
563    /// non-configurable, non-writable descriptor recorded for that one index.
564    pub fn element_is_locked(&self, index: u32) -> bool {
565        if !self.elements_writable() {
566            return true;
567        }
568        self.element_attributes(index)
569            .is_some_and(|property| !property.writable && !property.configurable)
570    }
571
572    /// The own property names, in definition order.
573    pub fn own_keys(&self) -> Vec<String> {
574        self.data
575            .borrow()
576            .props
577            .iter()
578            .map(|(key, _)| key.clone())
579            .collect()
580    }
581
582    /// The own *enumerable* property names, in definition order.
583    pub fn own_enumerable_keys(&self) -> Vec<String> {
584        self.data
585            .borrow()
586            .props
587            .iter()
588            .filter(|(_, property)| property.enumerable)
589            .map(|(key, _)| key.clone())
590            .collect()
591    }
592
593    /// The prototype chain, starting with the prototypes of this object.
594    pub fn chain(&self) -> Vec<Gc<JsObject>> {
595        let mut out = Vec::new();
596        let mut proto = self.proto();
597        while let Some(object) = proto {
598            proto = object.proto();
599            out.push(object);
600        }
601        out
602    }
603}
604
605/// Walk the prototype chain from `object` looking for `name`.
606///
607/// Returns the object that owns the property along with the property itself. The
608/// owner matters for a store: an inherited accessor is invoked on the receiver,
609/// while an inherited *data* property is shadowed by a new own property.
610pub fn lookup(object: &Gc<JsObject>, name: &str) -> Option<(Gc<JsObject>, Property)> {
611    if let Some(property) = object.own_property(name) {
612        return Some((object.clone(), property));
613    }
614    for ancestor in object.chain() {
615        if let Some(property) = ancestor.own_property(name) {
616            return Some((ancestor, property));
617        }
618    }
619    None
620}
621
622/// The array index a property key names, if it names one.
623///
624/// A key is an index when it is the canonical decimal spelling of an integer below
625/// `2^32 - 1` — the same rule the atom table uses to decide whether a key is a
626/// tagged index. `"01"` and `"-1"` are ordinary string keys.
627pub fn array_index(key: &str) -> Option<u32> {
628    if key.is_empty() || key.len() > 10 {
629        return None;
630    }
631    let bytes = key.as_bytes();
632    if !bytes.iter().all(u8::is_ascii_digit) {
633        return None;
634    }
635    if bytes[0] == b'0' && bytes.len() != 1 {
636        return None;
637    }
638    let value: u32 = key.parse().ok()?;
639    // `2^32 - 1` is reserved for the array length, so it is not an index.
640    (value < u32::MAX).then_some(value)
641}
642
643impl Trace for JsObject {
644    fn trace(&self, tracer: &mut Tracer) {
645        self.data.borrow().trace(tracer);
646    }
647}