diff --git a/crates/js/src/builtins/array.rs b/crates/js/src/builtins/array.rs index ac8dd4639c..0f45f1cb50 100644 --- a/crates/js/src/builtins/array.rs +++ b/crates/js/src/builtins/array.rs @@ -389,8 +389,15 @@ fn concat(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult let mut n = 0u64; for e in std::iter::once(Value::Object(o)).chain(args.iter().cloned()) { interp.use_fuel()?; - // A proxy whose target is an array is spread too (ECMA-262 2020 section 22.1.3.1.1). - let spread = if interp.is_array(&e)? { e.as_object() } else { None }; + // Code run without the ECMAScript 2015 option reads no such Symbol, even in a realm + // that has it from an earlier run. + let spreadable = if interp.options.es2015 { interp.well_known(|w| &w.is_concat_spreadable) } else { None }; + let override_spread = match (e.as_object(), spreadable) { + (Some(_), Some(sym)) => interp.get_value_sym(&e, &sym)?, + _ => Value::Undefined, + }; + let spread = if matches!(override_spread, Value::Undefined) { interp.is_array(&e)? } else { override_spread.truthy() }; + let spread = if spread { e.as_object() } else { None }; let Some(e) = spread else { if n >= 9_007_199_254_740_991 { return Err(interp.type_error("concat exceeds the maximum safe length")); diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 5a48799007..16c6a6a160 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -824,6 +824,23 @@ fn ctor_elem(interp: &mut Interp, this: &Value, name: &str) -> JsResult { Err(interp.type_error(&format!("TypedArray.{name} must be called on a typed array constructor"))) } +fn typed_create(interp: &mut Interp, this: &Value, len: u64, name: &str) -> JsResult { + if !this.as_object().is_some_and(|o| interp.is_proxy(o)) { + let elem = ctor_elem(interp, this, name)?; + return new_typed(interp, elem, len); + } + #[allow(clippy::cast_precision_loss)] + let result = interp.construct_value(this, &[Value::Number(len as f64)], this)?; + interp.rooted(std::slice::from_ref(&result), |interp| { + let Some(o) = result.as_object() else { return Err(interp.type_error("the constructor did not return a typed array")) }; + let Some(view) = view_of(interp, o) else { return Err(interp.type_error("the constructor did not return a typed array")) }; + if (view.length as u64) < len { + return Err(interp.type_error(&format!("TypedArray.{name} constructor returned a typed array that is too short"))); + } + Ok(o) + }) +} + /// `%TypedArray%.from(source, mapFn, thisArg)` (section 22.2.2.1). fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { if !interp.is_constructor(&this) { @@ -836,16 +853,15 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe } let this_arg = arg(args, 2); let map = mapping.then_some((&map_fn, &this_arg)); - typed_array_from(interp, &arg(args, 0), map, |interp, len| { - let elem = ctor_elem(interp, &this, "from")?; - new_typed(interp, elem, len) - }) + typed_array_from(interp, &arg(args, 0), map, |interp, len| typed_create(interp, &this, len, "from")) } /// `%TypedArray%.of(...items)` (section 22.2.2.2). fn typed_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let elem = ctor_elem(interp, &this, "of")?; - let ta = new_typed(interp, elem, args.len() as u64)?; + if !interp.is_constructor(&this) { + return Err(interp.type_error("TypedArray.of must be called on a typed array constructor")); + } + let ta = typed_create(interp, &this, args.len() as u64, "of")?; let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; interp.rooted(&[Value::Object(ta)], |interp| { for (i, v) in args.iter().enumerate() { diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index a6d8babc9e..e5027df1c6 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -414,6 +414,7 @@ fn revive(interp: &mut Interp, v: Value, reviver: &Value) -> JsResult { struct Settings { replacer: Option, properties: Option>, + _held_properties: Option, gap: Vec, } @@ -474,12 +475,14 @@ fn stringify_rooted(interp: &mut Interp, args: &[Value]) -> JsResult { /// Reads the replacer and the space argument (section 15.12.3, steps 4 to 8). fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult { - let mut s = Settings { replacer: None, properties: None, gap: Vec::new() }; + let mut s = Settings { replacer: None, properties: None, _held_properties: None, gap: Vec::new() }; if let Value::Object(r) = replacer { if interp.is_callable(replacer) { s.replacer = Some(replacer.clone()); } else if interp.is_array(replacer)? { - s.properties = Some(property_list(interp, *r)?); + let (keys, held) = property_list(interp, *r)?; + s.properties = Some(keys); + s._held_properties = Some(held); } } let space = unwrap_primitive(interp, space, false)?.unwrap_or_else(|| space.clone()); @@ -495,12 +498,13 @@ fn settings(interp: &mut Interp, replacer: &Value, space: &Value) -> JsResult JsResult> { +/// Each name kept is charged to the heap for as long as the returned holder lives. +fn property_list(interp: &mut Interp, r: ObjId) -> JsResult<(Vec, crate::interp::HeldBytes)> { let len = super::collections::length_of(interp, r)?; if len > interp.fuel { return Err(crate::interp::Abrupt::Limit(crate::LimitKind::Fuel)); } - interp.reserve_heap(usize::try_from(len).unwrap_or(usize::MAX).saturating_mul(ELEMENT_BYTES))?; + let mut held = crate::interp::HeldBytes::new(interp); let mut list: Vec = Vec::new(); let mut seen = HashSet::new(); for i in 0..len { @@ -529,10 +533,11 @@ fn property_list(interp: &mut Interp, r: ObjId) -> JsResult> { } // The list lives until the call returns, so its names are rooted. interp.temp_roots.push(Value::String(s)); + held.add(interp, ELEMENT_BYTES)?; list.push(k); } } - Ok(list) + Ok((list, held)) } /// Steps 1 to 4 and 10 of Str (section 15.12.3): reads `holder[key]`, applies `toJSON` and the diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index 0bbccebb1c..e020e6335b 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -18,6 +18,8 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> { ("hasInstance", well_known.has_instance.clone()), ("toPrimitive", well_known.to_primitive.clone()), ("toStringTag", well_known.to_string_tag.clone()), + ("unscopables", well_known.unscopables.clone()), + ("isConcatSpreadable", well_known.is_concat_spreadable.clone()), ]; let (to_string_tag, to_primitive, has_instance) = (well_known.to_string_tag.clone(), well_known.to_primitive.clone(), well_known.has_instance.clone()); @@ -171,7 +173,7 @@ fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bo interp.rooted(&[Value::Object(o)], |interp| { // A proxy's list stays counted against the heap until the array holds its Symbols. let (syms, _held) = if interp.is_proxy(o) { - let keys = interp.proxy_own_keys(o)?; + let keys = interp.proxy_own_keys(o, false)?; (keys.syms, keys.held) } else { let syms = interp.own_symbols(o)?; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 20640cc00d..2b7915c9b9 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1620,7 +1620,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return Ok(Resolved::Obj { object, with_this }); } cur = outer; @@ -1631,6 +1631,23 @@ impl Interp { Ok(Resolved::Unresolved) } + fn scope_binding(&mut self, object: ObjId, name: &Key, with_this: bool) -> JsResult { + if !self.scope_has(object, name)? { + return Ok(false); + } + if with_this + && self.options.es2015 + && let Some(sym) = self.well_known(|w| &w.unscopables) + { + let blocked = self.get_value_sym(&Value::Object(object), &sym)?; + if let Value::Object(o) = blocked { + let value = self.rooted(&[Value::Object(o)], |i| i.get_from(o, name, &Value::Object(o)))?; + return Ok(!value.truthy()); + } + } + Ok(true) + } + pub(crate) fn binding_value(&self, env: EnvId, name: &[u16]) -> JsResult { match self.heap.env(env) { Some(Env::Decl { bindings, .. }) => Ok(bindings.get(name).map_or(Value::Undefined, |b| b.value.clone())), @@ -1674,7 +1691,7 @@ impl Interp { cur = *outer; } Some(&Env::Obj { object, with_this, outer }) => { - if self.scope_has(object, name)? { + if self.scope_binding(object, name, with_this)? { return self.get_resolved(Resolved::Obj { object, with_this }, name); } let this = Value::Object(object); @@ -2390,7 +2407,7 @@ impl Interp { /// list is checked first. A proxy's names come from its `ownKeys` trap. pub(crate) fn own_keys(&mut self, id: ObjId) -> JsResult { if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, false); } let o = self.object(id)?; // A typed array's indices come first, as a String object's do (section 9.4.5.6). @@ -2423,14 +2440,15 @@ impl Interp { } pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult { - let mut keys = self.own_keys(id)?; - if !self.is_proxy(id) { - if matches!(self.object(id)?.class, Class::Array { .. }) { - let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; - keys.insert(0, length); - } - keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); + if self.is_proxy(id) { + return self.proxy_own_keys(id, true); } + let mut keys = self.own_keys(id)?; + if matches!(self.object(id)?.class, Class::Array { .. }) { + let length = keys.pop().ok_or_else(|| Abrupt::Internal("array has no length key".into()))?; + keys.insert(0, length); + } + keys.sort_by_key(|k| array_index(k).map_or((1, 0), |n| (0, n))); Ok(keys) } diff --git a/crates/js/src/proxy.rs b/crates/js/src/proxy.rs index fcb103b50c..b9bf04e87a 100644 --- a/crates/js/src/proxy.rs +++ b/crates/js/src/proxy.rs @@ -421,11 +421,11 @@ impl Interp { /// non-configurable key of the target, and of a non-extensible target exactly its keys. Each /// key takes a unit of fuel and counts against the heap limit until the caller drops the list, /// which keeps the trap's order in [`HeldKeys::ordered`]. - pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult { + pub(crate) fn proxy_own_keys(&mut self, p: ObjId, ecma_order: bool) -> JsResult { self.proxy_op(p, "list the properties of", &[], |i, target, handler| { let Some(trap) = i.proxy_trap(handler, "ownKeys")? else { // A target that is a proxy gives its Symbols with its names. - let mut keys = i.ecma_own_keys(target)?; + let mut keys = if ecma_order { i.ecma_own_keys(target)? } else { i.own_keys(target)? }; if !i.is_proxy(target) { keys.syms = i.own_symbols(target)?; keys.held.add(i, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; @@ -441,12 +441,15 @@ impl Interp { } /// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]: - /// one `ownKeys` trap call for a proxy. + /// one `ownKeys` trap call for a proxy. With [`crate::Options::es2015`] the names come in + /// ECMAScript order (array indices ascending first), through proxies without an `ownKeys` + /// trap too; without it they come in the order `for-in` visits them. pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult { + let ecma_order = self.options.es2015; if self.is_proxy(id) { - return self.proxy_own_keys(id); + return self.proxy_own_keys(id, ecma_order); } - let mut keys = self.own_keys(id)?; + let mut keys = if ecma_order { self.ecma_own_keys(id)? } else { self.own_keys(id)? }; keys.syms = self.own_symbols(id)?; keys.held.add(self, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?; Ok(keys) diff --git a/crates/js/src/proxy_tests.rs b/crates/js/src/proxy_tests.rs index 9f42ac53e5..aa64eb6b8e 100644 --- a/crates/js/src/proxy_tests.rs +++ b/crates/js/src/proxy_tests.rs @@ -626,6 +626,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( @@ -707,6 +744,184 @@ fn a_descriptor_a_trap_makes_stays_reachable_while_it_is_read() { // ---- proxies elsewhere in the language ---- +#[test] +fn proxy_with_bindings_honor_unscopables() { + truth_collecting( + "var x = 'outer', result, log = [], scope, blocked; + var p = new Proxy({ x: 'inner' }, { + has: function (t, k) { if (k === 'x') log.push('has'); return Reflect.has(t, k); }, + get: function (t, k, r) { + if (k === Symbol.unscopables) { + scope = r; + return new Proxy({ x: true }, { get: function (t, k, r) { + log.push(k); blocked = r; return t[k]; + } }); + } + throw 'unexpected binding read'; + } + }); + with (p) { result = x; } + result === 'outer' && scope === p && typeof blocked === 'object' && log.join() === 'has,x'", + ); + for blocked in ["undefined", "null", "false", "1", "{}", "{ x: false }"] { + truth(&format!( + "var x = 'outer', result, t = {{ x: 'inner' }}; + t[Symbol.unscopables] = {blocked}; + with (new Proxy(t, {{}})) {{ result = x; }} + result === 'inner'" + )); + } + truth( + "var x = 'outer', kind, result, t = { x: 'inner' }; + t[Symbol.unscopables] = { x: true }; + with (new Proxy(t, {})) { x = 'changed'; kind = typeof x; result = delete x; } + x === 'changed' && t.x === 'inner' && kind === 'string' && result === false", + ); + for trap in ["return new Proxy({}, { get: function () { throw marker; } });", "throw marker;"] { + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy({{ x: 1 }}, {{ get: function (t, k) {{ + if (k === Symbol.unscopables) {{ {trap} }} return t[k]; + }} }}); + try {{ with (p) {{ x; }} }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); + assert_eq!( + realm.run( + "function method() { return 'outer'; } + var t = { method: function () { return 'inner'; } }, result; + t[Symbol.unscopables] = { method: true }; + with (new Proxy(t, {})) { result = method(); } + result === 'outer'" + ), + Ok(JsValue::Bool(true)) + ); +} + +#[test] +fn transparent_proxies_preserve_object_key_order() { + truth_collecting( + "var o = { z: 0, 10: 10, 2: 2, a: 1 }, a = [1, 2]; a.label = 'a'; + [o, a].every(function (target) { + var p = new Proxy(new Proxy(target, {}), {}); + return Object.keys(p).join() === Object.keys(target).join() && + Object.getOwnPropertyNames(p).join() === Object.getOwnPropertyNames(target).join() && + Reflect.ownKeys(p).join() === Reflect.ownKeys(target).join(); + })", + ); + truth( + "var calls = 0, p = new Proxy({ a: 1, b: 2 }, { ownKeys: function () { calls++; return ['b', 'a']; } }); + var q = new Proxy(p, {}); + Object.keys(q).join() === 'b,a' && Object.getOwnPropertyNames(q).join() === 'b,a' && + Reflect.ownKeys(q).join() === 'b,a' && calls === 3", + ); +} + +#[test] +fn concat_honors_proxy_spreadability_overrides() { + truth_collecting( + "var reads = 0, receiver, p = new Proxy([1, 2], { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads++; receiver = r; return false; } + return Reflect.get(t, k, r); + } }); + var a = [].concat(p), b = p.concat(3); + a.length === 1 && a[0] === p && b.length === 2 && b[0] === p && b[1] === 3 && reads === 2 && receiver === p", + ); + truth_collecting( + "var reads = [], receiver; + var p = new Proxy({ 0: 'a', 2: 'c', length: 3 }, { get: function (t, k, r) { + if (k === Symbol.isConcatSpreadable) { reads.push('spread'); receiver = r; return true; } + reads.push(k); return Reflect.get(t, k, r); + } }); + var a = [].concat(p); + a.length === 3 && a[0] === 'a' && !(1 in a) && a[2] === 'c' && receiver === p && reads.join() === 'spread,length,0,2'", + ); + truth( + "var p = new Proxy([1, 2], {}), t = [3, 4]; t[Symbol.isConcatSpreadable] = null; + var q = new Proxy(t, {}), a = [].concat(p, q); + a.length === 3 && a[0] === 1 && a[1] === 2 && a[2] === q", + ); + truth( + "var marker = {}, caught = false; + var p = new Proxy([], { get: function (t, k) { if (k === Symbol.isConcatSpreadable) throw marker; return t[k]; } }); + try { [].concat(p); } catch (e) { caught = e === marker; } + caught", + ); + type_errors(&["var p = Proxy.revocable([], {}); p.revoke(); [].concat(p.proxy)"]); +} + +#[test] +fn spreadability_and_unscopables_kept_from_an_earlier_run_apply_only_with_the_option() { + let mut realm = es(); + let setup = "var a = [1, 2]; a[Symbol.isConcatSpreadable] = false; + var o = { x: 'own' }; o[Symbol.unscopables] = { x: true }; var x = 'outer'; true"; + assert_eq!(realm.run(setup), Ok(JsValue::Bool(true))); + realm.set_es2015(false); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 2 && c[0] === 1 && w === 'own'"), Ok(JsValue::Bool(true))); + realm.set_es2015(true); + assert_eq!(realm.run("var c = [].concat(a), w; with (o) { w = x; } c.length === 1 && c[0] === a && w === 'outer'"), Ok(JsValue::Bool(true))); +} + +#[test] +fn define_properties_defines_array_index_keys_in_ascending_order() { + truth( + "var log = [], bag = {}; bag.b = { value: 0 }; bag[2] = { value: 2 }; bag[1] = { value: 1 }; + var p = new Proxy({}, { defineProperty: function (t, k, d) { log.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(p, bag); + var wrapped = [], q = new Proxy({}, { defineProperty: function (t, k, d) { wrapped.push(k); return Reflect.defineProperty(t, k, d); } }); + Object.defineProperties(q, new Proxy(bag, {})); + log.join() === '1,2,b' && wrapped.join() === '1,2,b'", + ); + // Without the option, descriptors are read in the order for-in visits the names. + let mut realm = Realm::new(); + let src = "var order = [], bag = {}; bag.b = 0; bag[2] = 0; bag[1] = 0; + var seen = [], descs = {}; + for (var k in bag) { order.push(k); (function (k) { Object.defineProperty(descs, k, { enumerable: true, get: function () { seen.push(k); return { value: 0 }; } }); })(k); } + Object.defineProperties({}, descs); + seen.join() === order.join()"; + assert_eq!(realm.run(src), Ok(JsValue::Bool(true))); +} + +#[test] +fn typed_array_statics_construct_through_proxy_receivers() { + truth_collecting( + "var p = new Proxy(Uint8Array, {}), a = p.of(257, 2), b = p.from([3, 260]); + a instanceof Uint8Array && a.length === 2 && a[0] === 1 && a[1] === 2 && + b instanceof Uint8Array && b.length === 2 && b[0] === 3 && b[1] === 4", + ); + truth_collecting( + "var calls = [], receiver, context = { add: 1 }; + var p = new Proxy(Uint8Array, { construct: function (t, args, nt) { + calls.push(t === Uint8Array, args.length, args[0], nt === p); + return new Uint16Array(args[0]); + } }); + var a = p.of(257, 2), b = p.from({ 0: 300, length: 1 }, function (v, i) { receiver = this; return v + i + this.add; }, context); + a instanceof Uint16Array && a[0] === 257 && a[1] === 2 && b instanceof Uint16Array && b[0] === 301 && + receiver === context && calls.join() === 'true,1,2,true,true,1,1,true'", + ); + for method in ["of(1, 2)", "from([1, 2])"] { + for result in ["{}", "new Uint8Array(1)", "new Proxy(new Uint8Array(2), {})"] { + truth(&format!( + "var p = new Proxy(Uint8Array, {{ construct: function () {{ return {result}; }} }}); + type_error(function () {{ p.{method}; }})" + )); + } + truth(&format!( + "var marker = {{}}, caught = false; + var p = new Proxy(Uint8Array, {{ construct: function () {{ throw marker; }} }}); + try {{ p.{method}; }} catch (e) {{ caught = e === marker; }} + caught" + )); + } + truth( + "var pair = Proxy.revocable(Uint8Array, {}), p = pair.proxy; + pair.revoke(); + type_error(function () { Uint8Array.of.call(p, 1); }) && type_error(function () { Uint8Array.from.call(p, [1]); })", + ); +} + #[test] fn a_proxy_works_as_a_prototype_and_a_with_scope() { truth( @@ -732,21 +947,27 @@ fn a_proxy_works_as_a_prototype_and_a_with_scope() { fn typeof_reads_the_binding_a_with_scope_reported_once() { // GetBindingValue asks `has` again, and a binding gone by then reads as undefined without `get`. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return k === 'x' ? function () {} : undefined; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return k === 'x' ? function () {} : undefined; + } }); var r; with (p) { r = typeof x; } - r === 'undefined' && asked === 2 && got === 0", + r === 'undefined' && asked === 2 && got === 0 && unscopables === 1", ); // A plain read of the same binding takes the same path. truth( - "var asked = 0, got = 0; + "var asked = 0, got = 0, unscopables = 0; var p = new Proxy({}, { has: function (t, k) { return k === 'x' && asked++ === 0; }, - get: function (t, k) { got++; return 1; } }); + get: function (t, k) { + if (k === Symbol.unscopables) { unscopables++; return undefined; } + got++; return 1; + } }); var r; with (p) { r = x; } - r === undefined && asked === 2 && got === 0", + r === undefined && asked === 2 && got === 0 && unscopables === 1", ); } @@ -755,15 +976,19 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { for present in ["asked++ < 2", "asked++ === 0", "false"] { let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()); let src = format!( - "var asked = 0, got = 0, outer = 0, receiver; + "var asked = 0, got = 0, outer = 0, unscopables = 0, receiver; function method() {{ outer++; return 'outer'; }} var p = new Proxy({{}}, {{ has: function (t, k) {{ return k === 'method' && ({present}); }}, - get: function () {{ got++; return function () {{ receiver = this; return 'proxy'; }}; }} + get: function (t, k) {{ + if (k === Symbol.unscopables) {{ unscopables++; return undefined; }} + got++; return function () {{ receiver = this; return 'proxy'; }}; + }} }}); var result, caught = false; try {{ with (p) {{ result = method(); }} }} catch (e) {{ caught = e instanceof TypeError; }} - {expected}", + ({expected}) && unscopables === {unscopables}", + unscopables = usize::from(present != "false"), expected = match present { "asked++ < 2" => "result === 'proxy' && receiver === p && asked === 2 && got === 1 && outer === 0 && !caught", "asked++ === 0" => "caught && asked === 2 && got === 0 && outer === 0", @@ -779,16 +1004,21 @@ fn e4x_bare_calls_resolve_proxy_scopes_once() { #[test] fn concat_proxy_array_lengths_use_to_length() { truth( - "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0; + "var lengths = [-1, -Infinity, NaN, -0, 0.9], reads = 0, spreadReads = 0; var empty = lengths.every(function (length) { var p = new Proxy([7], { - get: function (t, k) { if (k === 'length') return length; reads++; return t[k]; }, + get: function (t, k) { + if (k === Symbol.isConcatSpreadable) { spreadReads++; return undefined; } + if (k === 'length') return length; + reads++; return t[k]; + }, has: function () { reads++; return true; } }); return [3].concat(new Proxy(p, {}), 9).join() === '3,9'; }); var p = new Proxy([7, 8], { get: function (t, k) { return k === 'length' ? '1.9' : t[k]; } }); - empty && reads === 0 && [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", + empty && reads === 0 && spreadReads === lengths.length && + [].concat(p).join() === '7' && Array.prototype.concat.call(p, 9).join() === '7,9'", ); } @@ -818,7 +1048,11 @@ fn concat_and_reviver_proxy_lengths_check_limits_before_reading_elements() { for length in ["4294967296", "Infinity"] { let setup = format!( "var p = new Proxy([], {{ - get: function (t, k) {{ if (k === 'length') return {length}; throw new Error('element read'); }}, + get: function (t, k) {{ + if (k === Symbol.isConcatSpreadable) return undefined; + if (k === 'length') return {length}; + throw new Error('element read'); + }}, has: function () {{ throw new Error('element checked'); }} }});" ); @@ -1129,6 +1363,23 @@ fn a_typed_array_receiver_converts_the_value_for_an_index_it_lacks() { ); } +#[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 }); + })", + ); +} + fn namespace_script(source: &str) -> Realm { let mut realm = es(); assert!(realm.run("var out = false;").is_ok()); @@ -1308,12 +1559,23 @@ fn a_host_function_refuses_a_proxy_and_names_the_argument() { } } assert!(seen.borrow().is_empty(), "the host function did not run"); - // The traps did not run either. + // The same argument with a trap is refused too, before the host function or the trap runs. let mut realm = es(); - let f: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + let calls = Rc::new(RefCell::new(0usize)); + let counter = calls.clone(); + let f: HostFunction = Rc::new(move |_| { + *counter.borrow_mut() += 1; + Ok(Data::Undefined) + }); realm.define_host_object("host", vec![("take".into(), HostItem::Function(f))]).unwrap(); - let r = realm.run("var ran = false; try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } catch (e) {} ran"); - assert_eq!(r, Ok(JsValue::Bool(false))); + let r = realm.run( + "var ran = false, threw = false; + try { host.take(new Proxy({}, { ownKeys: function () { ran = true; return []; } })); } + catch (e) { threw = e instanceof TypeError; } + threw && !ran", + ); + assert_eq!(r, Ok(JsValue::Bool(true))); + assert_eq!(*calls.borrow(), 0, "the host function did not run"); } #[test] @@ -1703,6 +1965,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| { @@ -2107,6 +2382,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"] { @@ -2132,13 +2415,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 @@ -2148,17 +2437,123 @@ fn json_proxy_lengths_check_limits_before_reading_elements() { #[test] fn transparent_proxies_construct_bound_builtins_without_allowing_subclasses() { truth( - "var B = Map.bind(null, [[1, 7]]), P = new Proxy(B, {}), Q = new Proxy(P, {}); + "var B = Map.bind(null, [[1, 7]]), proto = Object.create(Map.prototype); + Object.defineProperty(B, 'prototype', { value: proto }); + var P = new Proxy(B, {}), Q = new Proxy(P, {}); var a = new P(), b = new Q(), c = Reflect.construct(Q, []); var R = new Proxy(Q.bind(null), {}), d = new R(); var U = new Proxy(Uint8Array.bind(null, [7, 8]), {}), u = new U(); - Object.defineProperty(B, 'prototype', { value: Map.prototype }); a.get(1) === 7 && b.get(1) === 7 && c.get(1) === 7 && d.get(1) === 7 && - Object.getPrototypeOf(a) === Map.prototype && u.length === 2 && u[1] === 8 && + Object.getPrototypeOf(a) === proto && Object.getPrototypeOf(b) === proto && Object.getPrototypeOf(c) === proto && + Object.getPrototypeOf(d) === Map.prototype && u.length === 2 && u[1] === 8 && type_error(function () { class Child extends P {} new Child(); })", ); } +#[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.push(String(k)); + if (k === s) Object.defineProperty(t, u, { configurable: false }); + return Object.getOwnPropertyDescriptor(t, k); + } + }); + // The descriptor of `s`, read first, makes `u` non-configurable before `u` is read, so the + // outer trap that leaves `u` out breaks the invariant. + var threw = type_error(function () { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', 'a', s]; } })); }); + var ok = Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return ['b', u, 'a']; } })); + threw && reads.slice(0, 4).join() === 'Symbol(s),a,Symbol(u),b' && extensible === 2 && ok.length === 3", + ); + truth( + "var s = Symbol('s'), t = { a: 1 }, marker = {}; + Object.defineProperty(t, s, { value: 2 }); + var target = new Proxy(t, { + ownKeys: function () { return [s, 'a']; }, + getOwnPropertyDescriptor: function () { throw marker; } + }); + var caught; + try { Reflect.ownKeys(new Proxy(target, { ownKeys: function () { return []; } })); } + catch (e) { caught = e; } + caught === marker", + ); +} + +#[test] +fn own_keys_consumers_keep_interleaved_trap_keys() { + truth( + "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/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 7ebcacbbc2..5c083d7acd 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -157,7 +157,9 @@ pub(crate) struct WellKnown { pub(crate) has_instance: Sym, pub(crate) to_primitive: Sym, pub(crate) to_string_tag: Sym, - /// The five as values, for the collector. + pub(crate) unscopables: Sym, + pub(crate) is_concat_spreadable: Sym, + /// The Symbols as values, for the collector. values: Vec, } @@ -171,8 +173,14 @@ impl WellKnown { make("Symbol.toPrimitive"), make("Symbol.toStringTag"), ); - let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag].into_iter().cloned().map(Value::Symbol).collect(); - WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, values } + let unscopables = make("Symbol.unscopables"); + let is_concat_spreadable = make("Symbol.isConcatSpreadable"); + let values = [&iterator, &async_iterator, &has_instance, &to_primitive, &to_string_tag, &unscopables, &is_concat_spreadable] + .into_iter() + .cloned() + .map(Value::Symbol) + .collect(); + WellKnown { iterator, async_iterator, has_instance, to_primitive, to_string_tag, unscopables, is_concat_spreadable, values } } } @@ -543,7 +551,7 @@ impl Interp { /// the heap for the list is checked first. A proxy's Symbols come from its `ownKeys` trap. pub(crate) fn own_symbols(&mut self, id: ObjId) -> JsResult> { if self.is_proxy(id) { - return Ok(self.proxy_own_keys(id)?.syms); + return Ok(self.proxy_own_keys(id, false)?.syms); } let count = self.object(id)?.syms.as_ref().map_or(0, |m| m.len()); self.reserve_heap(count.saturating_mul(16))?; diff --git a/docs/mcp.md b/docs/mcp.md index bff228ca3a..5be2ab3749 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2882,6 +2882,8 @@ Existing globals with either name are preserved. If a missing global cannot be a is nonextensible, sealed or frozen, the run fails with an installation error before the script executes. An empty-handler proxy forwards construction of built-ins, including bound built-ins such as `Map.bind(null)` and bound typed-array constructors, and reads the proxy's `prototype` for the constructed object. +Typed-array `from` and `of` accept proxy constructors and run their `construct` traps. +A proxy constructor must return a typed array with at least the requested length; otherwise the method throws `TypeError`. `Reflect.construct` also accepts a distinct constructor as `newTarget` for `Map`, `Set`, `WeakMap`, `WeakSet` and typed arrays and uses its `prototype` for the new object. `Map`, `Set`, `WeakMap` and `WeakSet` initialize iterable arguments through the requested prototype's @@ -2902,20 +2904,25 @@ 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 walking indices or allocating traversal keys. `concat` throws `TypeError` if the combined length exceeds the maximum safe integer. Reviver traversal keys count against the heap limit until their traversal frame is dropped. +`concat` reads `Symbol.isConcatSpreadable` through proxy `get` traps. A defined value controls whether the object +is spread; an undefined value uses the array check. In E4X mode, a bare call resolves each scope once. An object binding still checks property membership again when reading its value; a binding removed between those checks does not select an outer function. The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating -its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations +its properties or calling descriptor traps. Its `find` method reads a receiver's own properties without +calling proxy traps, so a proxy receiver throws `TypeError`. Symbol property reads, writes, deletion, descriptor operations and symbol enumeration on a revoked proxy also throw `TypeError`. A Symbol key on a proxy goes through the same traps as a string key (`get`, `set`, `has`, `deleteProperty`, `defineProperty` and `getOwnPropertyDescriptor`), which receive the Symbol itself; without a trap the operation reaches the target. `Reflect`'s functions take Symbol keys too. +`Object.keys` and `Object.getOwnPropertyNames` keep the target's key order through empty-handler proxies. For an ordinary object, `Reflect.ownKeys` returns the string keys, then the Symbols in insertion order. Ordinary targets list array-index keys in ascending order, then other strings in insertion order; an array's `length` precedes its other non-index strings. A proxy's `ownKeys` trap determines its key order, with strings and Symbols mixed as the @@ -2930,6 +2937,9 @@ names are rejected; a later getter's exception takes precedence over the duplica Deleting a binding in a `with` scope calls the proxy's `deleteProperty` trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay reachable during proxy callbacks, including callbacks that revoke a nested target proxy. +A `with` scope checks `Symbol.unscopables` after finding a property. If that lookup returns an object whose +property for the binding name is truthy, resolution continues in the outer scope. Each read calls a proxy's `get` trap +when its receiver is a proxy. `Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype without creating a property on the receiver; when that typed array is the receiver, the value is converted to a number first. `Object.freeze`, `Object.seal`, `Object.isFrozen` and `Object.isSealed` include a proxy's Symbol