mirror of
https://github.com/pjh456/OxideJS.git
synced 2026-10-25 03:01:12 +08:00
fix: eval 脚本 var 声明落全局 configurable:true——is_eval_script 穿透
This commit is contained in:
@@ -2396,10 +2396,12 @@ impl Vm {
|
||||
Ok(func_val)
|
||||
}
|
||||
|
||||
/// 动态编译脚本(eval 脚本模式):把源码按脚本模式编译,var/函数声明落全局对象。
|
||||
/// 动态编译脚本(eval 脚本模式):把源码按脚本模式编译,var/函数声明落全局对象
|
||||
/// (属性 configurable:true,区别于普通脚本顶层的 false)。
|
||||
///
|
||||
/// # 步骤
|
||||
/// 1. parse(脚本模式)→ compile(emit_program 置 is_global_scope=true)。
|
||||
/// 1. parse(脚本模式)→ compile(emit_program 置 is_global_scope=true,
|
||||
/// Compiler 置 is_eval_script=true)。
|
||||
/// 2. 整棵模块树(根 flat_id=0 + 嵌套函数)追加进平表:`rehome_subtree(&module, base+1)`,
|
||||
/// 使根落 base、子函数 old→base+old,CREATE_CLOSURE imm16 同步重写。
|
||||
/// 3. 扩容 immutables_cache,建函数对象(sub_module_index = base)返回。
|
||||
@@ -2415,7 +2417,10 @@ impl Vm {
|
||||
let allocator = oxide_parser::Allocator::default();
|
||||
let program = oxide_parser::parse(&allocator, code)
|
||||
.map_err(|errs| errs.into_iter().map(|e| e.message).collect::<Vec<_>>().join("\n"))?;
|
||||
let module = oxide_compiler::compiler::Compiler::new().compile(&program)?;
|
||||
// eval 脚本:顶层 var/function 声明落全局属性 configurable:true。
|
||||
let module = oxide_compiler::compiler::Compiler::new()
|
||||
.with_eval_script(true)
|
||||
.compile(&program)?;
|
||||
let base = self.sub_modules.len() as u32;
|
||||
let mut added = Vec::new();
|
||||
// 根模块 flat_id=0 传 base+1,重编号后落 base(避开 sub_module_index()==0 守卫)。
|
||||
|
||||
@@ -299,10 +299,14 @@ impl Vm {
|
||||
/// 不一定是全局对象)。属性可写/可枚举/可配置(未声明标识符 PutValue 与
|
||||
/// eval 脚本 var/函数声明的属性描述符)。
|
||||
///
|
||||
/// # 步骤
|
||||
/// 1. 属性已存在:CreateGlobalVarBinding 不改既有描述符——保持原属性只更新
|
||||
/// 值(不可写数据/访问器:strict 抛 TypeError、sloppy 静默 no-op)。
|
||||
/// 2. 属性缺失:新建可写/可枚举/可配置属性;全局对象不可扩展 → TypeError
|
||||
/// (两模式均抛,CreateGlobalVarBinding 语义)。
|
||||
///
|
||||
/// # 边界与前提
|
||||
/// - 键常量必须是字符串(emit 侧保证);非字符串按错误返回。
|
||||
/// - 全局对象不可扩展且属性缺失 → TypeError(两模式均抛,CreateGlobalVarBinding 语义);
|
||||
/// 已有不可写属性时 sloppy PutValue 静默 no-op,严格模式抛错。
|
||||
pub(crate) fn dispatch_define_global_prop_c(&mut self, a: usize, key_idx: u16) -> Result<(), String> {
|
||||
let idx = key_idx as usize;
|
||||
vm_trace!("DEFINE_GLOBAL_PROP_C value={} idx={}", a, idx);
|
||||
@@ -315,18 +319,25 @@ impl Vm {
|
||||
let global_ptr = self.session.global_object().as_ptr() as *mut JsObject;
|
||||
// SAFETY: 全局对象钉在 session 永久区,指针在 VM 生命周期内有效。
|
||||
let obj = unsafe { &mut *global_ptr };
|
||||
// 属性已存在:保持原描述符只更新值,不升级 configurable(规范:
|
||||
// CreateGlobalVarBinding 对既有属性不改描述符)。
|
||||
if let Some(pos) = self.kernel_core.shape_forge().lookup_position(obj.shape_id(), si) {
|
||||
if let Some(current) = obj.prop_meta_at(pos) {
|
||||
let writable = !current.is_accessor && current.attributes.writable();
|
||||
if !writable {
|
||||
return if self.current_strict() {
|
||||
self.raise_error_kind("TypeError", "cannot assign to read-only property")
|
||||
} else {
|
||||
Ok(())
|
||||
};
|
||||
}
|
||||
return self.define_data_property(obj, si, value, current.attributes);
|
||||
}
|
||||
}
|
||||
// 属性缺失:新建;唯一失败面是全局对象不可扩展(两模式均抛 TypeError)。
|
||||
match self.define_data_property(obj, si, value, PropAttributes::new(true, true, true)) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(msg) => {
|
||||
// 不可扩展 + 新属性:规范两模式均抛;已有不可写属性:sloppy 静默、strict 抛。
|
||||
let non_extensible_new = self.kernel_core.shape_forge().lookup_position(obj.shape_id(), si).is_none()
|
||||
&& !obj.is_extensible();
|
||||
if non_extensible_new || self.current_strict() {
|
||||
self.raise_error_kind("TypeError", &msg)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(msg) => self.raise_error_kind("TypeError", &msg),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! eval 脚本 var/函数声明落全局对象的属性语义测试:configurable:true(区别于普通
|
||||
//! 脚本顶层的 false)、可 delete、跨 eval 轮次经全局对象可见。
|
||||
|
||||
use oxide_compiler::compiler::Compiler;
|
||||
use oxide_types::value::JsValue;
|
||||
use oxide_vm::vm::Vm;
|
||||
|
||||
fn eval(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))?;
|
||||
let mut vm = Vm::new();
|
||||
vm.run(&module)
|
||||
}
|
||||
|
||||
fn eval_many(lines: &[&str]) -> Result<JsValue, String> {
|
||||
eval(&lines.join("; "))
|
||||
}
|
||||
|
||||
fn assert_err_contains(result: Result<JsValue, String>, expected: &str) {
|
||||
match result {
|
||||
Ok(_) => panic!("expected error containing '{}', got Ok", expected),
|
||||
Err(e) => assert!(e.contains(expected), "expected error containing '{}', got: {}", expected, e),
|
||||
}
|
||||
}
|
||||
|
||||
/// 求值并把结果按字符串提取(`JsValue` Display 不携带字符串内容)。
|
||||
fn eval_str(source: &str) -> String {
|
||||
let allocator = oxide_parser::Allocator::default();
|
||||
let program = oxide_parser::parse(&allocator, source).expect("parse");
|
||||
let module = Compiler::new().compile(&program).expect("compile");
|
||||
let mut vm = Vm::new();
|
||||
let result = vm.run(&module).expect("run");
|
||||
vm.lookup_str(result).unwrap_or_else(|| format!("{result}"))
|
||||
}
|
||||
|
||||
// ── eval var 落全局属性 configurable:true ──
|
||||
#[test]
|
||||
fn eval_var_global_property_configurable_true() {
|
||||
let s = eval_str("eval('var x;'); var d = Object.getOwnPropertyDescriptor(globalThis, 'x'); String(d.configurable) + ':' + String(d.writable) + ':' + String(d.enumerable)");
|
||||
assert_eq!(s, "true:true:true", "eval var 全局属性描述符应全 true,实际 {s}");
|
||||
}
|
||||
|
||||
// ── eval var 属性可 delete(configurable:true 的推论) ──
|
||||
#[test]
|
||||
fn eval_var_global_property_deletable() {
|
||||
let r = eval_many(&["eval('var x = 1')", "delete globalThis.x === true && typeof x === 'undefined'"]).unwrap();
|
||||
assert!(r.is_bool() && r.as_bool(), "eval var 属性应可 delete 且删后读回 undefined,实际 {:?}", r);
|
||||
}
|
||||
|
||||
// ── eval var 带初始化值经全局对象可见 ──
|
||||
#[test]
|
||||
fn eval_var_with_initializer_lands_on_global() {
|
||||
let r = eval_many(&["eval('var x = 5')", "globalThis.x === 5"]).unwrap();
|
||||
assert!(r.is_bool() && r.as_bool(), "eval var 初始化值应落全局对象,实际 {:?}", r);
|
||||
}
|
||||
|
||||
// ── 跨 eval 轮次:全局属性经 session 全局对象共享 ──
|
||||
#[test]
|
||||
fn eval_var_visible_across_eval_rounds() {
|
||||
let r = eval_many(&["eval('var a = 1')", "eval('a') === 1"]).unwrap();
|
||||
assert!(r.is_bool() && r.as_bool(), "跨 eval 轮次应经全局对象可见,实际 {:?}", r);
|
||||
}
|
||||
|
||||
// ── eval 函数声明落全局属性 configurable:true 且可调用 ──
|
||||
#[test]
|
||||
fn eval_function_declaration_configurable_and_callable() {
|
||||
let s = eval_str(
|
||||
"eval('function f(){ return 1 }'); \
|
||||
var d = Object.getOwnPropertyDescriptor(globalThis, 'f'); \
|
||||
String(d.configurable) + ':' + String(f())",
|
||||
);
|
||||
assert_eq!(s, "true:1", "eval 函数声明应落全局 configurable:true 且可调用,实际 {s}");
|
||||
}
|
||||
|
||||
// ── 回归:普通脚本顶层 var 仍 configurable:false ──
|
||||
#[test]
|
||||
fn script_top_level_var_still_configurable_false() {
|
||||
let r = eval_many(&["var y;", "Object.getOwnPropertyDescriptor(globalThis, 'y').configurable === false"]).unwrap();
|
||||
assert!(r.is_bool() && r.as_bool(), "脚本顶层 var 应保持 configurable:false,实际 {:?}", r);
|
||||
}
|
||||
|
||||
// ── 严格 eval:未声明写抛 ReferenceError(Step 2 语义经 eval 路径) ──
|
||||
#[test]
|
||||
fn strict_eval_undeclared_write_throws_reference_error() {
|
||||
let result = eval("eval(\"'use strict'; x = 1\")");
|
||||
assert_err_contains(result, "x is not defined");
|
||||
}
|
||||
Reference in New Issue
Block a user