boa_engine 0.20.0

Boa is a Javascript lexer, parser and compiler written in Rust. Currently, it has support for some of the language.
Documentation
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
use crate::{
    js_string,
    native_function::{NativeFunctionObject, NativeFunctionPointer},
    object::{
        shape::{property_table::PropertyTableInner, slot::SlotAttributes},
        FunctionBinding, JsFunction, JsPrototype, CONSTRUCTOR, PROTOTYPE,
    },
    property::{Attribute, PropertyDescriptor, PropertyKey},
    realm::Realm,
    string::StaticJsStrings,
    JsObject, JsString, JsValue, NativeFunction,
};

use super::{function::ConstructorKind, BuiltInConstructor, IntrinsicObject};

/// Marker for a constructor function.
// TODO: Remove this marker and use `Constructor` directly.
#[allow(dead_code)]
pub(crate) struct Constructor {
    prototype: JsObject,
    inherits: JsPrototype,
    attributes: Attribute,
}

/// Marker for a constructor function without a custom prototype for its instances.
// TODO: Remove this marker and use `ConstructorNoProto` directly.
#[allow(dead_code)]
pub(crate) struct ConstructorNoProto;

/// Marker for an ordinary function.
pub(crate) struct OrdinaryFunction;

/// Indicates if the marker is a constructor.
pub(crate) trait IsConstructor {
    const IS_CONSTRUCTOR: bool;
}

impl IsConstructor for Constructor {
    const IS_CONSTRUCTOR: bool = true;
}

impl IsConstructor for ConstructorNoProto {
    const IS_CONSTRUCTOR: bool = true;
}

impl IsConstructor for OrdinaryFunction {
    const IS_CONSTRUCTOR: bool = false;
}

/// Marker for a callable object.
pub(crate) struct Callable<Kind> {
    function: NativeFunctionPointer,
    name: JsString,
    length: usize,
    kind: Kind,
    realm: Realm,
}

/// Marker for an ordinary object.
pub(crate) struct OrdinaryObject;

/// Applies the pending builder data to the object.
pub(crate) trait ApplyToObject {
    fn apply_to(self, object: &JsObject);
}

impl ApplyToObject for Constructor {
    fn apply_to(self, object: &JsObject) {
        object.insert(
            PROTOTYPE,
            PropertyDescriptor::builder()
                .value(self.prototype.clone())
                .writable(false)
                .enumerable(false)
                .configurable(false),
        );

        {
            let mut prototype = self.prototype.borrow_mut();
            prototype.set_prototype(self.inherits);
            prototype.insert(
                CONSTRUCTOR,
                PropertyDescriptor::builder()
                    .value(object.clone())
                    .writable(self.attributes.writable())
                    .enumerable(self.attributes.enumerable())
                    .configurable(self.attributes.configurable()),
            );
        }
    }
}

impl ApplyToObject for ConstructorNoProto {
    fn apply_to(self, _: &JsObject) {}
}

impl ApplyToObject for OrdinaryFunction {
    fn apply_to(self, _: &JsObject) {}
}

impl<S: ApplyToObject + IsConstructor> ApplyToObject for Callable<S> {
    fn apply_to(self, object: &JsObject) {
        {
            let mut function = object
                .downcast_mut::<NativeFunctionObject>()
                .expect("Builtin must be a function object");
            function.f = NativeFunction::from_fn_ptr(self.function);
            function.constructor = S::IS_CONSTRUCTOR.then_some(ConstructorKind::Base);
            function.realm = Some(self.realm);
        }
        object.insert(
            StaticJsStrings::LENGTH,
            PropertyDescriptor::builder()
                .value(self.length)
                .writable(false)
                .enumerable(false)
                .configurable(true),
        );
        object.insert(
            js_string!("name"),
            PropertyDescriptor::builder()
                .value(self.name)
                .writable(false)
                .enumerable(false)
                .configurable(true),
        );

        self.kind.apply_to(object);
    }
}

impl ApplyToObject for OrdinaryObject {
    fn apply_to(self, _: &JsObject) {}
}

// The number of properties that are always present in a standard constructor. See build method
const OWN_PROPS: usize = 3;

/// Builder for creating built-in objects, like `Array`.
///
/// The marker `ObjectType` restricts the methods that can be called depending on the
/// type of object that is being constructed.
#[derive(Debug)]
#[must_use = "You need to call the `build` method in order for this to correctly assign the inner data"]
pub(crate) struct BuiltInBuilder<'ctx, Kind> {
    realm: &'ctx Realm,
    object: JsObject,
    kind: Kind,
    prototype: JsObject,
}

impl<'ctx> BuiltInBuilder<'ctx, OrdinaryObject> {
    pub(crate) fn with_intrinsic<I: IntrinsicObject>(
        realm: &'ctx Realm,
    ) -> BuiltInBuilder<'ctx, OrdinaryObject> {
        BuiltInBuilder {
            realm,
            object: I::get(realm.intrinsics()),
            kind: OrdinaryObject,
            prototype: realm.intrinsics().constructors().object().prototype(),
        }
    }
}

pub(crate) struct BuiltInConstructorWithPrototype<'ctx> {
    realm: &'ctx Realm,
    function: NativeFunctionPointer,
    name: JsString,
    length: usize,

    object_property_table: PropertyTableInner,
    object_storage: Vec<JsValue>,
    object: JsObject,

    prototype_property_table: PropertyTableInner,
    prototype_storage: Vec<JsValue>,
    prototype: JsObject,
    __proto__: JsPrototype,
    inherits: Option<JsObject>,
    attributes: Attribute,
}

#[allow(dead_code)]
impl BuiltInConstructorWithPrototype<'_> {
    /// Specify how many arguments the constructor function takes.
    ///
    /// Default is `0`.
    #[inline]
    pub(crate) const fn length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

    /// Specify the name of the constructor function.
    ///
    /// Default is `""`
    pub(crate) fn name(mut self, name: JsString) -> Self {
        self.name = name;
        self
    }

    /// Adds a new static method to the builtin object.
    pub(crate) fn static_method<B>(
        mut self,
        function: NativeFunctionPointer,
        binding: B,
        length: usize,
    ) -> Self
    where
        B: Into<FunctionBinding>,
    {
        let binding = binding.into();
        let function = BuiltInBuilder::callable(self.realm, function)
            .name(binding.name)
            .length(length)
            .build();

        debug_assert!(!self
            .object_property_table
            .map
            .contains_key(&binding.binding));
        self.object_property_table.insert(
            binding.binding,
            SlotAttributes::WRITABLE | SlotAttributes::CONFIGURABLE,
        );
        self.object_storage.push(function.into());
        self
    }

    /// Adds a new static data property to the builtin object.
    pub(crate) fn static_property<K, V>(mut self, key: K, value: V, attribute: Attribute) -> Self
    where
        K: Into<PropertyKey>,
        V: Into<JsValue>,
    {
        let key = key.into();

        debug_assert!(!self.object_property_table.map.contains_key(&key));
        self.object_property_table
            .insert(key, SlotAttributes::from_bits_truncate(attribute.bits()));
        self.object_storage.push(value.into());
        self
    }

    /// Adds a new static accessor property to the builtin object.
    pub(crate) fn static_accessor<K>(
        mut self,
        key: K,
        get: Option<JsFunction>,
        set: Option<JsFunction>,
        attribute: Attribute,
    ) -> Self
    where
        K: Into<PropertyKey>,
    {
        let mut attributes = SlotAttributes::from_bits_truncate(attribute.bits());
        debug_assert!(!attributes.contains(SlotAttributes::WRITABLE));
        attributes.set(SlotAttributes::GET, get.is_some());
        attributes.set(SlotAttributes::SET, set.is_some());

        let key = key.into();

        debug_assert!(!self.object_property_table.map.contains_key(&key));
        self.object_property_table.insert(key, attributes);
        self.object_storage.extend([
            get.map(JsValue::new).unwrap_or_default(),
            set.map(JsValue::new).unwrap_or_default(),
        ]);
        self
    }

    /// Specify the `[[Prototype]]` internal field of the builtin object.
    ///
    /// Default is `Function.prototype` for constructors and `Object.prototype` for statics.
    pub(crate) fn prototype(mut self, prototype: JsObject) -> Self {
        self.__proto__ = Some(prototype);
        self
    }

    /// Adds a new method to the constructor's prototype.
    pub(crate) fn method<B>(
        mut self,
        function: NativeFunctionPointer,
        binding: B,
        length: usize,
    ) -> Self
    where
        B: Into<FunctionBinding>,
    {
        let binding = binding.into();
        let function = BuiltInBuilder::callable(self.realm, function)
            .name(binding.name)
            .length(length)
            .build();

        debug_assert!(!self
            .prototype_property_table
            .map
            .contains_key(&binding.binding));
        self.prototype_property_table.insert(
            binding.binding,
            SlotAttributes::WRITABLE | SlotAttributes::CONFIGURABLE,
        );
        self.prototype_storage.push(function.into());
        self
    }

    /// Adds a new data property to the constructor's prototype.
    pub(crate) fn property<K, V>(mut self, key: K, value: V, attribute: Attribute) -> Self
    where
        K: Into<PropertyKey>,
        V: Into<JsValue>,
    {
        let key = key.into();

        debug_assert!(!self.prototype_property_table.map.contains_key(&key));
        self.prototype_property_table
            .insert(key, SlotAttributes::from_bits_truncate(attribute.bits()));
        self.prototype_storage.push(value.into());
        self
    }

    /// Adds new accessor property to the constructor's prototype.
    pub(crate) fn accessor<K>(
        mut self,
        key: K,
        get: Option<JsFunction>,
        set: Option<JsFunction>,
        attribute: Attribute,
    ) -> Self
    where
        K: Into<PropertyKey>,
    {
        let mut attributes = SlotAttributes::from_bits_truncate(attribute.bits());
        debug_assert!(!attributes.contains(SlotAttributes::WRITABLE));
        attributes.set(SlotAttributes::GET, get.is_some());
        attributes.set(SlotAttributes::SET, set.is_some());

        let key = key.into();

        debug_assert!(!self.prototype_property_table.map.contains_key(&key));
        self.prototype_property_table.insert(key, attributes);
        self.prototype_storage.extend([
            get.map(JsValue::new).unwrap_or_default(),
            set.map(JsValue::new).unwrap_or_default(),
        ]);
        self
    }

    /// Specifies the parent prototype which objects created by this constructor inherit from.
    ///
    /// Default is `Object.prototype`.
    #[allow(clippy::missing_const_for_fn)]
    pub(crate) fn inherits(mut self, prototype: JsPrototype) -> Self {
        self.inherits = prototype;
        self
    }

    /// Specifies the property attributes of the prototype's "constructor" property.
    pub(crate) const fn constructor_attributes(mut self, attributes: Attribute) -> Self {
        self.attributes = attributes;
        self
    }

    pub(crate) fn build(mut self) {
        let length = self.length;
        let name = self.name.clone();
        let prototype = self.prototype.clone();
        self = self.static_property(js_string!("length"), length, Attribute::CONFIGURABLE);
        self = self.static_property(js_string!("name"), name, Attribute::CONFIGURABLE);
        self = self.static_property(PROTOTYPE, prototype, Attribute::empty());

        let attributes = self.attributes;
        let object = self.object.clone();
        self = self.property(CONSTRUCTOR, object, attributes);

        {
            let mut prototype = self.prototype.borrow_mut();
            prototype
                .properties_mut()
                .shape
                .as_unique()
                .expect("The object should have a unique shape")
                .override_internal(self.prototype_property_table, self.inherits);

            let prototype_old_storage = std::mem::replace(
                &mut prototype.properties_mut().storage,
                self.prototype_storage,
            );

            debug_assert_eq!(prototype_old_storage.len(), 0);
        }

        let mut object = self.object.borrow_mut();
        let function = object
            .downcast_mut::<NativeFunctionObject>()
            .expect("Builtin must be a function object");
        function.f = NativeFunction::from_fn_ptr(self.function);
        function.constructor = Some(ConstructorKind::Base);
        function.realm = Some(self.realm.clone());
        object
            .properties_mut()
            .shape
            .as_unique()
            .expect("The object should have a unique shape")
            .override_internal(self.object_property_table, self.__proto__);

        let object_old_storage =
            std::mem::replace(&mut object.properties_mut().storage, self.object_storage);

        debug_assert_eq!(object_old_storage.len(), 0);
    }

    pub(crate) fn build_without_prototype(mut self) {
        let length = self.length;
        let name = self.name.clone();
        self = self.static_property(js_string!("length"), length, Attribute::CONFIGURABLE);
        self = self.static_property(js_string!("name"), name, Attribute::CONFIGURABLE);

        let mut object = self.object.borrow_mut();
        let function = object
            .downcast_mut::<NativeFunctionObject>()
            .expect("Builtin must be a function object");
        function.f = NativeFunction::from_fn_ptr(self.function);
        function.constructor = Some(ConstructorKind::Base);
        function.realm = Some(self.realm.clone());
        object
            .properties_mut()
            .shape
            .as_unique()
            .expect("The object should have a unique shape")
            .override_internal(self.object_property_table, self.__proto__);

        let object_old_storage =
            std::mem::replace(&mut object.properties_mut().storage, self.object_storage);

        debug_assert_eq!(object_old_storage.len(), 0);
    }
}

pub(crate) struct BuiltInCallable<'ctx> {
    realm: &'ctx Realm,
    function: NativeFunctionPointer,
    name: JsString,
    length: usize,
}

impl BuiltInCallable<'_> {
    /// Specify how many arguments the constructor function takes.
    ///
    /// Default is `0`.
    #[inline]
    pub(crate) const fn length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

    /// Specify the name of the constructor function.
    ///
    /// Default is `""`
    pub(crate) fn name(mut self, name: JsString) -> Self {
        self.name = name;
        self
    }

    pub(crate) fn build(self) -> JsFunction {
        let object = self.realm.intrinsics().templates().function().create(
            NativeFunctionObject {
                f: NativeFunction::from_fn_ptr(self.function),
                constructor: None,
                realm: Some(self.realm.clone()),
            },
            vec![JsValue::new(self.length), JsValue::new(self.name)],
        );

        JsFunction::from_object_unchecked(object)
    }
}

impl<'ctx> BuiltInBuilder<'ctx, OrdinaryObject> {
    pub(crate) fn callable(
        realm: &'ctx Realm,
        function: NativeFunctionPointer,
    ) -> BuiltInCallable<'ctx> {
        BuiltInCallable {
            realm,
            function,
            length: 0,
            name: js_string!(),
        }
    }

    pub(crate) fn callable_with_intrinsic<I: IntrinsicObject>(
        realm: &'ctx Realm,
        function: NativeFunctionPointer,
    ) -> BuiltInBuilder<'ctx, Callable<OrdinaryFunction>> {
        BuiltInBuilder {
            realm,
            object: I::get(realm.intrinsics()),
            kind: Callable {
                function,
                name: js_string!(),
                length: 0,
                kind: OrdinaryFunction,
                realm: realm.clone(),
            },
            prototype: realm.intrinsics().constructors().function().prototype(),
        }
    }

    pub(crate) fn callable_with_object(
        realm: &'ctx Realm,
        object: JsObject,
        function: NativeFunctionPointer,
    ) -> BuiltInBuilder<'ctx, Callable<OrdinaryFunction>> {
        BuiltInBuilder {
            realm,
            object,
            kind: Callable {
                function,
                name: js_string!(),
                length: 0,
                kind: OrdinaryFunction,
                realm: realm.clone(),
            },
            prototype: realm.intrinsics().constructors().function().prototype(),
        }
    }
}

impl<'ctx> BuiltInBuilder<'ctx, Callable<Constructor>> {
    /// Create a new builder for a constructor function setting the properties ahead of time for optimizations (less reallocations)
    pub(crate) fn from_standard_constructor<SC: BuiltInConstructor>(
        realm: &'ctx Realm,
    ) -> BuiltInConstructorWithPrototype<'ctx> {
        let constructor = SC::STANDARD_CONSTRUCTOR(realm.intrinsics().constructors());
        BuiltInConstructorWithPrototype {
            realm,
            function: SC::constructor,
            name: js_string!(SC::NAME),
            length: SC::LENGTH,
            object_property_table: PropertyTableInner::with_capacity(SC::SP + OWN_PROPS),
            object_storage: Vec::with_capacity(SC::SP + OWN_PROPS),
            object: constructor.constructor(),
            prototype_property_table: PropertyTableInner::with_capacity(SC::P),
            prototype_storage: Vec::with_capacity(SC::P),
            prototype: constructor.prototype(),
            __proto__: Some(realm.intrinsics().constructors().function().prototype()),
            inherits: Some(realm.intrinsics().constructors().object().prototype()),
            attributes: Attribute::WRITABLE | Attribute::CONFIGURABLE | Attribute::NON_ENUMERABLE,
        }
    }
}

impl<T> BuiltInBuilder<'_, T> {
    /// Adds a new static method to the builtin object.
    pub(crate) fn static_method<B>(
        self,
        function: NativeFunctionPointer,
        binding: B,
        length: usize,
    ) -> Self
    where
        B: Into<FunctionBinding>,
    {
        let binding = binding.into();
        let function = BuiltInBuilder::callable(self.realm, function)
            .name(binding.name)
            .length(length)
            .build();

        self.object.insert(
            binding.binding,
            PropertyDescriptor::builder()
                .value(function)
                .writable(true)
                .enumerable(false)
                .configurable(true),
        );
        self
    }

    /// Adds a new static data property to the builtin object.
    pub(crate) fn static_property<K, V>(self, key: K, value: V, attribute: Attribute) -> Self
    where
        K: Into<PropertyKey>,
        V: Into<JsValue>,
    {
        let property = PropertyDescriptor::builder()
            .value(value)
            .writable(attribute.writable())
            .enumerable(attribute.enumerable())
            .configurable(attribute.configurable());
        self.object.insert(key, property);
        self
    }

    /// Specify the `[[Prototype]]` internal field of the builtin object.
    ///
    /// Default is `Function.prototype` for constructors and `Object.prototype` for statics.
    pub(crate) fn prototype(mut self, prototype: JsObject) -> Self {
        self.prototype = prototype;
        self
    }
}

impl<FnTyp> BuiltInBuilder<'_, Callable<FnTyp>> {
    /// Specify how many arguments the constructor function takes.
    ///
    /// Default is `0`.
    #[inline]
    pub(crate) const fn length(mut self, length: usize) -> Self {
        self.kind.length = length;
        self
    }

    /// Specify the name of the constructor function.
    ///
    /// Default is `""`
    pub(crate) fn name(mut self, name: JsString) -> Self {
        self.kind.name = name;
        self
    }
}

impl BuiltInBuilder<'_, OrdinaryObject> {
    /// Build the builtin object.
    pub(crate) fn build(self) -> JsObject {
        self.kind.apply_to(&self.object);

        self.object.set_prototype(Some(self.prototype));

        self.object
    }
}

impl<FnTyp: ApplyToObject + IsConstructor> BuiltInBuilder<'_, Callable<FnTyp>> {
    /// Build the builtin callable.
    pub(crate) fn build(self) -> JsFunction {
        self.kind.apply_to(&self.object);

        self.object.set_prototype(Some(self.prototype));

        JsFunction::from_object_unchecked(self.object)
    }
}