From cfd6aed392eb842f55cd03401d99b96326047df6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 21:18:51 -0800 Subject: [PATCH] JavaScript: proxies keep their traps after the merge with main Function.prototype.bind reads a proxy's prototype through its trap, Object.prototype.toString reads a proxy's Symbol.toStringTag from its target, Reflect.set writes a typed array's elements, a super assignment runs the set trap of a proxy on the home object's chain, and 'in' asks a proxy's has trap once. The name a trap is given is counted against the heap and fuel limits, and Proxy and Reflect stay reachable while their functions are installed. --- crates/js/src/builtins.rs | 34 ++++++++-- crates/js/src/builtins/binary.rs | 5 ++ crates/js/src/builtins/reflect.rs | 13 +++- crates/js/src/class_ops.rs | 23 ++++--- crates/js/src/host_classes.rs | 12 ++-- crates/js/src/interp.rs | 25 +++---- crates/js/src/proxy.rs | 63 +++++++++++++----- crates/js/src/proxy_tests.rs | 105 ++++++++++++++++++++++++++++++ crates/js/src/xml.rs | 6 +- docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 11 files changed, 233 insertions(+), 58 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f90112f93a..197e5be3c1 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -537,11 +537,14 @@ fn object_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> J // A proxy reads as an array when its target is one, and a revoked proxy is a // `TypeError` (ECMA-262 2020 section 19.1.3.6). Value::Object(o) if interp.is_proxy(*o) => { - if interp.is_array(&this)? { - "Array" - } else { - interp.heap.object(*o).map_or("Object", |o| o.class.name()) + let array = interp.is_array(&this)?; + // `Symbol.toStringTag` is read through the proxy to its target. + let o = *o; + if let Some(tag) = interp.rooted(std::slice::from_ref(&this), |i| i.string_tag_of(o))? { + let roots = [Value::String(tag.clone())]; + return interp.rooted(&roots, |i| i.wrap_str("[object ", Some(&tag), "]")); } + if array { "Array" } else { interp.heap.object(o).map_or("Object", |o| o.class.name()) } } _ => { let o = interp.to_object(&this)?; @@ -740,13 +743,30 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into(); // With ECMAScript 2015 the bound function inherits from the target's prototype, read before // `length` and `name` (ECMA-262 2020 section 9.4.1.3 step 2), so a bound generator function - // inherits from %GeneratorFunction.prototype%. - let target_proto = interp.heap.object(target).and_then(|o| o.proto); + // inherits from %GeneratorFunction.prototype%. A proxy's prototype comes from its + // `getPrototypeOf` trap, and it stays reachable while `length` and `name` are read. + let target_proto = if interp.options.es2015 { interp.get_prototype_of(target)? } else { interp.heap.object(target).and_then(|o| o.proto) }; + let mark = interp.temp_roots.len(); + interp.temp_roots.extend(target_proto.map(Value::Object)); + let r = bind_from(interp, &this, target, target_proto, bound_this, bound_args); + interp.temp_roots.truncate(mark); + r +} + +/// The steps of `Function.prototype.bind` after the target's prototype is read. +fn bind_from( + interp: &mut Interp, + this: &Value, + target: ObjId, + target_proto: Option, + bound_this: Value, + bound_args: Rc<[Value]>, +) -> JsResult { // A host function's `length` is an ordinary property a script can set, so it is converted // to an integer first, as later editions specify. With ECMAScript 2015 only an own `length` is // read (ECMA-262 2020 section 19.2.3.2 step 4), so an inherited getter does not run. let has_length = !interp.options.es2015 || interp.get_own_property(target, &key("length"))?.is_some(); - let length_value = if has_length { interp.get_from(target, &key("length"), &this)? } else { Value::Undefined }; + let length_value = if has_length { interp.get_from(target, &key("length"), this)? } else { Value::Undefined }; let target_length = match length_value { Value::Number(n) if n.is_nan() => 0.0, Value::Number(n) => n.trunc(), diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 3ec93edc07..b18a0cda67 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -342,6 +342,11 @@ pub(crate) fn set_element(interp: &mut Interp, id: ObjId, n: f64, v: &Value) -> Ok(()) } +/// Does the numeric name `n` name an element of the typed array `id` (IsValidIntegerIndex)? +pub(crate) fn is_element(interp: &Interp, id: ObjId, n: f64) -> bool { + view_of(interp, id).is_some_and(|view| valid_index(n, view.length).is_some()) +} + /// `[[DefineOwnProperty]]` of a numeric name of a typed array (section 9.4.5.3, with the /// configurable elements of later editions). pub(crate) fn define_element(interp: &mut Interp, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index 5e25784b59..2b5158624e 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -19,7 +19,9 @@ pub(super) fn install(interp: &mut Interp, keep: bool) -> JsResult<()> { let global = interp.global; if !(keep && interp.get_own_property(global, &key("Proxy"))?.is_some()) { let proxy = native(interp, "Proxy", proxy_ctor, 2, NativeKind::Plain, true)?; - method(interp, proxy, "revocable", revocable, 2)?; + // Naming a new method can collect, and the constructor is reachable from nowhere else + // until it is published. + interp.rooted(&[Value::Object(proxy)], |interp| method(interp, proxy, "revocable", revocable, 2))?; data(interp, global, "Proxy", Value::Object(proxy), HIDDEN)?; } if !(keep && interp.get_own_property(global, &key("Reflect"))?.is_some()) { @@ -34,6 +36,12 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> { let global = interp.global; let object_proto = interp.intrinsics.object_proto; let reflect = interp.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + interp.rooted(&[Value::Object(reflect)], |interp| reflect_methods(interp, reflect))?; + data(interp, global, "Reflect", Value::Object(reflect), HIDDEN) +} + +/// Defines `Reflect`'s functions on `reflect`, which the caller keeps reachable. +fn reflect_methods(interp: &mut Interp, reflect: ObjId) -> JsResult<()> { method(interp, reflect, "apply", apply, 3)?; method(interp, reflect, "construct", construct, 2)?; method(interp, reflect, "defineProperty", define_property, 3)?; @@ -46,8 +54,7 @@ fn install_reflect(interp: &mut Interp) -> JsResult<()> { method(interp, reflect, "ownKeys", own_keys, 1)?; method(interp, reflect, "preventExtensions", prevent_extensions, 1)?; method(interp, reflect, "set", set, 3)?; - method(interp, reflect, "setPrototypeOf", set_prototype_of, 2)?; - data(interp, global, "Reflect", Value::Object(reflect), HIDDEN) + method(interp, reflect, "setPrototypeOf", set_prototype_of, 2) } // ---- Proxy ---- diff --git a/crates/js/src/class_ops.rs b/crates/js/src/class_ops.rs index 99a52146cf..73a8f4d0f8 100644 --- a/crates/js/src/class_ops.rs +++ b/crates/js/src/class_ops.rs @@ -557,14 +557,6 @@ impl Interp { } } - /// The property `k` of `start` or an object it inherits from. - fn find_pk(&mut self, start: ObjId, k: &PropKey) -> JsResult> { - match k { - PropKey::Str(name) => self.find_property(start, name), - PropKey::Sym(s) => self.find_sym(start, s), - } - } - /// [[Get]] of `k` from `start` with `receiver` as `this`. fn get_pk_from(&mut self, start: ObjId, k: &PropKey, receiver: &Value) -> JsResult { match k { @@ -605,7 +597,20 @@ impl Interp { /// 6.2.3.2). fn super_put(&mut self, proto: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult<()> { let throw = self.strict_writes(); - let why = match self.find_pk(proto, &k)? { + let inherited = match &k { + PropKey::Str(name) => match self.lookup(proto, name)? { + crate::interp::Lookup::Proxy(p) => { + if !self.set_with_receiver(p, name.clone(), v, receiver)? { + return self.super_reject(throw, &k, "the proxy did not set it"); + } + return Ok(()); + } + crate::interp::Lookup::Found(prop) => Some(prop), + crate::interp::Lookup::Missing => None, + }, + PropKey::Sym(s) => self.find_sym(proto, s)?, + }; + let why = match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => Some("it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Some("it is read-only"), diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index d8b81fdcec..e5db3cb582 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -393,14 +393,18 @@ impl Interp { /// [[HasProperty]] of `k` on `id`: for an object of a host class with an indexer, an array index, /// or a name that the object and its prototypes lack, is there when the indexer gives a value other /// than `undefined` for it. - pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &[u16]) -> JsResult { - let index = crate::value::array_index(k).is_some(); - if (index || !self.has_property(id, k)?) + pub(crate) fn has_property_indexed(&mut self, id: ObjId, k: &Key) -> JsResult { + // The lookup runs once, so a proxy's `has` trap is asked once. + let found = if crate::value::array_index(k).is_some() { None } else { Some(self.has_property(id, k)?) }; + if found != Some(true) && let Some(f) = self.host_indexer(id)? { return Ok(!matches!(self.host_index(&f, id, Self::indexer_key(k), true)?, Value::Undefined)); } - self.has_property(id, k) + match found { + Some(found) => Ok(found), + None => self.has_property(id, k), + } } /// `d` as a JavaScript value, the objects of host classes in it made from their [`host_ref`]. diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index c177f6578c..c9cfe69b61 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1458,7 +1458,7 @@ impl Interp { // ---- variables ---- - fn resolve(&mut self, name: &[u16]) -> JsResult { + fn resolve(&mut self, name: &Key) -> JsResult { let mut cur = Some(self.frame()?.env); while let Some(e) = cur { match self.heap.env(e) { @@ -1685,7 +1685,7 @@ impl Interp { } /// [[GetOwnProperty]] (section 8.12.1), through a proxy's trap when `id` is a proxy. - pub(crate) fn get_own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + pub(crate) fn get_own_property(&mut self, id: ObjId, k: &Key) -> JsResult> { if self.is_proxy(id) { return self.proxy_get_own_property(id, k); } @@ -1783,7 +1783,7 @@ impl Interp { /// [[GetProperty]]: the property found on the object or its prototype chain, through the /// `getOwnPropertyDescriptor` and `getPrototypeOf` traps of the proxies on it. - pub(crate) fn find_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + pub(crate) fn find_property(&mut self, id: ObjId, k: &Key) -> JsResult> { // One root slot holds the prototype the walk has reached; each hop replaces it. let mark = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); @@ -1821,7 +1821,7 @@ impl Interp { } /// [[HasProperty]], through the `has` trap of a proxy on the prototype chain. - pub(crate) fn has_property(&mut self, id: ObjId, k: &[u16]) -> JsResult { + pub(crate) fn has_property(&mut self, id: ObjId, k: &Key) -> JsResult { match self.lookup(id, k)? { Lookup::Found(_) => Ok(true), Lookup::Missing => Ok(false), @@ -1831,7 +1831,7 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter, through the `get` trap /// of a proxy on the prototype chain. - pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + pub(crate) fn get_from(&mut self, start: ObjId, k: &Key, receiver: &Value) -> JsResult { // An array index of an object of a host class with an indexer is the indexer's answer. if let Some(i) = array_index(k) && let Some(f) = self.host_indexer(start)? @@ -1854,7 +1854,7 @@ impl Interp { /// [[Get]] of a name that is not an array index, without the indexer of an object of a host /// class: a name the object and its prototypes lack is `undefined`. For names the engine looks /// up itself, such as `toJSON`, which a collection's indexer would answer with an error. - pub(crate) fn get_property_only(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + pub(crate) fn get_property_only(&mut self, start: ObjId, k: &Key, receiver: &Value) -> JsResult { match self.lookup(start, k)? { Lookup::Missing | Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Lookup::Found(Prop::Data { value, .. }) => Ok(value), @@ -1880,7 +1880,7 @@ impl Interp { } /// `base[k]` for any value (GetValue, section 8.7.1). - pub(crate) fn get_value(&mut self, base: &Value, k: &[u16]) -> JsResult { + pub(crate) fn get_value(&mut self, base: &Value, k: &Key) -> JsResult { if self.options.e4x && self.is_xml(base) { return self.xml_get(base, &Value::String(Str::from_units(k.to_vec()))); } @@ -2253,7 +2253,7 @@ impl Interp { } /// [[Delete]] (section 8.12.7). - pub(crate) fn delete(&mut self, id: ObjId, k: &[u16], throw: bool) -> JsResult { + pub(crate) fn delete(&mut self, id: ObjId, k: &Key, throw: bool) -> JsResult { if self.is_proxy(id) { let deleted = self.proxy_delete(id, k)?; if !deleted && throw { @@ -3136,7 +3136,7 @@ impl Interp { /// the objects that follow it are searched. A name deleted or made non-enumerable after the /// names were listed is skipped, on an ordinary object as on a proxy. A proxy's `has` trap is /// not asked. Each proxy on the chain takes a unit of fuel. - fn for_in_still_has(&mut self, o: ObjId, k: &[u16]) -> JsResult { + fn for_in_still_has(&mut self, o: ObjId, k: &Key) -> JsResult { // One root slot holds the prototype the walk has reached; each hop replaces it. let mark = self.temp_roots.len(); self.temp_roots.push(Value::Undefined); @@ -3145,7 +3145,7 @@ impl Interp { r } - fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &[u16], slot: usize) -> JsResult { + fn for_in_still_has_rooted(&mut self, mut cur: ObjId, k: &Key, slot: usize) -> JsResult { loop { let p = match self.lookup(cur, k)? { Lookup::Found(prop) => return Ok(prop.enumerable()), @@ -4421,8 +4421,9 @@ impl Interp { return self.xml_has(b, a).map(Value::Bool); } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; - let k = self.to_prop_key(a)?; - self.has_pk_indexed(*o, &k).map(Value::Bool) + // The key stays rooted while a proxy's trap is given a copy of it. + let o = *o; + self.with_prop_key(a, |i, k| i.has_pk_indexed(o, &k)).map(Value::Bool) } } } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index bb35ea100a..01afb8ab00 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -109,8 +109,15 @@ impl Interp { Ok(v) } - fn key_value(k: &[u16]) -> Value { - Value::String(Str::from_units(k.to_vec())) + /// The property name a trap is given, a copy of `k` counted against the heap limit, its code + /// units charged as fuel. + fn key_value(&mut self, k: &Key) -> JsResult { + let bytes = string_bytes(k.len()); + self.reserve_heap(bytes)?; + crate::string_builtins::charge_units(self, k.len())?; + let copy = Value::String(Str::from_units(k.to_vec())); + self.heap.bytes = self.heap.bytes.saturating_add(bytes); + Ok(copy) } fn invariant(&mut self, trap: &str, why: &str) -> Abrupt { @@ -220,10 +227,11 @@ impl Interp { // ---- properties ---- /// [[GetOwnProperty]] of a proxy (section 9.5.5). - pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &[u16]) -> JsResult> { - self.proxy_op(p, "read a property of", &[], |i, target, handler| { + pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &Key) -> JsResult> { + self.proxy_op(p, "read a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.get_own_property(target, k) }; - let result = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?; + let name = i.key_value(k)?; + let result = i.call_trap(&trap, handler, &[Value::Object(target), name])?; if !matches!(result, Value::Object(_) | Value::Undefined) { return Err(i.invariant("getOwnPropertyDescriptor", "returned a value that is neither an object nor undefined")); } @@ -267,12 +275,14 @@ impl Interp { /// [[DefineOwnProperty]] of a proxy (section 9.5.6): whether the trap defined the property. pub(crate) fn proxy_define_own_property(&mut self, p: ObjId, k: &Key, desc: &Desc) -> JsResult { - let roots = desc_values(desc); + let mut roots = desc_values(desc); + roots.push(Value::String(Str::from_rc(k.clone()))); self.proxy_op(p, "define a property of", &roots, |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "defineProperty")? else { return i.define_own_property(target, k.clone(), desc, false) }; let desc_obj = from_desc(i, desc)?; i.temp_roots.push(desc_obj.clone()); - if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), desc_obj])?.truthy() { + let name = i.rooted(std::slice::from_ref(&desc_obj), |i| i.key_value(k))?; + if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() { return Ok(false); } let target_prop = i.get_own_property(target, k)?; @@ -305,10 +315,11 @@ impl Interp { } /// [[HasProperty]] of a proxy (section 9.5.7). - pub(crate) fn proxy_has(&mut self, p: ObjId, k: &[u16]) -> JsResult { - self.proxy_op(p, "test a property of", &[], |i, target, handler| { + pub(crate) fn proxy_has(&mut self, p: ObjId, k: &Key) -> JsResult { + self.proxy_op(p, "test a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_property(target, k) }; - let found = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?.truthy(); + let name = i.key_value(k)?; + let found = i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy(); if !found && let Some(current) = i.get_own_property(target, k)? { if !current.configurable() { return Err(i.invariant("has", "hid a non-configurable property of its target")); @@ -322,10 +333,11 @@ impl Interp { } /// [[Get]] of a proxy (section 9.5.8). - pub(crate) fn proxy_get(&mut self, p: ObjId, k: &[u16], receiver: &Value) -> JsResult { - self.proxy_op(p, "read a property of", std::slice::from_ref(receiver), |i, target, handler| { + pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value) -> JsResult { + self.proxy_op(p, "read a property of", &[receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_from(target, k, receiver) }; - let v = i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), receiver.clone()])?; + let name = i.key_value(k)?; + let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?; match i.get_own_property(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")) @@ -340,9 +352,10 @@ impl Interp { /// [[Set]] of a proxy (section 9.5.9): whether the trap set the property. fn proxy_set(&mut self, p: ObjId, k: &Key, v: &Value, receiver: &Value) -> JsResult { - self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone()], |i, target, handler| { + self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "set")? else { return i.set_with_receiver(target, k.clone(), v.clone(), receiver) }; - if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k), v.clone(), receiver.clone()])?.truthy() { + let name = i.key_value(k)?; + if !i.call_trap(&trap, handler, &[Value::Object(target), name, v.clone(), receiver.clone()])?.truthy() { return Ok(false); } match i.get_own_property(target, k)? { @@ -358,10 +371,11 @@ impl Interp { } /// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property. - pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &[u16]) -> JsResult { - self.proxy_op(p, "delete a property of", &[], |i, target, handler| { + 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| { let Some(trap) = i.proxy_trap(handler, "deleteProperty")? else { return i.delete(target, k, false) }; - if !i.call_trap(&trap, handler, &[Value::Object(target), Self::key_value(k)])?.truthy() { + let name = i.key_value(k)?; + if !i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy() { return Ok(false); } let Some(current) = i.get_own_property(target, k)? else { return Ok(true) }; @@ -468,6 +482,19 @@ impl Interp { } fn ordinary_set(&mut self, o: ObjId, k: Key, v: Value, receiver: &Value) -> JsResult { + // A typed array set on itself writes a numeric key as its element, converting the value + // and ignoring a key outside the view; with another receiver a key outside the view is + // ignored and an element is set on the receiver as usual, as the typed arrays' other + // writes follow the later editions (https://tc39.es/ecma262/#sec-typedarray-set). + if let Some(n) = crate::builtins::binary::typed_key(self, o, &k) { + if receiver.as_object() == Some(o) { + crate::builtins::binary::set_element(self, o, n, &v)?; + return Ok(true); + } + if !crate::builtins::binary::is_element(self, o, n) { + return Ok(true); + } + } let own = match self.lookup(o, &k)? { Lookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver), Lookup::Found(prop) => prop, diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index f1294b20d6..78f7785dea 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -42,6 +42,33 @@ fn limit(src: &str, limits: Limits) -> LimitKind { } } +#[test] +fn the_name_a_trap_is_given_counts_against_the_heap_limit() { + // The same key fits for an ordinary object, but its copy for the trap does not fit in what + // is left. + let limits = Limits { heap_bytes: 4 << 20, ..Limits::default() }; + let make = "var k = 'x'; while (k.length < 1048576) k += k;"; + assert_eq!(Realm::with_options(es_options(), limits.clone()).run(&format!("{make} k in {{}}")), Ok(JsValue::Bool(false))); + let src = format!("{make} var p = new Proxy({{}}, {{ has: function () {{ return false; }} }}); k in p"); + assert_eq!(limit(&src, limits.clone()), LimitKind::Heap); + // A key made fresh by converting an object stays counted while its copy is reserved. + let fresh = "var o = { toString: function () { var k = 'x'; while (k.length < 1048576) k += k; return k; } };"; + assert_eq!(Realm::with_options(es_options(), limits.clone()).run(&format!("{fresh} o in {{}}")), Ok(JsValue::Bool(false))); + let src = format!("{fresh} var p = new Proxy({{}}, {{ has: function () {{ return false; }} }}); o in p"); + assert_eq!(limit(&src, limits.clone()), LimitKind::Heap); + assert_eq!(Realm::with_options(es_options(), limits.clone()).run(&format!("{fresh} var t = {{}}; delete t[o]")), Ok(JsValue::Bool(true))); + let src = format!("{fresh} var p = new Proxy({{}}, {{ deleteProperty: function () {{ return true; }} }}); delete p[o]"); + assert_eq!(limit(&src, limits.clone()), LimitKind::Heap); + assert_eq!( + Realm::with_options(es_options(), limits.clone()).run(&format!("{fresh} Object.getOwnPropertyDescriptor({{}}, o) === undefined")), + Ok(JsValue::Bool(true)) + ); + let src = format!( + "{fresh} var p = new Proxy({{}}, {{ getOwnPropertyDescriptor: function () {{ return undefined; }} }}); Object.getOwnPropertyDescriptor(p, o)" + ); + assert_eq!(limit(&src, limits), LimitKind::Heap); +} + // ---- the realm gate ---- #[test] @@ -67,6 +94,24 @@ fn only_a_realm_that_ran_es2015_code_has_proxy_and_reflect() { assert_eq!(taken.run("Proxy + Reflect"), Ok(JsValue::Number(3.0))); } +#[test] +fn late_proxy_and_reflect_installation_keeps_their_methods_reachable() { + let mut realm = Realm::new(); + assert_eq!(realm.run("typeof Proxy + ' ' + typeof Reflect"), Ok(JsValue::String("undefined undefined".into()))); + realm.set_es2015(true); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let r = realm.run( + "var pair = Proxy.revocable({ a: 7 }, {}); + var keys = Reflect.ownKeys(pair.proxy); + var value = pair.proxy.a; + pair.revoke(); + value === 7 && keys.length === 1 && keys[0] === 'a'", + ); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(r, Ok(JsValue::Bool(true))); + assert!(realm.interp().heap.collections > 0); +} + // ---- Proxy ---- #[test] @@ -624,3 +669,63 @@ fn a_host_function_refuses_a_proxy_and_names_the_argument() { 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))); } + +#[test] +fn a_bound_proxy_inherits_from_the_prototype_its_trap_gives() { + truth( + "var p = new Proxy(function () { return 7; }, {}); + var b = p.bind(null); + Object.getPrototypeOf(b) === Function.prototype && typeof b.call === 'function' && b() === 7", + ); + // A prototype the trap makes stays the bound function's while `length` and `name` are read. + truth_collecting( + "var target = function () {}, reads = []; + Object.defineProperty(target, 'length', { get: function () { reads.push({ key: 'length' }); return 2; } }); + Object.defineProperty(target, 'name', { get: function () { reads.push({ key: 'name' }); return 'target'; } }); + var q = new Proxy(target, { getPrototypeOf: function () { return { tag: 'made' }; } }); + var c = q.bind(null); + Object.getPrototypeOf(c).tag === 'made' && c.length === 2 && c.name === 'bound target' + && reads.length === 2 && reads[0].key === 'length' && reads[1].key === 'name'", + ); +} + +#[test] +fn in_asks_a_proxy_s_has_trap_once() { + truth( + "var n = 0, p = new Proxy({}, { has: function () { n++; return false; } }); + !('a' in p) && n === 1 && !(0 in p) && n === 2", + ); +} + +#[test] +fn to_string_reads_the_tag_of_a_proxy_s_target() { + truth( + "var t = {}; t[Symbol.toStringTag] = 'Thing'; + Object.prototype.toString.call(new Proxy(t, {})) === '[object Thing]' + && Object.prototype.toString.call(new Proxy([], {})) === '[object Array]'", + ); +} + +#[test] +fn reflect_set_writes_a_typed_array_element_and_ignores_a_key_outside_the_view() { + truth( + "var a = new Uint8Array(1); + var converted = false, big = { valueOf: function () { converted = true; return 5; } }; + Reflect.set(a, '0', 300) && a[0] === 44 && Reflect.set(a, '3', big) && converted && a.length === 1 + && !a.hasOwnProperty('3') + && (function () { var r = {}; return Reflect.set(a, '0', 7, r) && a[0] === 44 && r[0] === 7; })() + && (function () { var r = {}; return Reflect.set(a, '5', 7, r) && !r.hasOwnProperty('5'); })()", + ); +} + +#[test] +fn a_super_assignment_runs_the_set_trap_of_a_proxy_on_the_chain() { + truth( + "var seen = []; + var base = new Proxy({}, { set: function (t, k, v, r) { seen.push(k); return true; } }); + var o = { m() { super.x = 1; } }; + Reflect.setPrototypeOf(o, base); + o.m(); + seen.join() === 'x' && !o.hasOwnProperty('x')", + ); +} diff --git a/crates/js/src/xml.rs b/crates/js/src/xml.rs index bb311cf1a8..a764f7e343 100644 --- a/crates/js/src/xml.rs +++ b/crates/js/src/xml.rs @@ -749,7 +749,7 @@ impl Interp { } /// Whether a scope object has the variable `name`. - pub(crate) fn scope_has(&mut self, object: ObjId, name: &[u16]) -> JsResult { + pub(crate) fn scope_has(&mut self, object: ObjId, name: &Key) -> JsResult { if self.options.e4x && self.is_xml(&Value::Object(object)) { let k = Value::String(Str::from_units(name.to_vec())); return self.xml_has(&Value::Object(object), &k); @@ -871,7 +871,7 @@ impl Interp { /// The function a call `base.name(...)` runs and its `this` (ECMA-357 section 11.2.2.1). A /// call looks the name up among the methods, never among the children. - pub(crate) fn xml_method(&mut self, base: &Value, name: &[u16]) -> JsResult<(Value, Value)> { + pub(crate) fn xml_method(&mut self, base: &Value, name: &Key) -> JsResult<(Value, Value)> { let mut base = base.clone(); loop { let Value::Object(o) = base else { return Err(self.not_xml()) }; @@ -896,7 +896,7 @@ impl Interp { } /// A method found through an XML value in scope, for a call of a bare name in a filter. - pub(crate) fn xml_scope_method(&mut self, name: &[u16]) -> JsResult> { + pub(crate) fn xml_scope_method(&mut self, name: &Key) -> JsResult> { let mut cur = Some(self.frame()?.env); while let Some(e) = cur { match self.heap.env(e) { diff --git a/docs/mcp.md b/docs/mcp.md index 358b636c56..7a3deef8a0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2810,7 +2810,8 @@ counts against the call depth. A generator function called in an engine that `#t throws a `TypeError`, since that engine was made without the ECMAScript 2015 built-ins. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script also has the globals `Proxy`, with `Proxy.revocable`, and `Reflect` (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 -and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, and +and 26.2), with string property names. A trap is a script call: it takes fuel and counts against the limit on nested calls, +the copy of the property name it is given counts against the heap limit, and a trap result that breaks one of the proxy invariants, 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 `.js` run and keeps them for later `.jsx` runs. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1c1152b00c..e53059cef0 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, 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 both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` 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 the first `.js` run does not replace it. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. 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. 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 both globals; a `.jsx` file and a `source` string have neither in a new engine or in an engine that has not run a `.js` file. An engine that `#targetengine` keeps gets both globals at its first `.js` 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 the first `.js` run does not replace it. `cargo xtask test262` runs the suite's `Proxy` and `Reflect` tests whose features are present: 573 of 663 runs pass with the option (0 without it). Of the 90 failing runs, 4 do not parse because the tests use method definitions, and 86 expect function `name` properties and a configurable function `length`, `Object.setPrototypeOf`, and integer keys listed before other keys, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.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. `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`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.