use boa_gc::{Finalize, Trace, WeakGc};
use crate::{
Context, JsArgs, JsNativeError, JsResult, JsString, JsValue,
builtins::{BuiltInBuilder, BuiltInConstructor, BuiltInObject, IntrinsicObject},
context::intrinsics::{Intrinsics, StandardConstructor, StandardConstructors},
js_string,
object::{ErasedVTableObject, JsObject, internal_methods::get_prototype_from_constructor},
property::Attribute,
realm::Realm,
string::StaticJsStrings,
symbol::JsSymbol,
};
#[derive(Debug, Clone, Trace, Finalize)]
pub(crate) struct WeakRef;
impl IntrinsicObject for WeakRef {
fn get(intrinsics: &Intrinsics) -> JsObject {
Self::STANDARD_CONSTRUCTOR(intrinsics.constructors()).constructor()
}
fn init(realm: &Realm) {
BuiltInBuilder::from_standard_constructor::<Self>(realm)
.property(
JsSymbol::to_string_tag(),
js_string!("WeakRef"),
Attribute::CONFIGURABLE,
)
.method(Self::deref, js_string!("deref"), 0)
.build();
}
}
impl BuiltInObject for WeakRef {
const NAME: JsString = StaticJsStrings::WEAK_REF;
const ATTRIBUTE: Attribute = Attribute::WRITABLE.union(Attribute::CONFIGURABLE);
}
impl BuiltInConstructor for WeakRef {
const CONSTRUCTOR_ARGUMENTS: usize = 1;
const PROTOTYPE_STORAGE_SLOTS: usize = 2;
const CONSTRUCTOR_STORAGE_SLOTS: usize = 0;
const STANDARD_CONSTRUCTOR: fn(&StandardConstructors) -> &StandardConstructor =
StandardConstructors::weak_ref;
fn constructor(
new_target: &JsValue,
args: &[JsValue],
context: &mut Context,
) -> JsResult<JsValue> {
if new_target.is_undefined() {
return Err(JsNativeError::typ()
.with_message("WeakRef: cannot call constructor without `new`")
.into());
}
let target = args.first().and_then(JsValue::as_object).ok_or_else(|| {
JsNativeError::typ().with_message(format!(
"WeakRef: expected target argument of type `object`, got target of type `{}`",
args.get_or_undefined(0).type_of()
))
})?;
let prototype =
get_prototype_from_constructor(new_target, StandardConstructors::weak_ref, context)?;
let weak_ref = JsObject::from_proto_and_data_with_shared_shape(
context.root_shape(),
prototype,
WeakGc::new(target.inner()),
);
context.kept_alive.push(target.clone());
Ok(weak_ref.into())
}
}
impl WeakRef {
pub(crate) fn deref(this: &JsValue, _: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
let object = this.as_object();
let weak_ref = object
.as_ref()
.and_then(JsObject::downcast_ref::<WeakGc<ErasedVTableObject>>)
.ok_or_else(|| {
JsNativeError::typ().with_message(
"WeakRef.prototype.deref: expected `this` to be a `WeakRef` object",
)
})?;
if let Some(object) = weak_ref.upgrade() {
let object = JsObject::from(object);
context.kept_alive.push(object.clone());
Ok(object.into())
} else {
Ok(JsValue::undefined())
}
}
}
#[cfg(test)]
mod tests {
use indoc::indoc;
use crate::{JsValue, TestAction, run_test_actions};
#[test]
fn weak_ref_collected() {
run_test_actions([
TestAction::assert_with_op(
indoc! {r#"
var ptr;
{
let obj = {a: 5, b: 6};
ptr = new WeakRef(obj);
}
ptr.deref()
"#},
|v, _| v.is_object(),
),
TestAction::inspect_context(|context| {
context.clear_kept_objects();
boa_gc::force_collect();
}),
TestAction::assert_eq("ptr.deref()", JsValue::undefined()),
]);
}
}