mirror of
https://github.com/pjh456/OxideJS.git
synced 2026-10-23 18:21:13 +08:00
fix: Array @@species 绑定并暴露真 [[Construct]],隐式返回交付当前 this
This commit is contained in:
@@ -66,6 +66,12 @@ pub fn array_is_array<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
NativeResult::Ok(JsValue::bool(unsafe { &*ptr }.is_array()))
|
||||
}
|
||||
|
||||
/// `Array[Symbol.species]` 访问器 getter:返回 receiver——派生类沿静态原型链
|
||||
/// 解析 `@@species` 时得到自身构造器,`Array` 自身解析得到 `Array`。
|
||||
pub fn array_species_get<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
NativeResult::ok(vm.reg(args[0]))
|
||||
}
|
||||
|
||||
/// `Array.of(...items)`:以参数为元素构造新数组。
|
||||
///
|
||||
/// # 步骤
|
||||
@@ -109,7 +115,7 @@ pub fn array_of<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
///
|
||||
/// # 注意事项
|
||||
/// - 迭代只读包装器 `next`/`done`/`value` 属性,与 spread 物化共用同一迭代协议。
|
||||
/// - new.target 不向被构造的 C 传播(与 Reflect.construct 同一简化)。
|
||||
/// - 构造走完整 Construct:new.target 向被构造的 C 传播(与 Reflect.construct 同面)。
|
||||
pub fn array_from<H: VmHost>(vm: &mut H, args: &[u8]) -> NativeResult {
|
||||
let items = if args.len() > 1 { vm.reg(args[1]) } else { JsValue::undefined() };
|
||||
if items.is_null() || items.is_undefined() {
|
||||
@@ -271,8 +277,9 @@ pub(crate) fn from_engine_error<H: VmHost>(vm: &mut H, err: &str) -> JsValue {
|
||||
.unwrap_or_else(|| crate::error::create_from_text(vm, err))
|
||||
}
|
||||
|
||||
/// 按构造函数 C 构造 Array.from 的结果对象:C 可构造时以 C.prototype 分配 `this`
|
||||
/// 后调用 C(返回非对象时回退 `this`),否则返回普通空数组。
|
||||
/// 按构造函数 C 构造 Array.from/of / species 的结果对象:C 可构造时走完整
|
||||
/// Construct(C, args)(native 值传递 / bytecode 压构造帧,含 derived 构造器
|
||||
/// super() 语义与 new.target 传播),否则返回普通空数组。
|
||||
///
|
||||
/// # 返回值
|
||||
/// `(结果对象指针, 是否为真数组)`。
|
||||
@@ -285,42 +292,17 @@ fn construct_array_from_result<H: VmHost>(
|
||||
let arr = vm.alloc_object(JsObject::new_array(EMPTY_SHAPE_ID, proto_val, 0, vm.epoch().bump()));
|
||||
(arr, true)
|
||||
};
|
||||
if !c.is_object() {
|
||||
// 不可构造(箭头函数 / 非构造器标记的 native 方法 / 普通值)回退普通数组。
|
||||
if !is_constructor_value(c) {
|
||||
return Ok(fallback_array());
|
||||
}
|
||||
let c_obj = unsafe { &*c.as_js_object_ptr() };
|
||||
// 不可构造:箭头函数、非构造器标记的 native 方法。
|
||||
let constructible = c_obj.is_function()
|
||||
&& !c_obj.is_arrow()
|
||||
&& !(c_obj.native_fn().is_some() && c_obj.type_tag != JsObject::OBJ_TYPE_CONSTRUCTOR);
|
||||
if !constructible {
|
||||
return Ok(fallback_array());
|
||||
}
|
||||
|
||||
// 仿 Reflect.construct:以 C.prototype 分配 this 后调用 C。
|
||||
let proto_si = vm.kernel_core().perm_interner().intern("prototype").0;
|
||||
let ctor_proto = match vm.resolve_property(c_obj, proto_si) {
|
||||
Some(p) if p.is_object() => p,
|
||||
_ => JsValue::from_js_object(vm.session().builtin_world().object_proto.as_ptr() as *mut JsObject),
|
||||
};
|
||||
let this_ptr = vm.alloc_object(JsObject::new_empty(EMPTY_SHAPE_ID, ctor_proto));
|
||||
let this_val = JsValue::from_js_object(this_ptr);
|
||||
match vm.call_function_sync(c, this_val, args) {
|
||||
Ok(ret) if ret.is_object() => {
|
||||
let ret_ptr = ret.as_js_object_ptr();
|
||||
let ret_tag = unsafe { &*ret_ptr }.type_tag;
|
||||
// 原始值包装对象(如 `Object(4)` 返回的 Number 包装)的索引属性存储不完整,
|
||||
// 回退到刚分配的对象;真数组/普通对象按规范使用构造返回对象。
|
||||
if matches!(
|
||||
ret_tag,
|
||||
JsObject::OBJ_TYPE_STRING_OBJ | JsObject::OBJ_TYPE_NUMBER_OBJ | JsObject::OBJ_TYPE_BOOLEAN_OBJ
|
||||
) {
|
||||
return Ok((this_ptr, false));
|
||||
}
|
||||
Ok((ret_ptr, unsafe { &*ret_ptr }.is_array()))
|
||||
match vm.construct_ctor(c, args) {
|
||||
Ok(obj) => {
|
||||
let obj_ptr = obj.as_js_object_ptr();
|
||||
Ok((obj_ptr, unsafe { &*obj_ptr }.is_array()))
|
||||
}
|
||||
Ok(_) => Ok((this_ptr, false)),
|
||||
Err(err) => Err(from_engine_error(vm, &err)),
|
||||
// 构造器抛错:原值经 Err 直传(保原值身份,不做文本降级重建)。
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -141,6 +141,20 @@ pub trait VmHost {
|
||||
|
||||
// 调用基础设施
|
||||
fn call_function_sync(&mut self, callee: JsValue, receiver: JsValue, args: &[JsValue]) -> Result<JsValue, String>;
|
||||
/// 构造调用(Construct(C, args)):native 构造器以新对象为 receiver 值传递调用,
|
||||
/// bytecode 构造器压构造帧执行(含 derived 构造器 super() 语义与 new.target
|
||||
/// 传播),返回值非对象时回退到新对象。
|
||||
///
|
||||
/// # 边界与前提
|
||||
/// - `ctor` 必须为可构造值(箭头 / 非构造 native / 普通值在入口处拒绝,
|
||||
/// 返回 `Err`);`args` 为完整实参列表。
|
||||
///
|
||||
/// # 副作用
|
||||
/// - bytecode 构造器压帧内嵌 dispatch:调用方执行状态在帧边界保存/恢复
|
||||
/// (寄存器窗口 / 表代际 / spill)。
|
||||
/// - 失败时已消费 `last_uncaught_value`,`Err` 直接携带原始抛出值
|
||||
/// (保原值身份,不做文本降级);调用方不得再取槽。
|
||||
fn construct_ctor(&mut self, ctor: JsValue, args: &[JsValue]) -> Result<JsValue, JsValue>;
|
||||
/// 取回在 String 展平调用边界上保留下来的原始抛出 JsValue,
|
||||
/// 使迭代器包装器能重新抛出原错误而非二次包装。
|
||||
fn take_uncaught_value(&mut self) -> Option<JsValue>;
|
||||
|
||||
@@ -75,4 +75,15 @@ pub fn bind_array(core: &Arc<KernelCore>, session: &KernelSession, global: &mut
|
||||
|
||||
let ctor_ptr = session.builtin_world().array_constructor.as_ptr() as *mut JsObject;
|
||||
bind_constructor!(core, global, "Array", ctor_ptr, oxide_builtins::array::array_constructor::<crate::vm::Vm>, 1, hash: true);
|
||||
// Array[Symbol.species] 访问器:getter 返回 receiver,派生类沿静态原型链
|
||||
// 解析 @@species 得自身构造器(规范不给 class 默认 static @@species,类上
|
||||
// 无 own 属性)。
|
||||
super::bind_accessor_getter_key(
|
||||
core,
|
||||
session,
|
||||
unsafe { &mut *ctor_ptr },
|
||||
oxide_types::private_key::make_well_known_symbol_key(oxide_types::private_key::WELL_KNOWN_SYMBOL_SPECIES),
|
||||
"get [Symbol.species]",
|
||||
oxide_builtins::array::array_species_get::<crate::vm::Vm> as *const (),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -146,31 +146,48 @@ pub(crate) fn apply_binding_table(
|
||||
}
|
||||
}
|
||||
|
||||
/// 在原型上绑定一个原生访问器 getter(如 Set/Map 的 `size`),set 恒为 undefined。
|
||||
/// 在原型上绑定一个字符串键的原生访问器 getter(如 Set/Map 的 `size`),
|
||||
/// set 恒为 undefined。
|
||||
///
|
||||
/// # 步骤
|
||||
/// 1. 构造一个 native getter 函数对象(name 为 `get <prop>`,length 0)。
|
||||
/// 2. 为属性名开 shape 槽位并写入访问器 meta。
|
||||
/// 1. 以 `get <prop>` 为 name 标签委托到 [`Self::bind_accessor_getter_key`]。
|
||||
///
|
||||
/// # 注意事项
|
||||
/// getter 函数对象登记进 world 释放表,与 `bind_method` 的方法 wrapper 同一生命周期约定
|
||||
/// (session 收尾时统一释放)。
|
||||
pub(crate) fn bind_accessor_getter(
|
||||
core: &Arc<KernelCore>, session: &KernelSession, proto: &mut JsObject, name: &str, getter_fn: *const (),
|
||||
) {
|
||||
let si = core.perm_interner().intern(name).0;
|
||||
let getter_name = format!("get {name}");
|
||||
bind_accessor_getter_key(core, session, proto, si, &getter_name, getter_fn)
|
||||
}
|
||||
|
||||
/// 在原型上按任意属性键(字符串 intern 键或 well-known symbol 键)绑定一个
|
||||
/// 原生访问器 getter,set 恒为 undefined。
|
||||
///
|
||||
/// # 步骤
|
||||
/// 1. 构造一个 native getter 函数对象(name 为 `getter_label`,length 0)。
|
||||
/// 2. 为键开 shape 槽位并写入访问器 meta(enumerable=false, configurable=true)。
|
||||
///
|
||||
/// # 注意事项
|
||||
/// getter 函数对象登记进 world 释放表,与 `bind_method` 的方法 wrapper 同一生命周期约定
|
||||
/// (session 收尾时统一释放)。
|
||||
pub(crate) fn bind_accessor_getter_key(
|
||||
core: &Arc<KernelCore>, session: &KernelSession, proto: &mut JsObject, key: u32, getter_label: &str,
|
||||
getter_fn: *const (),
|
||||
) {
|
||||
let shape_forge = core.shape_forge().as_ref();
|
||||
let string_forge = core.perm_interner().as_ref();
|
||||
let world = session.builtin_world();
|
||||
|
||||
let si = string_forge.intern(name).0;
|
||||
let getter_name = format!("get {name}");
|
||||
let si_label = string_forge.intern(&getter_name).0;
|
||||
let si_label = string_forge.intern(getter_label).0;
|
||||
// SAFETY: getter_fn 是转成 *const () 的 NativeFn 函数项指针。
|
||||
let getter_fn_ptr = unsafe { oxide_types::object::NativeFnPtr::from_raw(getter_fn) };
|
||||
// 选择性重建复用:同家族同槽旧 getter 迁移到新 proto 的访问器槽(proto
|
||||
// 槽已由重建收尾重指),不再新建对象。
|
||||
let reuse_key =
|
||||
oxide_kernel::builtin::FnWrapperKey::new(world.wrapper_family_of(proto as *const JsObject), 0, si, si_label);
|
||||
oxide_kernel::builtin::FnWrapperKey::new(world.wrapper_family_of(proto as *const JsObject), 0, key, si_label);
|
||||
let getter_ptr = match world.find_fn_wrapper(reuse_key, getter_fn_ptr, 0) {
|
||||
Some(ptr) => ptr,
|
||||
None => {
|
||||
@@ -203,7 +220,7 @@ pub(crate) fn bind_accessor_getter(
|
||||
};
|
||||
let getter_val = JsValue::from_js_object(getter_ptr);
|
||||
|
||||
let new_shape = shape_forge.make_shape(proto.shape_id(), si);
|
||||
let new_shape = shape_forge.make_shape(proto.shape_id(), key);
|
||||
proto.set_shape_id(new_shape);
|
||||
let pos = proto.push_prop(JsValue::undefined());
|
||||
proto.set_accessor_meta(pos, getter_val, JsValue::undefined(), PropAttributes::new(true, false, true));
|
||||
|
||||
@@ -580,14 +580,14 @@ impl Vm {
|
||||
}
|
||||
|
||||
if super_obj.native_fn().is_some() {
|
||||
self.regs[253] = derived_this;
|
||||
self.regs[254] = super_ctor; // bind_dispatcher 把 regs[254] 当作包装 callee 读取
|
||||
let (args_buf, len) = Self::build_native_args(first_arg_reg, arg_count, 253);
|
||||
// SAFETY: native_fn 经 set_native_fn 以合法 NativeFn 指针设置;
|
||||
// native_fn_ptr_to_fn 是 NativeFnPtr → NativeFn 的唯一强制转换点。
|
||||
let func: NativeFn = unsafe { native_fn_ptr_to_fn(super_obj.native_fn().unwrap()) };
|
||||
match func(self, &args_buf[..len]) {
|
||||
NativeResult::Ok(val) => {
|
||||
// 实参先物化再走同步调用收口:native 调用协议把 253/254 槽固定为
|
||||
// receiver/callee,实参寄存器(颜色 ≤253)占位 253 时裸引用会被覆写
|
||||
// (与 SUPER_CALL_SPREAD 路径同形)。
|
||||
let args: Vec<JsValue> = (0..arg_count)
|
||||
.map(|i| self.regs[first_arg_reg.wrapping_add(i as u8) as usize])
|
||||
.collect();
|
||||
match self.call_function_sync(super_ctor, derived_this, &args) {
|
||||
Ok(val) => {
|
||||
// super() 返回实例的 [[Prototype]] 须设为 new.target.prototype
|
||||
//(native 构造器不知道 new.target,由调用方设置)。
|
||||
let instance = if val.is_object() { val } else { derived_this };
|
||||
@@ -598,26 +598,18 @@ impl Vm {
|
||||
self.regs[rd] = self.regs[254];
|
||||
self.mark_super_called();
|
||||
}
|
||||
NativeResult::Err(err_val) => {
|
||||
self.exception_value = Some(err_val);
|
||||
self.pending_error_kind = Some(self.thrown_error_kind(err_val));
|
||||
Err(_) => {
|
||||
let exc = self
|
||||
.last_uncaught_value
|
||||
.take()
|
||||
.unwrap_or_else(|| oxide_builtins::error::create_error(self, "super() call failed"));
|
||||
self.exception_value = Some(exc);
|
||||
self.pending_error_kind = Some(self.thrown_error_kind(exc));
|
||||
match self.unwind() {
|
||||
Ok(()) => return Ok(true),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
NativeResult::TailCall { callee, this, args } => {
|
||||
// 如 bound 函数:解析尾调用,用其返回值作为构造实例
|
||||
// (或回退到 derived_this)。
|
||||
let val = self.call_function_sync(callee, this, &args)?;
|
||||
let instance = if val.is_object() { val } else { derived_this };
|
||||
if instance.is_object() {
|
||||
self.set_constructed_proto(instance, new_target_obj)?;
|
||||
}
|
||||
self.regs[254] = instance;
|
||||
self.regs[rd] = self.regs[254];
|
||||
self.mark_super_called();
|
||||
}
|
||||
}
|
||||
} else if super_obj.sub_module_index() > 0 {
|
||||
let sub_idx = super_obj.sub_module_index() as usize;
|
||||
|
||||
@@ -42,7 +42,11 @@ impl Vm {
|
||||
|
||||
/// 构造调用(Construct(C, args)):native 构造器值传递调用,bytecode 构造器
|
||||
/// 压构造帧执行(含 derived 构造器 super() 语义),返回值非对象时回退到新对象。
|
||||
pub(super) fn construct_ctor(&mut self, ctor: JsValue, args: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
///
|
||||
/// # 边界与前提
|
||||
/// - `ctor` 非可构造值(箭头 / 非构造 native / 普通值)返回 TypeError 的 `Err`;
|
||||
/// 消费 `last_uncaught_value`,调用方不得再取槽。
|
||||
pub(crate) fn construct_ctor(&mut self, ctor: JsValue, args: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
// IsConstructor 校验:arrow / 非构造 native / 普通值拒绝。
|
||||
if !is_constructor_value(ctor) {
|
||||
return Err(oxide_builtins::error::create_type_error(self, "constructor is not a constructor"));
|
||||
|
||||
@@ -130,6 +130,9 @@ impl oxide_runtime_api::VmHost for Vm {
|
||||
fn call_function_sync(&mut self, callee: JsValue, receiver: JsValue, args: &[JsValue]) -> Result<JsValue, String> {
|
||||
self.call_function_sync(callee, receiver, args)
|
||||
}
|
||||
fn construct_ctor(&mut self, ctor: JsValue, args: &[JsValue]) -> Result<JsValue, JsValue> {
|
||||
Vm::construct_ctor(self, ctor, args)
|
||||
}
|
||||
fn checked_object_ptr(&mut self, val: JsValue, error_msg: &str) -> Result<Option<*mut JsObject>, String> {
|
||||
self.checked_object_ptr(val, error_msg)
|
||||
}
|
||||
|
||||
@@ -741,16 +741,26 @@ impl Vm {
|
||||
let is_derived_constructor = frame.is_derived_constructor;
|
||||
let super_called = frame.super_called;
|
||||
let continuation = frame.continuation;
|
||||
// 隐式返回交付当前 this 绑定:super() 已把 regs[254] 换为父构造器新建
|
||||
// 的实例,restore_frame 会把压帧期旧值回写 regs[254],须先取。
|
||||
let current_this = self.regs[254];
|
||||
vm_trace!("RETURN frame: continuation={:?}, derived={}", continuation, is_derived_constructor);
|
||||
self.restore_frame(frame);
|
||||
if let (Some(target_reg), Some(constructed_this)) = (construct_result_reg, constructed_this) {
|
||||
// 规范 §9.2.2.2:derived 构造器返回非对象值(含 undefined/null/原始值)
|
||||
// 且未调用 super() 时抛 ReferenceError;调过 super() 则回退构造 this。
|
||||
// 且未调用 super() 时抛 ReferenceError;调过 super() 则回退当前 this
|
||||
// (super 已将其换为父构造器实例,构造 this 仅作非对象兜底)。
|
||||
if is_derived_constructor && !result.is_object() && !super_called {
|
||||
self.raise_error_kind("ReferenceError", "derived constructor must call super()")?;
|
||||
return Ok(None);
|
||||
}
|
||||
self.regs[target_reg as usize] = if result.is_object() { result } else { constructed_this };
|
||||
self.regs[target_reg as usize] = if result.is_object() {
|
||||
result
|
||||
} else if current_this.is_object() {
|
||||
current_this
|
||||
} else {
|
||||
constructed_this
|
||||
};
|
||||
self.regs[0] = self.regs[target_reg as usize];
|
||||
vm_trace!("RETURN constructor: target_reg={} regs[0]={:?}", target_reg, self.regs[0]);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Array[Symbol.species] 访问器绑定 + 内建侧真 [[Construct]] + derived 构造器
|
||||
//! 隐式返回交付当前 this 的引擎钉:派生类 B 经 map/filter/slice/flat/flatMap 的
|
||||
//! 结果实例身份回 B,静态链解析 B 自身,显式 super 构造器多参元素拷贝。
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use oxide_compiler::compiler::Compiler;
|
||||
use oxide_types::value::JsValue;
|
||||
use oxide_vm::vm::Vm;
|
||||
|
||||
fn eval_value(source: &str) -> Result<(Vm, 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))?;
|
||||
let mut vm = Vm::new();
|
||||
let result = vm.run(&Arc::new(module))?;
|
||||
Ok((vm, result))
|
||||
}
|
||||
|
||||
fn eval_str(source: &str) -> Result<String, String> {
|
||||
let (vm, result) = eval_value(source)?;
|
||||
vm.lookup_str(result)
|
||||
.ok_or_else(|| "completion value is not a string".to_string())
|
||||
}
|
||||
|
||||
// Array[Symbol.species] 是访问器属性:get 函数、set undefined、!enumerable、configurable。
|
||||
#[test]
|
||||
fn eval_species_accessor_descriptor() {
|
||||
let out = eval_str(
|
||||
"(() => { const d = Object.getOwnPropertyDescriptor(Array, Symbol.species); \
|
||||
return typeof d.get + '|' + (d.set === undefined) + '|' + d.enumerable + '|' + d.configurable; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "function|true|false|true");
|
||||
}
|
||||
|
||||
// species getter 的 Function.length 为 0。
|
||||
#[test]
|
||||
fn eval_species_getter_length_zero() {
|
||||
let out = eval_str("String(Object.getOwnPropertyDescriptor(Array, Symbol.species).get.length)").unwrap();
|
||||
assert_eq!(out, "0");
|
||||
}
|
||||
|
||||
// species getter 的 Function.name 为规范标签。
|
||||
#[test]
|
||||
fn eval_species_getter_name() {
|
||||
let out = eval_str("Object.getOwnPropertyDescriptor(Array, Symbol.species).get.name").unwrap();
|
||||
assert_eq!(out, "get [Symbol.species]");
|
||||
}
|
||||
|
||||
// species getter 返回 receiver(显式 call 形态)。
|
||||
#[test]
|
||||
fn eval_species_getter_returns_receiver() {
|
||||
let out = eval_str(
|
||||
"(() => { const o = {}; \
|
||||
return (Object.getOwnPropertyDescriptor(Array, Symbol.species).get.call(o) === o) + ''; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "true");
|
||||
}
|
||||
|
||||
// 派生类沿静态原型链解析 @@species 得自身构造器,且类上无 own 属性。
|
||||
#[test]
|
||||
fn eval_species_static_chain_resolves_self() {
|
||||
let out = eval_str(
|
||||
"(() => { class B extends Array {} \
|
||||
return (B[Symbol.species] === B) + '|' + \
|
||||
(Object.getOwnPropertyDescriptor(B, Symbol.species) === undefined); })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "true|true");
|
||||
}
|
||||
|
||||
// B 实例 map 结果 instanceof B(species 主形态)。
|
||||
#[test]
|
||||
fn eval_map_instance_of_derived() {
|
||||
let out =
|
||||
eval_str("(() => { class B extends Array {} return (new B(2).map(x => x) instanceof B) + ''; })()").unwrap();
|
||||
assert_eq!(out, "true");
|
||||
}
|
||||
|
||||
// B 实例 filter/slice/flat/flatMap 四挂载全回 B 实例。
|
||||
#[test]
|
||||
fn eval_filter_slice_flat_flatmap_instance_of_derived() {
|
||||
let out = eval_str(
|
||||
"(() => { class B extends Array {} const b = new B(2); b[0] = 1; b[1] = 2; \
|
||||
return (b.filter(x => true) instanceof B) + '|' + \
|
||||
(b.slice(0) instanceof B) + '|' + \
|
||||
(b.flat() instanceof B) + '|' + \
|
||||
(b.flatMap(x => x) instanceof B); })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "true|true|true|true");
|
||||
}
|
||||
|
||||
// 嵌套继承 C extends B:C 实例 map 回 C 实例。
|
||||
#[test]
|
||||
fn eval_nested_inheritance_map_instance_of() {
|
||||
let out = eval_str(
|
||||
"(() => { class B extends Array {} class C extends B {} \
|
||||
return (new C(2).map(x => x) instanceof C) + ''; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "true");
|
||||
}
|
||||
|
||||
// species 结果是真数组 exotic(Array.isArray 识别)。
|
||||
#[test]
|
||||
fn eval_species_result_is_array() {
|
||||
let out =
|
||||
eval_str("(() => { class B extends Array {} return Array.isArray(new B(2).map(x => x)) + ''; })()").unwrap();
|
||||
assert_eq!(out, "true");
|
||||
}
|
||||
|
||||
// 显式单参 super 构造器:隐式返回交付 super 新建的实例(length 来自父构造器)。
|
||||
#[test]
|
||||
fn eval_explicit_super_single_arg_length() {
|
||||
let out = eval_str(
|
||||
"(() => { class Sub extends Array { constructor(a) { super(a); } } \
|
||||
return new Sub(42).length + ''; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "42");
|
||||
}
|
||||
|
||||
// 显式多参 super 构造器:元素经父构造器拷贝进实例。
|
||||
#[test]
|
||||
fn eval_explicit_super_spread_elements() {
|
||||
let out = eval_str(
|
||||
"(() => { class Sub extends Array { constructor(...a) { super(...a); } } \
|
||||
return JSON.stringify(new Sub(1, 2, 3)); })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "[1,2,3]");
|
||||
}
|
||||
|
||||
// Array.of 经 C 构造:class 形态回 C 实例。
|
||||
#[test]
|
||||
fn eval_array_of_via_derived_ctor() {
|
||||
let out =
|
||||
eval_str("(() => { class B extends Array {} return (Array.of.call(B, 1, 2) instanceof B) + ''; })()").unwrap();
|
||||
assert_eq!(out, "true");
|
||||
}
|
||||
|
||||
// species 为普通可构造 Ctor:返回体直接作结果(元素 CDO 写入其上)。
|
||||
#[test]
|
||||
fn eval_species_plain_ctor_returned_body() {
|
||||
let out = eval_str(
|
||||
"(() => { function Ctor(n) { const a = [7, 8]; a.push(n); return a; } \
|
||||
const a = [1, 2]; a.constructor = {}; a.constructor[Symbol.species] = Ctor; \
|
||||
const r = a.map(x => x); \
|
||||
return r.length + '|' + r[0] + '|' + r[1] + '|' + r[2] + '|' + (r instanceof Array); })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "3|1|2|2|true");
|
||||
}
|
||||
|
||||
// 守卫:构造器直 new 面不回归。
|
||||
#[test]
|
||||
fn eval_guard_derived_new_instance() {
|
||||
let out = eval_str("(() => { class B extends Array {} return (new B(2) instanceof B) + ''; })()").unwrap();
|
||||
assert_eq!(out, "true");
|
||||
}
|
||||
|
||||
// 守卫:普通数组 map 结果 isArray + 值保真。
|
||||
#[test]
|
||||
fn eval_guard_plain_map_values() {
|
||||
let out = eval_str("(() => { const m = [1, 2].map(x => x); return Array.isArray(m) + '|' + m[1]; })()").unwrap();
|
||||
assert_eq!(out, "true|2");
|
||||
}
|
||||
|
||||
// 守卫:隐式 super 构造器 length 与多参元素。
|
||||
#[test]
|
||||
fn eval_guard_implicit_super() {
|
||||
let out = eval_str(
|
||||
"(() => { class Sub extends Array {} const s = new Sub(7); const t = new Sub(7, 8); \
|
||||
return s.length + '|' + t.length + '|' + t[0] + '|' + t[1]; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "7|2|7|8");
|
||||
}
|
||||
|
||||
// 守卫:native 父构造器 Reflect.construct 路径在位。
|
||||
#[test]
|
||||
fn eval_guard_reflect_construct_native() {
|
||||
let out = eval_str("String(Reflect.construct(Array, [3]).length)").unwrap();
|
||||
assert_eq!(out, "3");
|
||||
}
|
||||
|
||||
// 守卫:静态原型链果——B.prototype 的原型即 Array.prototype。
|
||||
#[test]
|
||||
fn eval_guard_prototype_chain() {
|
||||
let out = eval_str(
|
||||
"(() => { class B extends Array {} \
|
||||
return (Object.getPrototypeOf(B.prototype) === Array.prototype) + ''; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "true");
|
||||
}
|
||||
|
||||
// 守卫:c={} 形态(constructor 为普通对象、无 species)slice 回普通数组。
|
||||
#[test]
|
||||
fn eval_guard_plain_ctor_lookup() {
|
||||
let out = eval_str(
|
||||
"(() => { const a = [1, 2, 3]; a.constructor = {}; const s = a.slice(1); \
|
||||
return s.length + '|' + (s instanceof Array) + '|' + s[0]; })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "2|true|2");
|
||||
}
|
||||
|
||||
// 守卫:普通数组 slice/filter 结果 plain Array。
|
||||
#[test]
|
||||
fn eval_guard_plain_slice_filter() {
|
||||
let out = eval_str(
|
||||
"(() => { const a = [1, 2, 3]; \
|
||||
return (a.slice(1) instanceof Array) + '|' + (a.filter(x => true) instanceof Array); })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "true|true");
|
||||
}
|
||||
|
||||
// 守卫:String 无 species 绑定(不引入 String[Symbol.species])。
|
||||
#[test]
|
||||
fn eval_guard_string_no_species() {
|
||||
let out = eval_str(
|
||||
"(() => { class S extends String {} \
|
||||
return (S[Symbol.species] === undefined) + '|' + (String[Symbol.species] === undefined); })()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(out, "true|true");
|
||||
}
|
||||
Reference in New Issue
Block a user