From 91f76bc40aae9e3899e3b923f1746fc45ca64c07 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 01:09:46 -0800 Subject: [PATCH] JavaScript: Symbol reads through a proxy call its get trap, and ownKeys traps may return Symbol keys A read of a Symbol key on a proxy, or on an object with a proxy on its prototype chain, now calls the proxy's get trap with the Symbol and the receiver (ECMA-262 9.5.8) and checks the result against the target's non-configurable Symbol properties. An ownKeys trap may now return Symbol keys (9.5.11). A Symbol given twice, a non-configurable Symbol key of the target left out, and for a non-extensible target any Symbol key left out or added throw a TypeError. The target's descriptors are read in its key order with one isExtensible call. Reflect.ownKeys, Object.getOwnPropertySymbols and the Object functions that list keys take a proxy's keys from one trap call and keep the order the trap gave, Symbols included. --- crates/js/src/builtins/object.rs | 17 +++- crates/js/src/builtins/reflect.rs | 39 +++++---- crates/js/src/builtins/symbol.rs | 13 ++- crates/js/src/proxy.rs | 140 +++++++++++++++++++++++------- crates/js/src/proxy_tests.rs | 104 +++++++++++++++++++++- crates/js/src/symbol.rs | 78 +++++++++++++++-- docs/mcp.md | 15 ++-- docs/target-app-parity.md | 2 +- 8 files changed, 336 insertions(+), 72 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 8237c11f34..f1e0dd3fae 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -146,12 +146,23 @@ pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator JsResult<(Vec, crate::interp::HeldBytes)> { + if interp.is_proxy(o) { + let list = interp.own_keys_and_symbols(o)?; + let count = list.names.len() + list.syms.len(); + let roots = list.sym_values(); + return interp.rooted(&roots, |interp| { + let (keys, mut held) = list.into_prop_keys(); + held.add(interp, count.saturating_mul(std::mem::size_of::()))?; + Ok((keys.collect(), held)) + }); + } let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?; + let syms = interp.own_symbols(o)?; let mut keys: Vec = names.into_iter().map(PropKey::Str).collect(); - keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym)); + keys.extend(syms.into_iter().map(PropKey::Sym)); Ok((keys, held)) } diff --git a/crates/js/src/builtins/reflect.rs b/crates/js/src/builtins/reflect.rs index a49833739c..c6f0381b7d 100644 --- a/crates/js/src/builtins/reflect.rs +++ b/crates/js/src/builtins/reflect.rs @@ -4,13 +4,13 @@ use std::rc::Rc; -use super::object::{from_prop, names_array, to_desc}; -use super::{arg, method, native}; +use super::object::{from_prop, to_desc}; +use super::{arg, create_at, method, native, new_array}; use crate::heap::{CONFIGURABLE, Class, Func, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, Prop, WRITABLE, key}; use crate::interp::{Desc, Interp, JsResult}; use crate::proxy::desc_values; use crate::symbol::{PropKey, Sym}; -use crate::value::Value; +use crate::value::{Str, Value}; /// Defines `Proxy` and `Reflect` on the global object. With `keep`, for a realm that gets them /// after earlier runs, a global of the same name that a script defined stays as it is. Each @@ -229,22 +229,27 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe interp.is_extensible(o).map(Value::Bool) } -/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not, -/// then the own Symbol keys in the order they were added. A proxy's Symbol keys are its -/// target's. +/// `Reflect.ownKeys(target)` (section 26.1.10): an ordinary object's own property names, +/// enumerable or not, then its Symbol keys in insertion order. A proxy's keys come from one call of +/// its `ownKeys` trap, in the order it gave them. fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = target(interp, args, "ownKeys")?; - let names = interp.ecma_own_keys(o)?; - let count = names.len(); - let syms = interp.own_symbols(o)?; - let a = names_array(interp, names)?; - let Value::Object(id) = a else { return Ok(a) }; - interp.rooted(&[Value::Object(id)], |interp| { - for (i, s) in syms.into_iter().enumerate() { - interp.use_fuel()?; - super::create_at(interp, id, (count + i) as f64, Value::Symbol(s))?; - } - Ok(Value::Object(id)) + let list = interp.own_keys_and_symbols(o)?; + let roots = list.sym_values(); + interp.rooted(&roots, |interp| { + let (keys, _held) = list.into_prop_keys(); + let id = new_array(interp, 0)?; + interp.rooted(&[Value::Object(id)], |interp| { + for (i, k) in keys.enumerate() { + interp.use_fuel()?; + let v = match k { + PropKey::Str(k) => Value::String(Str::from_rc(k)), + PropKey::Sym(s) => Value::Symbol(s), + }; + create_at(interp, id, i as f64, v)?; + } + Ok(Value::Object(id)) + }) }) } diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index beec94c6a5..4503ffb5ca 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -169,9 +169,16 @@ fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { - let syms = interp.own_symbols(o)?; - let a = new_array(interp, 0)?; - interp.rooted(&[Value::Object(a)], |interp| { + let (syms, _held) = if interp.is_proxy(o) { + let list = interp.own_keys_and_symbols(o)?; + (list.syms, Some(list.names.held)) + } else { + (interp.own_symbols(o)?, None) + }; + let mut roots: Vec = syms.iter().cloned().map(Value::Symbol).collect(); + let a = interp.rooted(&roots, |interp| new_array(interp, 0))?; + roots.push(Value::Object(a)); + interp.rooted(&roots, |interp| { for (i, s) in syms.into_iter().enumerate() { interp.use_fuel()?; create_at(interp, a, i as f64, Value::Symbol(s))?; diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index fa88173b16..1c9767c6c2 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -20,11 +20,15 @@ use crate::heap::{ CONFIGURABLE, Class, ENUMERABLE, Key, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, PROXY_BYTES, Prop, ProxyData, WRITABLE, key, string_bytes, }; use crate::interp::{Abrupt, Desc, ErrorType, HeldBytes, HeldKeys, Interp, JsResult, KEY_ENTRY_BYTES, ProxyCall, SetLookup, merge_desc, same_value}; +use crate::symbol::{OwnKeyList, PropKey, Sym}; use crate::value::{Str, Value, index_key}; /// The most names an `ownKeys` trap may give. const MAX_OWN_KEYS: f64 = (1u64 << 24) as f64; +/// An `ownKeys` trap's names, its Symbol keys, and each Symbol's place in the whole list. +type TrapKeys = (Vec, Vec, Vec); + impl Interp { pub(crate) fn is_proxy(&self, id: ObjId) -> bool { matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_))) @@ -387,6 +391,24 @@ impl Interp { }) } + /// [[Get]] of a proxy (section 9.5.8) for the Symbol key `k`: the `get` trap with the Symbol + /// and `receiver`, or a read from the target when the handler has no `get` trap. + pub(crate) fn proxy_get_sym(&mut self, p: ObjId, k: &Sym, receiver: &Value) -> JsResult { + self.proxy_op(p, "read a property of", &[receiver.clone(), Value::Symbol(k.clone())], |i, target, handler| { + let Some(trap) = i.proxy_trap(handler, "get")? else { return i.get_sym_from(target, k, receiver) }; + let v = i.call_trap(&trap, handler, &[Value::Object(target), Value::Symbol(k.clone()), receiver.clone()])?; + match i.get_own_sym(target, k)? { + Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(&v, &value) => { + Err(i.invariant("get", "gave a value other than its target's non-configurable, read-only property")) + } + Some(Prop::Accessor { get: None, flags, .. }) if flags & CONFIGURABLE == 0 && !matches!(v, Value::Undefined) => { + Err(i.invariant("get", "gave a value for a non-configurable property of its target that has no getter")) + } + _ => Ok(v), + } + }) + } + /// [[Delete]] of a proxy (section 9.5.10): whether the trap deleted the property. pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &Key) -> JsResult { self.proxy_op(p, "delete a property of", &[Value::String(Str::from_rc(k.clone()))], |i, target, handler| { @@ -406,24 +428,44 @@ impl Interp { }) } - /// [[OwnPropertyKeys]] of a proxy (section 9.5.11). The trap must give an array-like object - /// of distinct strings, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable - /// name of the target, and of a non-extensible target exactly its names. Each name takes a - /// unit of fuel and counts against the heap limit until the caller drops the list. + /// The string names of a proxy's [[OwnPropertyKeys]] (section 9.5.11); see + /// [`Interp::proxy_own_keys_and_symbols`]. pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { + self.proxy_own_keys_and_symbols(p).map(|list| list.names) + } + + /// [[OwnPropertyKeys]] of a proxy (section 9.5.11): its string names and its Symbol keys, each + /// in the order the trap gave them. The trap must give an array-like object of distinct + /// strings and Symbols, at most [`MAX_OWN_KEYS`] of them, that holds every non-configurable + /// key of the target, and of a non-extensible target exactly its keys. Each key takes a unit + /// of fuel and counts against the heap limit until the caller drops the list. + pub(crate) fn proxy_own_keys_and_symbols(&mut self, p: ObjId) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { - let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.ecma_own_keys(target) }; + let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { return i.own_keys_and_symbols(target) }; let result = i.call_trap(&trap, handler, &[Value::Object(target)])?; - let mut held = HeldBytes::new(i); - let keys = i.trap_key_list(&result, &mut held)?; - i.check_own_keys(target, &keys)?; - Ok(HeldKeys { keys, held }) + let mark = i.temp_roots.len(); + let r = i.checked_trap_keys(target, &result); + i.temp_roots.truncate(mark); + r }) } + /// Steps 7 to 23 of section 9.5.11 for the `ownKeys` trap's `result`. Each Symbol it gives is + /// kept in the temporary roots, which the caller truncates. + fn checked_trap_keys(&mut self, target: ObjId, result: &Value) -> JsResult { + let mut held = HeldBytes::new(self); + let (keys, syms, slots) = self.trap_key_list(result, &mut held)?; + let extensible = self.is_extensible(target)?; + let target_list = self.own_keys_and_symbols(target)?; + self.temp_roots.extend(target_list.sym_values()); + self.check_own_keys(target, extensible, target_list, &keys, &syms)?; + Ok(OwnKeyList { names: HeldKeys { keys, held }, syms, slots }) + } + /// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result, refusing a value - /// that is not a string and a name given twice. - fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult> { + /// that is neither a string nor a Symbol and a key given twice. The string names and the + /// Symbol keys come back as separate lists, with each Symbol's place in the whole list. + fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult { let Value::Object(list) = result else { return Err(self.invariant("ownKeys", "returned a value that is not an object")) }; let length = self.get_from(*list, &key("length"), result)?; let n = self.to_number(&length)?; @@ -434,11 +476,28 @@ impl Interp { } let mut keys = Vec::new(); let mut seen: HashSet = HashSet::new(); + let mut syms = Vec::new(); + let mut slots = Vec::new(); + let mut seen_syms: HashSet = HashSet::new(); let mut duplicate = None; + let mut duplicate_sym = false; for index in 0..n as u32 { self.use_fuel()?; let v = self.get_from(*list, &index_key(index), result)?; - let Value::String(s) = v else { return Err(self.invariant("ownKeys", "returned a name that is not a string")) }; + let s = match v { + Value::String(s) => s, + Value::Symbol(sym) => { + self.temp_roots.push(Value::Symbol(sym.clone())); + held.add(self, 2 * KEY_ENTRY_BYTES)?; + if !seen_syms.insert(sym.addr()) { + duplicate_sym = true; + } + syms.push(sym); + slots.push(index as usize); + continue; + } + _ => return Err(self.invariant("ownKeys", "returned a key that is not a string or a Symbol")), + }; held.add(self, string_bytes(s.len()).saturating_add(2 * KEY_ENTRY_BYTES))?; let k = s.flat(); if !seen.insert(k.clone()) && duplicate.is_none() { @@ -450,45 +509,60 @@ impl Interp { let name = String::from_utf16_lossy(&k); return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice"))); } - Ok(keys) + if duplicate_sym { + return Err(self.invariant("ownKeys", "returned a Symbol key twice")); + } + Ok((keys, syms, slots)) } - /// Steps 16 to 23 of section 9.5.11: the names `keys` the trap gave against the target's. - fn check_own_keys(&mut self, target: ObjId, keys: &[Key]) -> JsResult<()> { - let extensible = self.is_extensible(target)?; - let target_keys = self.own_keys(target)?; + /// Steps 16 to 23 of section 9.5.11: reads target descriptors in key order, then checks + /// the trap's string and Symbol keys against the non-configurable and configurable keys. + fn check_own_keys(&mut self, target: ObjId, extensible: bool, target_keys: OwnKeyList, keys: &[Key], syms: &[Sym]) -> JsResult<()> { + let count = target_keys.names.len() + target_keys.syms.len(); + let (target_keys, mut held) = target_keys.into_prop_keys(); + held.add(self, count.saturating_mul(std::mem::size_of::()))?; let mut fixed = Vec::new(); let mut configurable = Vec::new(); - for k in target_keys.iter() { + for k in target_keys { self.use_fuel()?; - if self.own_property(target, k)?.is_some_and(|p| !p.configurable()) { - fixed.push(k.clone()); + if self.own_pk(target, &k)?.is_some_and(|p| !p.configurable()) { + fixed.push(k); } else { - configurable.push(k.clone()); + configurable.push(k); } } if extensible && fixed.is_empty() { return Ok(()); } let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect(); - for k in &fixed { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target"))); + let mut unchecked_syms: HashSet = syms.iter().map(Sym::addr).collect(); + for (list, non_configurable) in [(&fixed, true), (&configurable, false)] { + if !non_configurable && extensible { + return Ok(()); } - } - if extensible { - return Ok(()); - } - for k in &configurable { - if !unchecked.remove(&**k) { - let name = String::from_utf16_lossy(k); - return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target"))); + for k in list { + match k { + PropKey::Str(k) if !unchecked.remove(&**k) => { + let name = String::from_utf16_lossy(k); + let what = if non_configurable { "non-configurable property" } else { "property" }; + let target = if non_configurable { "target" } else { "non-extensible target" }; + return Err(self.invariant("ownKeys", &format!("left out the {what} '{name}' of its {target}"))); + } + PropKey::Sym(k) if !unchecked_syms.remove(&k.addr()) => { + let name = self.sym_name(k)?; + let what = if non_configurable { "non-configurable property" } else { "property" }; + return Err(self.invariant("ownKeys", &format!("left out the {what} {name} of its target"))); + } + _ => {} + } } } if !unchecked.is_empty() { return Err(self.invariant("ownKeys", "gave a name its non-extensible target does not have")); } + if !unchecked_syms.is_empty() { + return Err(self.invariant("ownKeys", "gave a Symbol key its non-extensible target does not have")); + } Ok(()) } diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index cac32535b4..22d56a6557 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -999,8 +999,7 @@ fn proxy_integrity_operations_include_the_targets_symbol_properties() { truth( "var s = Symbol('x'), p = new Proxy({}, { ownKeys: function () { return []; } }); p[s] = 1; - Object.freeze(p); - Object.isFrozen(p) && !Object.getOwnPropertyDescriptor(p, s).writable", + type_error(function () { Object.freeze(p); })", ); } @@ -1767,6 +1766,107 @@ fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { ); } +#[test] +fn own_keys_traps_may_give_symbols_and_keep_the_symbol_invariants() { + truth( + "var s = Symbol('s'), hidden = Symbol('h'), t = {}; t[hidden] = 1; + var calls = 0; + var open = new Proxy(t, { ownKeys: function () { calls++; return ['a', s]; } }); + var listed = Reflect.ownKeys(open); + var syms = Object.getOwnPropertySymbols(open); + listed.length === 2 && listed[0] === 'a' && listed[1] === s && syms.length === 1 && syms[0] === s && calls === 2", + ); + truth( + "var s = Symbol('s'); + var mixed = Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, 'a', 'b']; } })); + mixed.length === 3 && mixed[0] === s && mixed[1] === 'a' && mixed[2] === 'b'", + ); + type_errors(&[ + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return []; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [s, s]; } }))", + "var s = Symbol('s'); Reflect.ownKeys(new Proxy(Object.preventExtensions({}), { ownKeys: function () { return [s]; } }))", + "Reflect.ownKeys(new Proxy({}, { ownKeys: function () { return [1]; } }))", + ]); + truth( + "var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + Reflect.ownKeys(new Proxy(t, { ownKeys: function () { return [s]; } })).length === 1", + ); +} + +#[test] +fn own_keys_checks_target_descriptors_in_combined_key_order() { + truth( + "var s = Symbol('s'), u = Symbol('u'), t = { a: 1, b: 2 }; + t[s] = 3; t[u] = 4; + var reads = '', extensible = 0; + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a', u, 'b']; }, + isExtensible: function () { extensible++; return true; }, + getOwnPropertyDescriptor: function (t, k) { + reads += k; + Object.defineProperty(t, k === 'a' ? s : u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + var keys = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a']; } })); + keys.length === 2 && keys[0] === 'b' && keys[1] === 'a' && reads === 'ab' && extensible === 1", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + +#[test] +fn own_keys_consumers_keep_interleaved_trap_keys() { + truth( + "var s = Symbol('s'), u = Symbol('u'); + var p = new Proxy({}, { ownKeys: function () { return ['a', s, 'b', u, 'c']; } }); + var keys = Reflect.ownKeys(p); + keys.length === 5 && keys[0] === 'a' && keys[1] === s && keys[2] === 'b' && keys[3] === u && keys[4] === 'c'", + ); + truth( + "var s = Symbol('s'), t = { a: { value: 1 }, b: { value: 3 } }; + t[s] = { value: 2 }; + var order = []; + var props = new Proxy(t, { + ownKeys: function () { return ['a', s, 'b']; }, + get: function (t, k) { order.push(k); return t[k]; } + }); + var o = Object.defineProperties({}, props); + order.length === 3 && order[0] === 'a' && order[1] === s && order[2] === 'b' && o.a === 1 && o[s] === 2 && o.b === 3", + ); +} + +#[test] +fn symbol_reads_through_a_proxy_call_its_get_trap() { + truth( + "var s = Symbol('s'); var seen; + var p = new Proxy({}, { get: function (t, k, r) { seen = [k, r]; return 5; } }); + var child = Object.create(p); + p[s] === 5 && seen[0] === s && seen[1] === p && child[s] === 5 && seen[1] === child", + ); + truth( + "var s = Symbol('s'); var t = {}; t[s] = 3; + new Proxy(t, {})[s] === 3 && Object.create(new Proxy(t, {}))[s] === 3", + ); + type_errors(&["var s = Symbol('s'); var t = {}; Object.defineProperty(t, s, { value: 1 }); + new Proxy(t, { get: function () { return 2; } })[s]"]); + truth( + "var p = new Proxy({}, { get: function (t, k) { if (k === Symbol.toPrimitive) return function () { return 9; }; } }); + +p === 9", + ); +} + #[test] fn json_transparent_host_proxies_skip_indexers_but_call_get_traps() { let calls = Rc::new(RefCell::new(0)); diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index d4e451e766..91a7119038 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -148,6 +148,35 @@ pub(crate) enum PropKey { Sym(Sym), } +/// An object's own property keys from one [[OwnPropertyKeys]] call (section 9.1.11), its names +/// and its Symbol keys apart. `slots[i]` is the place of `syms[i]` in the whole list, so a +/// proxy's keys keep the order its `ownKeys` trap gave them in. +pub(crate) struct OwnKeyList { + pub(crate) names: crate::interp::HeldKeys, + pub(crate) syms: Vec, + pub(crate) slots: Vec, +} + +impl OwnKeyList { + /// The Symbol keys as values, to keep them reachable while the caller allocates. + pub(crate) fn sym_values(&self) -> Vec { + self.syms.iter().cloned().map(Value::Symbol).collect() + } + + /// Iterates over the whole list in order, with its heap charge held separately. + pub(crate) fn into_prop_keys(self) -> (impl Iterator, crate::interp::HeldBytes) { + let crate::interp::HeldKeys { keys: names, held } = self.names; + let total = names.len() + self.syms.len(); + let mut names = names.into_iter(); + let mut syms = self.syms.into_iter().zip(self.slots).peekable(); + let keys = (0..total).filter_map(move |at| match syms.next_if(|(_, slot)| *slot == at) { + Some((s, _)) => Some(PropKey::Sym(s)), + None => names.next().map(PropKey::Str), + }); + (keys, held) + } +} + /// The well-known Symbols a realm has (section 6.1.5.1): `Symbol.iterator` and the others the /// language reads, with `Symbol.asyncIterator`, which nothing reads yet. pub(crate) struct WellKnown { @@ -349,13 +378,32 @@ impl Interp { Ok(None) } - /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. + /// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter. A proxy on the + /// prototype chain handles the read with its `get` trap (section 9.5.8). Each step to a + /// prototype takes a unit of fuel. pub(crate) fn get_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult { - match self.find_sym(start, k)? { - None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), - Some(Prop::Data { value, .. }) => Ok(value), - Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), + let mut cur = Some(start); + let mut steps = 0usize; + while let Some(o) = cur { + if self.is_proxy(o) { + return self.proxy_get_sym(o, k, receiver); + } + match self.get_own_sym(o, k)? { + None => {} + Some(Prop::Accessor { get: None, .. }) => return Ok(Value::Undefined), + Some(Prop::Data { value, .. }) => return Ok(value), + Some(Prop::Accessor { get: Some(g), .. }) => return self.call(&Value::Object(g), receiver, &[]), + } + cur = self.object(o)?.proto; + if cur.is_some() { + self.use_fuel()?; + } + steps += 1; + if steps > 1_000_000 { + return Err(crate::interp::Abrupt::Internal("prototype chain too long".into())); + } } + Ok(Value::Undefined) } /// `base[k]` for any value. @@ -498,10 +546,24 @@ impl Interp { } } - /// An object's own Symbol keys in the order they were added. Each takes a unit of fuel, and - /// the heap for the list is checked first. + /// An object's own property names in the order of section 9.1.11 and its own Symbol keys, + /// listed with one [[OwnPropertyKeys]] call; for a proxy, one call of its `ownKeys` trap. + pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + if self.is_proxy(id) { + return self.proxy_own_keys_and_symbols(id); + } + let names = self.ecma_own_keys(id)?; + let syms = self.own_symbols(id)?; + let slots = (names.len()..names.len() + syms.len()).collect(); + Ok(OwnKeyList { names, syms, slots }) + } + + /// An object's own Symbol keys in the order they were added; a proxy's come from its + /// `ownKeys` trap. Each takes a unit of fuel, and the heap for the list is checked first. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { - let id = self.sym_home(id)?; + if self.is_proxy(id) { + return self.proxy_own_keys_and_symbols(id).map(|list| list.syms); + } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; for _ in 0..count { diff --git a/docs/mcp.md b/docs/mcp.md index 9b02f91101..e79cc1b818 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2908,11 +2908,16 @@ In E4X mode, a bare call resolves each scope once. An object binding still check when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without -calling proxy traps, so a proxy receiver throws `TypeError`. A Symbol property key on a proxy goes to its innermost -target without calling a trap: reads, writes, definitions, deletion and descriptor reads act on that target's -Symbol properties. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. -The `Reflect` functions take Symbol keys as well as strings. `Reflect.ownKeys` returns the string keys, then the -Symbol keys in the order they were added; a proxy's Symbol keys are its innermost target's. Ordinary targets list +calling proxy traps, so a proxy receiver throws `TypeError`. A read of a Symbol property key through a proxy, on +the proxy itself or on an object that has it as a prototype, calls the proxy's `get` trap with the Symbol and the +receiver, and reads from the target when the handler has no `get` trap. Other operations with a Symbol key on a proxy +go to its innermost target without calling a trap: writes, definitions, deletion and descriptor reads act on that +target's Symbol properties. An `ownKeys` trap may return Symbol keys as well as strings; a Symbol key given twice, a +non-configurable Symbol key of the target left out, and for a non-extensible target any of its Symbol keys left out +or one it lacks throw `TypeError`. Symbol property operations and symbol enumeration on a revoked proxy throw `TypeError`. +The `Reflect` functions take Symbol keys as well as strings. For ordinary objects, `Reflect.ownKeys` returns the string keys, +then the Symbol keys in the order they were added. A proxy's keys come from one call of its `ownKeys` trap and keep +the trap's order, including Symbol keys. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines the order of its string keys. A `for-in` prototype walk keeps the current proxy reachable through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index da3ad29e7d..0f98b4fdb1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1195,7 +1195,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. - `Options::es2015` also reads and runs two ECMAScript 2020 forms (https://262.ecma-international.org/11.0/): optional chains (`a?.b`, `a?.[key]`, `f?.(args)` and the accesses and calls after them), which evaluate their base once and give `undefined` without evaluating the rest of the chain when a value before `?.` is `undefined` or `null`, keep the object as `this` for `a?.b()` and `a.b?.()`, make `eval?.(code)` an indirect eval and make `delete a?.b` true when `a` is `undefined` or `null`; and `??`, which keeps any left side other than `undefined` and `null`. `?.` before a digit reads as `?` and a number (`a?.5:1`). Mixing `??` with `&&` or `||` without parentheses, assigning to or updating an optional chain, a tagged template after one and `new a?.b()` are syntax errors. A skipped part of a chain takes no fuel, and a chain of any length compiles without recursion. Using the ECMAScript 2015 option for them, so `.js` files read them and `.jsx` files and `source` strings do not, is VectorCraft's own rule. With the suite's `expressions/optional-chaining` and `expressions/coalesce` tests that need only the forms above, `cargo xtask test262` reads 426 of 426 negative parse runs and 591 of 782 other runs as passing with the option (409 and 27 without it). Of the 191 failing runs, 175 are those the entry above names, and 16 do not parse because the tests also use method definitions, classes, `for`-`of` or `new.target`. Tests: `crates/js/src/es2020_tests.rs`, `crates/js/tests/test262.rs`. - - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key on a proxy goes to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string property names for traps; a Symbol key read through a proxy calls its `get` trap, an `ownKeys` trap may return Symbol keys, and other Symbol-key operations on a proxy go to its innermost target without a trap. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string or a Symbol), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. When an earlier run made the global object non-extensible, the engine adds neither global and its ECMAScript 2015 runs go on without them. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module by default; `module: false` runs it as a script. Any script run with `module: true` runs as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. An object of a host class with an indexer, such as a script collection of the document's objects, is always visited index by index. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.