mirror of
https://github.com/pjh456/OxideJS.git
synced 2026-10-24 02:31:13 +08:00
feat: WeakMap 构造体与四方法本体落地及 stub 剥离
This commit is contained in:
@@ -9,10 +9,6 @@ fn stub_error<H: VmHost>(vm: &mut H, name: &str) -> NativeResult {
|
||||
pub fn proxy_stub<H: VmHost>(vm: &mut H, _args: &[u8]) -> NativeResult {
|
||||
stub_error(vm, "Proxy")
|
||||
}
|
||||
/// `WeakMap` 全局占位:始终抛 TypeError。WeakMap 按设计延后实现。
|
||||
pub fn weakmap_stub<H: VmHost>(vm: &mut H, _args: &[u8]) -> NativeResult {
|
||||
stub_error(vm, "WeakMap")
|
||||
}
|
||||
/// `WeakSet` 全局占位:始终抛 TypeError。WeakSet 按设计延后实现。
|
||||
pub fn weakset_stub<H: VmHost>(vm: &mut H, _args: &[u8]) -> NativeResult {
|
||||
stub_error(vm, "WeakSet")
|
||||
|
||||
@@ -4,9 +4,14 @@
|
||||
//! 值为强引用(值边进 mark 边扫描与晋升改写)。存储盒经 `Box::into_raw` 挂
|
||||
//! `JsObject.native_data`,GC 六站点(mark 边 / 移动式 sweep / 晋升克隆 /
|
||||
//! 原地晋升 / drop / 字节账目)经本模块五函数族接线,口径与 Map/Set 同形。
|
||||
//! 构造体(iterable 协议)与 set/get/has/delete 四方法的品牌三分枝守卫
|
||||
//! (set/delete 对非 WeakMap this 抛 TypeError,get/has 静默返 undefined/false)
|
||||
//! 也在本模块。
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use oxide_kernel::shape_forge::EMPTY_SHAPE_ID;
|
||||
use oxide_runtime_api::{NativeResult, VmHost};
|
||||
use oxide_types::object::JsObject;
|
||||
use oxide_types::value::JsValue;
|
||||
|
||||
@@ -59,6 +64,11 @@ impl WeakMapInner {
|
||||
self.entries.insert(key, value);
|
||||
}
|
||||
|
||||
/// 删除条目:命中返回 true,缺失静默(规范 delete 面返 false)。
|
||||
pub(crate) fn remove(&mut self, key: &WeakKey) -> bool {
|
||||
self.entries.remove(key).is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn iter(&self) -> impl Iterator<Item = (WeakKey, JsValue)> + '_ {
|
||||
self.entries.iter().map(|(k, v)| (*k, *v))
|
||||
}
|
||||
@@ -235,7 +245,7 @@ pub fn weak_map_entry_count(obj: &JsObject) -> usize {
|
||||
}
|
||||
|
||||
/// 读给定弱键对应的值(测试探针):非 WeakMap / 盒缺失 / 键缺失返回 undefined。
|
||||
pub fn weak_map_get(obj: &JsObject, key: JsValue) -> JsValue {
|
||||
pub fn weak_map_probe_get(obj: &JsObject, key: JsValue) -> JsValue {
|
||||
if !obj.is_weak_map_obj() {
|
||||
return JsValue::undefined();
|
||||
}
|
||||
@@ -269,3 +279,232 @@ pub fn weak_map_insert(obj: &mut JsObject, key: JsValue, value: JsValue) {
|
||||
// SAFETY: 单测在盒写入前对象独占,指针指向有效盒。
|
||||
unsafe { (*inner).insert(key, value) }
|
||||
}
|
||||
|
||||
/// 读出 %WeakMap.prototype% 原型对象指针:经全局 `WeakMap` 构造器的
|
||||
/// `prototype` 槽现值读取(弱族不占 BuiltinWorld 槽,重绑原位更新全局槽,
|
||||
/// 经全局路径读恒为当前值)。
|
||||
fn weak_map_proto_ptr<H: VmHost>(vm: &mut H) -> Result<*const JsObject, JsValue> {
|
||||
let global_ptr = vm.session().global_object().as_ptr();
|
||||
// SAFETY: 全局对象为 session 级根,本调用内有效。
|
||||
let global = unsafe { &*global_ptr };
|
||||
let global_val = JsValue::from_js_object(global_ptr as *mut JsObject);
|
||||
let si_weakmap = vm.kernel_core().perm_interner().intern("WeakMap").0;
|
||||
let ctor_val = vm
|
||||
.ordinary_get(global, si_weakmap, global_val)
|
||||
.map_err(|e| crate::iterator::engine_error(vm, &e))?;
|
||||
let ctor_ptr = ctor_val.as_js_object_ptr();
|
||||
if ctor_ptr.is_null() {
|
||||
return Err(crate::error::create_type_error(vm, "WeakMap constructor unavailable"));
|
||||
}
|
||||
let si_prototype = vm.kernel_core().perm_interner().intern("prototype").0;
|
||||
let proto_val = vm
|
||||
.ordinary_get(unsafe { &*ctor_ptr }, si_prototype, ctor_val)
|
||||
.map_err(|e| crate::iterator::engine_error(vm, &e))?;
|
||||
let proto_ptr = proto_val.as_js_object_ptr();
|
||||
if proto_ptr.is_null() {
|
||||
return Err(crate::error::create_type_error(vm, "WeakMap prototype unavailable"));
|
||||
}
|
||||
Ok(proto_ptr as *const JsObject)
|
||||
}
|
||||
|
||||
/// NewTarget 判定:`this` 的原型链(深度上限 16)命中 %WeakMap.prototype%——
|
||||
/// `new WeakMap()` 直接命中,子类 `super()` 经子类 prototype 链命中;普通
|
||||
/// 调用(global/undefined)不命中。
|
||||
fn is_new_target_this(this_val: JsValue, proto_ptr: *const JsObject) -> bool {
|
||||
if !this_val.is_object() {
|
||||
return false;
|
||||
}
|
||||
let this_ptr = this_val.as_js_object_ptr();
|
||||
if this_ptr.is_null() {
|
||||
return false;
|
||||
}
|
||||
// SAFETY: this 为执行核心产出的对象值,指针在本调用内有效。
|
||||
let mut proto = unsafe { &*this_ptr }.proto();
|
||||
for _ in 0..16 {
|
||||
if !proto.is_object() {
|
||||
return false;
|
||||
}
|
||||
let proto_obj_ptr = proto.as_js_object_ptr();
|
||||
if proto_obj_ptr.is_null() {
|
||||
return false;
|
||||
}
|
||||
if std::ptr::eq(proto_obj_ptr, proto_ptr) {
|
||||
return true;
|
||||
}
|
||||
// SAFETY: 原型链为执行核心产出的有效对象链。
|
||||
proto = unsafe { &*proto_obj_ptr }.proto();
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// `WeakMap` 构造器:NewTarget 校验(`this` 原型链命中 %WeakMap.prototype%)
|
||||
/// 后建带空条目表的对象;提供可迭代实参时逐元素取 `[0]`/`[1]` 作键值,
|
||||
/// 经原型链读出的 `set` 方法逐项调用(set 抛面即品牌三分枝抛面)。
|
||||
///
|
||||
/// # 步骤
|
||||
/// 1. 经全局构造器 `prototype` 槽读 %WeakMap.prototype%。
|
||||
/// 2. 校验 NewTarget:`this` 原型链须命中该原型(普通调用 `WeakMap()` 抛
|
||||
/// TypeError)。
|
||||
/// 3. 创建空 WeakMap(proto = %WeakMap.prototype%,带空条目盒)。
|
||||
/// 4. 取 adder = Get(map, "set"),要求可调用(否则 TypeError);对可迭代实参
|
||||
/// 逐元素:元素须为对象(否则 TypeError),读 `0`/`1` 后调用 adder。
|
||||
///
|
||||
/// # 边界与前提
|
||||
/// - 无实参或实参为 null/undefined 时返回空 WeakMap,不触碰 adder。
|
||||
/// - 空可迭代不调用 adder(原型 set 覆写探针口径)。
|
||||
/// - 任一环节抛错先 IteratorClose 再透传原异常。
|
||||
pub fn weak_map_constructor<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let proto_ptr = match weak_map_proto_ptr(vm) {
|
||||
Ok(ptr) => ptr,
|
||||
Err(exc) => return NativeResult::Err(exc),
|
||||
};
|
||||
|
||||
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||
if !is_new_target_this(this_val, proto_ptr) {
|
||||
return NativeResult::Err(crate::error::create_type_error(vm, "WeakMap constructor requires 'new'"));
|
||||
}
|
||||
|
||||
let mut obj = JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::from_js_object(proto_ptr as *mut JsObject));
|
||||
obj.type_tag = JsObject::OBJ_TYPE_WEAK_MAP;
|
||||
obj.set_native_data(Box::into_raw(Box::new(WeakMapInner::new())) as *mut u8);
|
||||
let map_obj = vm.alloc_object(obj);
|
||||
let map_val = JsValue::from_js_object(map_obj);
|
||||
|
||||
if args.len() > 1 {
|
||||
let iterable = vm.reg(args[1]);
|
||||
if !iterable.is_undefined() && !iterable.is_null() {
|
||||
let map_ref = unsafe { &*map_obj };
|
||||
let set_si = vm.kernel_core().perm_interner().intern("set").0;
|
||||
let adder = match vm.ordinary_get(map_ref, set_si, map_val) {
|
||||
Ok(v) => v,
|
||||
Err(err) => return NativeResult::Err(crate::iterator::engine_error(vm, &err)),
|
||||
};
|
||||
if !crate::iterator::is_callable(adder) {
|
||||
return NativeResult::Err(crate::error::create_type_error(vm, "WeakMap.set is not callable"));
|
||||
}
|
||||
// entry 读取键按 ToPropertyKey 规范化:数组 entry 的元素区与对象
|
||||
// entry 的 shape 链都走整数键,`[k,v]` 与 `{0:k,1:v}` 两形态都命中。
|
||||
let key_si = vm.property_key_si(JsValue::int(0));
|
||||
let value_si = vm.property_key_si(JsValue::int(1));
|
||||
if let Err(err) = crate::iterator::iterate_elements(vm, iterable, |vm, item| {
|
||||
if !item.is_object() {
|
||||
return Err(crate::error::create_type_error(vm, "iterator value is not an entry object"));
|
||||
}
|
||||
let item_obj = unsafe { &*item.as_js_object_ptr() };
|
||||
let k = match vm.ordinary_get(item_obj, key_si, item) {
|
||||
Ok(v) => v,
|
||||
Err(err) => return Err(crate::iterator::engine_error(vm, &err)),
|
||||
};
|
||||
let v = match vm.ordinary_get(item_obj, value_si, item) {
|
||||
Ok(v) => v,
|
||||
Err(err) => return Err(crate::iterator::engine_error(vm, &err)),
|
||||
};
|
||||
match vm.call_function_sync(adder, map_val, &[k, v]) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(err) => Err(crate::iterator::engine_error(vm, &err)),
|
||||
}
|
||||
}) {
|
||||
return NativeResult::Err(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NativeResult::Ok(map_val)
|
||||
}
|
||||
|
||||
/// 品牌守卫只读核:receiver 为带条目盒的 WeakMap 时返回盒指针,其余形态
|
||||
/// (非对象 / 无 [[WeakMapData]] 内部槽 / 盒缺失)返回 `None`,四方法一律
|
||||
/// 按 `RequireInternalSlot` 抛 TypeError(仅键类型检查存在抛静差异)。
|
||||
fn weak_map_brand_inner(this_val: JsValue) -> Option<*mut WeakMapInner> {
|
||||
if !this_val.is_object() {
|
||||
return None;
|
||||
}
|
||||
let ptr = this_val.as_js_object_ptr();
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: receiver 为调用方传入的值,native 执行期间有效。
|
||||
let obj = unsafe { &*ptr };
|
||||
if !obj.is_weak_map_obj() {
|
||||
return None;
|
||||
}
|
||||
let inner = obj.native_data() as *mut WeakMapInner;
|
||||
if inner.is_null() {
|
||||
return None;
|
||||
}
|
||||
Some(inner)
|
||||
}
|
||||
|
||||
/// `WeakMap.prototype.set(key, value)`:键不可弱持(非对象非 symbol、HTML
|
||||
/// DDA)抛 TypeError,receiver 非 WeakMap 抛 TypeError;成功后返回 this。
|
||||
pub fn weak_map_set<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||
let Some(inner) = weak_map_brand_inner(this_val) else {
|
||||
return NativeResult::Err(crate::error::create_type_error(
|
||||
vm,
|
||||
"WeakMap.prototype.set called on non-WeakMap object",
|
||||
));
|
||||
};
|
||||
let key = vm.reg(if args.len() > 1 { args[1] } else { 0 });
|
||||
let value = vm.reg(if args.len() > 2 { args[2] } else { 0 });
|
||||
let Some(key) = weak_key_of(key) else {
|
||||
return NativeResult::Err(crate::error::create_type_error(vm, "WeakMap key must be an object"));
|
||||
};
|
||||
// SAFETY: 盒指针由构造路径写入,本调用内独占。
|
||||
unsafe { (*inner).insert(key, value) };
|
||||
NativeResult::Ok(this_val)
|
||||
}
|
||||
|
||||
/// `WeakMap.prototype.get(key)`:receiver 非 WeakMap(非对象 / 无内部槽)抛
|
||||
/// TypeError;键不可弱持静默返 undefined;命中返存储值,未命中返 undefined。
|
||||
pub fn weak_map_get<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||
let Some(inner) = weak_map_brand_inner(this_val) else {
|
||||
return NativeResult::Err(crate::error::create_type_error(
|
||||
vm,
|
||||
"WeakMap.prototype.get called on non-WeakMap object",
|
||||
));
|
||||
};
|
||||
let key = vm.reg(if args.len() > 1 { args[1] } else { 0 });
|
||||
let Some(key) = weak_key_of(key) else {
|
||||
return NativeResult::Ok(JsValue::undefined());
|
||||
};
|
||||
// SAFETY: 盒指针由构造路径写入,本调用内独占。
|
||||
unsafe { NativeResult::Ok((*inner).get(&key).unwrap_or(JsValue::undefined())) }
|
||||
}
|
||||
|
||||
/// `WeakMap.prototype.has(key)`:receiver 非 WeakMap(非对象 / 无内部槽)抛
|
||||
/// TypeError;键不可弱持静默返 false;命中返 true。
|
||||
pub fn weak_map_has<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||
let Some(inner) = weak_map_brand_inner(this_val) else {
|
||||
return NativeResult::Err(crate::error::create_type_error(
|
||||
vm,
|
||||
"WeakMap.prototype.has called on non-WeakMap object",
|
||||
));
|
||||
};
|
||||
let key = vm.reg(if args.len() > 1 { args[1] } else { 0 });
|
||||
let Some(key) = weak_key_of(key) else {
|
||||
return NativeResult::Ok(JsValue::bool(false));
|
||||
};
|
||||
// SAFETY: 盒指针由构造路径写入,本调用内独占。
|
||||
unsafe { NativeResult::Ok(JsValue::bool((*inner).get(&key).is_some())) }
|
||||
}
|
||||
|
||||
/// `WeakMap.prototype.delete(key)`:receiver 非 WeakMap 抛 TypeError;键不可
|
||||
/// 弱持静默返 false;命中删除返 true。
|
||||
pub fn weak_map_delete<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let this_val = vm.reg(if args.is_empty() { 0 } else { args[0] });
|
||||
let Some(inner) = weak_map_brand_inner(this_val) else {
|
||||
return NativeResult::Err(crate::error::create_type_error(
|
||||
vm,
|
||||
"WeakMap.prototype.delete called on non-WeakMap object",
|
||||
));
|
||||
};
|
||||
let key = vm.reg(if args.len() > 1 { args[1] } else { 0 });
|
||||
let Some(key) = weak_key_of(key) else {
|
||||
return NativeResult::Ok(JsValue::bool(false));
|
||||
};
|
||||
// SAFETY: 盒指针由构造路径写入,本调用内独占。
|
||||
unsafe { NativeResult::Ok(JsValue::bool((*inner).remove(&key))) }
|
||||
}
|
||||
|
||||
@@ -11,18 +11,12 @@ use crate::bindings::{bind_global_value, configure_native_constructor};
|
||||
/// 未实现内置的 stub 表:(全局名、native 函数项指针、形参个数、
|
||||
/// 原型 @@toStringTag、是否安装原型对象)。
|
||||
///
|
||||
/// `tag` 为 `None` 的条目(Proxy)原型对象不设 @@toStringTag;四弱族各取族名。
|
||||
/// `tag` 为 `None` 的条目(Proxy)原型对象不设 @@toStringTag;弱族 stub
|
||||
/// (WeakSet/WeakRef/FinalizationRegistry)各取族名。
|
||||
/// 规范 25.1 的 %Proxy% 无 prototype 属性(`has_prototype` = false),
|
||||
/// 四弱族各装带 constructor 回指的原型对象。
|
||||
const STUBS: [(&str, *const (), u8, Option<&str>, bool); 5] = [
|
||||
/// 弱族 stub 各装带 constructor 回指的原型对象。
|
||||
const STUBS: [(&str, *const (), u8, Option<&str>, bool); 4] = [
|
||||
("Proxy", oxide_builtins::stubs::proxy_stub::<crate::vm::Vm> as *const (), 2, None, false),
|
||||
(
|
||||
"WeakMap",
|
||||
oxide_builtins::stubs::weakmap_stub::<crate::vm::Vm> as *const (),
|
||||
0,
|
||||
Some("WeakMap"),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"WeakSet",
|
||||
oxide_builtins::stubs::weakset_stub::<crate::vm::Vm> as *const (),
|
||||
@@ -56,11 +50,12 @@ fn set_data_property(core: &Arc<KernelCore>, obj: &mut JsObject, si: u32, value:
|
||||
obj.bump_generation();
|
||||
}
|
||||
|
||||
/// 把未实现内置(Proxy/WeakMap/WeakSet/WeakRef/FinalizationRegistry)的 stub 构造器
|
||||
/// 绑定到 global,并登记到 `stub_objects` 供快照跟踪。
|
||||
/// 把未实现内置(Proxy/WeakSet/WeakRef/FinalizationRegistry)的 stub 构造器
|
||||
/// 绑定到 global,并登记到 `stub_objects` 供快照跟踪。WeakMap 已落地真构造器,
|
||||
/// 走 `bind_weak` 绑定面,不在此表。
|
||||
///
|
||||
/// # 副作用
|
||||
/// 每个 stub 按规范补装构造器面属性:`length`、`name`(五族全装);四弱族
|
||||
/// 每个 stub 按规范补装构造器面属性:`length`、`name`(四族全装);弱族 stub
|
||||
/// 另装 `prototype`(新建 plain 对象,原型链落 Object.prototype,其上带指回
|
||||
/// stub 的 `constructor` 与 @@toStringTag)——规范 25.1 的 %Proxy% 无
|
||||
/// prototype 属性,不装;描述符均不可枚举,`prototype` 另不可写、不可配置。
|
||||
@@ -81,7 +76,7 @@ pub fn bind_stubs(core: &Arc<KernelCore>, session: &mut KernelSession, global: &
|
||||
let stub = P::new(stub);
|
||||
let stub_ptr = stub.as_ptr() as *mut JsObject;
|
||||
|
||||
// 构造器面属性:length / name 五族全装;prototype 仅四弱族(%Proxy% 无)。
|
||||
// 构造器面属性:length / name 四族全装;prototype 仅弱族 stub(%Proxy% 无)。
|
||||
// SAFETY: stub 尚未发布到 global,局部 Arc 为唯一持有者,可变访问无读者冲突。
|
||||
let stub_obj = unsafe { &mut *stub_ptr };
|
||||
if has_prototype {
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Weak 族绑定:WeakMap 构造器 + 原型四方法(set/get/has/delete)安装。
|
||||
//!
|
||||
//! 弱族不占 BuiltinWorld 槽:构造器经 `P` 留存 `stub_objects`(global
|
||||
//! 重建路径原位重绑,索引 4 紧随 stub 族四条目),原型对象经
|
||||
//! `Box::into_raw` 登记 world 释放登记表(属性装完再登记,登记点世代即
|
||||
//! 洁净基线),恒存活至 session 收尾统一释放;选择性重建经
|
||||
//! `inherit_leaked_objects` 迁移登记表、`retire_replaced` 重指原型链,
|
||||
//! 重绑时全局槽原位更新不追加。
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::bind_constructor;
|
||||
use crate::bindings::configure_native_constructor;
|
||||
use oxide_kernel::kernel::{KernelCore, KernelSession};
|
||||
use oxide_kernel::shape_forge::EMPTY_SHAPE_ID;
|
||||
use oxide_types::mem::P;
|
||||
use oxide_types::object::{JsObject, PropAttributes};
|
||||
use oxide_types::value::JsValue;
|
||||
|
||||
/// 在原型上安装一条 native 方法,站点标签 = 族名 perm 键:非 P 原型目标
|
||||
/// 全部落 family-0,无标签时 WeakMap 与后续弱族同名方法槽(has/delete)
|
||||
/// 在 FnWrapperKey 复用键上撞键,重绑会迁移到错误家族的 wrapper。
|
||||
fn bind_labeled_method(
|
||||
world: &oxide_kernel::builtin::BuiltinWorld, proto: &mut JsObject, core: &Arc<KernelCore>, label: u32, name: &str,
|
||||
func: *const (), nargs: u8,
|
||||
) {
|
||||
let shape_forge = core.shape_forge().as_ref();
|
||||
let string_forge = core.perm_interner().as_ref();
|
||||
// SAFETY: func 是转成 *const () 的 NativeFn 函数项指针。
|
||||
let fn_ptr = unsafe { oxide_types::object::NativeFnPtr::from_raw(func) };
|
||||
let _ = oxide_kernel::builtin::BuiltinWorld::bind_method_labeled_static(
|
||||
proto,
|
||||
shape_forge,
|
||||
string_forge,
|
||||
name,
|
||||
fn_ptr,
|
||||
nargs,
|
||||
world,
|
||||
label,
|
||||
);
|
||||
}
|
||||
|
||||
/// 把 WeakMap 构造器与原型四方法绑定到 global。
|
||||
///
|
||||
/// # 副作用
|
||||
/// - 构造器经 `P` 留存 `stub_objects`(索引 4,紧随 stub 族四条目);
|
||||
/// 原型对象经释放登记表登记,恒存活至 session 收尾;全局 `WeakMap` 槽
|
||||
/// 经 `bind_constructor!` 原位安装(既有槽更新槽值,不追加新槽)。
|
||||
/// - 方法 wrapper 带族名站点标签登记复用键,选择性重建时按键迁移,
|
||||
/// 登记表跨重建不增长。
|
||||
pub fn bind_weak_map(core: &Arc<KernelCore>, session: &mut KernelSession, global: &mut JsObject) {
|
||||
// world 唯一属主期:全程走可变引用(stub_objects 留存 + 释放登记同表)。
|
||||
let world = Arc::get_mut(&mut session.builtin_world)
|
||||
.expect("BuiltinWorld must be uniquely owned during init_kernel_builtins");
|
||||
let object_proto_ptr = world.object_proto.as_ptr() as *mut JsObject;
|
||||
let function_proto_ptr = world.function_proto.as_ptr() as *mut JsObject;
|
||||
let label = core.perm_interner().intern("WeakMap").0;
|
||||
let si_name = core.perm_interner().intern("name").0;
|
||||
|
||||
// 构造器对象:Function 原型链 + native 函数项;name 由本函数安装
|
||||
// (bind_constructor! 只补 length),描述符 { f,f,t }。
|
||||
let mut ctor = JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::from_js_object(function_proto_ptr));
|
||||
ctor.set_function(true);
|
||||
configure_native_constructor(
|
||||
&mut ctor,
|
||||
oxide_builtins::weak_map::weak_map_constructor::<crate::vm::Vm> as *const (),
|
||||
0,
|
||||
);
|
||||
let name_shape = core.shape_forge().make_shape(ctor.shape_id(), si_name);
|
||||
ctor.set_shape_id(name_shape);
|
||||
ctor.ensure_hash_props().push(JsValue::perm_string(
|
||||
core.perm_interner().string_ptr(core.perm_interner().intern("WeakMap").0),
|
||||
));
|
||||
let name_pos = ctor.hash_props_vec().map_or(0, |v| v.len() as u32).saturating_sub(1);
|
||||
ctor.set_data_meta(name_pos, PropAttributes::new(false, false, true));
|
||||
|
||||
let stub = P::new(ctor);
|
||||
let ctor_ptr = stub.as_ptr() as *mut JsObject;
|
||||
|
||||
// 原型对象:constructor 回指({ w,f,t })+ @@toStringTag({ f,f,t }),
|
||||
// 四方法 { w,f,t } 经站点标签绑定;属性装完再登记释放登记表。
|
||||
let mut proto = JsObject::new_empty(EMPTY_SHAPE_ID, JsValue::from_js_object(object_proto_ptr));
|
||||
let si_constructor = core.perm_interner().intern("constructor").0;
|
||||
let ctor_shape = core.shape_forge().make_shape(proto.shape_id(), si_constructor);
|
||||
proto.set_shape_id(ctor_shape);
|
||||
proto.ensure_hash_props().push(JsValue::from_js_object(ctor_ptr));
|
||||
let ctor_pos = proto.hash_props_vec().map_or(0, |v| v.len() as u32).saturating_sub(1);
|
||||
proto.set_data_meta(ctor_pos, PropAttributes::new(true, false, true));
|
||||
let tag_key =
|
||||
oxide_types::private_key::make_well_known_symbol_key(oxide_types::private_key::WELL_KNOWN_SYMBOL_TO_STRING_TAG);
|
||||
let tag_shape = core.shape_forge().make_shape(proto.shape_id(), tag_key);
|
||||
proto.set_shape_id(tag_shape);
|
||||
proto.ensure_hash_props().push(JsValue::perm_string(
|
||||
core.perm_interner().string_ptr(core.perm_interner().intern("WeakMap").0),
|
||||
));
|
||||
let tag_pos = proto.hash_props_vec().map_or(0, |v| v.len() as u32).saturating_sub(1);
|
||||
proto.set_data_meta(tag_pos, PropAttributes::new(false, false, true));
|
||||
bind_labeled_method(
|
||||
world,
|
||||
&mut proto,
|
||||
core,
|
||||
label,
|
||||
"set",
|
||||
oxide_builtins::weak_map::weak_map_set::<crate::vm::Vm> as *const (),
|
||||
2,
|
||||
);
|
||||
bind_labeled_method(
|
||||
world,
|
||||
&mut proto,
|
||||
core,
|
||||
label,
|
||||
"get",
|
||||
oxide_builtins::weak_map::weak_map_get::<crate::vm::Vm> as *const (),
|
||||
1,
|
||||
);
|
||||
bind_labeled_method(
|
||||
world,
|
||||
&mut proto,
|
||||
core,
|
||||
label,
|
||||
"has",
|
||||
oxide_builtins::weak_map::weak_map_has::<crate::vm::Vm> as *const (),
|
||||
1,
|
||||
);
|
||||
bind_labeled_method(
|
||||
world,
|
||||
&mut proto,
|
||||
core,
|
||||
label,
|
||||
"delete",
|
||||
oxide_builtins::weak_map::weak_map_delete::<crate::vm::Vm> as *const (),
|
||||
1,
|
||||
);
|
||||
let proto_ptr = Box::into_raw(Box::new(proto));
|
||||
world.track_leaked_object(proto_ptr);
|
||||
|
||||
// 构造器 prototype 槽({ f,f,f }):P 留存 stub_objects(global 重建
|
||||
// 原位重绑依赖索引 4)后,经 bind_constructor! 安装全局槽。
|
||||
// SAFETY: ctor 尚未发布到 global,局部 P 为唯一持有者,可变访问无读者冲突。
|
||||
let ctor = unsafe { &mut *ctor_ptr };
|
||||
let si_prototype = core.perm_interner().intern("prototype").0;
|
||||
let proto_shape = core.shape_forge().make_shape(ctor.shape_id(), si_prototype);
|
||||
ctor.set_shape_id(proto_shape);
|
||||
ctor.ensure_hash_props().push(JsValue::from_js_object(proto_ptr));
|
||||
let proto_pos = ctor.hash_props_vec().map_or(0, |v| v.len() as u32).saturating_sub(1);
|
||||
ctor.set_data_meta(proto_pos, PropAttributes::new(false, false, false));
|
||||
world.stub_objects.push(stub);
|
||||
|
||||
bind_constructor!(
|
||||
core,
|
||||
global,
|
||||
"WeakMap",
|
||||
ctor_ptr,
|
||||
oxide_builtins::weak_map::weak_map_constructor::<crate::vm::Vm>,
|
||||
0,
|
||||
hash: true
|
||||
);
|
||||
}
|
||||
@@ -58,6 +58,8 @@ pub mod bind_symbol;
|
||||
pub mod bind_temporal;
|
||||
/// 各 TypedArray 构造器与共享原型的 native 方法绑定。
|
||||
pub mod bind_typed_array;
|
||||
/// WeakMap 构造器与原型四方法的 native 绑定(弱族不占 BuiltinWorld 槽)。
|
||||
pub mod bind_weak;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -880,9 +882,10 @@ fn bind_iterator_global(core: &Arc<KernelCore>, session: &KernelSession, global:
|
||||
}
|
||||
|
||||
fn bind_stub_globals(core: &Arc<KernelCore>, session: &KernelSession, global: &mut JsObject) {
|
||||
// 索引 4 = WeakMap 真构造器(bind_weak 留存 stub_objects 末位),global
|
||||
// 重建时原位重绑;四 stub 族索引 0-3 紧随其后。
|
||||
for (index, (name, native_fn, arg_count)) in [
|
||||
("Proxy", oxide_builtins::stubs::proxy_stub::<crate::vm::Vm> as *const (), 2),
|
||||
("WeakMap", oxide_builtins::stubs::weakmap_stub::<crate::vm::Vm> as *const (), 0),
|
||||
("WeakSet", oxide_builtins::stubs::weakset_stub::<crate::vm::Vm> as *const (), 0),
|
||||
("WeakRef", oxide_builtins::stubs::weakref_stub::<crate::vm::Vm> as *const (), 1),
|
||||
(
|
||||
@@ -890,6 +893,7 @@ fn bind_stub_globals(core: &Arc<KernelCore>, session: &KernelSession, global: &m
|
||||
oxide_builtins::stubs::finalization_registry_stub::<crate::vm::Vm> as *const (),
|
||||
1,
|
||||
),
|
||||
("WeakMap", oxide_builtins::weak_map::weak_map_constructor::<crate::vm::Vm> as *const (), 0),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
@@ -1223,6 +1227,9 @@ pub fn rebind_dirty_builtins(core: &Arc<KernelCore>, session: &mut KernelSession
|
||||
}
|
||||
if dirty.map_or(true, |d| d.stubs) {
|
||||
bind_stubs::bind_stubs(core, session, global);
|
||||
// WeakMap 真构造器面与 stub 族同脏位:原型对象经 leaked 登记表迁移,
|
||||
// 重绑时全局槽原位更新,不占 BuiltinWorld 槽。
|
||||
bind_weak::bind_weak_map(core, session, global);
|
||||
}
|
||||
if dirty.map_or(true, |d| d.stubs) {
|
||||
bind_bigint::bind_bigint(core, session, global);
|
||||
|
||||
@@ -544,7 +544,8 @@ fn weak_map_entry_survives_promotion_with_live_key() {
|
||||
vm.regs[0] = JsValue::from_js_object(wm_session);
|
||||
vm.regs[1] = JsValue::from_js_object(key);
|
||||
// 值的强根取晋升克隆(表内读回):原件随 epoch 出局。
|
||||
let value_root = oxide_builtins::weak_map::weak_map_get(unsafe { &*wm_session }, JsValue::from_js_object(key));
|
||||
let value_root =
|
||||
oxide_builtins::weak_map::weak_map_probe_get(unsafe { &*wm_session }, JsValue::from_js_object(key));
|
||||
vm.regs[2] = value_root;
|
||||
let mut gc = std::mem::take(&mut vm.gc_state.session_gc);
|
||||
gc.collect(&mut vm);
|
||||
@@ -552,7 +553,7 @@ fn weak_map_entry_survives_promotion_with_live_key() {
|
||||
|
||||
let live_wm = unsafe { &*vm.regs[0].as_js_object_ptr() };
|
||||
assert_eq!(oxide_builtins::weak_map::weak_map_entry_count(live_wm), 1, "强可达键的条目须在收集后存活");
|
||||
let stored = oxide_builtins::weak_map::weak_map_get(live_wm, JsValue::from_js_object(key));
|
||||
let stored = oxide_builtins::weak_map::weak_map_probe_get(live_wm, JsValue::from_js_object(key));
|
||||
assert_eq!(stored, vm.regs[2], "值须按原键读回同一克隆体");
|
||||
assert!(!std::ptr::eq(stored.as_js_object_ptr(), value), "值边须改写到晋升克隆");
|
||||
}
|
||||
@@ -616,7 +617,7 @@ fn weak_map_value_edge_keeps_value_alive() {
|
||||
vm.gc_state.session_gc = gc;
|
||||
|
||||
let live_wm = unsafe { &*vm.regs[0].as_js_object_ptr() };
|
||||
let stored = oxide_builtins::weak_map::weak_map_get(live_wm, JsValue::from_js_object(key));
|
||||
let stored = oxide_builtins::weak_map::weak_map_probe_get(live_wm, JsValue::from_js_object(key));
|
||||
assert!(stored.is_object(), "唯一经值边引用的值须存活");
|
||||
assert!(!std::ptr::eq(stored.as_js_object_ptr(), value_session), "值边须在搬移后改写到新址");
|
||||
assert!(vm.is_session_ptr(stored.as_js_object_ptr()));
|
||||
|
||||
@@ -76,41 +76,45 @@ fn weak_family_proto_to_string_tag() {
|
||||
assert!(result.as_bool());
|
||||
}
|
||||
|
||||
/// 原型成员读不抛钉:缺失方法读返 undefined(非对象 receiver 抛错形态消除);
|
||||
/// %Proxy% 无 prototype 属性,钉其缺失。
|
||||
/// 原型成员读不抛钉:WeakMap 四方法已装为函数;其余弱族 stub 缺失方法
|
||||
/// 读返 undefined(非对象 receiver 抛错形态消除);%Proxy% 无 prototype
|
||||
/// 属性,钉其缺失。
|
||||
#[test]
|
||||
fn stub_proto_member_read_returns_undefined() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(
|
||||
&mut vm,
|
||||
"(function () { \
|
||||
return typeof WeakMap.prototype.get === 'undefined' \
|
||||
&& typeof WeakSet.prototype.add === 'undefined' \
|
||||
&& typeof WeakRef.prototype.deref === 'undefined' \
|
||||
&& typeof FinalizationRegistry.prototype.register === 'undefined' \
|
||||
&& Proxy.prototype === undefined; })()",
|
||||
return typeof WeakMap.prototype.get === 'function' \
|
||||
&& typeof WeakMap.prototype.set === 'function' \
|
||||
&& typeof WeakMap.prototype.has === 'function' \
|
||||
&& typeof WeakMap.prototype.delete === 'function' \
|
||||
&& typeof WeakSet.prototype.add === 'undefined' \
|
||||
&& typeof WeakRef.prototype.deref === 'undefined' \
|
||||
&& typeof FinalizationRegistry.prototype.register === 'undefined' \
|
||||
&& Proxy.prototype === undefined; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.as_bool());
|
||||
}
|
||||
|
||||
/// 构造体不回归钉:五 stub 构造调用仍抛 TypeError(消息含 "… is not implemented")。
|
||||
/// 构造体不回归钉:四 stub 构造调用仍抛 TypeError(消息含 "… is not
|
||||
/// implemented");WeakMap 已落地真构造器,不在此列。
|
||||
#[test]
|
||||
fn stub_ctor_call_still_throws_not_implemented() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(
|
||||
&mut vm,
|
||||
"(function () { \
|
||||
function probe(ctor, args, name) { \
|
||||
try { Reflect.construct(ctor, args, ctor); } \
|
||||
catch (e) { return e instanceof TypeError && e.message.indexOf(name + ' is not implemented') === 0; } \
|
||||
return false; \
|
||||
} \
|
||||
return probe(WeakMap, [], 'WeakMap') \
|
||||
&& probe(WeakSet, [], 'WeakSet') \
|
||||
&& probe(WeakRef, [{}], 'WeakRef') \
|
||||
&& probe(FinalizationRegistry, [function () {}], 'FinalizationRegistry') \
|
||||
&& probe(Proxy, [ {}, {} ], 'Proxy'); })()",
|
||||
function probe(ctor, args, name) { \
|
||||
try { Reflect.construct(ctor, args, ctor); } \
|
||||
catch (e) { return e instanceof TypeError && e.message.indexOf(name + ' is not implemented') === 0; } \
|
||||
return false; \
|
||||
} \
|
||||
return probe(WeakSet, [], 'WeakSet') \
|
||||
&& probe(WeakRef, [{}], 'WeakRef') \
|
||||
&& probe(FinalizationRegistry, [function () {}], 'FinalizationRegistry') \
|
||||
&& probe(Proxy, [ {}, {} ], 'Proxy'); })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.as_bool());
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! WeakMap 构造体与四方法钉:NewTarget 抛面、iterable 协议步序、品牌三分枝
|
||||
//! (set/delete 对非 WeakMap this 抛 TypeError,get/has 静默返 undefined/false)、
|
||||
//! 键面(对象/symbol 可弱持,原始值 set 抛、get/has/delete 静默)。
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use oxide_compiler::compiler::Compiler;
|
||||
use oxide_types::value::JsValue;
|
||||
use oxide_vm::vm::Vm;
|
||||
|
||||
fn eval(vm: &mut Vm, source: &str) -> Result<JsValue, String> {
|
||||
let allocator = oxide_parser::Allocator::default();
|
||||
let program = oxide_parser::parse(&allocator, source).map_err(|e| format!("Parse error: {:?}", e))?;
|
||||
let module = Compiler::new().compile(&program).map_err(|e| format!("Compile error: {}", e))?;
|
||||
vm.run(&Arc::new(module))
|
||||
}
|
||||
|
||||
/// 构造体身份钉:new 形态实例原型链落 WeakMap.prototype、instanceof 成立;
|
||||
/// 普通调用(无 NewTarget)抛 TypeError。
|
||||
#[test]
|
||||
fn weakmap_ctor_instance_and_newtarget_throw() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(
|
||||
&mut vm,
|
||||
"(function () { \
|
||||
var m = new WeakMap(); \
|
||||
if (Object.getPrototypeOf(m) !== WeakMap.prototype) { return false; } \
|
||||
if (!(m instanceof WeakMap)) { return false; } \
|
||||
if (WeakMap.name !== 'WeakMap' || WeakMap.length !== 0) { return false; } \
|
||||
try { WeakMap(); return false; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return false; } } \
|
||||
try { WeakMap([]); return false; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return false; } } \
|
||||
return true; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.as_bool());
|
||||
}
|
||||
|
||||
/// iterable 协议钉:对象键与 symbol 键逐元素 set;空可迭代不调用原型 set
|
||||
/// (覆写计数器探针);对象形态 entry({0,1} 属性)同命中。
|
||||
#[test]
|
||||
fn weakmap_ctor_iterable_protocol() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(
|
||||
&mut vm,
|
||||
"(function () { \
|
||||
var k1 = {}, k2 = {}, ks = Symbol('key'); \
|
||||
var m = new WeakMap([[k1, 'a'], [k2, 'b'], [ks, 's']]); \
|
||||
if (m.get(k1) !== 'a' || m.get(k2) !== 'b' || m.get(ks) !== 's') { return false; } \
|
||||
var count = 0; \
|
||||
var saved = WeakMap.prototype.set; \
|
||||
WeakMap.prototype.set = function () { count += 1; }; \
|
||||
try { \
|
||||
new WeakMap([]); \
|
||||
} finally { \
|
||||
WeakMap.prototype.set = saved; \
|
||||
} \
|
||||
if (count !== 0) { return false; } \
|
||||
var m2 = new WeakMap([{0: k1, 1: 'c'}]); \
|
||||
return m2.get(k1) === 'c'; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.as_bool());
|
||||
}
|
||||
|
||||
/// iterable 失败面钉:set 方法读取出抛原样透传;set 不可调用抛 TypeError;
|
||||
/// 元素非对象抛 TypeError;set 抛错时迭代器经 IteratorClose 恰好关闭一次。
|
||||
#[test]
|
||||
fn weakmap_ctor_iterable_failure_branches() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(
|
||||
&mut vm,
|
||||
"(function () { \
|
||||
var getter = Object.getOwnPropertyDescriptor(WeakMap.prototype, 'set'); \
|
||||
Object.defineProperty(WeakMap.prototype, 'set', { \
|
||||
get: function () { throw new RangeError('boom'); }, \
|
||||
configurable: true \
|
||||
}); \
|
||||
try { new WeakMap([]); return false; } \
|
||||
catch (e) { if (!(e instanceof RangeError)) { return false; } } \
|
||||
finally { Object.defineProperty(WeakMap.prototype, 'set', getter); } \
|
||||
WeakMap.prototype.set = 'not a function'; \
|
||||
try { new WeakMap([[{}, 1]]); return false; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return false; } } \
|
||||
finally { delete WeakMap.prototype.set; } \
|
||||
try { new WeakMap([42]); return false; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return false; } } \
|
||||
var closed = 0; \
|
||||
var k = {}; \
|
||||
var it = { \
|
||||
n: 0, \
|
||||
next: function () { \
|
||||
this.n += 1; \
|
||||
if (this.n === 1) { return { value: [k, 1], done: false }; } \
|
||||
return { done: true }; \
|
||||
}, \
|
||||
return: function () { closed += 1; } \
|
||||
}; \
|
||||
var iterable = {}; \
|
||||
iterable[Symbol.iterator] = function () { return it; }; \
|
||||
WeakMap.prototype.set = function () { throw new Error('x'); }; \
|
||||
try { new WeakMap(iterable); } catch (e) {} \
|
||||
delete WeakMap.prototype.set; \
|
||||
return closed === 1; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(result.as_bool());
|
||||
}
|
||||
|
||||
/// 品牌守卫钉:四方法对非 WeakMap this(plain 对象 / Map 对象 / 各原始 this)
|
||||
/// 均抛 TypeError(`RequireInternalSlot` 语义);合法 this 下未命中键静默返
|
||||
/// undefined/false 且 set 返回 this。
|
||||
#[test]
|
||||
fn weakmap_method_brand_guard() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(
|
||||
&mut vm,
|
||||
"(function () { \
|
||||
var bad = [{}, new Map(), undefined, null, true, 's', 5, Symbol('t')]; \
|
||||
for (var i = 0; i < bad.length; i++) { \
|
||||
try { WeakMap.prototype.set.call(bad[i], {}, 1); return 'set-' + i; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return 'set-kind-' + i; } } \
|
||||
try { WeakMap.prototype.delete.call(bad[i], {}); return 'del-' + i; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return 'del-kind-' + i; } } \
|
||||
try { WeakMap.prototype.get.call(bad[i], {}); return 'get-' + i; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return 'get-kind-' + i; } } \
|
||||
try { WeakMap.prototype.has.call(bad[i], {}); return 'has-' + i; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return 'has-kind-' + i; } } \
|
||||
} \
|
||||
var m = new WeakMap(); \
|
||||
if (WeakMap.prototype.set.call(m, {}, 'v') !== m) { return 'returns-this'; } \
|
||||
if (m.get({}) !== undefined) { return 'fresh-get'; } \
|
||||
if (m.has({}) !== false) { return 'fresh-has'; } \
|
||||
if (m.delete({}) !== false) { return 'fresh-delete'; } \
|
||||
return true; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result, JsValue::bool(true));
|
||||
}
|
||||
|
||||
/// 键面钉:原始值键 set 抛 TypeError;symbol 键经 set/get/has/delete 全链
|
||||
/// 成立(弱键 symbol 臂);原始值键 get/has/delete 静默。
|
||||
#[test]
|
||||
fn weakmap_key_surface_object_and_symbol() {
|
||||
let mut vm = Vm::new();
|
||||
let result = eval(
|
||||
&mut vm,
|
||||
"(function () { \
|
||||
var m = new WeakMap(); \
|
||||
var badKeys = [1, '', undefined, null, true]; \
|
||||
for (var i = 0; i < badKeys.length; i++) { \
|
||||
try { m.set(badKeys[i], 1); return 'set-' + i; } \
|
||||
catch (e) { if (!(e instanceof TypeError)) { return 'set-kind-' + i; } } \
|
||||
if (m.get(badKeys[i]) !== undefined) { return 'get-' + i; } \
|
||||
if (m.has(badKeys[i]) !== false) { return 'has-' + i; } \
|
||||
if (m.delete(badKeys[i]) !== false) { return 'del-' + i; } \
|
||||
} \
|
||||
var s = Symbol('k'); \
|
||||
m.set(s, 'v'); \
|
||||
if (m.get(s) !== 'v' || !m.has(s)) { return 'symbol-roundtrip'; } \
|
||||
m.set(s, 'v2'); \
|
||||
if (m.get(s) !== 'v2') { return 'symbol-overwrite'; } \
|
||||
if (m.delete(s) !== true || m.has(s)) { return 'symbol-delete'; } \
|
||||
return true; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result, JsValue::bool(true));
|
||||
}
|
||||
Reference in New Issue
Block a user