boa_engine 0.17.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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
//! Boa's ECMAScript built-in object implementations, e.g. Object, String, Math, Array, etc.

pub mod array;
pub mod array_buffer;
pub mod async_function;
pub mod async_generator;
pub mod async_generator_function;
pub mod bigint;
pub mod boolean;
pub mod dataview;
pub mod date;
pub mod error;
pub mod eval;
pub mod function;
pub mod generator;
pub mod generator_function;
pub mod iterable;
pub mod json;
pub mod map;
pub mod math;
pub mod number;
pub mod object;
pub mod promise;
pub mod proxy;
pub mod reflect;
pub mod regexp;
pub mod set;
pub mod string;
pub mod symbol;
pub mod typed_array;
pub mod uri;
pub mod weak;
pub mod weak_map;
pub mod weak_set;

#[cfg(feature = "annex-b")]
pub mod escape;

#[cfg(feature = "intl")]
pub mod intl;

pub(crate) use self::{
    array::Array,
    async_function::AsyncFunction,
    bigint::BigInt,
    boolean::Boolean,
    dataview::DataView,
    date::Date,
    error::{
        AggregateError, Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError,
        UriError,
    },
    eval::Eval,
    function::BuiltInFunctionObject,
    json::Json,
    map::Map,
    math::Math,
    number::{IsFinite, IsNaN, Number, ParseFloat, ParseInt},
    object::Object as BuiltInObjectObject,
    promise::Promise,
    proxy::Proxy,
    reflect::Reflect,
    regexp::RegExp,
    set::Set,
    string::String,
    symbol::Symbol,
    typed_array::{
        BigInt64Array, BigUint64Array, Float32Array, Float64Array, Int16Array, Int32Array,
        Int8Array, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray,
    },
};

use crate::{
    builtins::{
        array::ArrayIterator,
        array_buffer::ArrayBuffer,
        async_generator::AsyncGenerator,
        async_generator_function::AsyncGeneratorFunction,
        error::r#type::ThrowTypeError,
        generator::Generator,
        generator_function::GeneratorFunction,
        iterable::{AsyncFromSyncIterator, AsyncIterator, Iterator},
        map::MapIterator,
        object::for_in_iterator::ForInIterator,
        regexp::RegExpStringIterator,
        set::SetIterator,
        string::StringIterator,
        typed_array::TypedArray,
        uri::{DecodeUri, DecodeUriComponent, EncodeUri, EncodeUriComponent},
        weak::WeakRef,
        weak_map::WeakMap,
        weak_set::WeakSet,
    },
    context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
    js_string,
    native_function::{NativeFunction, NativeFunctionPointer},
    object::{
        shape::{property_table::PropertyTableInner, slot::SlotAttributes},
        FunctionBinding, JsFunction, JsObject, JsPrototype, Object, ObjectData, ObjectKind,
        CONSTRUCTOR, PROTOTYPE,
    },
    property::{Attribute, PropertyDescriptor, PropertyKey},
    realm::Realm,
    string::utf16,
    Context, JsResult, JsString, JsValue,
};

/// A [Well-Known Intrinsic Object].
///
/// Well-known intrinsics are built-in objects that are explicitly referenced by the algorithms of
/// the specification and which usually have realm-specific identities.
///
/// [Well-Known Intrinsic Object]: https://tc39.es/ecma262/#sec-well-known-intrinsic-objects
pub(crate) trait IntrinsicObject {
    /// Initializes the intrinsic object.
    ///
    /// This is where the methods, properties, static methods and the constructor of a built-in must
    /// be initialized to be accessible from ECMAScript.
    fn init(realm: &Realm);

    /// Gets the intrinsic object.
    fn get(intrinsics: &Intrinsics) -> JsObject;
}

/// A [built-in object].
///
/// This trait must be implemented for any global built-in that lives in the global context of a script.
///
/// [built-in object]: https://tc39.es/ecma262/#sec-built-in-object
pub(crate) trait BuiltInObject: IntrinsicObject {
    /// Binding name of the builtin inside the global object.
    ///
    /// E.g. If you want access the properties of a `Complex` built-in with the name `Cplx` you must
    /// assign `"Cplx"` to this constant, making any property inside it accessible from ECMAScript
    /// as `Cplx.prop`
    const NAME: &'static str;

    /// Property attribute flags of the built-in. Check [`Attribute`] for more information.
    const ATTRIBUTE: Attribute = Attribute::WRITABLE
        .union(Attribute::NON_ENUMERABLE)
        .union(Attribute::CONFIGURABLE);
}

/// A [built-in object] that is also a constructor.
///
/// This trait must be implemented for any global built-in that can also be called with `new` to
/// construct an object instance e.g. `Array`, `Map` or `Object`.
///
/// [built-in object]: https://tc39.es/ecma262/#sec-built-in-object
pub(crate) trait BuiltInConstructor: BuiltInObject {
    /// The amount of arguments this function object takes.
    const LENGTH: usize;

    /// The corresponding standard constructor of this constructor.
    const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor;

    /// The native constructor function.
    fn constructor(
        new_target: &JsValue,
        args: &[JsValue],
        context: &mut Context<'_>,
    ) -> JsResult<JsValue>;
}

fn global_binding<B: BuiltInObject>(context: &mut Context<'_>) -> JsResult<()> {
    let name = B::NAME;
    let attr = B::ATTRIBUTE;
    let intrinsic = B::get(context.intrinsics());
    let global_object = context.global_object();

    global_object.define_property_or_throw(
        name,
        PropertyDescriptor::builder()
            .value(intrinsic)
            .writable(attr.writable())
            .enumerable(attr.enumerable())
            .configurable(attr.configurable())
            .build(),
        context,
    )?;
    Ok(())
}

impl Realm {
    /// Abstract operation [`CreateIntrinsics ( realmRec )`][spec]
    ///
    /// [spec]: https://tc39.es/ecma262/#sec-createintrinsics
    pub(crate) fn initialize(&self) {
        BuiltInFunctionObject::init(self);
        BuiltInObjectObject::init(self);
        Iterator::init(self);
        AsyncIterator::init(self);
        AsyncFromSyncIterator::init(self);
        ForInIterator::init(self);
        Math::init(self);
        Json::init(self);
        Array::init(self);
        ArrayIterator::init(self);
        Proxy::init(self);
        ArrayBuffer::init(self);
        BigInt::init(self);
        Boolean::init(self);
        Date::init(self);
        DataView::init(self);
        Map::init(self);
        MapIterator::init(self);
        IsFinite::init(self);
        IsNaN::init(self);
        ParseInt::init(self);
        ParseFloat::init(self);
        Number::init(self);
        Eval::init(self);
        Set::init(self);
        SetIterator::init(self);
        String::init(self);
        StringIterator::init(self);
        RegExp::init(self);
        RegExpStringIterator::init(self);
        TypedArray::init(self);
        Int8Array::init(self);
        Uint8Array::init(self);
        Uint8ClampedArray::init(self);
        Int16Array::init(self);
        Uint16Array::init(self);
        Int32Array::init(self);
        Uint32Array::init(self);
        BigInt64Array::init(self);
        BigUint64Array::init(self);
        Float32Array::init(self);
        Float64Array::init(self);
        Symbol::init(self);
        Error::init(self);
        RangeError::init(self);
        ReferenceError::init(self);
        TypeError::init(self);
        ThrowTypeError::init(self);
        SyntaxError::init(self);
        EvalError::init(self);
        UriError::init(self);
        AggregateError::init(self);
        Reflect::init(self);
        Generator::init(self);
        GeneratorFunction::init(self);
        Promise::init(self);
        AsyncFunction::init(self);
        AsyncGenerator::init(self);
        AsyncGeneratorFunction::init(self);
        EncodeUri::init(self);
        EncodeUriComponent::init(self);
        DecodeUri::init(self);
        DecodeUriComponent::init(self);
        WeakRef::init(self);
        WeakMap::init(self);
        WeakSet::init(self);

        #[cfg(feature = "annex-b")]
        {
            escape::Escape::init(self);
            escape::Unescape::init(self);
        }

        #[cfg(feature = "intl")]
        {
            intl::Intl::init(self);
            intl::Collator::init(self);
            intl::ListFormat::init(self);
            intl::Locale::init(self);
            intl::DateTimeFormat::init(self);
            intl::Segmenter::init(self);
            intl::segmenter::Segments::init(self);
            intl::segmenter::SegmentIterator::init(self);
        }
    }
}

/// Abstract operation [`SetDefaultGlobalBindings ( realmRec )`][spec].
///
/// [spec]: https://tc39.es/ecma262/#sec-setdefaultglobalbindings
pub(crate) fn set_default_global_bindings(context: &mut Context<'_>) -> JsResult<()> {
    let global_object = context.global_object();

    global_object.define_property_or_throw(
        utf16!("globalThis"),
        PropertyDescriptor::builder()
            .value(context.realm().global_this().clone())
            .writable(true)
            .enumerable(false)
            .configurable(true),
        context,
    )?;
    let restricted = PropertyDescriptor::builder()
        .writable(false)
        .enumerable(false)
        .configurable(false);
    global_object.define_property_or_throw(
        utf16!("Infinity"),
        restricted.clone().value(f64::INFINITY),
        context,
    )?;
    global_object.define_property_or_throw(
        utf16!("NaN"),
        restricted.clone().value(f64::NAN),
        context,
    )?;
    global_object.define_property_or_throw(
        utf16!("undefined"),
        restricted.value(JsValue::undefined()),
        context,
    )?;

    global_binding::<BuiltInFunctionObject>(context)?;
    global_binding::<BuiltInObjectObject>(context)?;
    global_binding::<Math>(context)?;
    global_binding::<Json>(context)?;
    global_binding::<Array>(context)?;
    global_binding::<Proxy>(context)?;
    global_binding::<ArrayBuffer>(context)?;
    global_binding::<BigInt>(context)?;
    global_binding::<Boolean>(context)?;
    global_binding::<Date>(context)?;
    global_binding::<DataView>(context)?;
    global_binding::<Map>(context)?;
    global_binding::<IsFinite>(context)?;
    global_binding::<IsNaN>(context)?;
    global_binding::<ParseInt>(context)?;
    global_binding::<ParseFloat>(context)?;
    global_binding::<Number>(context)?;
    global_binding::<Eval>(context)?;
    global_binding::<Set>(context)?;
    global_binding::<String>(context)?;
    global_binding::<RegExp>(context)?;
    global_binding::<TypedArray>(context)?;
    global_binding::<Int8Array>(context)?;
    global_binding::<Uint8Array>(context)?;
    global_binding::<Uint8ClampedArray>(context)?;
    global_binding::<Int16Array>(context)?;
    global_binding::<Uint16Array>(context)?;
    global_binding::<Int32Array>(context)?;
    global_binding::<Uint32Array>(context)?;
    global_binding::<BigInt64Array>(context)?;
    global_binding::<BigUint64Array>(context)?;
    global_binding::<Float32Array>(context)?;
    global_binding::<Float64Array>(context)?;
    global_binding::<Symbol>(context)?;
    global_binding::<Error>(context)?;
    global_binding::<RangeError>(context)?;
    global_binding::<ReferenceError>(context)?;
    global_binding::<TypeError>(context)?;
    global_binding::<SyntaxError>(context)?;
    global_binding::<EvalError>(context)?;
    global_binding::<UriError>(context)?;
    global_binding::<AggregateError>(context)?;
    global_binding::<Reflect>(context)?;
    global_binding::<Promise>(context)?;
    global_binding::<EncodeUri>(context)?;
    global_binding::<EncodeUriComponent>(context)?;
    global_binding::<DecodeUri>(context)?;
    global_binding::<DecodeUriComponent>(context)?;
    global_binding::<WeakRef>(context)?;
    global_binding::<WeakMap>(context)?;
    global_binding::<WeakSet>(context)?;

    #[cfg(feature = "annex-b")]
    {
        global_binding::<escape::Escape>(context)?;
        global_binding::<escape::Unescape>(context)?;
    }

    #[cfg(feature = "intl")]
    global_binding::<intl::Intl>(context)?;

    Ok(())
}

// === Builder typestate ===

#[derive(Debug)]
enum BuiltInObjectInitializer {
    Shared(JsObject),
    Unique { object: Object, data: ObjectData },
}

impl BuiltInObjectInitializer {
    /// Inserts a new property descriptor into the builtin.
    fn insert<K, P>(&mut self, key: K, property: P)
    where
        K: Into<PropertyKey>,
        P: Into<PropertyDescriptor>,
    {
        match self {
            Self::Shared(obj) => obj.borrow_mut().insert(key, property),
            Self::Unique { object, .. } => object.insert(key, property),
        };
    }

    /// Sets the prototype of the builtin
    fn set_prototype(&mut self, prototype: JsObject) {
        match self {
            Self::Shared(obj) => {
                let mut obj = obj.borrow_mut();
                obj.set_prototype(prototype);
            }
            Self::Unique { object, .. } => {
                object.set_prototype(prototype);
            }
        }
    }

    /// Sets the `ObjectData` of the builtin.
    ///
    /// # Panics
    ///
    /// Panics if the builtin is a shared builtin and the data's vtable is not the same as the
    /// builtin's vtable.
    fn set_data(&mut self, new_data: ObjectData) {
        match self {
            Self::Shared(obj) => {
                assert!(
                    std::ptr::eq(obj.vtable(), new_data.internal_methods),
                    "intrinsic object's vtable didn't match with new data"
                );
                *obj.borrow_mut().kind_mut() = new_data.kind;
            }
            Self::Unique { ref mut data, .. } => *data = new_data,
        }
    }

    /// Gets a shared object from the builtin, transitioning its state if it's necessary.
    fn as_shared(&mut self) -> JsObject {
        match std::mem::replace(
            self,
            Self::Unique {
                object: Object::default(),
                data: ObjectData::ordinary(),
            },
        ) {
            Self::Shared(obj) => {
                *self = Self::Shared(obj.clone());
                obj
            }
            Self::Unique { mut object, data } => {
                *object.kind_mut() = data.kind;
                let obj = JsObject::from_object_and_vtable(object, data.internal_methods);
                *self = Self::Shared(obj.clone());
                obj
            }
        }
    }

    /// Converts the builtin into a shared object.
    fn into_shared(mut self) -> JsObject {
        self.as_shared()
    }
}

/// Marker for a constructor function.
struct Constructor {
    prototype: JsObject,
    inherits: JsPrototype,
    attributes: Attribute,
}

/// Marker for a constructor function without a custom prototype for its instances.
struct ConstructorNoProto;

/// Marker for an ordinary function.
struct OrdinaryFunction;

/// Indicates if the marker is a constructor.
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.
struct Callable<Kind> {
    function: NativeFunctionPointer,
    name: JsString,
    length: usize,
    kind: Kind,
    realm: Realm,
}

/// Marker for an ordinary object.
struct OrdinaryObject;

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

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

        let object = object.as_shared();

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

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

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

impl<S: ApplyToObject + IsConstructor> ApplyToObject for Callable<S> {
    fn apply_to(self, object: &mut BuiltInObjectInitializer) {
        let function = ObjectData::function(
            function::Function::new(
                function::FunctionKind::Native {
                    function: NativeFunction::from_fn_ptr(self.function),
                    constructor: S::IS_CONSTRUCTOR.then_some(function::ConstructorKind::Base),
                },
                self.realm,
            ),
            S::IS_CONSTRUCTOR,
        );
        object.set_data(function);
        object.insert(
            utf16!("length"),
            PropertyDescriptor::builder()
                .value(self.length)
                .writable(false)
                .enumerable(false)
                .configurable(true),
        );
        object.insert(
            utf16!("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, _: &mut BuiltInObjectInitializer) {}
}

/// 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"]
struct BuiltInBuilder<'ctx, Kind> {
    realm: &'ctx Realm,
    object: BuiltInObjectInitializer,
    kind: Kind,
    prototype: JsObject,
}

impl<'ctx> BuiltInBuilder<'ctx, OrdinaryObject> {
    // fn new(realm: &'ctx Realm) -> BuiltInBuilder<'ctx, OrdinaryObject> {
    //     BuiltInBuilder {
    //         realm,
    //         object: BuiltInObjectInitializer::Unique {
    //             object: Object::default(),
    //             data: ObjectData::ordinary(),
    //         },
    //         kind: OrdinaryObject,
    //         prototype: realm.intrinsics().constructors().object().prototype(),
    //     }
    // }

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

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]
    const fn length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

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

    /// Adds a new static method to the builtin object.
    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
            .get(&binding.binding)
            .is_none());
        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.
    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.get(&key).is_none());
        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.
    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.get(&key).is_none());
        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.
    fn prototype(mut self, prototype: JsObject) -> Self {
        self.__proto__ = Some(prototype);
        self
    }

    /// Adds a new method to the constructor's prototype.
    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
            .get(&binding.binding)
            .is_none());
        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.
    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.get(&key).is_none());
        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.
    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.get(&key).is_none());
        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)]
    fn inherits(mut self, prototype: JsPrototype) -> Self {
        self.inherits = prototype;
        self
    }

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

    fn build(mut self) {
        let function = function::Function::new(
            function::FunctionKind::Native {
                function: NativeFunction::from_fn_ptr(self.function),
                constructor: (true).then_some(function::ConstructorKind::Base),
            },
            self.realm.clone(),
        );

        let length = self.length;
        let name = self.name.clone();
        let prototype = self.prototype.clone();
        self = self.static_property("length", length, Attribute::CONFIGURABLE);
        self = self.static_property("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();
        *object.kind_mut() = ObjectKind::Function(function);
        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);
    }

    fn build_without_prototype(mut self) {
        let function = function::Function::new(
            function::FunctionKind::Native {
                function: NativeFunction::from_fn_ptr(self.function),
                constructor: (true).then_some(function::ConstructorKind::Base),
            },
            self.realm.clone(),
        );

        let length = self.length;
        let name = self.name.clone();
        self = self.static_property("length", length, Attribute::CONFIGURABLE);
        self = self.static_property("name", name, Attribute::CONFIGURABLE);

        let mut object = self.object.borrow_mut();
        *object.kind_mut() = ObjectKind::Function(function);
        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);
    }
}

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]
    const fn length(mut self, length: usize) -> Self {
        self.length = length;
        self
    }

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

    fn build(self) -> JsFunction {
        let function = function::FunctionKind::Native {
            function: NativeFunction::from_fn_ptr(self.function),
            constructor: None,
        };

        let function = function::Function::new(function, self.realm.clone());

        let object = self.realm.intrinsics().templates().function().create(
            ObjectData::function(function, false),
            vec![JsValue::new(self.length), JsValue::new(self.name)],
        );

        JsFunction::from_object_unchecked(object)
    }
}

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

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

    fn callable_with_object(
        realm: &'ctx Realm,
        object: JsObject,
        function: NativeFunctionPointer,
    ) -> BuiltInBuilder<'ctx, Callable<OrdinaryFunction>> {
        BuiltInBuilder {
            realm,
            object: BuiltInObjectInitializer::Shared(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>> {
    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::default(),
            object_storage: Vec::default(),
            object: constructor.constructor(),
            prototype_property_table: PropertyTableInner::default(),
            prototype_storage: Vec::default(),
            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.
    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();

        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.
    fn static_property<K, V>(mut 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.
    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]
    const fn length(mut self, length: usize) -> Self {
        self.kind.length = length;
        self
    }

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

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

        self.object.set_prototype(self.prototype);

        self.object.into_shared()
    }
}

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

        self.object.set_prototype(self.prototype);

        JsFunction::from_object_unchecked(self.object.into_shared())
    }
}