From 938de6e8a3dbd7f159f1b8fe16cc244a6bf936bf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 1 Dec 2026 20:31:33 -0800 Subject: [PATCH] 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`.