use datatypes::ObjectData;
pub use jsobject::{RecursionLimiter, Ref, RefMut};
pub use operations::IntegrityLevel;
pub use property_map::*;
use thin_vec::ThinVec;
use self::{internal_methods::ORDINARY_INTERNAL_METHODS, shape::Shape};
use crate::{
Context, JsString, JsSymbol, JsValue,
builtins::{OrdinaryObject, function::ConstructorKind},
context::intrinsics::StandardConstructor,
js_string,
native_function::{NativeFunction, NativeFunctionObject},
property::{Attribute, PropertyDescriptor, PropertyKey},
realm::Realm,
string::StaticJsStrings,
};
use boa_gc::{Finalize, Trace};
use std::{
any::{Any, TypeId},
fmt::Debug,
};
#[cfg(test)]
mod tests;
pub(crate) mod internal_methods;
pub mod builtins;
mod datatypes;
mod jsobject;
mod operations;
mod property_map;
pub mod shape;
pub(crate) use builtins::*;
pub use datatypes::JsData;
pub use jsobject::*;
pub const CONSTRUCTOR: JsString = js_string!("constructor");
pub const PROTOTYPE: JsString = js_string!("prototype");
pub type JsPrototype = Option<JsObject>;
pub(crate) type ObjectStorage = Vec<JsValue>;
pub trait NativeObject: Any + Trace + JsData {
fn as_any(&self) -> &dyn Any;
fn as_mut_any(&mut self) -> &mut dyn Any;
fn type_name_of_value(&self) -> &'static str;
}
impl<T: Any + Trace + JsData> NativeObject for T {
fn as_any(&self) -> &dyn Any {
self
}
fn as_mut_any(&mut self) -> &mut dyn Any {
self
}
fn type_name_of_value(&self) -> &'static str {
fn name_of_val<T: ?Sized>(_val: &T) -> &'static str {
std::any::type_name::<T>()
}
name_of_val(self)
}
}
impl dyn NativeObject {
#[inline]
pub fn is<T: NativeObject>(&self) -> bool {
let t = TypeId::of::<T>();
let concrete = self.type_id();
t == concrete
}
#[inline]
pub fn downcast_ref<T: NativeObject>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe { Some(self.downcast_ref_unchecked()) }
} else {
None
}
}
#[inline]
pub fn downcast_mut<T: NativeObject>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe { Some(self.downcast_mut_unchecked()) }
} else {
None
}
}
#[inline]
pub unsafe fn downcast_ref_unchecked<T: NativeObject>(&self) -> &T {
debug_assert!(self.is::<T>());
let ptr: *const dyn NativeObject = self;
unsafe { &*ptr.cast::<T>() }
}
#[inline]
pub unsafe fn downcast_mut_unchecked<T: NativeObject>(&mut self) -> &mut T {
debug_assert!(self.is::<T>());
let ptr: *mut dyn NativeObject = self;
unsafe { &mut *ptr.cast::<T>() }
}
}
#[derive(Debug, Finalize, Trace)]
#[boa_gc(unsafe_no_drop)]
#[repr(C)]
pub struct Object<T: ?Sized> {
pub(crate) properties: PropertyMap,
pub(crate) extensible: bool,
private_elements: ThinVec<(PrivateName, PrivateElement)>,
data: ObjectData<T>,
}
impl<T: Default> Default for Object<T> {
fn default() -> Self {
Self {
properties: PropertyMap::default(),
extensible: true,
private_elements: ThinVec::new(),
data: ObjectData::default(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Trace, Finalize)]
pub struct PrivateName {
description: JsString,
id: usize,
}
impl PrivateName {
pub(crate) const fn new(description: JsString, id: usize) -> Self {
Self { description, id }
}
}
#[derive(Clone, Debug, Trace, Finalize)]
pub enum PrivateElement {
Field(JsValue),
Method(JsObject),
Accessor {
getter: Option<JsObject>,
setter: Option<JsObject>,
},
}
impl<T: ?Sized> Object<T> {
#[must_use]
pub const fn shape(&self) -> &Shape {
&self.properties.shape
}
#[inline]
#[must_use]
pub fn data(&self) -> &T {
self.data.as_ref()
}
#[inline]
#[must_use]
pub fn data_mut(&mut self) -> &mut T {
self.data.as_mut()
}
#[inline]
#[must_use]
pub fn prototype(&self) -> JsPrototype {
self.properties.shape.prototype()
}
#[track_caller]
pub fn set_prototype<O: Into<JsPrototype>>(&mut self, prototype: O) -> bool {
let prototype = prototype.into();
if self.extensible {
self.properties.shape = self.properties.shape.change_prototype_transition(prototype);
true
} else {
self.prototype() == prototype
}
}
#[inline]
#[must_use]
pub const fn properties(&self) -> &PropertyMap {
&self.properties
}
#[inline]
pub(crate) fn properties_mut(&mut self) -> &mut PropertyMap {
&mut self.properties
}
pub(crate) fn insert<K, P>(&mut self, key: K, property: P) -> bool
where
K: Into<PropertyKey>,
P: Into<PropertyDescriptor>,
{
self.properties.insert(&key.into(), property.into())
}
#[inline]
pub(crate) fn remove(&mut self, key: &PropertyKey) -> bool {
self.properties.remove(key)
}
pub(crate) fn append_private_element(&mut self, name: PrivateName, element: PrivateElement) {
if let PrivateElement::Accessor { getter, setter } = &element {
for (key, value) in &mut self.private_elements {
if name == *key
&& let PrivateElement::Accessor {
getter: existing_getter,
setter: existing_setter,
} = value
{
if existing_getter.is_none() {
existing_getter.clone_from(getter);
}
if existing_setter.is_none() {
existing_setter.clone_from(setter);
}
return;
}
}
}
self.private_elements.push((name, element));
}
}
#[derive(Debug, Clone)]
pub struct FunctionBinding {
pub(crate) binding: PropertyKey,
pub(crate) name: JsString,
}
impl From<JsString> for FunctionBinding {
#[inline]
fn from(name: JsString) -> Self {
Self {
binding: name.clone().into(),
name,
}
}
}
impl From<JsSymbol> for FunctionBinding {
#[inline]
fn from(binding: JsSymbol) -> Self {
Self {
name: binding.fn_name(),
binding: binding.into(),
}
}
}
impl<B, N> From<(B, N)> for FunctionBinding
where
B: Into<PropertyKey>,
N: Into<JsString>,
{
fn from((binding, name): (B, N)) -> Self {
Self {
binding: binding.into(),
name: name.into(),
}
}
}
#[derive(Debug)]
pub struct FunctionObjectBuilder<'realm> {
realm: &'realm Realm,
function: NativeFunction,
constructor: Option<ConstructorKind>,
name: JsString,
length: usize,
}
impl<'realm> FunctionObjectBuilder<'realm> {
#[inline]
#[must_use]
pub fn new(realm: &'realm Realm, function: NativeFunction) -> Self {
Self {
realm,
function,
constructor: None,
name: js_string!(),
length: 0,
}
}
#[must_use]
pub fn name<N>(mut self, name: N) -> Self
where
N: Into<JsString>,
{
self.name = name.into();
self
}
#[inline]
#[must_use]
pub const fn length(mut self, length: usize) -> Self {
self.length = length;
self
}
#[must_use]
pub fn constructor(mut self, yes: bool) -> Self {
self.constructor = yes.then_some(ConstructorKind::Base);
self
}
#[must_use]
pub fn build(self) -> JsFunction {
let object = self.realm.intrinsics().templates().function().create(
NativeFunctionObject {
f: self.function,
name: self.name.clone(),
constructor: self.constructor,
realm: Some(self.realm.clone()),
},
vec![self.length.into(), self.name.into()],
);
JsFunction::from_object_unchecked(object)
}
}
#[derive(Debug)]
pub struct ObjectInitializer<'ctx> {
context: &'ctx mut Context,
object: JsObject,
}
impl<'ctx> ObjectInitializer<'ctx> {
#[inline]
pub fn new(context: &'ctx mut Context) -> Self {
let object = JsObject::with_object_proto(context.intrinsics());
Self { context, object }
}
pub fn with_native_data<T: NativeObject>(data: T, context: &'ctx mut Context) -> Self {
let object = JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
context.intrinsics().constructors().object().prototype(),
data,
);
Self { context, object }
}
pub fn with_native_data_and_proto<T: NativeObject>(
data: T,
proto: JsObject,
context: &'ctx mut Context,
) -> Self {
let object =
JsObject::from_proto_and_data_with_shared_shape(context.root_shape(), proto, data);
Self { context, object }
}
pub fn function<B>(&mut self, function: NativeFunction, binding: B, length: usize) -> &mut Self
where
B: Into<FunctionBinding>,
{
let binding = binding.into();
let function = FunctionObjectBuilder::new(self.context.realm(), function)
.name(binding.name)
.length(length)
.constructor(false)
.build();
self.object.borrow_mut().insert(
binding.binding,
PropertyDescriptor::builder()
.value(function)
.writable(true)
.enumerable(false)
.configurable(true),
);
self
}
pub fn property<K, V>(&mut self, key: K, value: V, attribute: Attribute) -> &mut 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.borrow_mut().insert(key, property);
self
}
pub fn accessor<K>(
&mut self,
key: K,
get: Option<JsFunction>,
set: Option<JsFunction>,
attribute: Attribute,
) -> &mut Self
where
K: Into<PropertyKey>,
{
assert!(set.is_some() || get.is_some());
let property = PropertyDescriptor::builder()
.maybe_get(get)
.maybe_set(set)
.enumerable(attribute.enumerable())
.configurable(attribute.configurable());
self.object.borrow_mut().insert(key, property);
self
}
#[inline]
pub fn build(&mut self) -> JsObject {
self.object.clone()
}
#[inline]
pub fn context(&mut self) -> &mut Context {
self.context
}
}
#[derive(Debug)]
pub struct ConstructorBuilder<'ctx> {
context: &'ctx mut Context,
function: NativeFunction,
constructor_object: Object<OrdinaryObject>,
has_prototype_property: bool,
prototype: Object<OrdinaryObject>,
name: JsString,
length: usize,
callable: bool,
kind: Option<ConstructorKind>,
inherit: Option<JsPrototype>,
custom_prototype: Option<JsPrototype>,
}
impl<'ctx> ConstructorBuilder<'ctx> {
#[inline]
pub fn new(context: &'ctx mut Context, function: NativeFunction) -> ConstructorBuilder<'ctx> {
Self {
context,
function,
constructor_object: Object {
data: ObjectData::new(OrdinaryObject),
properties: PropertyMap::default(),
extensible: true,
private_elements: ThinVec::new(),
},
prototype: Object {
data: ObjectData::new(OrdinaryObject),
properties: PropertyMap::default(),
extensible: true,
private_elements: ThinVec::new(),
},
length: 0,
name: js_string!(),
callable: true,
kind: Some(ConstructorKind::Base),
inherit: None,
custom_prototype: None,
has_prototype_property: true,
}
}
pub fn method<B>(&mut self, function: NativeFunction, binding: B, length: usize) -> &mut Self
where
B: Into<FunctionBinding>,
{
let binding = binding.into();
let function = FunctionObjectBuilder::new(self.context.realm(), function)
.name(binding.name)
.length(length)
.constructor(false)
.build();
self.prototype.insert(
binding.binding,
PropertyDescriptor::builder()
.value(function)
.writable(true)
.enumerable(false)
.configurable(true),
);
self
}
pub fn static_method<B>(
&mut self,
function: NativeFunction,
binding: B,
length: usize,
) -> &mut Self
where
B: Into<FunctionBinding>,
{
let binding = binding.into();
let function = FunctionObjectBuilder::new(self.context.realm(), function)
.name(binding.name)
.length(length)
.constructor(false)
.build();
self.constructor_object.insert(
binding.binding,
PropertyDescriptor::builder()
.value(function)
.writable(true)
.enumerable(false)
.configurable(true),
);
self
}
pub fn property<K, V>(&mut self, key: K, value: V, attribute: Attribute) -> &mut Self
where
K: Into<PropertyKey>,
V: Into<JsValue>,
{
let property = PropertyDescriptor::builder()
.value(value)
.writable(attribute.writable())
.enumerable(attribute.enumerable())
.configurable(attribute.configurable());
self.prototype.insert(key, property);
self
}
pub fn static_property<K, V>(&mut self, key: K, value: V, attribute: Attribute) -> &mut Self
where
K: Into<PropertyKey>,
V: Into<JsValue>,
{
let property = PropertyDescriptor::builder()
.value(value)
.writable(attribute.writable())
.enumerable(attribute.enumerable())
.configurable(attribute.configurable());
self.constructor_object.insert(key, property);
self
}
pub fn accessor<K>(
&mut self,
key: K,
get: Option<JsFunction>,
set: Option<JsFunction>,
attribute: Attribute,
) -> &mut Self
where
K: Into<PropertyKey>,
{
let property = PropertyDescriptor::builder()
.maybe_get(get)
.maybe_set(set)
.enumerable(attribute.enumerable())
.configurable(attribute.configurable());
self.prototype.insert(key, property);
self
}
pub fn static_accessor<K>(
&mut self,
key: K,
get: Option<JsFunction>,
set: Option<JsFunction>,
attribute: Attribute,
) -> &mut Self
where
K: Into<PropertyKey>,
{
let property = PropertyDescriptor::builder()
.maybe_get(get)
.maybe_set(set)
.enumerable(attribute.enumerable())
.configurable(attribute.configurable());
self.constructor_object.insert(key, property);
self
}
pub fn property_descriptor<K, P>(&mut self, key: K, property: P) -> &mut Self
where
K: Into<PropertyKey>,
P: Into<PropertyDescriptor>,
{
let property = property.into();
self.prototype.insert(key, property);
self
}
pub fn static_property_descriptor<K, P>(&mut self, key: K, property: P) -> &mut Self
where
K: Into<PropertyKey>,
P: Into<PropertyDescriptor>,
{
let property = property.into();
self.constructor_object.insert(key, property);
self
}
#[inline]
pub fn length(&mut self, length: usize) -> &mut Self {
self.length = length;
self
}
pub fn name<N>(&mut self, name: N) -> &mut Self
where
N: AsRef<str>,
{
self.name = name.as_ref().into();
self
}
#[inline]
pub fn callable(&mut self, callable: bool) -> &mut Self {
self.callable = callable;
self
}
#[inline]
pub fn constructor(&mut self, constructor: bool) -> &mut Self {
self.kind = constructor.then_some(ConstructorKind::Base);
self
}
pub fn inherit<O: Into<JsPrototype>>(&mut self, prototype: O) -> &mut Self {
self.inherit = Some(prototype.into());
self
}
pub fn custom_prototype<O: Into<JsPrototype>>(&mut self, prototype: O) -> &mut Self {
self.custom_prototype = Some(prototype.into());
self
}
#[inline]
pub fn has_prototype_property(&mut self, has_prototype_property: bool) -> &mut Self {
self.has_prototype_property = has_prototype_property;
self
}
#[inline]
pub fn context(&mut self) -> &mut Context {
self.context
}
#[must_use]
pub fn build(mut self) -> StandardConstructor {
let length = PropertyDescriptor::builder()
.value(self.length)
.writable(false)
.enumerable(false)
.configurable(true);
let name = PropertyDescriptor::builder()
.value(self.name.clone())
.writable(false)
.enumerable(false)
.configurable(true);
let prototype = {
if let Some(proto) = self.inherit.take() {
self.prototype.set_prototype(proto);
} else {
self.prototype.set_prototype(
self.context
.intrinsics()
.constructors()
.object()
.prototype(),
);
}
JsObject::from_object_and_vtable(self.prototype, &ORDINARY_INTERNAL_METHODS)
};
let constructor = {
let data = NativeFunctionObject {
f: self.function,
name: self.name.clone(),
constructor: self.kind,
realm: Some(self.context.realm().clone()),
};
let internal_methods = data.internal_methods();
let mut constructor = Object {
properties: self.constructor_object.properties,
extensible: self.constructor_object.extensible,
private_elements: self.constructor_object.private_elements,
data: ObjectData::new(data),
};
constructor.insert(StaticJsStrings::LENGTH, length);
constructor.insert(js_string!("name"), name);
if let Some(proto) = self.custom_prototype.take() {
constructor.set_prototype(proto);
} else {
constructor.set_prototype(
self.context
.intrinsics()
.constructors()
.function()
.prototype(),
);
}
if self.has_prototype_property {
constructor.insert(
PROTOTYPE,
PropertyDescriptor::builder()
.value(prototype.clone())
.writable(false)
.enumerable(false)
.configurable(false),
);
}
JsObject::from_object_and_vtable(constructor, internal_methods)
};
{
let mut prototype = prototype.borrow_mut();
prototype.insert(
CONSTRUCTOR,
PropertyDescriptor::builder()
.value(constructor.clone())
.writable(true)
.enumerable(false)
.configurable(true),
);
}
StandardConstructor::new(JsFunction::from_object_unchecked(constructor), prototype)
}
}