Skip to main content

boa_engine/object/
mod.rs

1//! Boa's representation of a JavaScript object and builtin object wrappers
2//!
3//! For the builtin object wrappers, please see [`object::builtins`][builtins] for implementors.
4
5use datatypes::ObjectData;
6pub use jsobject::{RecursionLimiter, Ref, RefMut};
7pub use operations::IntegrityLevel;
8pub use property_map::*;
9use thin_vec::ThinVec;
10
11use self::{internal_methods::ORDINARY_INTERNAL_METHODS, shape::Shape};
12use crate::{
13    Context, JsString, JsSymbol, JsValue,
14    builtins::{OrdinaryObject, function::ConstructorKind},
15    context::intrinsics::StandardConstructor,
16    js_string,
17    native_function::{NativeFunction, NativeFunctionObject},
18    property::{Attribute, PropertyDescriptor, PropertyKey},
19    realm::Realm,
20    string::StaticJsStrings,
21};
22
23use boa_gc::{Finalize, Trace};
24use std::{
25    any::{Any, TypeId},
26    fmt::Debug,
27};
28
29#[cfg(test)]
30mod tests;
31
32pub(crate) mod internal_methods;
33
34pub mod builtins;
35mod datatypes;
36mod jsobject;
37mod operations;
38mod property_map;
39
40pub mod shape;
41
42pub(crate) use builtins::*;
43
44pub use datatypes::JsData;
45pub use jsobject::*;
46
47/// Const `constructor`, usually set on prototypes as a key to point to their respective constructor object.
48pub const CONSTRUCTOR: JsString = js_string!("constructor");
49
50/// Const `prototype`, usually set on constructors as a key to point to their respective prototype object.
51pub const PROTOTYPE: JsString = js_string!("prototype");
52
53/// A type alias for an object prototype.
54///
55/// A `None` values means that the prototype is the `null` value.
56pub type JsPrototype = Option<JsObject>;
57
58/// The internal storage of an object's property values.
59///
60/// The [`shape::Shape`] contains the property names and attributes.
61pub(crate) type ObjectStorage = Vec<JsValue>;
62
63/// This trait allows Rust types to be passed around as objects.
64///
65/// This is automatically implemented when a type implements `Any`, `Trace`, and `JsData`.
66pub trait NativeObject: Any + Trace + JsData {
67    /// Convert the Rust type which implements `NativeObject` to a `&dyn Any`.
68    fn as_any(&self) -> &dyn Any;
69
70    /// Convert the Rust type which implements `NativeObject` to a `&mut dyn Any`.
71    fn as_mut_any(&mut self) -> &mut dyn Any;
72
73    /// Gets the type name of the value.
74    fn type_name_of_value(&self) -> &'static str;
75}
76
77// TODO: Use super trait casting in Rust 1.75
78impl<T: Any + Trace + JsData> NativeObject for T {
79    fn as_any(&self) -> &dyn Any {
80        self
81    }
82
83    fn as_mut_any(&mut self) -> &mut dyn Any {
84        self
85    }
86
87    fn type_name_of_value(&self) -> &'static str {
88        fn name_of_val<T: ?Sized>(_val: &T) -> &'static str {
89            std::any::type_name::<T>()
90        }
91
92        name_of_val(self)
93    }
94}
95
96// TODO: Use super trait casting in Rust 1.75
97impl dyn NativeObject {
98    /// Returns `true` if the inner type is the same as `T`.
99    #[inline]
100    pub fn is<T: NativeObject>(&self) -> bool {
101        // Get `TypeId` of the type this function is instantiated with.
102        let t = TypeId::of::<T>();
103
104        // Get `TypeId` of the type in the trait object (`self`).
105        let concrete = self.type_id();
106
107        // Compare both `TypeId`s on equality.
108        t == concrete
109    }
110
111    /// Returns some reference to the inner value if it is of type `T`, or
112    /// `None` if it isn't.
113    #[inline]
114    pub fn downcast_ref<T: NativeObject>(&self) -> Option<&T> {
115        if self.is::<T>() {
116            // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
117            // that check for memory safety because we have implemented NativeObject for all types; no other
118            // impls can exist as they would conflict with our impl.
119            unsafe { Some(self.downcast_ref_unchecked()) }
120        } else {
121            None
122        }
123    }
124
125    /// Returns some mutable reference to the inner value if it is of type `T`, or
126    /// `None` if it isn't.
127    #[inline]
128    pub fn downcast_mut<T: NativeObject>(&mut self) -> Option<&mut T> {
129        if self.is::<T>() {
130            // SAFETY: Already checked if inner type is T, so this is safe.
131            unsafe { Some(self.downcast_mut_unchecked()) }
132        } else {
133            None
134        }
135    }
136
137    /// Returns a reference to the inner value as type `dyn T`.
138    ///
139    /// # Safety
140    ///
141    /// The contained value must be of type `T`. Calling this method
142    /// with the incorrect type is *undefined behavior*.
143    #[inline]
144    pub unsafe fn downcast_ref_unchecked<T: NativeObject>(&self) -> &T {
145        debug_assert!(self.is::<T>());
146        let ptr: *const dyn NativeObject = self;
147        // SAFETY: caller guarantees that T is the correct type
148        unsafe { &*ptr.cast::<T>() }
149    }
150
151    /// Returns a mutable reference to the inner value as type `dyn T`.
152    ///
153    /// # Safety
154    ///
155    /// The contained value must be of type `T`. Calling this method
156    /// with the incorrect type is *undefined behavior*.
157    #[inline]
158    pub unsafe fn downcast_mut_unchecked<T: NativeObject>(&mut self) -> &mut T {
159        debug_assert!(self.is::<T>());
160        // SAFETY: caller guarantees that T is the correct type
161        let ptr: *mut dyn NativeObject = self;
162        unsafe { &mut *ptr.cast::<T>() }
163    }
164}
165
166/// The internal representation of a JavaScript object.
167#[derive(Debug, Finalize, Trace)]
168// SAFETY: This does not implement drop, so this is safe.
169#[boa_gc(unsafe_no_drop)]
170// SAFETY: This type must use `#[repr(C)]` to prevent the compiler from reordering fields,
171//         as it is used for casting between types.
172#[repr(C)]
173pub struct Object<T: ?Sized> {
174    /// The collection of properties contained in the object
175    pub(crate) properties: PropertyMap,
176    /// Whether it can have new properties added to it.
177    pub(crate) extensible: bool,
178    /// The `[[PrivateElements]]` internal slot.
179    private_elements: ThinVec<(PrivateName, PrivateElement)>,
180    /// The inner object data
181    data: ObjectData<T>,
182}
183
184impl<T: Default> Default for Object<T> {
185    fn default() -> Self {
186        Self {
187            properties: PropertyMap::default(),
188            extensible: true,
189            private_elements: ThinVec::new(),
190            data: ObjectData::default(),
191        }
192    }
193}
194
195/// A Private Name.
196#[derive(Clone, Debug, PartialEq, Eq, Trace, Finalize)]
197pub struct PrivateName {
198    /// The `[[Description]]` internal slot of the private name.
199    description: JsString,
200
201    /// The unique identifier of the private name.
202    id: usize,
203}
204
205impl PrivateName {
206    /// Create a new private name.
207    pub(crate) const fn new(description: JsString, id: usize) -> Self {
208        Self { description, id }
209    }
210}
211
212/// The representation of private object elements.
213#[derive(Clone, Debug, Trace, Finalize)]
214pub enum PrivateElement {
215    /// A private field.
216    Field(JsValue),
217
218    /// A private method.
219    Method(JsObject),
220
221    /// A private element accessor.
222    Accessor {
223        /// A getter function.
224        getter: Option<JsObject>,
225
226        /// A setter function.
227        setter: Option<JsObject>,
228    },
229}
230
231impl<T: ?Sized> Object<T> {
232    /// Returns the shape of the object.
233    #[must_use]
234    pub const fn shape(&self) -> &Shape {
235        &self.properties.shape
236    }
237
238    /// Returns the data of the object.
239    #[inline]
240    #[must_use]
241    pub fn data(&self) -> &T {
242        self.data.as_ref()
243    }
244
245    /// Returns the data of the object.
246    #[inline]
247    #[must_use]
248    pub fn data_mut(&mut self) -> &mut T {
249        self.data.as_mut()
250    }
251
252    /// Gets the prototype instance of this object.
253    #[inline]
254    #[must_use]
255    pub fn prototype(&self) -> JsPrototype {
256        self.properties.shape.prototype()
257    }
258
259    /// Sets the prototype instance of the object.
260    ///
261    /// [More information][spec]
262    ///
263    /// [spec]: https://tc39.es/ecma262/#sec-invariants-of-the-essential-internal-methods
264    #[track_caller]
265    pub fn set_prototype<O: Into<JsPrototype>>(&mut self, prototype: O) -> bool {
266        let prototype = prototype.into();
267        if self.extensible {
268            self.properties.shape = self.properties.shape.change_prototype_transition(prototype);
269            true
270        } else {
271            // If target is non-extensible, [[SetPrototypeOf]] must return false
272            // unless V is the SameValue as the target's observed [[GetPrototypeOf]] value.
273            self.prototype() == prototype
274        }
275    }
276
277    /// Returns the properties of the object.
278    #[inline]
279    #[must_use]
280    pub const fn properties(&self) -> &PropertyMap {
281        &self.properties
282    }
283
284    #[inline]
285    pub(crate) fn properties_mut(&mut self) -> &mut PropertyMap {
286        &mut self.properties
287    }
288
289    /// Inserts a field in the object `properties` without checking if it's writable.
290    ///
291    /// If a field was already in the object with the same name, then `true` is returned
292    /// otherwise, `false` is returned.
293    pub(crate) fn insert<K, P>(&mut self, key: K, property: P) -> bool
294    where
295        K: Into<PropertyKey>,
296        P: Into<PropertyDescriptor>,
297    {
298        self.properties.insert(&key.into(), property.into())
299    }
300
301    /// Helper function for property removal without checking if it's configurable.
302    ///
303    /// Returns `true` if the property was removed, `false` otherwise.
304    #[inline]
305    pub(crate) fn remove(&mut self, key: &PropertyKey) -> bool {
306        self.properties.remove(key)
307    }
308
309    /// Append a private element to an object.
310    pub(crate) fn append_private_element(&mut self, name: PrivateName, element: PrivateElement) {
311        if let PrivateElement::Accessor { getter, setter } = &element {
312            for (key, value) in &mut self.private_elements {
313                if name == *key
314                    && let PrivateElement::Accessor {
315                        getter: existing_getter,
316                        setter: existing_setter,
317                    } = value
318                {
319                    if existing_getter.is_none() {
320                        existing_getter.clone_from(getter);
321                    }
322                    if existing_setter.is_none() {
323                        existing_setter.clone_from(setter);
324                    }
325                    return;
326                }
327            }
328        }
329
330        self.private_elements.push((name, element));
331    }
332}
333
334/// The functions binding.
335///
336/// Specifies what is the name of the function object (`name` property),
337/// and the binding name of the function object which can be different
338/// from the function name.
339///
340/// The only way to construct this is with the `From` trait.
341///
342/// There are two implementations:
343///  - From a single type `T` which implements `Into<FunctionBinding>` which sets the binding
344///    name and the function name to the same value.
345///  - From a tuple `(B: Into<PropertyKey>, N: Into<JsString>)`, where the `B` is the binding name
346///    and the `N` is the function name.
347#[derive(Debug, Clone)]
348pub struct FunctionBinding {
349    pub(crate) binding: PropertyKey,
350    pub(crate) name: JsString,
351}
352
353impl From<JsString> for FunctionBinding {
354    #[inline]
355    fn from(name: JsString) -> Self {
356        Self {
357            binding: name.clone().into(),
358            name,
359        }
360    }
361}
362
363impl From<JsSymbol> for FunctionBinding {
364    #[inline]
365    fn from(binding: JsSymbol) -> Self {
366        Self {
367            name: binding.fn_name(),
368            binding: binding.into(),
369        }
370    }
371}
372
373impl<B, N> From<(B, N)> for FunctionBinding
374where
375    B: Into<PropertyKey>,
376    N: Into<JsString>,
377{
378    fn from((binding, name): (B, N)) -> Self {
379        Self {
380            binding: binding.into(),
381            name: name.into(),
382        }
383    }
384}
385
386/// Builder for creating native function objects
387#[derive(Debug)]
388pub struct FunctionObjectBuilder<'realm> {
389    realm: &'realm Realm,
390    function: NativeFunction,
391    constructor: Option<ConstructorKind>,
392    name: JsString,
393    length: usize,
394}
395
396impl<'realm> FunctionObjectBuilder<'realm> {
397    /// Create a new `FunctionBuilder` for creating a native function.
398    #[inline]
399    #[must_use]
400    pub fn new(realm: &'realm Realm, function: NativeFunction) -> Self {
401        Self {
402            realm,
403            function,
404            constructor: None,
405            name: js_string!(),
406            length: 0,
407        }
408    }
409
410    /// Specify the name property of object function object.
411    ///
412    /// The default is `""` (empty string).
413    #[must_use]
414    pub fn name<N>(mut self, name: N) -> Self
415    where
416        N: Into<JsString>,
417    {
418        self.name = name.into();
419        self
420    }
421
422    /// Specify the length property of object function object.
423    ///
424    /// How many arguments this function takes.
425    ///
426    /// The default is `0`.
427    #[inline]
428    #[must_use]
429    pub const fn length(mut self, length: usize) -> Self {
430        self.length = length;
431        self
432    }
433
434    /// Specify whether the object function object can be called with `new` keyword.
435    ///
436    /// The default is `false`.
437    #[must_use]
438    pub fn constructor(mut self, yes: bool) -> Self {
439        self.constructor = yes.then_some(ConstructorKind::Base);
440        self
441    }
442
443    /// Build the function object.
444    #[must_use]
445    pub fn build(self) -> JsFunction {
446        let object = self.realm.intrinsics().templates().function().create(
447            NativeFunctionObject {
448                f: self.function,
449                name: self.name.clone(),
450                constructor: self.constructor,
451                realm: Some(self.realm.clone()),
452            },
453            vec![self.length.into(), self.name.into()],
454        );
455
456        JsFunction::from_object_unchecked(object)
457    }
458}
459
460/// Builder for creating objects with properties.
461///
462/// # Examples
463///
464/// ```
465/// # use boa_engine::{
466/// #     Context,
467/// #     JsValue,
468/// #     NativeFunction,
469/// #     object::ObjectInitializer,
470/// #     property::Attribute,
471/// #     js_string,
472/// # };
473/// let mut context = Context::default();
474/// let object = ObjectInitializer::new(&mut context)
475///     .property(js_string!("hello"), js_string!("world"), Attribute::all())
476///     .property(1, 1, Attribute::all())
477///     .function(
478///         NativeFunction::from_fn_ptr(|_, _, _| Ok(JsValue::undefined())),
479///         js_string!("func"),
480///         0,
481///     )
482///     .build();
483/// ```
484///
485/// The equivalent in JavaScript would be:
486/// ```text
487/// let object = {
488///     hello: "world",
489///     "1": 1,
490///     func: function() {}
491/// }
492/// ```
493#[derive(Debug)]
494pub struct ObjectInitializer<'ctx> {
495    context: &'ctx mut Context,
496    object: JsObject,
497}
498
499impl<'ctx> ObjectInitializer<'ctx> {
500    /// Create a new `ObjectBuilder`.
501    #[inline]
502    pub fn new(context: &'ctx mut Context) -> Self {
503        let object = JsObject::with_object_proto(context.intrinsics());
504        Self { context, object }
505    }
506
507    /// Create a new `ObjectBuilder` with custom [`NativeObject`] data.
508    pub fn with_native_data<T: NativeObject>(data: T, context: &'ctx mut Context) -> Self {
509        let object = JsObject::from_proto_and_data_with_shared_shape(
510            context.root_shape(),
511            context.intrinsics().constructors().object().prototype(),
512            data,
513        );
514        Self { context, object }
515    }
516
517    /// Create a new `ObjectBuilder` with custom [`NativeObject`] data and custom prototype.
518    pub fn with_native_data_and_proto<T: NativeObject>(
519        data: T,
520        proto: JsObject,
521        context: &'ctx mut Context,
522    ) -> Self {
523        let object =
524            JsObject::from_proto_and_data_with_shared_shape(context.root_shape(), proto, data);
525        Self { context, object }
526    }
527
528    /// Add a function to the object.
529    pub fn function<B>(&mut self, function: NativeFunction, binding: B, length: usize) -> &mut Self
530    where
531        B: Into<FunctionBinding>,
532    {
533        let binding = binding.into();
534        let function = FunctionObjectBuilder::new(self.context.realm(), function)
535            .name(binding.name)
536            .length(length)
537            .constructor(false)
538            .build();
539
540        self.object.borrow_mut().insert(
541            binding.binding,
542            PropertyDescriptor::builder()
543                .value(function)
544                .writable(true)
545                .enumerable(false)
546                .configurable(true),
547        );
548        self
549    }
550
551    /// Add a property to the object.
552    pub fn property<K, V>(&mut self, key: K, value: V, attribute: Attribute) -> &mut Self
553    where
554        K: Into<PropertyKey>,
555        V: Into<JsValue>,
556    {
557        let property = PropertyDescriptor::builder()
558            .value(value)
559            .writable(attribute.writable())
560            .enumerable(attribute.enumerable())
561            .configurable(attribute.configurable());
562        self.object.borrow_mut().insert(key, property);
563        self
564    }
565
566    /// Add new accessor property to the object.
567    ///
568    /// # Panics
569    ///
570    /// If both getter or setter are [`None`].
571    pub fn accessor<K>(
572        &mut self,
573        key: K,
574        get: Option<JsFunction>,
575        set: Option<JsFunction>,
576        attribute: Attribute,
577    ) -> &mut Self
578    where
579        K: Into<PropertyKey>,
580    {
581        // Accessors should have at least one function.
582        assert!(set.is_some() || get.is_some());
583
584        let property = PropertyDescriptor::builder()
585            .maybe_get(get)
586            .maybe_set(set)
587            .enumerable(attribute.enumerable())
588            .configurable(attribute.configurable());
589        self.object.borrow_mut().insert(key, property);
590        self
591    }
592
593    /// Build the object.
594    #[inline]
595    pub fn build(&mut self) -> JsObject {
596        self.object.clone()
597    }
598
599    /// Gets the context used to create the object.
600    #[inline]
601    pub fn context(&mut self) -> &mut Context {
602        self.context
603    }
604}
605
606/// Builder for creating constructors objects, like `Array`.
607#[derive(Debug)]
608pub struct ConstructorBuilder<'ctx> {
609    context: &'ctx mut Context,
610    function: NativeFunction,
611    constructor_object: Object<OrdinaryObject>,
612    has_prototype_property: bool,
613    prototype: Object<OrdinaryObject>,
614    name: JsString,
615    length: usize,
616    callable: bool,
617    kind: Option<ConstructorKind>,
618    inherit: Option<JsPrototype>,
619    custom_prototype: Option<JsPrototype>,
620}
621
622impl<'ctx> ConstructorBuilder<'ctx> {
623    /// Create a new `ConstructorBuilder`.
624    #[inline]
625    pub fn new(context: &'ctx mut Context, function: NativeFunction) -> ConstructorBuilder<'ctx> {
626        Self {
627            context,
628            function,
629            constructor_object: Object {
630                data: ObjectData::new(OrdinaryObject),
631                properties: PropertyMap::default(),
632                extensible: true,
633                private_elements: ThinVec::new(),
634            },
635            prototype: Object {
636                data: ObjectData::new(OrdinaryObject),
637                properties: PropertyMap::default(),
638                extensible: true,
639                private_elements: ThinVec::new(),
640            },
641            length: 0,
642            name: js_string!(),
643            callable: true,
644            kind: Some(ConstructorKind::Base),
645            inherit: None,
646            custom_prototype: None,
647            has_prototype_property: true,
648        }
649    }
650
651    /// Add new method to the constructors prototype.
652    pub fn method<B>(&mut self, function: NativeFunction, binding: B, length: usize) -> &mut Self
653    where
654        B: Into<FunctionBinding>,
655    {
656        let binding = binding.into();
657        let function = FunctionObjectBuilder::new(self.context.realm(), function)
658            .name(binding.name)
659            .length(length)
660            .constructor(false)
661            .build();
662
663        self.prototype.insert(
664            binding.binding,
665            PropertyDescriptor::builder()
666                .value(function)
667                .writable(true)
668                .enumerable(false)
669                .configurable(true),
670        );
671        self
672    }
673
674    /// Add new static method to the constructors object itself.
675    pub fn static_method<B>(
676        &mut self,
677        function: NativeFunction,
678        binding: B,
679        length: usize,
680    ) -> &mut Self
681    where
682        B: Into<FunctionBinding>,
683    {
684        let binding = binding.into();
685        let function = FunctionObjectBuilder::new(self.context.realm(), function)
686            .name(binding.name)
687            .length(length)
688            .constructor(false)
689            .build();
690
691        self.constructor_object.insert(
692            binding.binding,
693            PropertyDescriptor::builder()
694                .value(function)
695                .writable(true)
696                .enumerable(false)
697                .configurable(true),
698        );
699        self
700    }
701
702    /// Add new data property to the constructor's prototype.
703    pub fn property<K, V>(&mut self, key: K, value: V, attribute: Attribute) -> &mut Self
704    where
705        K: Into<PropertyKey>,
706        V: Into<JsValue>,
707    {
708        let property = PropertyDescriptor::builder()
709            .value(value)
710            .writable(attribute.writable())
711            .enumerable(attribute.enumerable())
712            .configurable(attribute.configurable());
713        self.prototype.insert(key, property);
714        self
715    }
716
717    /// Add new static data property to the constructor object itself.
718    pub fn static_property<K, V>(&mut self, key: K, value: V, attribute: Attribute) -> &mut Self
719    where
720        K: Into<PropertyKey>,
721        V: Into<JsValue>,
722    {
723        let property = PropertyDescriptor::builder()
724            .value(value)
725            .writable(attribute.writable())
726            .enumerable(attribute.enumerable())
727            .configurable(attribute.configurable());
728        self.constructor_object.insert(key, property);
729        self
730    }
731
732    /// Add new accessor property to the constructor's prototype.
733    pub fn accessor<K>(
734        &mut self,
735        key: K,
736        get: Option<JsFunction>,
737        set: Option<JsFunction>,
738        attribute: Attribute,
739    ) -> &mut Self
740    where
741        K: Into<PropertyKey>,
742    {
743        let property = PropertyDescriptor::builder()
744            .maybe_get(get)
745            .maybe_set(set)
746            .enumerable(attribute.enumerable())
747            .configurable(attribute.configurable());
748        self.prototype.insert(key, property);
749        self
750    }
751
752    /// Add new static accessor property to the constructor object itself.
753    pub fn static_accessor<K>(
754        &mut self,
755        key: K,
756        get: Option<JsFunction>,
757        set: Option<JsFunction>,
758        attribute: Attribute,
759    ) -> &mut Self
760    where
761        K: Into<PropertyKey>,
762    {
763        let property = PropertyDescriptor::builder()
764            .maybe_get(get)
765            .maybe_set(set)
766            .enumerable(attribute.enumerable())
767            .configurable(attribute.configurable());
768        self.constructor_object.insert(key, property);
769        self
770    }
771
772    /// Add new property to the constructor's prototype.
773    pub fn property_descriptor<K, P>(&mut self, key: K, property: P) -> &mut Self
774    where
775        K: Into<PropertyKey>,
776        P: Into<PropertyDescriptor>,
777    {
778        let property = property.into();
779        self.prototype.insert(key, property);
780        self
781    }
782
783    /// Add new static property to the constructor object itself.
784    pub fn static_property_descriptor<K, P>(&mut self, key: K, property: P) -> &mut Self
785    where
786        K: Into<PropertyKey>,
787        P: Into<PropertyDescriptor>,
788    {
789        let property = property.into();
790        self.constructor_object.insert(key, property);
791        self
792    }
793
794    /// Specify how many arguments the constructor function takes.
795    ///
796    /// Default is `0`.
797    #[inline]
798    pub fn length(&mut self, length: usize) -> &mut Self {
799        self.length = length;
800        self
801    }
802
803    /// Specify the name of the constructor function.
804    ///
805    /// Default is `"[object]"`
806    pub fn name<N>(&mut self, name: N) -> &mut Self
807    where
808        N: AsRef<str>,
809    {
810        self.name = name.as_ref().into();
811        self
812    }
813
814    /// Specify whether the constructor function can be called.
815    ///
816    /// Default is `true`
817    #[inline]
818    pub fn callable(&mut self, callable: bool) -> &mut Self {
819        self.callable = callable;
820        self
821    }
822
823    /// Specify whether the constructor function can be called with `new` keyword.
824    ///
825    /// Default is `true`
826    #[inline]
827    pub fn constructor(&mut self, constructor: bool) -> &mut Self {
828        self.kind = constructor.then_some(ConstructorKind::Base);
829        self
830    }
831
832    /// Specify the parent prototype which objects created by this constructor
833    /// inherit from.
834    ///
835    /// Default is `Object.prototype`
836    pub fn inherit<O: Into<JsPrototype>>(&mut self, prototype: O) -> &mut Self {
837        self.inherit = Some(prototype.into());
838        self
839    }
840
841    /// Specify the `[[Prototype]]` internal field of this constructor.
842    ///
843    /// Default is `Function.prototype`
844    pub fn custom_prototype<O: Into<JsPrototype>>(&mut self, prototype: O) -> &mut Self {
845        self.custom_prototype = Some(prototype.into());
846        self
847    }
848
849    /// Specify whether the constructor function has a 'prototype' property.
850    ///
851    /// Default is `true`
852    #[inline]
853    pub fn has_prototype_property(&mut self, has_prototype_property: bool) -> &mut Self {
854        self.has_prototype_property = has_prototype_property;
855        self
856    }
857
858    /// Return the current context.
859    #[inline]
860    pub fn context(&mut self) -> &mut Context {
861        self.context
862    }
863
864    /// Build the constructor function object.
865    #[must_use]
866    pub fn build(mut self) -> StandardConstructor {
867        let length = PropertyDescriptor::builder()
868            .value(self.length)
869            .writable(false)
870            .enumerable(false)
871            .configurable(true);
872        let name = PropertyDescriptor::builder()
873            .value(self.name.clone())
874            .writable(false)
875            .enumerable(false)
876            .configurable(true);
877
878        let prototype = {
879            if let Some(proto) = self.inherit.take() {
880                self.prototype.set_prototype(proto);
881            } else {
882                self.prototype.set_prototype(
883                    self.context
884                        .intrinsics()
885                        .constructors()
886                        .object()
887                        .prototype(),
888                );
889            }
890
891            JsObject::from_object_and_vtable(self.prototype, &ORDINARY_INTERNAL_METHODS)
892        };
893
894        let constructor = {
895            let data = NativeFunctionObject {
896                f: self.function,
897                name: self.name.clone(),
898                constructor: self.kind,
899                realm: Some(self.context.realm().clone()),
900            };
901            let internal_methods = data.internal_methods();
902            let mut constructor = Object {
903                properties: self.constructor_object.properties,
904                extensible: self.constructor_object.extensible,
905                private_elements: self.constructor_object.private_elements,
906                data: ObjectData::new(data),
907            };
908
909            constructor.insert(StaticJsStrings::LENGTH, length);
910            constructor.insert(js_string!("name"), name);
911
912            if let Some(proto) = self.custom_prototype.take() {
913                constructor.set_prototype(proto);
914            } else {
915                constructor.set_prototype(
916                    self.context
917                        .intrinsics()
918                        .constructors()
919                        .function()
920                        .prototype(),
921                );
922            }
923
924            if self.has_prototype_property {
925                constructor.insert(
926                    PROTOTYPE,
927                    PropertyDescriptor::builder()
928                        .value(prototype.clone())
929                        .writable(false)
930                        .enumerable(false)
931                        .configurable(false),
932                );
933            }
934
935            JsObject::from_object_and_vtable(constructor, internal_methods)
936        };
937
938        {
939            let mut prototype = prototype.borrow_mut();
940            prototype.insert(
941                CONSTRUCTOR,
942                PropertyDescriptor::builder()
943                    .value(constructor.clone())
944                    .writable(true)
945                    .enumerable(false)
946                    .configurable(true),
947            );
948        }
949
950        StandardConstructor::new(JsFunction::from_object_unchecked(constructor), prototype)
951    }
952}