1use 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
47pub const CONSTRUCTOR: JsString = js_string!("constructor");
49
50pub const PROTOTYPE: JsString = js_string!("prototype");
52
53pub type JsPrototype = Option<JsObject>;
57
58pub(crate) type ObjectStorage = Vec<JsValue>;
62
63pub trait NativeObject: Any + Trace + JsData {
67 fn as_any(&self) -> &dyn Any;
69
70 fn as_mut_any(&mut self) -> &mut dyn Any;
72
73 fn type_name_of_value(&self) -> &'static str;
75}
76
77impl<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
96impl dyn NativeObject {
98 #[inline]
100 pub fn is<T: NativeObject>(&self) -> bool {
101 let t = TypeId::of::<T>();
103
104 let concrete = self.type_id();
106
107 t == concrete
109 }
110
111 #[inline]
114 pub fn downcast_ref<T: NativeObject>(&self) -> Option<&T> {
115 if self.is::<T>() {
116 unsafe { Some(self.downcast_ref_unchecked()) }
120 } else {
121 None
122 }
123 }
124
125 #[inline]
128 pub fn downcast_mut<T: NativeObject>(&mut self) -> Option<&mut T> {
129 if self.is::<T>() {
130 unsafe { Some(self.downcast_mut_unchecked()) }
132 } else {
133 None
134 }
135 }
136
137 #[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 unsafe { &*ptr.cast::<T>() }
149 }
150
151 #[inline]
158 pub unsafe fn downcast_mut_unchecked<T: NativeObject>(&mut self) -> &mut T {
159 debug_assert!(self.is::<T>());
160 let ptr: *mut dyn NativeObject = self;
162 unsafe { &mut *ptr.cast::<T>() }
163 }
164}
165
166#[derive(Debug, Finalize, Trace)]
168#[boa_gc(unsafe_no_drop)]
170#[repr(C)]
173pub struct Object<T: ?Sized> {
174 pub(crate) properties: PropertyMap,
176 pub(crate) extensible: bool,
178 private_elements: ThinVec<(PrivateName, PrivateElement)>,
180 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#[derive(Clone, Debug, PartialEq, Eq, Trace, Finalize)]
197pub struct PrivateName {
198 description: JsString,
200
201 id: usize,
203}
204
205impl PrivateName {
206 pub(crate) const fn new(description: JsString, id: usize) -> Self {
208 Self { description, id }
209 }
210}
211
212#[derive(Clone, Debug, Trace, Finalize)]
214pub enum PrivateElement {
215 Field(JsValue),
217
218 Method(JsObject),
220
221 Accessor {
223 getter: Option<JsObject>,
225
226 setter: Option<JsObject>,
228 },
229}
230
231impl<T: ?Sized> Object<T> {
232 #[must_use]
234 pub const fn shape(&self) -> &Shape {
235 &self.properties.shape
236 }
237
238 #[inline]
240 #[must_use]
241 pub fn data(&self) -> &T {
242 self.data.as_ref()
243 }
244
245 #[inline]
247 #[must_use]
248 pub fn data_mut(&mut self) -> &mut T {
249 self.data.as_mut()
250 }
251
252 #[inline]
254 #[must_use]
255 pub fn prototype(&self) -> JsPrototype {
256 self.properties.shape.prototype()
257 }
258
259 #[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 self.prototype() == prototype
274 }
275 }
276
277 #[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 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 #[inline]
305 pub(crate) fn remove(&mut self, key: &PropertyKey) -> bool {
306 self.properties.remove(key)
307 }
308
309 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#[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#[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 #[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 #[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 #[inline]
428 #[must_use]
429 pub const fn length(mut self, length: usize) -> Self {
430 self.length = length;
431 self
432 }
433
434 #[must_use]
438 pub fn constructor(mut self, yes: bool) -> Self {
439 self.constructor = yes.then_some(ConstructorKind::Base);
440 self
441 }
442
443 #[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#[derive(Debug)]
494pub struct ObjectInitializer<'ctx> {
495 context: &'ctx mut Context,
496 object: JsObject,
497}
498
499impl<'ctx> ObjectInitializer<'ctx> {
500 #[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 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 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 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 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 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 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 #[inline]
595 pub fn build(&mut self) -> JsObject {
596 self.object.clone()
597 }
598
599 #[inline]
601 pub fn context(&mut self) -> &mut Context {
602 self.context
603 }
604}
605
606#[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 #[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 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 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 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 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 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 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 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 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 #[inline]
798 pub fn length(&mut self, length: usize) -> &mut Self {
799 self.length = length;
800 self
801 }
802
803 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 #[inline]
818 pub fn callable(&mut self, callable: bool) -> &mut Self {
819 self.callable = callable;
820 self
821 }
822
823 #[inline]
827 pub fn constructor(&mut self, constructor: bool) -> &mut Self {
828 self.kind = constructor.then_some(ConstructorKind::Base);
829 self
830 }
831
832 pub fn inherit<O: Into<JsPrototype>>(&mut self, prototype: O) -> &mut Self {
837 self.inherit = Some(prototype.into());
838 self
839 }
840
841 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 #[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 #[inline]
860 pub fn context(&mut self) -> &mut Context {
861 self.context
862 }
863
864 #[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}