From 938de6e8a3dbd7f159f1b8fe16cc244a6bf936bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:31:33 -0800 Subject: [PATCH 1/6] JavaScript: Symbol keys reach a proxy's target, Reflect keeps Symbol keys, and a sealed global skips Proxy and Reflect - A Symbol key on a proxy now goes to its innermost target for every operation: a definition, write or deletion no longer lands on the proxy object itself. Object.freeze, Object.seal, Object.isFrozen and Object.isSealed therefore work on a proxy whose target has Symbol properties instead of throwing a TypeError. - Reflect.get, set, has, defineProperty, deleteProperty and getOwnPropertyDescriptor keep a Symbol key as a Symbol, and Reflect.ownKeys lists Symbol keys after the string keys. - A realm whose global object an earlier run made non-extensible runs its ECMAScript 2015 code without Proxy and Reflect, instead of failing every run with an installation error. - JSON.stringify charges a replacer array's names to the heap as they are kept, not the array's whole length up front. - for-in checks each name's descriptor from the object that listed it, so a proxy that did not list a name does not hide an inherited one. - An Array subclass constructed with a proxy newTarget runs the proxy's get trap before any revoked inner proxy is reached. - The legacy reflect.find reads its lists without calling proxy traps. --- crates/js/src/builtins/json.rs | 15 ++- crates/js/src/builtins/object.rs | 21 ----- crates/js/src/builtins/reflect.rs | 82 ++++++++++++++--- crates/js/src/class_ops.rs | 4 +- crates/js/src/heap.rs | 6 +- crates/js/src/interp.rs | 46 +++++++--- crates/js/src/proxy.rs | 2 +- crates/js/src/proxy_tests.rs | 148 ++++++++++++++++++++++++------ crates/js/src/realm.rs | 4 +- crates/js/src/reflect.rs | 8 +- crates/js/src/symbol.rs | 29 ++++-- docs/mcp.md | 29 +++--- docs/target-app-parity.md | 2 +- 13 files changed, 286 insertions(+), 110 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 4d9c87a4d9..f0ce3384c6 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult { struct Settings { replacer: Option, properties: Option>, + _held_properties: Option, gap: Vec, } @@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { /// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8). fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult { - let mut s = Settings { replacer: None, properties: None, gap: Vec::new() }; + let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() }; if let Value::Object(r) = replacer { if interp.is_callable(replacer) { s.replacer = Some(replacer.clone()); } else if interp.is_array(replacer)? { - s.properties = Some(property_list(interp, *r)?); + let crate::interp::HeldKeys { keys, held } = property_list(interp, *r)?; + s.properties = Some(keys); + s._held_properties = Some(held); } } let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone()); @@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { +/// Each name kept is charged to the heap for as long as the returned holder lives. +fn property_list(interp: &mut Interp, r: ObjId) -> JsResult { let len = super::collections::length_of(interp, r)?; if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { @@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult> { } // The list lives until the call returns, so its names are rooted. interp.temp_roots.push(Value::String(s)); + held.add(interp, ELEMENT_BYTES)?; list.push(k); } } - Ok(list) + Ok(crate::interp::HeldKeys { keys: list, held }) } /// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 599519c0e0..8237c11f34 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -259,13 +259,11 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> { /// 15.2.3.8 and 15.2.3.9). A proxy that does not become non-extensible is a `TypeError`. fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { let Value::Object(o) = v else { return Ok(v) }; - check_integrity_symbols(interp, o)?; if !interp.prevent_extensions(o)? { let what = if freeze { "frozen" } else { "sealed" }; return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible"))); } let (keys, _held) = own_prop_keys(interp, o)?; - check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; let desc = if freeze { @@ -279,7 +277,6 @@ fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult { }; interp.define_own_pk(o, k, &desc, true)?; } - check_integrity_symbols(interp, o)?; Ok(Value::Object(o)) } @@ -308,12 +305,10 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let Value::Object(o) = v else { return Ok(Value::Bool(true)) }; let o = *o; - check_integrity_symbols(interp, o)?; if interp.is_extensible(o)? { return Ok(Value::Bool(false)); } let (keys, _held) = own_prop_keys(interp, o)?; - check_integrity_symbols(interp, o)?; for k in keys { interp.use_fuel()?; let Some(prop) = interp.own_pk(o, &k)? else { continue }; @@ -321,7 +316,6 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { return Ok(Value::Bool(false)); } } - check_integrity_symbols(interp, o)?; Ok(Value::Bool(true)) } @@ -329,21 +323,6 @@ fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult locked(interp, &arg(args, 0), false) } -fn check_integrity_symbols(interp: &mut Interp, o: ObjId) -> JsResult<()> { - if !interp.is_proxy(o) { - return Ok(()); - } - let mut current = o; - loop { - if interp.object(current)?.syms.as_ref().is_some_and(|m| m.len() != 0) { - return Err(interp.type_error("proxy integrity operations with symbol properties are not supported")); - } - let Some(target) = interp.symbol_lookup_target(current)? else { return Ok(()) }; - interp.use_fuel()?; - current = target; - } -} - fn is_frozen(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { locked(interp, &arg(args, 0), true) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 0b0f60cacf..a49833739c 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -6,17 +6,24 @@ use std::rc::Rc; use super::object::{from_prop, names_array, to_desc}; use super::{arg, method, native}; -use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, key}; +use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; +use crate::symbol::{PropKey, Sym}; use crate::value::Value; /// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them /// after earlier runs, a global of the same name that a script defined stays as it is. Each /// global is defined after its functions, so an install that stops part way leaves no global -/// that a later install would keep without them. +/// that a later install would keep without them. A global object that an earlier run made +/// non-extensible cannot become extensible again, so a name it lacks is left out and the realm's +/// runs go on without it. pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> { let global = interp.global; + if keep && interp.heap.object(global).is_some_and(|g| !g.extensible) { + interp.es2015_installed = true; + return Ok(()); + } if !(keep && interp.get_own_property(global, &key("Proxy"))?.is_some()) { let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; // Naming a new method can collect, and the constructor is reachable from nowhere else @@ -161,32 +168,41 @@ fn construct(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult /// property was defined. fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "defineProperty")?; - interp.with_key(&arg(args, 1), |interp, k| { + interp.with_prop_key(&arg(args, 1), |interp, k| { let desc: Desc = to_desc(interp, &arg(args, 2))?; let roots = desc_values(&desc); - interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, false)).map(Value::Bool) + interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, false)).map(Value::Bool) }) } /// `Reflect.deleteProperty(target, propertyKey)` (section 26.1.4): whether the property is gone. fn delete_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "deleteProperty")?; - interp.with_key(&arg(args, 1), |interp, k| interp.delete(o, &k, false)).map(Value::Bool) + interp.with_prop_key(&arg(args, 1), |interp, k| interp.delete_pk(o, &k, false)).map(Value::Bool) } /// `Reflect.get(target, propertyKey[, receiver])` (section 26.1.5). fn get(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "get")?; let receiver = if args.len() > 2 { arg(args, 2) } else { Value::Object(o) }; - interp.with_key(&arg(args, 1), |interp, k| interp.get_from(o, &k, &receiver)) + interp.with_prop_key(&arg(args, 1), |interp, k| match k { + PropKey::Str(k) => interp.get_from(o, &k, &receiver), + PropKey::Sym(s) => interp.get_sym_from(o, &s, &receiver), + }) } /// `Reflect.getOwnPropertyDescriptor(target, propertyKey)` (section 26.1.6). fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "getOwnPropertyDescriptor")?; - interp.with_key(&arg(args, 1), |interp, k| match interp.own_property(o, &k)? { - Some(p) => from_prop(interp, &p), - None => Ok(Value::Undefined), + interp.with_prop_key(&arg(args, 1), |interp, k| { + let prop = match k { + PropKey::Str(k) => interp.own_property(o, &k)?, + PropKey::Sym(s) => interp.get_own_sym(o, &s)?, + }; + match prop { + Some(p) => from_prop(interp, &p), + None => Ok(Value::Undefined), + } }) } @@ -199,7 +215,12 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J /// `Reflect.has(target, propertyKey)` (section 26.1.8). fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "has")?; - interp.with_key(&arg(args, 1), |interp, k| interp.has_property_indexed(o, &k)).map(Value::Bool) + interp + .with_prop_key(&arg(args, 1), |interp, k| match k { + PropKey::Str(k) => interp.has_property_indexed(o, &k), + PropKey::Sym(s) => Ok(interp.find_sym(o, &s)?.is_some()), + }) + .map(Value::Bool) } /// `Reflect.isExtensible(target)` (section 26.1.9). @@ -208,11 +229,23 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.is_extensible(o).map(Value::Bool) } -/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not. +/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not, +/// then the own Symbol keys in the order they were added. A proxy's Symbol keys are its +/// target's. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; let names = interp.ecma_own_keys(o)?; - names_array(interp, names) + let count = names.len(); + let syms = interp.own_symbols(o)?; + let a = names_array(interp, names)?; + let Value::Object(id) = a else { return Ok(a) }; + interp.rooted(&[Value::Object(id)], |interp| { + for (i, s) in syms.into_iter().enumerate() { + interp.use_fuel()?; + super::create_at(interp, id, (count + i) as f64, Value::Symbol(s))?; + } + Ok(Value::Object(id)) + }) } /// `Reflect.preventExtensions(target)` (section 26.1.11): whether the object is now not @@ -228,7 +261,30 @@ fn set(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult 3 { arg(args, 3) } else { Value::Object(o) }; let v = arg(args, 2); - interp.with_key(&arg(args, 1), |interp, k| interp.set_with_receiver(o, k, v, &receiver)).map(Value::Bool) + interp + .with_prop_key(&arg(args, 1), |interp, k| match k { + PropKey::Str(k) => interp.set_with_receiver(o, k, v, &receiver), + PropKey::Sym(s) => set_sym(interp, o, s, v, &receiver), + }) + .map(Value::Bool) +} + +/// OrdinarySet (section 9.1.9.1) for a Symbol key: whether `receiver` took the value. +fn set_sym(interp: &mut Interp, o: ObjId, s: Sym, v: Value, receiver: &Value) -> JsResult { + match interp.find_sym(o, &s)? { + Some(Prop::Accessor { set: Some(f), .. }) => return interp.call(&Value::Object(f), receiver, &[v]).map(|_| true), + Some(Prop::Accessor { set: None, .. }) => return Ok(false), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return Ok(false), + _ => {} + } + let Value::Object(r) = receiver else { return Ok(false) }; + let desc = match interp.get_own_sym(*r, &s)? { + Some(Prop::Accessor { .. }) => return Ok(false), + Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return Ok(false), + Some(Prop::Data { .. }) => Desc { value: Some(v), ..Desc::default() }, + None => Desc::data(v, OPEN), + }; + interp.define_own_sym(*r, s, &desc, false) } /// `Reflect.setPrototypeOf(target, proto)` (section 26.1.13): whether the prototype was set. A diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index ced17a3507..99b63f4f56 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -313,7 +313,9 @@ impl Interp { Some(Func::Native { f: native, constructor: true, name, .. }) => { // `Proxy` does not read `new.target` (section 26.2.1.1). let subclass = nt != callee && name != "Proxy"; - if !boundary && subclass && !forwarding && self.unwrapped_proxy_target(nt)? != callee && !self.subclassable(callee)? { + // A built-in that can be subclassed takes any `newTarget`, so its proxies are not + // unwrapped, and a revoked inner proxy does not stop the outer one's traps. + if !boundary && subclass && !forwarding && !self.subclassable(callee)? && self.unwrapped_proxy_target(nt)? != callee { return Err(self.type_error("this built-in cannot be subclassed")); } let intrinsic = match self.get_own_property(callee, &key("prototype"))? { diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 89fb2c0a2e..2417e3bd7a 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -211,10 +211,12 @@ pub(crate) struct ArgMap { pub(crate) names: Vec>, } -/// A `for-in` loop's state: the names listed when it started, and the object they came from. +/// A `for-in` loop's state: the names listed when it started, the object on the prototype chain +/// that listed each name, and the object they came from. #[derive(Clone, Debug)] pub(crate) struct ForIn { pub(crate) keys: Vec, + pub(crate) from: Vec, pub(crate) pos: usize, pub(crate) object: Option, } @@ -1178,7 +1180,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u } } Class::ForIn(state) => { - work.extend(state.object.iter().map(|o| o.0)); + work.extend(state.object.iter().chain(state.from.iter()).map(|o| o.0)); strings.bytes += state.keys.iter().map(|k| string_bytes(k.len())).sum::(); } Class::Symbol(s) => strings.add_symbol(s), diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f92cf9500f..3a3f8e1461 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3283,27 +3283,37 @@ impl Interp { /// /// For a String object, the heap budget for all its index names is checked before any is /// built. Each index name and each property visited takes a unit of fuel. - fn enumerable_keys(&mut self, id: ObjId) -> JsResult> { + /// + /// With each name comes the object on the chain that listed it. Those objects stay in + /// `temp_roots` after a successful return, for the caller to keep or drop. + fn enumerable_keys(&mut self, id: ObjId) -> JsResult<(Vec, Vec)> { if self.options.e4x && self.is_xml(&Value::Object(id)) { - return self.xml_enumerate(id); + let keys = self.xml_enumerate(id)?; + let from = vec![id; keys.len()]; + return Ok((keys, from)); } let slot = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); let r = self.enumerable_keys_from(id, slot); - self.temp_roots.truncate(slot); + if r.is_err() { + self.temp_roots.truncate(slot); + } r } /// [`Self::enumerable_keys`] after the XML case. A proxy on the chain gives its names with its /// `ownKeys` trap and the next object with its `getPrototypeOf` trap. /// `temp_roots[slot]` roots the current proxy through that lookup, then the returned prototype. - /// Descriptors are checked when iteration reaches each name. - fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult> { + /// Descriptors are checked when iteration reaches each name, starting at the object that + /// listed it. Each object on the chain is pushed to `temp_roots` after `slot`. + fn enumerable_keys_from(&mut self, id: ObjId, slot: usize) -> JsResult<(Vec, Vec)> { let mut seen = std::collections::HashSet::new(); let mut held = HeldBytes::new(self); let mut out = Vec::new(); + let mut from = Vec::new(); let mut cur = Some(id); while let Some(o) = cur { + self.temp_roots.push(Value::Object(o)); if self.is_proxy(o) { if let Some(root) = self.temp_roots.get_mut(slot) { *root = Value::Object(o); @@ -3317,6 +3327,7 @@ impl Interp { held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; seen.insert(k.clone()); out.push(k); + from.push(o); } cur = self.get_prototype_of(o)?; if let Some(root) = self.temp_roots.get_mut(slot) { @@ -3340,6 +3351,7 @@ impl Interp { held.add(self, string_bytes(k.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; seen.insert(k.clone()); out.push(k); + from.push(o); } } } @@ -3361,17 +3373,18 @@ impl Interp { for (k, p) in obj.props.iter() { if seen.insert(k.clone()) && p.enumerable() { out.push(k.clone()); + from.push(o); } } cur = obj.proto; } - Ok(out) + Ok((out, from)) } fn op_for_in_start(&mut self) -> JsResult<()> { let v = self.peek(0)?; - let (keys, object) = if v.is_nullish() { - (Vec::new(), None) + let ((keys, from), object) = if v.is_nullish() { + ((Vec::new(), Vec::new()), None) } else { let o = self.to_object(&v)?; // A wrapper made by ToObject is not on the stack; a collection while the names are @@ -3380,16 +3393,18 @@ impl Interp { self.temp_roots.push(Value::Object(o)); // Listing a namespace object's exports does not read them (ECMA-262 2015 section // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. - let keys = self.enumerable_keys(o).and_then(|keys| { + let keys = self.enumerable_keys(o).and_then(|(keys, from)| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); - Ok(keys) + Ok((keys, from)) }); + // Allocating the iterator does not collect, so the objects that listed the names stay + // alive until it holds them. self.temp_roots.truncate(saved); (keys?, Some(o)) }; - let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, pos: 0, object })), None)); + let iter = self.heap.alloc_object(Object::new(Class::ForIn(Box::new(ForIn { keys, from, pos: 0, object })), None)); self.replace(1, Value::Object(iter)) } @@ -3398,10 +3413,17 @@ impl Interp { loop { let Class::ForIn(state) = &mut self.object_mut(iter)?.class else { return internal("not a for-in iterator") }; let Some(k) = state.keys.get(state.pos).cloned() else { return self.jump_to(target) }; + let lister = state.from.get(state.pos).copied(); state.pos += 1; let object = state.object; let Some(o) = object else { continue }; - let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { self.scope_has(o, &k)? } else { self.for_in_still_has(o, &k)? }; + // The check starts at the object that listed the name, so a proxy that did not list + // it does not hide it. + let visit = if self.options.e4x && self.is_xml(&Value::Object(o)) { + self.scope_has(o, &k)? + } else { + self.for_in_still_has(lister.unwrap_or(o), &k)? + }; if visit { return self.push(Value::String(Str::from_rc(k))); } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index 7a53949a83..fa88173b16 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -30,7 +30,7 @@ impl Interp { matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_))) } - /// The target that a lookup of a Symbol key on the proxy `id` goes on to, since traps take + /// The target that an operation on a Symbol key of the proxy `id` goes on to, since traps take /// string property names only; `None` when `id` is not a proxy. A revoked proxy is a /// `TypeError`. pub(crate) fn symbol_lookup_target(&mut self, id: ObjId) -> JsResult> { diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index a3ed321311..01495b4fc5 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -119,23 +119,16 @@ fn late_proxy_and_reflect_installation_respects_global_extensibility() { [("", false, false), ("var Proxy = 7;", true, false), ("var Reflect = 8;", false, true), ("var Proxy = 7, Reflect = 8;", true, true)] { let mut realm = Realm::new(); - assert_eq!(realm.run(&format!("{setup} var runs = 0; Object.{operation}(this); 0")), Ok(JsValue::Number(0.0))); + assert_eq!(realm.run(&format!("{setup} Object.{operation}(this); 0")), Ok(JsValue::Number(0.0))); realm.set_es2015(true); - if has_proxy && has_reflect { - assert_eq!(realm.run("Proxy + Reflect"), Ok(JsValue::Number(15.0))); - } else { - for _ in 0..2 { - let err = realm.run("runs++").unwrap_err(); - assert_eq!(err.kind, RunErrorKind::Internal); - assert!(err.message.contains("Proxy and Reflect could not be installed"), "{err:?}"); - assert!(err.message.contains("the object is not extensible"), "{err:?}"); - let missing = if has_proxy { "Reflect" } else { "Proxy" }; - assert!(err.message.contains(missing), "{err:?}"); - } + // ES2015 runs go on without the names the sealed global lacks. + let names = format!("{} {}", if has_proxy { "number" } else { "undefined" }, if has_reflect { "number" } else { "undefined" }); + for _ in 0..2 { + assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String(names.clone().into())), "{operation}: {setup}"); } realm.set_es2015(false); let check = format!( - "runs === 0 && !Object.isExtensible(this) && this.hasOwnProperty('Proxy') === {has_proxy} + "!Object.isExtensible(this) && this.hasOwnProperty('Proxy') === {has_proxy} && this.hasOwnProperty('Reflect') === {has_reflect} && (typeof Proxy === 'undefined' || Proxy === 7) && (typeof Reflect === 'undefined' || Reflect === 8)" ); @@ -626,6 +619,43 @@ fn reflect_methods_answer_with_booleans_and_receivers() { ); } +#[test] +fn reflect_keeps_symbol_keys_as_symbols() { + truth( + "var s = Symbol('x'), o = { a: 1 }; o[s] = 7; + var read = Reflect.get(o, s) === 7 && Reflect.has(o, s) && !Reflect.has(o, Symbol('x')) + && Reflect.getOwnPropertyDescriptor(o, s).value === 7; + var written = Reflect.set(o, s, 8) && o[s] === 8; + var r = {}, base = {}; Object.defineProperty(base, s, { value: 1, writable: true }); + var received = Reflect.set(base, s, 2, r) && r[s] === 2 && base[s] === 1; + var fixed = {}; Object.defineProperty(fixed, s, { value: 1 }); + var refused = !Reflect.set(fixed, s, 2) && !Reflect.deleteProperty(fixed, s); + var t = Symbol('t'), defined = Reflect.defineProperty(o, t, { value: 3, configurable: true }) && o[t] === 3; + var deleted = Reflect.deleteProperty(o, t) && !(t in o) && o['Symbol(t)'] === undefined; + var keys = Reflect.ownKeys(o); + read && written && received && refused && defined && deleted && keys.length === 2 && keys[0] === 'a' && keys[1] === s", + ); + // A proxy's Symbol keys are its target's. + truth( + "var s = Symbol('x'), t = { a: 1 }; t[s] = 1; + var keys = Reflect.ownKeys(new Proxy(t, {})); + keys.length === 2 && keys[0] === 'a' && keys[1] === s", + ); +} + +#[test] +fn a_subclassable_built_in_runs_the_outer_get_trap_of_a_new_target_whose_inner_proxy_is_revoked() { + // The outer trap runs; its invariant check then reads the revoked target and throws + // (ECMA-262 2020 section 9.5.8, step 9). + truth( + "class DerivedArray extends Array {} + var P = {}, inner = Proxy.revocable(function () {}, {}), reads = 0; + var outer = new Proxy(inner.proxy, { get: function (t, k) { if (k === 'prototype') { reads++; return P; } } }); + inner.revoke(); + type_error(function () { Reflect.construct(DerivedArray, [], outer); }) && reads === 1", + ); +} + #[test] fn reflect_construct_gives_a_built_in_object_the_prototype_of_new_target() { truth( @@ -949,24 +979,45 @@ fn transparent_builtin_constructors_read_the_proxy_new_target_prototype() { } #[test] -fn proxy_integrity_operations_reject_symbol_properties() { +fn proxy_integrity_operations_include_the_targets_symbol_properties() { truth( "var s = Symbol('x'), t = {}; t[s] = 1; var p = new Proxy(new Proxy(t, {}), {}); - var freeze = type_error(function () { Object.freeze(p); }); - var seal = type_error(function () { Object.seal(p); }); - var extensible = Object.isExtensible(t); - Object.preventExtensions(t); - freeze && seal && extensible && type_error(function () { Object.isFrozen(p); }) && - type_error(function () { Object.isSealed(p); }) && Object.getOwnPropertyDescriptor(t, s).writable", + var before = !Object.isFrozen(p) && !Object.isSealed(p); + Object.freeze(p); + var d = Object.getOwnPropertyDescriptor(t, s); + before && Object.isFrozen(p) && Object.isSealed(p) && !d.writable && !d.configurable && t[s] === 1", ); truth( - "var p = new Proxy({}, {}); p[Symbol('x')] = 1; - type_error(function () { Object.freeze(p); }) && type_error(function () { Object.isFrozen(p); })", + "var s = Symbol('x'), t = {}; t[s] = 1; Object.preventExtensions(t); + var p = new Proxy(t, {}); + var open = !Object.isSealed(p); + Object.seal(p); + var d = Object.getOwnPropertyDescriptor(t, s); + open && Object.isSealed(p) && !Object.isFrozen(p) && d.writable && !d.configurable", ); truth( - "var p = new Proxy({}, { ownKeys: function () { p[Symbol('x')] = 1; return []; } }); - type_error(function () { Object.freeze(p); })", + "var s = Symbol('x'), p = new Proxy({}, { ownKeys: function () { return []; } }); + p[s] = 1; + Object.freeze(p); + Object.isFrozen(p) && !Object.getOwnPropertyDescriptor(p, s).writable", + ); +} + +#[test] +fn symbol_keys_pass_through_a_proxy_to_its_target() { + truth( + "var s = Symbol('x'), t = {}, p = new Proxy(t, {}); + Object.defineProperty(p, s, { value: 7, writable: true, configurable: true }); + var defined = t[s] === 7 && p[s] === 7 && Object.getOwnPropertySymbols(p)[0] === s; + p[s] = 8; + var written = t[s] === 8; + delete p[s]; + var self = null, u = {}; Object.defineProperty(u, s, { set: function () { self = this; } }); + var q = new Proxy(u, {}); q[s] = 1; + defined && written && !(s in t) && self === q && type_error(function () { + var pair = Proxy.revocable({}, {}); pair.revoke(); Object.defineProperty(pair.proxy, s, { value: 1 }); + })", ); } @@ -1244,7 +1295,7 @@ fn for_in_keeps_a_proxy_reachable_after_its_own_keys_trap_detaches_it() { })); var seen = []; for (var k in o) seen.push(k); - reads === 1 && seen.length === 0 && Object.getPrototypeOf(o) === null", + reads === 1 && seen.join() === 'first,second' && Object.getPrototypeOf(o) === null", ); } @@ -1295,6 +1346,18 @@ fn for_in_checks_proxy_descriptors_only_when_each_candidate_is_reached() { for (var k in p) { seen.push(k); calls.push('body'); } seen.join() === 'x' && calls.join() === 'x,body,y'", ); + // A name the proxy did not list is checked on the prototype that listed it, so the proxy's + // descriptor for it does not hide it. + truth( + "var asked = [], seen = []; + var p = new Proxy({}, { + ownKeys: function () { return []; }, + getPrototypeOf: function () { return { x: 1 }; }, + getOwnPropertyDescriptor: function (t, k) { asked.push(k); return { value: 0, enumerable: false, configurable: true }; } + }); + for (var k in p) seen.push(k); + seen.join() === 'x' && asked.length === 0", + ); } #[test] @@ -1475,6 +1538,19 @@ fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); } +#[test] +fn legacy_reflect_find_reads_a_proxy_receiver_without_its_traps() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var r = ({{ a: 1 }}).reflect, find = r.find, calls = 0; + var p = new Proxy(r, {{ getOwnPropertyDescriptor: function (t, k) {{ calls++; return Object.getOwnPropertyDescriptor(t, k); }} }}); + find.call(r, 'a') !== null && type_error(function () {{ find.call(p, 'a'); }}) && calls === 0" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + #[test] fn transparent_proxy_and_reflect_membership_use_host_indexers() { let index: HostFunction = Rc::new(|args| { @@ -1625,6 +1701,14 @@ fn json_proxy_replacer_lengths_use_to_length() { ); } +#[test] +fn json_replacer_lists_charge_only_the_names_they_keep() { + // A long, sparse replacer array keeps one name, so only that name counts against the heap. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let src = "var r = ['a']; r.length = 50000; JSON.stringify({ a: 1, b: 2 }, r) === '{\"a\":1}'"; + assert_eq!(Realm::with_options(es_options(), limits).run(src), Ok(JsValue::Bool(true))); +} + #[test] fn json_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { @@ -1650,13 +1734,19 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { ), LimitKind::Fuel ); + // A replacer list's length alone is not charged to the heap; the names it keeps are. let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run( + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : undefined; } }); + JSON.stringify({ a: 1 }, p) === '{}'" + ), + Ok(JsValue::Bool(true)) + ); assert_eq!( limit( - "var p = new Proxy([], { get: function (t, k) { - if (k === 'length') return 1000000; - throw new Error('element read'); - } }); JSON.stringify({}, p)", + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : 'name' + k; } }); + JSON.stringify({}, p)", limits, ), LimitKind::Heap diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index aeb4db0227..f71b1d3f42 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -254,7 +254,9 @@ impl Realm { /// `const` names earlier runs declared stay visible when it is turned off. A run begun with /// [`Realm::start`] that is still going keeps the language it started with for the code it /// evaluates; the new one applies once it ends. A realm made without the option gets `Proxy` - /// and `Reflect` at its first run with it, and keeps them when it is turned off. + /// and `Reflect` at its first run with it, and keeps them when it is turned off. A global of + /// either name that an earlier run defined keeps its value, and a global object that an + /// earlier run made non-extensible gets neither name. pub fn set_es2015(&mut self, es2015: bool) { if self.is_running() || self.interp.waiting { self.interp.next_es2015 = Some(es2015); diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 62c63c6bb0..2949ccba0c 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -328,15 +328,17 @@ fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult flat_charged(interp, &s)?, Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?, _ => continue, diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index e90652ec00..d4e451e766 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -315,8 +315,15 @@ impl Interp { self.reject(true, &name, why) } + /// The object that holds `id`'s Symbol-keyed properties: for a proxy, its innermost target, + /// since Symbol keys pass through proxies without traps; otherwise `id` itself. A revoked + /// proxy on the way is a `TypeError`. + pub(crate) fn sym_home(&mut self, id: ObjId) -> JsResult { + self.unwrapped_proxy_target(id) + } + pub(crate) fn get_own_sym(&mut self, id: ObjId, k: &Sym) -> JsResult> { - self.symbol_lookup_target(id)?; + let id = self.sym_home(id)?; Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned()) } @@ -326,13 +333,11 @@ impl Interp { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { + let o = self.sym_home(o)?; if let Some(p) = self.get_own_sym(o, k)? { return Ok(Some(p)); } - cur = match self.symbol_lookup_target(o)? { - Some(target) => Some(target), - None => self.object(o)?.proto, - }; + cur = self.object(o)?.proto; if cur.is_some() { self.use_fuel()?; } @@ -365,7 +370,7 @@ impl Interp { /// Adds or replaces an own property directly, keeping the heap estimate. pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> { - self.symbol_lookup_target(id)?; + let id = self.sym_home(id)?; let o = self.object_mut(id)?; if o.syms.get_or_insert_with(Box::default).insert(k, prop) { self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES); @@ -375,6 +380,7 @@ impl Interp { /// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key. pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult { + let id = self.sym_home(id)?; let Some(current) = self.get_own_sym(id, &k)? else { if !self.object(id)?.extensible { return self.reject_sym_bool(throw, &k, "the object is not extensible"); @@ -399,6 +405,9 @@ impl Interp { /// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key. pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> { + // A setter gets the object written to as `this`, a proxy included. + let receiver = Value::Object(id); + let id = self.sym_home(id)?; match self.get_own_sym(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -409,7 +418,7 @@ impl Interp { } return Ok(()); } - Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &receiver, &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), None => {} } @@ -417,6 +426,7 @@ impl Interp { let mut inherited = None; let mut steps = 0usize; while let Some(object) = cur { + let object = self.sym_home(object)?; if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) { return self.reject_sym(throw, &k, "a module namespace object is read-only"); } @@ -434,7 +444,7 @@ impl Interp { } } match inherited { - Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), + Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &receiver, &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject_sym(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject_sym(throw, &k, "it is read-only"), _ => {} @@ -471,6 +481,7 @@ impl Interp { /// [[Delete]] (section 9.1.10) for a Symbol key. pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult { + let id = self.sym_home(id)?; match self.get_own_sym(id, k)? { None => Ok(true), Some(p) if p.configurable() => { @@ -490,7 +501,7 @@ impl Interp { /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and /// the heap for the list is checked first. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { - self.symbol_lookup_target(id)?; + let id = self.sym_home(id)?; let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { diff --git a/docs/mcp.md b/docs/mcp.md index 63ec896128..c7f3ecc035 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2867,8 +2867,8 @@ or any operation on a revoked proxy, throws a `TypeError`. A proxy in a command's params throws a `TypeError` without running its traps. An engine that `#targetengine` keeps gets `Proxy` and `Reflect` at its first ECMAScript 2015 run and keeps them for later `.jsx` runs. A `.jsx` script or a `source` string run as a script has neither global in a fresh engine. -Existing globals with either name are preserved. If a missing global cannot be added because the global object -is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. +Existing globals with either name are preserved. When an earlier run made the global object nonextensible, sealed +or frozen, the engine does not add either global, and its ECMAScript 2015 runs go on without them. An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)` and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object. `Reflect.construct` also accepts a distinct constructor @@ -2891,7 +2891,8 @@ A conversion or syntax error throws before that prototype getter runs. membership checks use host collection indexers, including numeric indices and named items. `JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys -or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped. +or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped, +and each distinct name a replacer array keeps counts against it until the call returns. Its `toJSON` lookup skips host collection indexers through empty-handler proxies and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before @@ -2900,21 +2901,25 @@ the maximum safe integer. Reviver traversal keys count against the heap limit un In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating -its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations -and symbol enumeration on a revoked proxy also throw `TypeError`. -`Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order, -then other strings in insertion order; an array's `length` precedes its other non-index strings. -A proxy's `ownKeys` trap determines its key order. A `for-in` prototype walk keeps the current proxy reachable -through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain. -A `for-in` loop checks each proxy candidate's descriptor -when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate +its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without +calling proxy traps, so a proxy receiver throws `TypeError`. A Symbol property key on a proxy goes to its innermost +target without calling a trap: reads, writes, definitions, deletion and descriptor reads act on that target's +Symbol properties. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. +The `Reflect` functions take Symbol keys as well as strings. `Reflect.ownKeys` returns the string keys, then the +Symbol keys in the order they were added; a proxy's Symbol keys are its innermost target's. Ordinary targets list +array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other +non-index strings. A proxy's `ownKeys` trap determines the order of its string keys. A `for-in` prototype walk keeps +the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from +the receiver's prototype chain. A `for-in` loop checks each name's descriptor when iteration reaches that name, +starting at the object on the prototype chain that listed it, so a proxy that did not list a name does not hide an +inherited one. An `ownKeys` result is read and its elements are validated before duplicate names are rejected; a later getter's exception takes precedence over the duplicate-name error. Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay reachable during proxy callbacks, including callbacks that revoke a nested target proxy. `Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Object.isFrozen` -and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties. +and `Object.isSealed` on a proxy include its innermost target's Symbol properties. `Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace object before it finds the property. `Reflect.getOwnPropertyDescriptor` and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. Proxy invariant diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 241ea00306..b6fb4090aa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1189,7 +1189,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key on a proxy goes to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. From 7e3feff63111a8ed93e9293b5a8bd09d6a0c7fa5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 00:32:34 -0800 Subject: [PATCH 2/6] Tests: drop a String-to-String conversion in the sealed-global proxy test Clippy's useless_conversion lint stopped the gate at crates/js/src/proxy_tests.rs:127, where `names.clone().into()` converted a String to itself. The assertion compares the same value. --- crates/js/src/proxy_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 01495b4fc5..cac32535b4 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -124,7 +124,7 @@ fn late_proxy_and_reflect_installation_respects_global_extensibility() { // ES2015 runs go on without the names the sealed global lacks. let names = format!("{} {}", if has_proxy { "number" } else { "undefined" }, if has_reflect { "number" } else { "undefined" }); for _ in 0..2 { - assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String(names.clone().into())), "{operation}: {setup}"); + assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String(names.clone())), "{operation}: {setup}"); } realm.set_es2015(false); let check = format!( From 91f76bc40aae9e3899e3b923f1746fc45ca64c07 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:09:46 -0800 Subject: [PATCH 3/6] JavaScript: Symbol reads through a proxy call its get trap, and ownKeys traps may return Symbol keys A read of a Symbol key on a proxy, or on an object with a proxy on its prototype chain, now calls the proxy's get trap with the Symbol and the receiver (ECMA-262 9.5.8) and checks the result against the target's non-configurable Symbol properties. An ownKeys trap may now return Symbol keys (9.5.11). A Symbol given twice, a non-configurable Symbol key of the target left out, and for a non-extensible target any Symbol key left out or added throw a TypeError. The target's descriptors are read in its key order with one isExtensible call. Reflect.ownKeys, Object.getOwnPropertySymbols and the Object functions that list keys take a proxy's keys from one trap call and keep the order the trap gave, Symbols included. --- crates/js/src/builtins/object.rs | 17 +++- crates/js/src/builtins/reflect.rs | 39 +++++---- crates/js/src/builtins/symbol.rs | 13 ++- crates/js/src/proxy.rs | 140 +++++++++++++++++++++++------- crates/js/src/proxy_tests.rs | 104 +++++++++++++++++++++- crates/js/src/symbol.rs | 78 +++++++++++++++-- docs/mcp.md | 15 ++-- docs/target-app-parity.md | 2 +- 8 files changed, 336 insertions(+), 72 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 8237c11f34..f1e0dd3fae 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -146,12 +146,23 @@ pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator JsResult<(Vec, crate::interp::HeldBytes)> { + if interp.is_proxy(o) { + let list = interp.own_keys_and_symbols(o)?; + let count = list.names.len() + list.syms.len(); + let roots = list.sym_values(); + return interp.rooted(&roots, |interp| { + let (keys, mut held) = list.into_prop_keys(); + held.add(interp, count.saturating_mul(std::mem::size_of::()))?; + Ok((keys.collect(), held)) + }); + } let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + let syms = interp.own_symbols(o)?; let mut keys: Vec = names.into_iter().map(PropKey::Str).collect(); - keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); + keys.extend(syms.into_iter().map(PropKey::Sym)); Ok((keys, held)) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index a49833739c..c6f0381b7d 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -4,13 +4,13 @@ use std::rc::Rc; -use super::object::{from_prop, names_array, to_desc}; -use super::{arg, method, native}; +use super::object::{from_prop, to_desc}; +use super::{arg, create_at, method, native, new_array}; use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; use crate::symbol::{PropKey, Sym}; -use crate::value::Value; +use crate::value::{Str, Value}; /// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them /// after earlier runs, a global of the same name that a script defined stays as it is. Each @@ -229,22 +229,27 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.is_extensible(o).map(Value::Bool) } -/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not, -/// then the own Symbol keys in the order they were added. A proxy's Symbol keys are its -/// target's. +/// `Reflect.ownKeys(target)` (section 26.1.10): an ordinary object's own property names, +/// enumerable or not, then its Symbol keys in insertion order. A proxy's keys come from one call of +/// its `ownKeys` trap, in the order it gave them. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; - let names = interp.ecma_own_keys(o)?; - let count = names.len(); - let syms = interp.own_symbols(o)?; - let a = names_array(interp, names)?; - let Value::Object(id) = a else { return Ok(a) }; - interp.rooted(&[Value::Object(id)], |interp| { - for (i, s) in syms.into_iter().enumerate() { - interp.use_fuel()?; - super::create_at(interp, id, (count + i) as f64, Value::Symbol(s))?; - } - Ok(Value::Object(id)) + let list = interp.own_keys_and_symbols(o)?; + let roots = list.sym_values(); + interp.rooted(&roots, |interp| { + let (keys, _held) = list.into_prop_keys(); + let id = new_array(interp, 0)?; + interp.rooted(&[Value::Object(id)], |interp| { + for (i, k) in keys.enumerate() { + interp.use_fuel()?; + let v = match k { + PropKey::Str(k) => Value::String(Str::from_rc(k)), + PropKey::Sym(s) => Value::Symbol(s), + }; + create_at(interp, id, i as f64, v)?; + } + Ok(Value::Object(id)) + }) }) } diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index beec94c6a5..4503ffb5ca 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -169,9 +169,16 @@ fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let syms = interp.own_symbols(o)?; - let a = new_array(interp, 0)?; - interp.rooted(&[Value::Object(a)], |interp| { + let (syms, _held) = if interp.is_proxy(o) { + let list = interp.own_keys_and_symbols(o)?; + (list.syms, Some(list.names.held)) + } else { + (interp.own_symbols(o)?, None) + }; + let mut roots: Vec = syms.iter().cloned().map(Value::Symbol).collect(); + let a = interp.rooted(&roots, |interp| new_array(interp, 0))?; + roots.push(Value::Object(a)); + interp.rooted(&roots, |interp| { for (i, s) in syms.into_iter().enumerate() { interp.use_fuel()?; create_at(interp, a, i as f64, Value::Symbol(s))?; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index fa88173b16..1c9767c6c2 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -20,11 +20,15 @@ use crate::heap::{ CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, }; use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, HeldKeys, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; +use crate::symbol::{OwnKeyList, PropKey, Sym}; use crate::value::{Str, Value, index_key}; /// The most names an `ownKeys` trap may give. const MAX_OWN_KEYS: f64 = (1u64 << 24) as f64; +/// An `ownKeys` trap's names, its Symbol keys, and each Symbol's place in the whole list. +type TrapKeys = (Vec, Vec, Vec); + impl Interp { pub(crate) fn is_proxy(&self, id: ObjId) -> bool { matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_))) @@ -387,6 +391,24 @@ impl Interp { }) } + /// [[Get]] of a proxy (section 9.5.8) for the Symbol key `k`: the `get` trap with the Symbol + /// and `receiver`, or a read from the target when the handler has no `get` trap. + pub(crate) fn proxy_get_sym(&mut self, p: ObjId, k: &Sym, receiver: &Value) -> JsResult { + self.proxy_op(p, "read a property of", &[receiver.clone(), Value::Symbol(k.clone())], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_sym_from(target, k, receiver) }; + let v = i.call_trap(&trap, handler, &[Value::Object(target), Value::Symbol(k.clone()), receiver.clone()])?; + match i.get_own_sym(target, k)? { + Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { + Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) + } + Some(Prop::Accessor { get: None, flags, .. }) if flags & CONFIGURABLE == 0 && !matches!(v, Value::Undefined) => { + Err(i.invariant("get", "gave a value for a non-configurable property of its target that has no getter")) + } + _ => Ok(v), + } + }) + } + /// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property. pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &Key) -> JsResult { self.proxy_op(p, "delete a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { @@ -406,24 +428,44 @@ impl Interp { }) } - /// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object - /// of distinct strings, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable - /// name of the target, and of a non-extensible target exactly its names. Each name takes a - /// unit of fuel and counts against the heap limit until the caller drops the list. + /// The string names of a proxy's [[OwnPropertyKeys]] (section 9.5.11); see + /// [`Interp::proxy_own_keys_and_symbols`]. pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { + self.proxy_own_keys_and_symbols(p).map(|list| list.names) + } + + /// [[OwnPropertyKeys]] of a proxy (section 9.5.11): its string names and its Symbol keys, each + /// in the order the trap gave them. The trap must give an array-like object of distinct + /// strings and Symbols, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable + /// key of the target, and of a non-extensible target exactly its keys. Each key takes a unit + /// of fuel and counts against the heap limit until the caller drops the list. + pub(crate) fn proxy_own_keys_and_symbols(&mut self, p: ObjId) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.ecma_own_keys(target) }; + let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.own_keys_and_symbols(target) }; let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; - let mut held = HeldBytes::new(i); - let keys = i.trap_key_list(&result, &mut held)?; - i.check_own_keys(target, &keys)?; - Ok(HeldKeys { keys, held }) + let mark = i.temp_roots.len(); + let r = i.checked_trap_keys(target, &result); + i.temp_roots.truncate(mark); + r }) } + /// Steps 7 to 23 of section 9.5.11 for the `ownKeys` trap's `result`. Each Symbol it gives is + /// kept in the temporary roots, which the caller truncates. + fn checked_trap_keys(&mut self, target: ObjId, result: &Value) -> JsResult { + let mut held = HeldBytes::new(self); + let (keys, syms, slots) = self.trap_key_list(result, &mut held)?; + let extensible = self.is_extensible(target)?; + let target_list = self.own_keys_and_symbols(target)?; + self.temp_roots.extend(target_list.sym_values()); + self.check_own_keys(target, extensible, target_list, &keys, &syms)?; + Ok(OwnKeyList { names: HeldKeys { keys, held }, syms, slots }) + } + /// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result, refusing a value - /// that is not a string and a name given twice. - fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult> { + /// that is neither a string nor a Symbol and a key given twice. The string names and the + /// Symbol keys come back as separate lists, with each Symbol's place in the whole list. + fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult { let Value::Object(list) = result else { return Err(self.invariant("ownKeys", "returned a value that is not an object")) }; let length = self.get_from(*list, &key("length"), result)?; let n = self.to_number(&length)?; @@ -434,11 +476,28 @@ impl Interp { } let mut keys = Vec::new(); let mut seen: HashSet = HashSet::new(); + let mut syms = Vec::new(); + let mut slots = Vec::new(); + let mut seen_syms: HashSet = HashSet::new(); let mut duplicate = None; + let mut duplicate_sym = false; for index in 0..n as u32 { self.use_fuel()?; let v = self.get_from(*list, &index_key(index), result)?; - let Value::String(s) = v else { return Err(self.invariant("ownKeys", "returned a name that is not a string")) }; + let s = match v { + Value::String(s) => s, + Value::Symbol(sym) => { + self.temp_roots.push(Value::Symbol(sym.clone())); + held.add(self, 2 * KEY_ENTRY_BYTES)?; + if !seen_syms.insert(sym.addr()) { + duplicate_sym = true; + } + syms.push(sym); + slots.push(index as usize); + continue; + } + _ => return Err(self.invariant("ownKeys", "returned a key that is not a string or a Symbol")), + }; held.add(self, string_bytes(s.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; let k = s.flat(); if !seen.insert(k.clone()) && duplicate.is_none() { @@ -450,45 +509,60 @@ impl Interp { let name = String::from_utf16_lossy(&k); return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice"))); } - Ok(keys) + if duplicate_sym { + return Err(self.invariant("ownKeys", "returned a Symbol key twice")); + } + Ok((keys, syms, slots)) } - /// Steps 16 to 23 of section 9.5.11: the names `keys` the trap gave against the target's. - fn check_own_keys(&mut self, target: ObjId, keys: &[Key]) -> JsResult<()> { - let extensible = self.is_extensible(target)?; - let target_keys = self.own_keys(target)?; + /// Steps 16 to 23 of section 9.5.11: reads target descriptors in key order, then checks + /// the trap's string and Symbol keys against the non-configurable and configurable keys. + fn check_own_keys(&mut self, target: ObjId, extensible: bool, target_keys: OwnKeyList, keys: &[Key], syms: &[Sym]) -> JsResult<()> { + let count = target_keys.names.len() + target_keys.syms.len(); + let (target_keys, mut held) = target_keys.into_prop_keys(); + held.add(self, count.saturating_mul(std::mem::size_of::()))?; let mut fixed = Vec::new(); let mut configurable = Vec::new(); - for k in target_keys.iter() { + for k in target_keys { self.use_fuel()?; - if self.own_property(target, k)?.is_some_and(|p| !p.configurable()) { - fixed.push(k.clone()); + if self.own_pk(target, &k)?.is_some_and(|p| !p.configurable()) { + fixed.push(k); } else { - configurable.push(k.clone()); + configurable.push(k); } } if extensible && fixed.is_empty() { return Ok(()); } let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect(); - for k in &fixed { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target"))); + let mut unchecked_syms: HashSet = syms.iter().map(Sym::addr).collect(); + for (list, non_configurable) in [(&fixed, true), (&configurable, false)] { + if !non_configurable && extensible { + return Ok(()); } - } - if extensible { - return Ok(()); - } - for k in &configurable { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target"))); + for k in list { + match k { + PropKey::Str(k) if !unchecked.remove(&**k) => { + let name = String::from_utf16_lossy(k); + let what = if non_configurable { "non-configurable property" } else { "property" }; + let target = if non_configurable { "target" } else { "non-extensible target" }; + return Err(self.invariant("ownKeys", &format!("left out the {what} '{name}' of its {target}"))); + } + PropKey::Sym(k) if !unchecked_syms.remove(&k.addr()) => { + let name = self.sym_name(k)?; + let what = if non_configurable { "non-configurable property" } else { "property" }; + return Err(self.invariant("ownKeys", &format!("left out the {what} {name} of its target"))); + } + _ => {} + } } } if !unchecked.is_empty() { return Err(self.invariant("ownKeys", "gave a name its non-extensible target does not have")); } + if !unchecked_syms.is_empty() { + return Err(self.invariant("ownKeys", "gave a Symbol key its non-extensible target does not have")); + } Ok(()) } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index cac32535b4..22d56a6557 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -999,8 +999,7 @@ fn proxy_integrity_operations_include_the_targets_symbol_properties() { truth( "var s = Symbol('x'), p = new Proxy({}, { ownKeys: function () { return []; } }); p[s] = 1; - Object.freeze(p); - Object.isFrozen(p) && !Object.getOwnPropertyDescriptor(p, s).writable", + type_error(function () { Object.freeze(p); })", ); } @@ -1767,6 +1766,107 @@ fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { ); } +#[test] +fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() { + truth( + "var s = Symbol('s'), hidden = Symbol('h'), t = {}; t[hidden] = 1; + var calls = 0; + var open = new Proxy(t, { ownKeys: function () { calls++; return ['a', s]; } }); + var listed = Reflect.ownKeys(open); + var syms = Object.getOwnPropertySymbols(open); + listed.length === 2 && listed[0] === 'a' && listed[1] === s && syms.length === 1 && syms[0] === s && calls === 2", + ); + truth( + "var s = Symbol('s'); + var mixed = Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, 'a', 'b']; } })); + mixed.length === 3 && mixed[0] === s && mixed[1] === 'a' && mixed[2] === 'b'", + ); + type_errors(&[ + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return []; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, s]; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy(Object.preventExtensions({}), { ownKeys: function () { return [s]; } }))", + "Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [1]; } }))", + ]); + truth( + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return [s]; } })).length === 1", + ); +} + +#[test] +fn own_keys_checks_target_descriptors_in_combined_key_order() { + truth( + "var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 }; + t[s] = 3; t[u] = 4; + var reads = '', extensible = 0; + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a', u, 'b']; }, + isExtensible: function () { extensible++; return true; }, + getOwnPropertyDescriptor: function (t, k) { + reads += k; + Object.defineProperty(t, k === 'a' ? s : u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + var keys = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a']; } })); + keys.length === 2 && keys[0] === 'b' && keys[1] === 'a' && reads === 'ab' && extensible === 1", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + +#[test] +fn own_keys_consumers_keep_interleaved_trap_keys() { + truth( + "var s = Symbol('s'), u = Symbol('u'); + var p = new Proxy({}, { ownKeys: function () { return ['a', s, 'b', u, 'c']; } }); + var keys = Reflect.ownKeys(p); + keys.length === 5 && keys[0] === 'a' && keys[1] === s && keys[2] === 'b' && keys[3] === u && keys[4] === 'c'", + ); + truth( + "var s = Symbol('s'), t = { a: { value: 1 }, b: { value: 3 } }; + t[s] = { value: 2 }; + var order = []; + var props = new Proxy(t, { + ownKeys: function () { return ['a', s, 'b']; }, + get: function (t, k) { order.push(k); return t[k]; } + }); + var o = Object.defineProperties({}, props); + order.length === 3 && order[0] === 'a' && order[1] === s && order[2] === 'b' && o.a === 1 && o[s] === 2 && o.b === 3", + ); +} + +#[test] +fn symbol_reads_through_a_proxy_call_its_get_trap() { + truth( + "var s = Symbol('s'); var seen; + var p = new Proxy({}, { get: function (t, k, r) { seen = [k, r]; return 5; } }); + var child = Object.create(p); + p[s] === 5 && seen[0] === s && seen[1] === p && child[s] === 5 && seen[1] === child", + ); + truth( + "var s = Symbol('s'); var t = {}; t[s] = 3; + new Proxy(t, {})[s] === 3 && Object.create(new Proxy(t, {}))[s] === 3", + ); + type_errors(&["var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + new Proxy(t, { get: function () { return 2; } })[s]"]); + truth( + "var p = new Proxy({}, { get: function (t, k) { if (k === Symbol.toPrimitive) return function () { return 9; }; } }); + +p === 9", + ); +} + #[test] fn json_transparent_host_proxies_skip_indexers_but_call_get_traps() { let calls = Rc::new(RefCell::new(0)); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index d4e451e766..91a7119038 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -148,6 +148,35 @@ pub(crate) enum PropKey { Sym(Sym), } +/// An object's own property keys from one [[OwnPropertyKeys]] call (section 9.1.11), its names +/// and its Symbol keys apart. `slots[i]` is the place of `syms[i]` in the whole list, so a +/// proxy's keys keep the order its `ownKeys` trap gave them in. +pub(crate) struct OwnKeyList { + pub(crate) names: crate::interp::HeldKeys, + pub(crate) syms: Vec, + pub(crate) slots: Vec, +} + +impl OwnKeyList { + /// The Symbol keys as values, to keep them reachable while the caller allocates. + pub(crate) fn sym_values(&self) -> Vec { + self.syms.iter().cloned().map(Value::Symbol).collect() + } + + /// Iterates over the whole list in order, with its heap charge held separately. + pub(crate) fn into_prop_keys(self) -> (impl Iterator, crate::interp::HeldBytes) { + let crate::interp::HeldKeys { keys: names, held } = self.names; + let total = names.len() + self.syms.len(); + let mut names = names.into_iter(); + let mut syms = self.syms.into_iter().zip(self.slots).peekable(); + let keys = (0..total).filter_map(move |at| match syms.next_if(|(_, slot)| *slot == at) { + Some((s, _)) => Some(PropKey::Sym(s)), + None => names.next().map(PropKey::Str), + }); + (keys, held) + } +} + /// The well-known Symbols a realm has (section 6.1.5.1): `Symbol.iterator` and the others the /// language reads, with `Symbol.asyncIterator`, which nothing reads yet. pub(crate) struct WellKnown { @@ -349,13 +378,32 @@ impl Interp { Ok(None) } - /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. + /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. A proxy on the + /// prototype chain handles the read with its `get` trap (section 9.5.8). Each step to a + /// prototype takes a unit of fuel. pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult { - match self.find_sym(start, k)? { - None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), - Some(Prop::Data { value, .. }) => Ok(value), - Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + let mut cur = Some(start); + let mut steps = 0usize; + while let Some(o) = cur { + if self.is_proxy(o) { + return self.proxy_get_sym(o, k, receiver); + } + match self.get_own_sym(o, k)? { + None => {} + Some(Prop::Accessor { get: None, .. }) => return Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => return Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => return self.call(&Value::Object(g), receiver, &[]), + } + cur = self.object(o)?.proto; + if cur.is_some() { + self.use_fuel()?; + } + steps += 1; + if steps > 1_000_000 { + return Err(crate::interp::Abrupt::Internal("prototype chain too long".into())); + } } + Ok(Value::Undefined) } /// `base[k]` for any value. @@ -498,10 +546,24 @@ impl Interp { } } - /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and - /// the heap for the list is checked first. + /// An object's own property names in the order of section 9.1.11 and its own Symbol keys, + /// listed with one [[OwnPropertyKeys]] call; for a proxy, one call of its `ownKeys` trap. + pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + if self.is_proxy(id) { + return self.proxy_own_keys_and_symbols(id); + } + let names = self.ecma_own_keys(id)?; + let syms = self.own_symbols(id)?; + let slots = (names.len()..names.len() + syms.len()).collect(); + Ok(OwnKeyList { names, syms, slots }) + } + + /// An object's own Symbol keys in the order they were added; a proxy's come from its + /// `ownKeys` trap. Each takes a unit of fuel, and the heap for the list is checked first. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { - let id = self.sym_home(id)?; + if self.is_proxy(id) { + return self.proxy_own_keys_and_symbols(id).map(|list| list.syms); + } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { diff --git a/docs/mcp.md b/docs/mcp.md index 9b02f91101..e79cc1b818 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2908,11 +2908,16 @@ In E4X mode, a bare call resolves each scope once. An object binding still check when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without -calling proxy traps, so a proxy receiver throws `TypeError`. A Symbol property key on a proxy goes to its innermost -target without calling a trap: reads, writes, definitions, deletion and descriptor reads act on that target's -Symbol properties. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. -The `Reflect` functions take Symbol keys as well as strings. `Reflect.ownKeys` returns the string keys, then the -Symbol keys in the order they were added; a proxy's Symbol keys are its innermost target's. Ordinary targets list +calling proxy traps, so a proxy receiver throws `TypeError`. A read of a Symbol property key through a proxy, on +the proxy itself or on an object that has it as a prototype, calls the proxy's `get` trap with the Symbol and the +receiver, and reads from the target when the handler has no `get` trap. Other operations with a Symbol key on a proxy +go to its innermost target without calling a trap: writes, definitions, deletion and descriptor reads act on that +target's Symbol properties. An `ownKeys` trap may return Symbol keys as well as strings; a Symbol key given twice, a +non-configurable Symbol key of the target left out, and for a non-extensible target any of its Symbol keys left out +or one it lacks throw `TypeError`. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. +The `Reflect` functions take Symbol keys as well as strings. For ordinary objects, `Reflect.ownKeys` returns the string keys, +then the Symbol keys in the order they were added. A proxy's keys come from one call of its `ownKeys` trap and keep +the trap's order, including Symbol keys. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines the order of its string keys. A `for-in` prototype walk keeps the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index da3ad29e7d..0f98b4fdb1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1195,7 +1195,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key on a proxy goes to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key read through a proxy calls its `get` trap, an `ownKeys` trap may return Symbol keys, and other Symbol-key operations on a proxy go to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string or a Symbol), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. From 080f3c4a84d8be0c01ee8a86e16b55089601dbfd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:01:07 -0800 Subject: [PATCH 4/6] JavaScript: legacy reflect find skips proxy traps; replacer lists charge kept names - `reflect.find` reads the reflection object and its lists with ordinary [[GetOwnProperty]], so a proxy receiver throws a TypeError without its getOwnPropertyDescriptor trap running. - `JSON.stringify` charges each distinct name a replacer array keeps for the length of the call, instead of reserving bytes for the whole length, so a long sparse replacer list no longer hits the heap limit. - A test checks that an outer proxy reads an inner proxy target's descriptors in its trap's combined order of names and Symbols. --- crates/js/src/builtins/json.rs | 15 +++++--- crates/js/src/proxy_tests.rs | 70 ++++++++++++++++++++++++++++++++-- crates/js/src/reflect.rs | 8 ++-- docs/mcp.md | 6 ++- 4 files changed, 85 insertions(+), 14 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index a6d8babc9e..e5027df1c6 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult { struct Settings { replacer: Option, properties: Option>, + _held_properties: Option, gap: Vec, } @@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { /// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8). fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult { - let mut s = Settings { replacer: None, properties: None, gap: Vec::new() }; + let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() }; if let Value::Object(r) = replacer { if interp.is_callable(replacer) { s.replacer = Some(replacer.clone()); } else if interp.is_array(replacer)? { - s.properties = Some(property_list(interp, *r)?); + let (keys, held) = property_list(interp, *r)?; + s.properties = Some(keys); + s._held_properties = Some(held); } } let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone()); @@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { +/// Each name kept is charged to the heap for as long as the returned holder lives. +fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { let len = super::collections::length_of(interp, r)?; if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { @@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult> { } // The list lives until the call returns, so its names are rooted. interp.temp_roots.push(Value::String(s)); + held.add(interp, ELEMENT_BYTES)?; list.push(k); } } - Ok(list) + Ok((list, held)) } /// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 20338eeca2..a3655d2b17 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -1757,6 +1757,19 @@ fn legacy_reflection_rejects_proxy_receivers_without_enumerating_them() { assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); } +#[test] +fn legacy_reflect_find_reads_a_proxy_receiver_without_its_traps() { + let mut realm = es(); + realm.add_script_extensions().unwrap(); + let src = format!( + "{PRELUDE} + var r = ({{ a: 1 }}).reflect, find = r.find, calls = 0; + var p = new Proxy(r, {{ getOwnPropertyDescriptor: function (t, k) {{ calls++; return Object.getOwnPropertyDescriptor(t, k); }} }}); + find.call(r, 'a') !== null && type_error(function () {{ find.call(p, 'a'); }}) && calls === 0" + ); + assert_eq!(realm.run(&src), Ok(JsValue::Bool(true))); +} + #[test] fn transparent_proxy_and_reflect_membership_use_host_indexers() { let index: HostFunction = Rc::new(|args| { @@ -2036,6 +2049,14 @@ fn json_proxy_replacer_lengths_use_to_length() { ); } +#[test] +fn json_replacer_lists_charge_only_the_names_they_keep() { + // A long, sparse replacer array keeps one name, so only that name counts against the heap. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let src = "var r = ['a']; r.length = 50000; JSON.stringify({ a: 1, b: 2 }, r) === '{\"a\":1}'"; + assert_eq!(Realm::with_options(es_options(), limits).run(src), Ok(JsValue::Bool(true))); +} + #[test] fn json_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { @@ -2061,13 +2082,19 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { ), LimitKind::Fuel ); + // A replacer list's length alone is not charged to the heap; the names it keeps are. let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run( + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : undefined; } }); + JSON.stringify({ a: 1 }, p) === '{}'" + ), + Ok(JsValue::Bool(true)) + ); assert_eq!( limit( - "var p = new Proxy([], { get: function (t, k) { - if (k === 'length') return 1000000; - throw new Error('element read'); - } }); JSON.stringify({}, p)", + "var p = new Proxy([], { get: function (t, k) { return k === 'length' ? 200000 : 'name' + k; } }); + JSON.stringify({}, p)", limits, ), LimitKind::Heap @@ -2116,6 +2143,41 @@ fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() { ); } +#[test] +fn own_keys_checks_target_descriptors_in_combined_key_order() { + truth( + "var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 }; + t[s] = 3; t[u] = 4; + var reads = [], extensible = 0; + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a', u, 'b']; }, + isExtensible: function () { extensible++; return true; }, + getOwnPropertyDescriptor: function (t, k) { + reads.push(String(k)); + if (k === s) Object.defineProperty(t, u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + // The descriptor of `s`, read first, makes `u` non-configurable before `u` is read, so the + // outer trap that leaves `u` out breaks the invariant. + var threw = type_error(function () { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a', s]; } })); }); + var ok = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', u, 'a']; } })); + threw && reads.slice(0, 4).join() === 'Symbol(s),a,Symbol(u),b' && extensible === 2 && ok.length === 3", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + #[test] fn own_keys_consumers_keep_interleaved_trap_keys() { truth( diff --git a/crates/js/src/reflect.rs b/crates/js/src/reflect.rs index 62c63c6bb0..2949ccba0c 100644 --- a/crates/js/src/reflect.rs +++ b/crates/js/src/reflect.rs @@ -328,15 +328,17 @@ fn find(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult flat_charged(interp, &s)?, Some(Prop::Data { value: Value::Number(n), .. }) => flat_charged(interp, &number_to_str(n))?, _ => continue, diff --git a/docs/mcp.md b/docs/mcp.md index 27ec011196..4e380d9057 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2902,7 +2902,8 @@ A conversion or syntax error throws before that prototype getter runs. membership checks use host collection indexers, including numeric indices and named items. `JSON.stringify` uses `ToLength` for proxy array lengths and proxy replacer-array lengths, so negative lengths become zero and fractional lengths are truncated. It checks run limits before allocating array traversal keys -or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped. +or iterating either list. Array traversal keys count against the heap limit until their writing frame is dropped, +and each distinct name a replacer array keeps counts against it until the call returns. Its `toJSON` lookup skips host collection indexers through empty-handler proxies and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before @@ -2911,7 +2912,8 @@ the maximum safe integer. Reviver traversal keys count against the heap limit un In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating -its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations +its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without +calling proxy traps, so a proxy receiver throws `TypeError`. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`, `defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation From 337b47a309ad1e405659ac56cf893cd7c668d123 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 06:23:12 -0800 Subject: [PATCH 5/6] JavaScript: with scopes honor Symbol.unscopables; concat reads isConcatSpreadable - A `with` scope reads `Symbol.unscopables` after it finds a name, through a proxy's `get` trap, and skips the binding when that object's property for the name is truthy. - `concat` reads `Symbol.isConcatSpreadable`, through proxy traps; a defined value decides whether the object is spread. - `Object.keys` and `Object.getOwnPropertyNames` keep the target's order through empty-handler proxies. - `%TypedArray%.from` and `of` construct through a proxy constructor and check that the result is a typed array long enough. --- crates/js/src/builtins/array.rs | 8 +- crates/js/src/builtins/binary.rs | 28 ++++- crates/js/src/builtins/symbol.rs | 4 +- crates/js/src/interp.rs | 35 ++++-- crates/js/src/proxy.rs | 6 +- crates/js/src/proxy_tests.rs | 191 ++++++++++++++++++++++++++++--- crates/js/src/symbol.rs | 16 ++- docs/mcp.md | 8 ++ 8 files changed, 257 insertions(+), 39 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index ac8dd4639c..48dfe1832a 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -389,8 +389,12 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult let mut n = 0u64; for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) { interp.use_fuel()?; - // A proxy whose target is an array is spread too (ECMA-262 2020 section 22.1.3.1.1). - let spread = if interp.is_array(&e)? { e.as_object() } else { None }; + let override_spread = match (e.as_object(), interp.well_known(|w| &w.is_concat_spreadable)) { + (Some(_), Some(sym)) => interp.get_value_sym(&e, &sym)?, + _ => Value::Undefined, + }; + let spread = if matches!(override_spread, Value::Undefined) { interp.is_array(&e)? } else { override_spread.truthy() }; + let spread = if spread { e.as_object() } else { None }; let Some(e) = spread else { if n >= 9_007_199_254_740_991 { return Err(interp.type_error("concat exceeds the maximum safe length")); diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 5a48799007..16c6a6a160 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -824,6 +824,23 @@ fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) } +fn typed_create(interp: &mut Interp, this: &Value, len: u64, name: &str) -> JsResult { + if !this.as_object().is_some_and(|o| interp.is_proxy(o)) { + let elem = ctor_elem(interp, this, name)?; + return new_typed(interp, elem, len); + } + #[allow(clippy::cast_precision_loss)] + let result = interp.construct_value(this, &[Value::Number(len as f64)], this)?; + interp.rooted(std::slice::from_ref(&result), |interp| { + let Some(o) = result.as_object() else { return Err(interp.type_error("the constructor did not return a typed array")) }; + let Some(view) = view_of(interp, o) else { return Err(interp.type_error("the constructor did not return a typed array")) }; + if (view.length as u64) < len { + return Err(interp.type_error(&format!("TypedArray.{name} constructor returned a typed array that is too short"))); + } + Ok(o) + }) +} + /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { if !interp.is_constructor(&this) { @@ -836,16 +853,15 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe } let this_arg = arg(args, 2); let map = mapping.then_some((&map_fn, &this_arg)); - typed_array_from(interp, &arg(args, 0), map, |interp, len| { - let elem = ctor_elem(interp, &this, "from")?; - new_typed(interp, elem, len) - }) + typed_array_from(interp, &arg(args, 0), map, |interp, len| typed_create(interp, &this, len, "from")) } /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let elem = ctor_elem(interp, &this, "of")?; - let ta = new_typed(interp, elem, args.len() as u64)?; + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); + } + let ta = typed_create(interp, &this, args.len() as u64, "of")?; let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index 0bbccebb1c..e020e6335b 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -18,6 +18,8 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { ("hasInstance", well_known.has_instance.clone()), ("toPrimitive", well_known.to_primitive.clone()), ("toStringTag", well_known.to_string_tag.clone()), + ("unscopables", well_known.unscopables.clone()), + ("isConcatSpreadable", well_known.is_concat_spreadable.clone()), ]; let (to_string_tag, to_primitive, has_instance) = (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); @@ -171,7 +173,7 @@ fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bo interp.rooted(&[Value::Object(o)], |interp| { // A proxy's list stays counted against the heap until the array holds its Symbols. let (syms, _held) = if interp.is_proxy(o) { - let keys = interp.proxy_own_keys(o)?; + let keys = interp.proxy_own_keys(o, false)?; (keys.syms, keys.held) } else { let syms = interp.own_symbols(o)?; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 5f1f170b8b..2aa5c933c9 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1619,7 +1619,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return Ok(Resolved::Obj { object, with_this }); } cur = outer; @@ -1630,6 +1630,20 @@ impl Interp { Ok(Resolved::Unresolved) } + fn scope_binding(&mut self, object: ObjId, name: &Key, with_this: bool) -> JsResult { + if !self.scope_has(object, name)? { + return Ok(false); + } + if with_this && let Some(sym) = self.well_known(|w| &w.unscopables) { + let blocked = self.get_value_sym(&Value::Object(object), &sym)?; + if let Value::Object(o) = blocked { + let value = self.rooted(&[Value::Object(o)], |i| i.get_from(o, name, &Value::Object(o)))?; + return Ok(!value.truthy()); + } + } + Ok(true) + } + pub(crate) fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult { match self.heap.env(env) { Some(Env::Decl { bindings, .. }) => Ok(bindings.get(name).map_or(Value::Undefined, |b| b.value.clone())), @@ -1673,7 +1687,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return self.get_resolved(Resolved::Obj { object, with_this }, name); } let this = Value::Object(object); @@ -2389,7 +2403,7 @@ impl Interp { /// list is checked first. A proxy's names come from its `ownKeys` trap. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, false); } let o = self.object(id)?; // A typed array's indices come first, as a String object's do (section 9.4.5.6). @@ -2422,14 +2436,15 @@ impl Interp { } pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult { - let mut keys = self.own_keys(id)?; - if !self.is_proxy(id) { - if matches!(self.object(id)?.class, Class::Array { .. }) { - let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; - keys.insert(0, length); - } - keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); + if self.is_proxy(id) { + return self.proxy_own_keys(id, true); } + let mut keys = self.own_keys(id)?; + if matches!(self.object(id)?.class, Class::Array { .. }) { + let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; + keys.insert(0, length); + } + keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); Ok(keys) } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index fcb103b50c..e709cfd808 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -421,11 +421,11 @@ impl Interp { /// non-configurable key of the target, and of a non-extensible target exactly its keys. Each /// key takes a unit of fuel and counts against the heap limit until the caller drops the list, /// which keeps the trap's order in [`HeldKeys::ordered`]. - pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { + pub(crate) fn proxy_own_keys(&mut self, p: ObjId, ecma_order: bool) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { // A target that is a proxy gives its Symbols with its names. - let mut keys = i.ecma_own_keys(target)?; + let mut keys = if ecma_order { i.ecma_own_keys(target)? } else { i.own_keys(target)? }; if !i.is_proxy(target) { keys.syms = i.own_symbols(target)?; keys.held.add(i, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; @@ -444,7 +444,7 @@ impl Interp { /// one `ownKeys` trap call for a proxy. pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, false); } let mut keys = self.own_keys(id)?; keys.syms = self.own_symbols(id)?; diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index a3655d2b17..efb6bb78e8 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -744,6 +744,152 @@ fn a_descriptor_a_trap_makes_stays_reachable_while_it_is_read() { // ---- proxies elsewhere in the language ---- +#[test] +fn proxy_with_bindings_honor_unscopables() { + truth_collecting( + "var x = 'outer', result, log = [], scope, blocked; + var p = new Proxy({ x: 'inner' }, { + has: function (t, k) { if (k === 'x') log.push('has'); return Reflect.has(t, k); }, + get: function (t, k, r) { + if (k === Symbol.unscopables) { + scope = r; + return new Proxy({ x: true }, { get: function (t, k, r) { + log.push(k); blocked = r; return t[k]; + } }); + } + throw 'unexpected binding read'; + } + }); + with (p) { result = x; } + result === 'outer' && scope === p && typeof blocked === 'object' && log.join() === 'has,x'", + ); + for blocked in ["undefined", "null", "false", "1", "{}", "{ x: false }"] { + truth(&format!( + "var x = 'outer', result, t = {{ x: 'inner' }}; + t[Symbol.unscopables] = {blocked}; + with (new Proxy(t, {{}})) {{ result = x; }} + result === 'inner'" + )); + } + truth( + "var x = 'outer', kind, result, t = { x: 'inner' }; + t[Symbol.unscopables] = { x: true }; + with (new Proxy(t, {})) { x = 'changed'; kind = typeof x; result = delete x; } + x === 'changed' && t.x === 'inner' && kind === 'string' && result === false", + ); + for trap in ["return new Proxy({}, { get: function () { throw marker; } });", "throw marker;"] { + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy({{ x: 1 }}, {{ get: function (t, k) {{ + if (k === Symbol.unscopables) {{ {trap} }} return t[k]; + }} }}); + try {{ with (p) {{ x; }} }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); + assert_eq!( + realm.run( + "function method() { return 'outer'; } + var t = { method: function () { return 'inner'; } }, result; + t[Symbol.unscopables] = { method: true }; + with (new Proxy(t, {})) { result = method(); } + result === 'outer'" + ), + Ok(JsValue::Bool(true)) + ); +} + +#[test] +fn transparent_proxies_preserve_object_key_order() { + truth_collecting( + "var o = { z: 0, 10: 10, 2: 2, a: 1 }, a = [1, 2]; a.label = 'a'; + [o, a].every(function (target) { + var p = new Proxy(new Proxy(target, {}), {}); + return Object.keys(p).join() === Object.keys(target).join() && + Object.getOwnPropertyNames(p).join() === Object.getOwnPropertyNames(target).join() && + Reflect.ownKeys(p).join() === Reflect.ownKeys(target).join(); + })", + ); + truth( + "var calls = 0, p = new Proxy({ a: 1, b: 2 }, { ownKeys: function () { calls++; return ['b', 'a']; } }); + var q = new Proxy(p, {}); + Object.keys(q).join() === 'b,a' && Object.getOwnPropertyNames(q).join() === 'b,a' && + Reflect.ownKeys(q).join() === 'b,a' && calls === 3", + ); +} + +#[test] +fn concat_honors_proxy_spreadability_overrides() { + truth_collecting( + "var reads = 0, receiver, p = new Proxy([1, 2], { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads++; receiver = r; return false; } + return Reflect.get(t, k, r); + } }); + var a = [].concat(p), b = p.concat(3); + a.length === 1 && a[0] === p && b.length === 2 && b[0] === p && b[1] === 3 && reads === 2 && receiver === p", + ); + truth_collecting( + "var reads = [], receiver; + var p = new Proxy({ 0: 'a', 2: 'c', length: 3 }, { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads.push('spread'); receiver = r; return true; } + reads.push(k); return Reflect.get(t, k, r); + } }); + var a = [].concat(p); + a.length === 3 && a[0] === 'a' && !(1 in a) && a[2] === 'c' && receiver === p && reads.join() === 'spread,length,0,2'", + ); + truth( + "var p = new Proxy([1, 2], {}), t = [3, 4]; t[Symbol.isConcatSpreadable] = null; + var q = new Proxy(t, {}), a = [].concat(p, q); + a.length === 3 && a[0] === 1 && a[1] === 2 && a[2] === q", + ); + truth( + "var marker = {}, caught = false; + var p = new Proxy([], { get: function (t, k) { if (k === Symbol.isConcatSpreadable) throw marker; return t[k]; } }); + try { [].concat(p); } catch (e) { caught = e === marker; } + caught", + ); + type_errors(&["var p = Proxy.revocable([], {}); p.revoke(); [].concat(p.proxy)"]); +} + +#[test] +fn typed_array_statics_construct_through_proxy_receivers() { + truth_collecting( + "var p = new Proxy(Uint8Array, {}), a = p.of(257, 2), b = p.from([3, 260]); + a instanceof Uint8Array && a.length === 2 && a[0] === 1 && a[1] === 2 && + b instanceof Uint8Array && b.length === 2 && b[0] === 3 && b[1] === 4", + ); + truth_collecting( + "var calls = [], receiver, context = { add: 1 }; + var p = new Proxy(Uint8Array, { construct: function (t, args, nt) { + calls.push(t === Uint8Array, args.length, args[0], nt === p); + return new Uint16Array(args[0]); + } }); + var a = p.of(257, 2), b = p.from({ 0: 300, length: 1 }, function (v, i) { receiver = this; return v + i + this.add; }, context); + a instanceof Uint16Array && a[0] === 257 && a[1] === 2 && b instanceof Uint16Array && b[0] === 301 && + receiver === context && calls.join() === 'true,1,2,true,true,1,1,true'", + ); + for method in ["of(1, 2)", "from([1, 2])"] { + for result in ["{}", "new Uint8Array(1)", "new Proxy(new Uint8Array(2), {})"] { + truth(&format!( + "var p = new Proxy(Uint8Array, {{ construct: function () {{ return {result}; }} }}); + type_error(function () {{ p.{method}; }})" + )); + } + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy(Uint8Array, {{ construct: function () {{ throw marker; }} }}); + try {{ p.{method}; }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + truth( + "var pair = Proxy.revocable(Uint8Array, {}), p = pair.proxy; + pair.revoke(); + type_error(function () { Uint8Array.of.call(p, 1); }) && type_error(function () { Uint8Array.from.call(p, [1]); })", + ); +} + #[test] fn a_proxy_works_as_a_prototype_and_a_with_scope() { truth( @@ -769,21 +915,27 @@ fn a_proxy_works_as_a_prototype_and_a_with_scope() { fn typeof_reads_the_binding_a_with_scope_reported_once() { // GetBindingValue asks `has` again, and a binding gone by then reads as undefined without `get`. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return k === 'x' ? function () {} : undefined; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return k === 'x' ? function () {} : undefined; + } }); var r; with (p) { r = typeof x; } - r === 'undefined' && asked === 2 && got === 0", + r === 'undefined' && asked === 2 && got === 0 && unscopables === 1", ); // A plain read of the same binding takes the same path. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return 1; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return 1; + } }); var r; with (p) { r = x; } - r === undefined && asked === 2 && got === 0", + r === undefined && asked === 2 && got === 0 && unscopables === 1", ); } @@ -792,15 +944,19 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { for present in ["asked++ < 2", "asked++ === 0", "false"] { let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); let src = format!( - "var asked = 0, got = 0, outer = 0, receiver; + "var asked = 0, got = 0, outer = 0, unscopables = 0, receiver; function method() {{ outer++; return 'outer'; }} var p = new Proxy({{}}, {{ has: function (t, k) {{ return k === 'method' && ({present}); }}, - get: function () {{ got++; return function () {{ receiver = this; return 'proxy'; }}; }} + get: function (t, k) {{ + if (k === Symbol.unscopables) {{ unscopables++; return undefined; }} + got++; return function () {{ receiver = this; return 'proxy'; }}; + }} }}); var result, caught = false; try {{ with (p) {{ result = method(); }} }} catch (e) {{ caught = e instanceof TypeError; }} - {expected}", + ({expected}) && unscopables === {unscopables}", + unscopables = usize::from(present != "false"), expected = match present { "asked++ < 2" => "result === 'proxy' && receiver === p && asked === 2 && got === 1 && outer === 0 && !caught", "asked++ === 0" => "caught && asked === 2 && got === 0 && outer === 0", @@ -816,16 +972,21 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { #[test] fn concat_proxy_array_lengths_use_to_length() { truth( - "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0; + "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0, spreadReads = 0; var empty = lengths.every(function (length) { var p = new Proxy([7], { - get: function (t, k) { if (k === 'length') return length; reads++; return t[k]; }, + get: function (t, k) { + if (k === Symbol.isConcatSpreadable) { spreadReads++; return undefined; } + if (k === 'length') return length; + reads++; return t[k]; + }, has: function () { reads++; return true; } }); return [3].concat(new Proxy(p, {}), 9).join() === '3,9'; }); var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } }); - empty && reads === 0 && [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", + empty && reads === 0 && spreadReads === lengths.length && + [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", ); } @@ -855,7 +1016,11 @@ fn concat_and_reviver_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { let setup = format!( "var p = new Proxy([], {{ - get: function (t, k) {{ if (k === 'length') return {length}; throw new Error('element read'); }}, + get: function (t, k) {{ + if (k === Symbol.isConcatSpreadable) return undefined; + if (k === 'length') return {length}; + throw new Error('element read'); + }}, has: function () {{ throw new Error('element checked'); }} }});" ); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 7ebcacbbc2..5c083d7acd 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -157,7 +157,9 @@ pub(crate) struct WellKnown { pub(crate) has_instance: Sym, pub(crate) to_primitive: Sym, pub(crate) to_string_tag: Sym, - /// The five as values, for the collector. + pub(crate) unscopables: Sym, + pub(crate) is_concat_spreadable: Sym, + /// The Symbols as values, for the collector. values: Vec, } @@ -171,8 +173,14 @@ impl WellKnown { make("Symbol.toPrimitive"), make("Symbol.toStringTag"), ); - let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect(); - WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values } + let unscopables = make("Symbol.unscopables"); + let is_concat_spreadable = make("Symbol.isConcatSpreadable"); + let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag, &unscopables, &is_concat_spreadable] + .into_iter() + .cloned() + .map(Value::Symbol) + .collect(); + WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, unscopables, is_concat_spreadable, values } } } @@ -543,7 +551,7 @@ impl Interp { /// the heap for the list is checked first. A proxy's Symbols come from its `ownKeys` trap. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { if self.is_proxy(id) { - return Ok(self.proxy_own_keys(id)?.syms); + return Ok(self.proxy_own_keys(id, false)?.syms); } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; diff --git a/docs/mcp.md b/docs/mcp.md index 4e380d9057..2f3cddb74c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2882,6 +2882,8 @@ Existing globals with either name are preserved. If a missing global cannot be a is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)` and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object. +Typed-array `from` and `of` accept proxy constructors and run their `construct` traps. +A proxy constructor must return a typed array with at least the requested length; otherwise the method throws `TypeError`. `Reflect.construct` also accepts a distinct constructor as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object. `Map`, `Set`, `WeakMap` and `WeakSet` initialize iterable arguments through the requested prototype's @@ -2909,6 +2911,8 @@ and calls an explicit `get` trap when present. `concat` and `JSON.parse` reviver traversal also use `ToLength` for proxy arrays. They check lengths before walking indices or allocating traversal keys. `concat` throws `TypeError` if the combined length exceeds the maximum safe integer. Reviver traversal keys count against the heap limit until their traversal frame is dropped. +`concat` reads `Symbol.isConcatSpreadable` through proxy `get` traps. A defined value controls whether the object +is spread; an undefined value uses the array check. In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating @@ -2918,6 +2922,7 @@ and symbol enumeration on a revoked proxy also throw `TypeError`. A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`, `defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation reaches the target. `Reflect`'s functions take Symbol keys too. +`Object.keys` and `Object.getOwnPropertyNames` keep the target's key order through empty-handler proxies. For an ordinary object, `Reflect.ownKeys` returns the string keys, then the Symbols in insertion order. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines its key order, with strings and Symbols mixed as the @@ -2932,6 +2937,9 @@ names are rejected; a later getter's exception takes precedence over the duplica Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay reachable during proxy callbacks, including callbacks that revoke a nested target proxy. +A `with` scope checks `Symbol.unscopables` after finding a property. If that lookup returns an object whose +property for the binding name is truthy, resolution continues in the outer scope. Each read calls a proxy's `get` trap +when its receiver is a proxy. `Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype without creating a property on the receiver; when that typed array is the receiver, the value is converted to a number first. `Object.freeze`, `Object.seal`, `Object.isFrozen` and `Object.isSealed` include a proxy's Symbol From ff165a7ec29d2342709cf0fcd2a68ba3718199b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 08:10:45 -0800 Subject: [PATCH 6/6] JavaScript: descriptor bags keep ECMAScript key order; Symbol hooks need ES2015 Object.defineProperties, Object.create, seal and freeze read an ordinary object's own names in ECMAScript order (array indices ascending first) in an ES2015 run, through proxies without an ownKeys trap too; without the option they keep the order for-in visits. concat reads Symbol.isConcatSpreadable and with scopes read Symbol.unscopables only in an ES2015 run, so a Symbol set by an earlier run does not change code run without the option. Tests: the host-function proxy refusal checks the throw and that neither the host function nor the trap ran; the bound-constructor test sets the custom prototype before constructing. --- crates/js/src/builtins/array.rs | 5 ++- crates/js/src/interp.rs | 5 ++- crates/js/src/proxy.rs | 9 +++-- crates/js/src/proxy_tests.rs | 59 +++++++++++++++++++++++++++++---- 4 files changed, 66 insertions(+), 12 deletions(-) diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index 48dfe1832a..0f45f1cb50 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -389,7 +389,10 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult let mut n = 0u64; for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) { interp.use_fuel()?; - let override_spread = match (e.as_object(), interp.well_known(|w| &w.is_concat_spreadable)) { + // Code run without the ECMAScript 2015 option reads no such Symbol, even in a realm + // that has it from an earlier run. + let spreadable = if interp.options.es2015 { interp.well_known(|w| &w.is_concat_spreadable) } else { None }; + let override_spread = match (e.as_object(), spreadable) { (Some(_), Some(sym)) => interp.get_value_sym(&e, &sym)?, _ => Value::Undefined, }; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 2aa5c933c9..206f7b93c7 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1634,7 +1634,10 @@ impl Interp { if !self.scope_has(object, name)? { return Ok(false); } - if with_this && let Some(sym) = self.well_known(|w| &w.unscopables) { + if with_this + && self.options.es2015 + && let Some(sym) = self.well_known(|w| &w.unscopables) + { let blocked = self.get_value_sym(&Value::Object(object), &sym)?; if let Value::Object(o) = blocked { let value = self.rooted(&[Value::Object(o)], |i| i.get_from(o, name, &Value::Object(o)))?; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index e709cfd808..b9bf04e87a 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -441,12 +441,15 @@ impl Interp { } /// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]: - /// one `ownKeys` trap call for a proxy. + /// one `ownKeys` trap call for a proxy. With [`crate::Options::es2015`] the names come in + /// ECMAScript order (array indices ascending first), through proxies without an `ownKeys` + /// trap too; without it they come in the order `for-in` visits them. pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + let ecma_order = self.options.es2015; if self.is_proxy(id) { - return self.proxy_own_keys(id, false); + return self.proxy_own_keys(id, ecma_order); } - let mut keys = self.own_keys(id)?; + let mut keys = if ecma_order { self.ecma_own_keys(id)? } else { self.own_keys(id)? }; keys.syms = self.own_symbols(id)?; keys.held.add(self, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; Ok(keys) diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index efb6bb78e8..09ffb4b7a3 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -852,6 +852,38 @@ fn concat_honors_proxy_spreadability_overrides() { type_errors(&["var p = Proxy.revocable([], {}); p.revoke(); [].concat(p.proxy)"]); } +#[test] +fn spreadability_and_unscopables_kept_from_an_earlier_run_apply_only_with_the_option() { + let mut realm = es(); + let setup = "var a = [1, 2]; a[Symbol.isConcatSpreadable] = false; + var o = { x: 'own' }; o[Symbol.unscopables] = { x: true }; var x = 'outer'; true"; + assert_eq!(realm.run(setup), Ok(JsValue::Bool(true))); + realm.set_es2015(false); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 2 && c[0] === 1 && w === 'own'"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 1 && c[0] === a && w === 'outer'"), Ok(JsValue::Bool(true))); +} + +#[test] +fn define_properties_defines_array_index_keys_in_ascending_order() { + truth( + "var log = [], bag = {}; bag.b = { value: 0 }; bag[2] = { value: 2 }; bag[1] = { value: 1 }; + var p = new Proxy({}, { defineProperty: function (t, k, d) { log.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(p, bag); + var wrapped = [], q = new Proxy({}, { defineProperty: function (t, k, d) { wrapped.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(q, new Proxy(bag, {})); + log.join() === '1,2,b' && wrapped.join() === '1,2,b'", + ); + // Without the option, descriptors are read in the order for-in visits the names. + let mut realm = Realm::new(); + let src = "var order = [], bag = {}; bag.b = 0; bag[2] = 0; bag[1] = 0; + var seen = [], descs = {}; + for (var k in bag) { order.push(k); (function (k) { Object.defineProperty(descs, k, { enumerable: true, get: function () { seen.push(k); return { value: 0 }; } }); })(k); } + Object.defineProperties({}, descs); + seen.join() === order.join()"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); +} + #[test] fn typed_array_statics_construct_through_proxy_receivers() { truth_collecting( @@ -1527,12 +1559,23 @@ fn a_host_function_refuses_a_proxy_and_names_the_argument() { } } assert!(seen.borrow().is_empty(), "the host function did not run"); - // The traps did not run either. + // The same argument with a trap is refused too, before the host function or the trap runs. let mut realm = es(); - let f: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + let calls = Rc::new(RefCell::new(0usize)); + let counter = calls.clone(); + let f: HostFunction = Rc::new(move |_| { + *counter.borrow_mut() += 1; + Ok(Data::Undefined) + }); realm.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); - let r = realm.run("var ran = false; try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } catch (e) {} ran"); - assert_eq!(r, Ok(JsValue::Bool(false))); + let r = realm.run( + "var ran = false, threw = false; + try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } + catch (e) { threw = e instanceof TypeError; } + threw && !ran", + ); + assert_eq!(r, Ok(JsValue::Bool(true))); + assert_eq!(*calls.borrow(), 0, "the host function did not run"); } #[test] @@ -2269,13 +2312,15 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { #[test] fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { truth( - "var B = Map.bind(null, [[1, 7]]), P = new Proxy(B, {}), Q = new Proxy(P, {}); + "var B = Map.bind(null, [[1, 7]]), proto = Object.create(Map.prototype); + Object.defineProperty(B, 'prototype', { value: proto }); + var P = new Proxy(B, {}), Q = new Proxy(P, {}); var a = new P(), b = new Q(), c = Reflect.construct(Q, []); var R = new Proxy(Q.bind(null), {}), d = new R(); var U = new Proxy(Uint8Array.bind(null, [7, 8]), {}), u = new U(); - Object.defineProperty(B, 'prototype', { value: Map.prototype }); a.get(1) === 7 && b.get(1) === 7 && c.get(1) === 7 && d.get(1) === 7 && - Object.getPrototypeOf(a) === Map.prototype && u.length === 2 && u[1] === 8 && + Object.getPrototypeOf(a) === proto && Object.getPrototypeOf(b) === proto && Object.getPrototypeOf(c) === proto && + Object.getPrototypeOf(d) === Map.prototype && u.length === 2 && u[1] === 8 && type_error(function () { class Child extends P {} new Child(); })", ); }