mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Scripts: proxies take Symbol keys through their traps
A Symbol key on a proxy read, wrote, tested, deleted and described the proxy's own Symbol table, so the target never saw it and no trap ran. Every Symbol path now resolves a proxy the way a string key does: the get, set, has, deleteProperty, defineProperty and getOwnPropertyDescriptor traps receive the Symbol, and without a trap the operation reaches the target with its writable and accessor checks. A super write and a write on a primitive that reach a proxy go through its [[Set]]. - ownKeys traps may return Symbols; a duplicate Symbol (by identity) or any other value is a TypeError, and the result is checked against the target's non-configurable and, for a non-extensible target, all keys of both kinds, in the target's own key order. - Reflect.ownKeys lists Symbols, in the trap's order for a proxy, and Reflect's other functions take Symbol keys. Object.freeze, seal, isFrozen and isSealed include a proxy's Symbols instead of throwing. - Symbol key lists stay rooted and charged to the heap until released. - new Proxy and Proxy.revocable reject a revoked target or handler. - A typed array reached on the prototype chain as the receiver converts the value for an index it lacks. - The eval redeclaration test asserts the runtime SyntaxError.
This commit is contained in:
1 parent
3ce03dbf6e
commit
fd50e7dba1
13 files changed
+724
-217
No files matched your search
@@ -355,7 +355,7 @@ fn enter(interp: &mut Interp, holder: ObjId, name: Key) -> JsResult<Walk> {
|
||||
keys.push(key_of(i as f64));
|
||||
}
|
||||
} else {
|
||||
let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?;
|
||||
let crate::interp::HeldKeys { keys: names, held, .. } = interp.own_keys(o)?;
|
||||
held_keys = Some(held);
|
||||
for k in names {
|
||||
if interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()) {
|
||||
@@ -671,7 +671,7 @@ fn open(interp: &mut Interp, settings: &Settings, w: &mut Writer, o: ObjId) -> J
|
||||
} else if let Some(list) = &settings.properties {
|
||||
list.clone()
|
||||
} else {
|
||||
let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?;
|
||||
let crate::interp::HeldKeys { keys: names, held, .. } = interp.own_keys(o)?;
|
||||
held_keys = Some(held);
|
||||
let mut keys = Vec::new();
|
||||
for k in names {
|
||||
|
||||
@@ -153,10 +153,17 @@ pub(crate) fn names_array(interp: &mut Interp, names: impl IntoIterator<Item = K
|
||||
/// The object's own property keys: its names, then its Symbols (ECMA-262 11th edition, section
|
||||
/// 9.1.11).
|
||||
fn own_prop_keys(interp: &mut Interp, o: ObjId) -> JsResult<(Vec<PropKey>, crate::interp::HeldBytes)> {
|
||||
let crate::interp::HeldKeys { keys: names, held } = interp.own_keys(o)?;
|
||||
let mut keys: Vec<PropKey> = names.into_iter().map(PropKey::Str).collect();
|
||||
keys.extend(interp.own_symbols(o)?.into_iter().map(PropKey::Sym));
|
||||
Ok((keys, held))
|
||||
Ok(interp.own_keys_and_symbols(o)?.into_prop_keys())
|
||||
}
|
||||
|
||||
/// Returns the Symbol roots for a property-key list.
|
||||
fn prop_key_roots(keys: &[PropKey]) -> Vec<Value> {
|
||||
keys.iter()
|
||||
.filter_map(|k| match k {
|
||||
PropKey::Sym(s) => Some(Value::Symbol(s.clone())),
|
||||
PropKey::Str(_) => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `Object.getPrototypeOf` (section 15.2.3.2).
|
||||
@@ -285,28 +292,28 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> {
|
||||
/// 15.2.3.8 and 15.2.3.9). A proxy that does not become non-extensible is a `TypeError`.
|
||||
fn lock(interp: &mut Interp, v: Value, freeze: bool) -> JsResult<Value> {
|
||||
let Value::Object(o) = v else { return Ok(v) };
|
||||
check_integrity_symbols(interp, o)?;
|
||||
if !interp.prevent_extensions(o)? {
|
||||
let what = if freeze { "frozen" } else { "sealed" };
|
||||
return Err(interp.type_error(&format!("the object cannot be {what}: it did not stop being extensible")));
|
||||
}
|
||||
let (keys, _held) = own_prop_keys(interp, o)?;
|
||||
check_integrity_symbols(interp, o)?;
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
let desc = if freeze {
|
||||
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
|
||||
match prop {
|
||||
Prop::Data { .. } => Desc { configurable: Some(false), writable: Some(false), ..Desc::default() },
|
||||
Prop::Accessor { .. } => Desc { configurable: Some(false), ..Desc::default() },
|
||||
}
|
||||
} else {
|
||||
Desc { configurable: Some(false), ..Desc::default() }
|
||||
};
|
||||
interp.define_own_pk(o, k, &desc, true)?;
|
||||
}
|
||||
check_integrity_symbols(interp, o)?;
|
||||
Ok(Value::Object(o))
|
||||
let roots = prop_key_roots(&keys);
|
||||
interp.rooted(&roots, |interp| {
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
let desc = if freeze {
|
||||
let Some(prop) = interp.get_own_pk(o, &k)? else { continue };
|
||||
match prop {
|
||||
Prop::Data { .. } => Desc { configurable: Some(false), writable: Some(false), ..Desc::default() },
|
||||
Prop::Accessor { .. } => Desc { configurable: Some(false), ..Desc::default() },
|
||||
}
|
||||
} else {
|
||||
Desc { configurable: Some(false), ..Desc::default() }
|
||||
};
|
||||
interp.define_own_pk(o, k, &desc, true)?;
|
||||
}
|
||||
Ok(Value::Object(o))
|
||||
})
|
||||
}
|
||||
|
||||
fn seal(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
@@ -334,42 +341,27 @@ fn prevent_extensions(interp: &mut Interp, _: Value, args: &[Value], _: bool) ->
|
||||
fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult<Value> {
|
||||
let Value::Object(o) = v else { return Ok(Value::Bool(true)) };
|
||||
let o = *o;
|
||||
check_integrity_symbols(interp, o)?;
|
||||
if interp.is_extensible(o)? {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
let (keys, _held) = own_prop_keys(interp, o)?;
|
||||
check_integrity_symbols(interp, o)?;
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.own_pk(o, &k)? else { continue };
|
||||
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
|
||||
return Ok(Value::Bool(false));
|
||||
let roots = prop_key_roots(&keys);
|
||||
interp.rooted(&roots, |interp| {
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
let Some(prop) = interp.own_pk(o, &k)? else { continue };
|
||||
if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) {
|
||||
return Ok(Value::Bool(false));
|
||||
}
|
||||
}
|
||||
}
|
||||
check_integrity_symbols(interp, o)?;
|
||||
Ok(Value::Bool(true))
|
||||
Ok(Value::Bool(true))
|
||||
})
|
||||
}
|
||||
|
||||
fn is_sealed(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
locked(interp, &arg(args, 0), false)
|
||||
}
|
||||
|
||||
fn check_integrity_symbols(interp: &mut Interp, o: ObjId) -> JsResult<()> {
|
||||
if !interp.is_proxy(o) {
|
||||
return Ok(());
|
||||
}
|
||||
let mut current = o;
|
||||
loop {
|
||||
if interp.object(current)?.syms.as_ref().is_some_and(|m| m.len() != 0) {
|
||||
return Err(interp.type_error("proxy integrity operations with symbol properties are not supported"));
|
||||
}
|
||||
let Some(target) = interp.symbol_lookup_target(current)? else { return Ok(()) };
|
||||
interp.use_fuel()?;
|
||||
current = target;
|
||||
}
|
||||
}
|
||||
|
||||
fn is_frozen(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
locked(interp, &arg(args, 0), true)
|
||||
}
|
||||
@@ -384,7 +376,7 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
|
||||
fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = interp.to_object(&arg(args, 0))?;
|
||||
interp.rooted(&[Value::Object(o)], |interp| {
|
||||
let crate::interp::HeldKeys { keys, held } = interp.own_keys(o)?;
|
||||
let crate::interp::HeldKeys { keys, held, .. } = interp.own_keys(o)?;
|
||||
let mut names = Vec::new();
|
||||
for k in keys {
|
||||
interp.use_fuel()?;
|
||||
@@ -392,6 +384,6 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Valu
|
||||
names.push(k);
|
||||
}
|
||||
}
|
||||
names_array(interp, crate::interp::HeldKeys { keys: names, held })
|
||||
names_array(interp, crate::interp::HeldKeys { keys: names, syms: Vec::new(), ordered: None, held })
|
||||
})
|
||||
}
|
||||
@@ -4,12 +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, key};
|
||||
use crate::interp::{Desc, Interp, JsResult};
|
||||
use crate::proxy::desc_values;
|
||||
use crate::value::Value;
|
||||
use crate::symbol::PropKey;
|
||||
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
|
||||
@@ -161,30 +162,33 @@ fn construct(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult
|
||||
/// property was defined.
|
||||
fn define_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "defineProperty")?;
|
||||
interp.with_key(&arg(args, 1), |interp, k| {
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| {
|
||||
let desc: Desc = to_desc(interp, &arg(args, 2))?;
|
||||
let roots = desc_values(&desc);
|
||||
interp.rooted(&roots, |interp| interp.define_own_property(o, k, &desc, false)).map(Value::Bool)
|
||||
interp.rooted(&roots, |interp| interp.define_own_pk(o, k, &desc, false)).map(Value::Bool)
|
||||
})
|
||||
}
|
||||
|
||||
/// `Reflect.deleteProperty(target, propertyKey)` (section 26.1.4): whether the property is gone.
|
||||
fn delete_property(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "deleteProperty")?;
|
||||
interp.with_key(&arg(args, 1), |interp, k| interp.delete(o, &k, false)).map(Value::Bool)
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| interp.delete_pk(o, &k, false)).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.get(target, propertyKey[, receiver])` (section 26.1.5).
|
||||
fn get(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "get")?;
|
||||
let receiver = if args.len() > 2 { arg(args, 2) } else { Value::Object(o) };
|
||||
interp.with_key(&arg(args, 1), |interp, k| interp.get_from(o, &k, &receiver))
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| match k {
|
||||
PropKey::Str(name) => interp.get_from(o, &name, &receiver),
|
||||
PropKey::Sym(s) => interp.get_sym_from(o, &s, &receiver),
|
||||
})
|
||||
}
|
||||
|
||||
/// `Reflect.getOwnPropertyDescriptor(target, propertyKey)` (section 26.1.6).
|
||||
fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "getOwnPropertyDescriptor")?;
|
||||
interp.with_key(&arg(args, 1), |interp, k| match interp.own_property(o, &k)? {
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| match interp.own_pk(o, &k)? {
|
||||
Some(p) => from_prop(interp, &p),
|
||||
None => Ok(Value::Undefined),
|
||||
})
|
||||
@@ -199,7 +203,7 @@ fn get_prototype_of(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> J
|
||||
/// `Reflect.has(target, propertyKey)` (section 26.1.8).
|
||||
fn has(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "has")?;
|
||||
interp.with_key(&arg(args, 1), |interp, k| interp.has_property_indexed(o, &k)).map(Value::Bool)
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| interp.has_pk_indexed(o, &k)).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.isExtensible(target)` (section 26.1.9).
|
||||
@@ -208,11 +212,32 @@ fn is_extensible(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
|
||||
interp.is_extensible(o).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.ownKeys(target)` (section 26.1.10): every own property name, enumerable or not.
|
||||
/// `Reflect.ownKeys(target)` (section 26.1.10): every own property key, enumerable or not: the
|
||||
/// names, then the Symbols.
|
||||
fn own_keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = target(interp, args, "ownKeys")?;
|
||||
let names = interp.ecma_own_keys(o)?;
|
||||
names_array(interp, names)
|
||||
// A proxy's list holds its Symbols already, in its trap's order, from the one `ownKeys` call.
|
||||
let mut keys = interp.ecma_own_keys(o)?;
|
||||
if !interp.is_proxy(o) {
|
||||
keys.syms = interp.own_symbols(o)?;
|
||||
keys.held.add(interp, keys.syms.len().saturating_mul(crate::interp::KEY_ENTRY_BYTES))?;
|
||||
}
|
||||
let roots: Vec<Value> = keys.syms.iter().cloned().map(Value::Symbol).collect();
|
||||
let (keys, _held) = keys.into_prop_keys();
|
||||
interp.rooted(&roots, |interp| {
|
||||
let a = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(a)], |interp| {
|
||||
for (i, k) in keys.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
let v = match k {
|
||||
PropKey::Str(name) => Value::String(Str::from_rc(name)),
|
||||
PropKey::Sym(s) => Value::Symbol(s),
|
||||
};
|
||||
create_at(interp, a, i as f64, v)?;
|
||||
}
|
||||
Ok(Value::Object(a))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// `Reflect.preventExtensions(target)` (section 26.1.11): whether the object is now not
|
||||
@@ -228,7 +253,7 @@ fn set(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value
|
||||
let o = target(interp, args, "set")?;
|
||||
let receiver = if args.len() > 3 { arg(args, 3) } else { Value::Object(o) };
|
||||
let v = arg(args, 2);
|
||||
interp.with_key(&arg(args, 1), |interp, k| interp.set_with_receiver(o, k, v, &receiver)).map(Value::Bool)
|
||||
interp.with_prop_key(&arg(args, 1), |interp, k| interp.set_pk_with_receiver(o, k, v, &receiver)).map(Value::Bool)
|
||||
}
|
||||
|
||||
/// `Reflect.setPrototypeOf(target, proto)` (section 26.1.13): whether the prototype was set. A
|
||||
|
||||
@@ -169,14 +169,26 @@ 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<Value> {
|
||||
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| {
|
||||
for (i, s) in syms.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
create_at(interp, a, i as f64, Value::Symbol(s))?;
|
||||
}
|
||||
Ok(Value::Object(a))
|
||||
// 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)?;
|
||||
(keys.syms, keys.held)
|
||||
} else {
|
||||
let syms = interp.own_symbols(o)?;
|
||||
let mut held = crate::interp::HeldBytes::new(interp);
|
||||
held.add(interp, syms.len().saturating_mul(crate::interp::KEY_ENTRY_BYTES))?;
|
||||
(syms, held)
|
||||
};
|
||||
let roots: Vec<Value> = syms.iter().cloned().map(Value::Symbol).collect();
|
||||
interp.rooted(&roots, |interp| {
|
||||
let a = new_array(interp, 0)?;
|
||||
interp.rooted(&[Value::Object(a)], |interp| {
|
||||
for (i, s) in syms.into_iter().enumerate() {
|
||||
interp.use_fuel()?;
|
||||
create_at(interp, a, i as f64, Value::Symbol(s))?;
|
||||
}
|
||||
Ok(Value::Object(a))
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -577,7 +577,7 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The key as text for a message.
|
||||
fn pk_name(&mut self, k: &PropKey) -> JsResult<String> {
|
||||
pub(crate) fn pk_name(&mut self, k: &PropKey) -> JsResult<String> {
|
||||
match k {
|
||||
PropKey::Str(name) => Ok(String::from_utf16_lossy(name)),
|
||||
PropKey::Sym(s) => self.sym_name(s),
|
||||
@@ -635,7 +635,16 @@ impl Interp {
|
||||
crate::interp::Lookup::Found(prop) => Some(prop),
|
||||
crate::interp::Lookup::Missing => None,
|
||||
},
|
||||
PropKey::Sym(s) => self.find_sym(proto, s)?,
|
||||
PropKey::Sym(s) => match self.sym_holder(proto, s)? {
|
||||
Some((p, None)) => {
|
||||
if !self.set_sym_with_receiver(p, s.clone(), v, receiver)? {
|
||||
return self.super_reject(throw, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Some((_, prop)) => prop,
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
let why = match inherited {
|
||||
Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), receiver, &[v]).map(drop),
|
||||
|
||||
@@ -311,7 +311,7 @@ fn eval_without_the_option_cannot_redeclare_an_earlier_runs_let() {
|
||||
realm.set_es2015(false);
|
||||
for src in ["eval('var x = 2')", "eval('function x() {}')", "(0, eval)('var x = 2')"] {
|
||||
let r = realm.run(src);
|
||||
assert!(matches!(&r, Err(RunError { message, .. }) if message.starts_with("SyntaxError")), "{src}: {r:?}");
|
||||
assert!(is_thrown(&r, "SyntaxError"), "{src}: {r:?}");
|
||||
}
|
||||
assert_eq!(realm.run("x === 1 && !this.hasOwnProperty('x')"), Ok(JsValue::Bool(true)));
|
||||
// A name no `let` holds is still declared.
|
||||
|
||||
+28
-11
@@ -485,9 +485,24 @@ impl Drop for HeldBytes {
|
||||
|
||||
pub(crate) struct HeldKeys {
|
||||
pub(crate) keys: Vec<Key>,
|
||||
/// The Symbols, when the list was asked for with them: empty otherwise.
|
||||
pub(crate) syms: Vec<crate::symbol::Sym>,
|
||||
/// Both kinds of key in the order a proxy's `ownKeys` trap gave them; `None` for a list
|
||||
/// whose names come before its Symbols.
|
||||
pub(crate) ordered: Option<Vec<PropKey>>,
|
||||
pub(crate) held: HeldBytes,
|
||||
}
|
||||
|
||||
impl HeldKeys {
|
||||
/// Every key of both kinds, in the trap's order or with the names first, and what keeps them
|
||||
/// counted.
|
||||
pub(crate) fn into_prop_keys(self) -> (Vec<PropKey>, HeldBytes) {
|
||||
let HeldKeys { keys, syms, ordered, held } = self;
|
||||
let all = ordered.unwrap_or_else(|| keys.into_iter().map(PropKey::Str).chain(syms.into_iter().map(PropKey::Sym)).collect());
|
||||
(all, held)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for HeldKeys {
|
||||
type Target = Vec<Key>;
|
||||
|
||||
@@ -1804,7 +1819,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: &Key) -> JsResult<Option<Prop>> {
|
||||
if self.is_proxy(id) {
|
||||
return self.proxy_get_own_property(id, k);
|
||||
return self.proxy_get_own_property(id, &PropKey::Str(k.clone()));
|
||||
}
|
||||
self.ordinary_own_property(id, k)
|
||||
}
|
||||
@@ -1899,8 +1914,8 @@ impl Interp {
|
||||
if let Some(p) = self.ordinary_own_property(o, k)? {
|
||||
return Ok(SetLookup::Found(p));
|
||||
}
|
||||
if crate::builtins::binary::typed_key(self, o, k).is_some() {
|
||||
return Ok(SetLookup::Ignored);
|
||||
if let Some(n) = crate::builtins::binary::typed_key(self, o, k) {
|
||||
return Ok(SetLookup::TypedArray(o, n));
|
||||
}
|
||||
cur = self.object(o)?.proto;
|
||||
steps += 1;
|
||||
@@ -2009,7 +2024,7 @@ impl Interp {
|
||||
match self.lookup(id, k)? {
|
||||
Lookup::Found(_) => Ok(true),
|
||||
Lookup::Missing => Ok(false),
|
||||
Lookup::Proxy(p) => self.proxy_has(p, k),
|
||||
Lookup::Proxy(p) => self.proxy_has(p, &PropKey::Str(k.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2038,7 +2053,7 @@ impl Interp {
|
||||
Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Lookup::Found(Prop::Data { value, .. }) => Ok(value),
|
||||
Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, k, receiver, true),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, &PropKey::Str(k.clone()), receiver, true),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2054,7 +2069,7 @@ impl Interp {
|
||||
Lookup::Missing | Lookup::Found(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined),
|
||||
Lookup::Found(Prop::Data { value, .. }) => Ok(value),
|
||||
Lookup::Found(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, k, receiver, false),
|
||||
Lookup::Proxy(p) => self.proxy_get(p, &PropKey::Str(k.clone()), receiver, false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2121,7 +2136,7 @@ impl Interp {
|
||||
/// `throw` a rejection throws a `TypeError` instead.
|
||||
pub(crate) fn define_own_property(&mut self, id: ObjId, k: Key, desc: &Desc, throw: bool) -> JsResult<bool> {
|
||||
if self.is_proxy(id) {
|
||||
let defined = self.proxy_define_own_property(id, &k, desc)?;
|
||||
let defined = self.proxy_define_own_property(id, &PropKey::Str(k.clone()), desc)?;
|
||||
if !defined {
|
||||
return self.reject_bool(throw, &k, "the proxy's defineProperty trap returned false");
|
||||
}
|
||||
@@ -2341,7 +2356,7 @@ impl Interp {
|
||||
if is_array {
|
||||
out.push(key("length"));
|
||||
}
|
||||
Ok(HeldKeys { keys: out, held })
|
||||
Ok(HeldKeys { keys: out, syms: Vec::new(), ordered: None, held })
|
||||
}
|
||||
|
||||
pub(crate) fn ecma_own_keys(&mut self, id: ObjId) -> JsResult<HeldKeys> {
|
||||
@@ -2407,7 +2422,7 @@ impl Interp {
|
||||
};
|
||||
let inherited = match lookup {
|
||||
SetLookup::ReadOnly => return self.reject(throw, &k, "a module namespace object is read-only"),
|
||||
SetLookup::Ignored => return Ok(()),
|
||||
SetLookup::TypedArray(..) => return Ok(()),
|
||||
SetLookup::Proxy(p) => {
|
||||
if !self.set_with_receiver(p, k.clone(), v, &Value::Object(id))? {
|
||||
return self.reject(throw, &k, "the proxy did not set it");
|
||||
@@ -2489,7 +2504,7 @@ impl Interp {
|
||||
/// [[Delete]] (section 8.12.7).
|
||||
pub(crate) fn delete(&mut self, id: ObjId, k: &Key, throw: bool) -> JsResult<bool> {
|
||||
if self.is_proxy(id) {
|
||||
let deleted = self.proxy_delete(id, k)?;
|
||||
let deleted = self.proxy_delete(id, &PropKey::Str(k.clone()))?;
|
||||
if !deleted && throw {
|
||||
let key = String::from_utf16_lossy(k);
|
||||
return Err(self.type_error(&format!("cannot delete property '{key}': the proxy's deleteProperty trap returned false")));
|
||||
@@ -5058,7 +5073,9 @@ pub(crate) enum SetLookup {
|
||||
Proxy(ObjId),
|
||||
Missing,
|
||||
ReadOnly,
|
||||
Ignored,
|
||||
/// A typed array on the chain with a numeric name it has no element for: the write is
|
||||
/// ignored, after converting the value when the typed array is the receiver.
|
||||
TypedArray(ObjId, f64),
|
||||
}
|
||||
|
||||
/// What a proxy's [[Call]] or [[Construct]] did.
|
||||
|
||||
@@ -124,9 +124,8 @@
|
||||
//!
|
||||
//! With [`Options::es2015`], the realm also has `Proxy`, with `Proxy.revocable`, and `Reflect`, as
|
||||
//! ECMAScript 2020 defines them (sections 26.1 and 26.2 and 9.5,
|
||||
//! <https://262.ecma-international.org/11.0/>), with string property names: a trap is given only
|
||||
//! string keys, `Reflect.ownKeys` lists only string keys, and a Symbol key read through a proxy
|
||||
//! goes to its target without a trap.
|
||||
//! <https://262.ecma-international.org/11.0/>), with string and Symbol property keys: a trap is
|
||||
//! given either kind of key, an `ownKeys` trap may return both, and `Reflect.ownKeys` lists both.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
|
||||
+251
-87
@@ -20,6 +20,7 @@ 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::{PropKey, Sym};
|
||||
use crate::value::{Str, Value, index_key};
|
||||
|
||||
/// The most names an `ownKeys` trap may give.
|
||||
@@ -30,8 +31,7 @@ impl Interp {
|
||||
matches!(self.heap.object(id).map(|o| &o.class), Some(Class::Proxy(_)))
|
||||
}
|
||||
|
||||
/// The target that a lookup of a Symbol key on the proxy `id` goes on to, since traps take
|
||||
/// string property names only; `None` when `id` is not a proxy. A revoked proxy is a
|
||||
/// The target of the proxy `id`, `None` when `id` is not a proxy. A revoked proxy is a
|
||||
/// `TypeError`.
|
||||
pub(crate) fn symbol_lookup_target(&mut self, id: ObjId) -> JsResult<Option<ObjId>> {
|
||||
let Some(ProxyData { target, handler, .. }) = self.proxy_data(id) else { return Ok(None) };
|
||||
@@ -60,6 +60,12 @@ impl Interp {
|
||||
pub(crate) fn proxy_create(&mut self, target: &Value, handler: &Value) -> JsResult<ObjId> {
|
||||
let Value::Object(t) = target else { return Err(self.type_error("a proxy's target must be an object")) };
|
||||
let Value::Object(h) = handler else { return Err(self.type_error("a proxy's handler must be an object")) };
|
||||
// A revoked proxy is neither a target nor a handler (section 9.5.14, steps 2 and 4).
|
||||
for (o, what) in [(*t, "target"), (*h, "handler")] {
|
||||
if matches!(self.proxy_data(o), Some(ProxyData { handler: None, .. })) {
|
||||
return Err(self.type_error(&format!("a proxy's {what} cannot be a revoked proxy")));
|
||||
}
|
||||
}
|
||||
let data = ProxyData { target: Some(*t), handler: Some(*h), callable: self.is_callable(target), constructor: self.is_constructor(target) };
|
||||
self.rooted(&[target.clone(), handler.clone()], |i| i.reserve_heap(OBJECT_BYTES + PROXY_BYTES))?;
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(PROXY_BYTES);
|
||||
@@ -239,15 +245,15 @@ impl Interp {
|
||||
// ---- properties ----
|
||||
|
||||
/// [[GetOwnProperty]] of a proxy (section 9.5.5).
|
||||
pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &Key) -> JsResult<Option<Prop>> {
|
||||
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.own_property(target, k) };
|
||||
let name = i.key_value(k)?;
|
||||
pub(crate) fn proxy_get_own_property(&mut self, p: ObjId, k: &PropKey) -> JsResult<Option<Prop>> {
|
||||
self.proxy_op(p, "read a property of", &[pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "getOwnPropertyDescriptor")? else { return i.own_pk(target, k) };
|
||||
let name = i.pk_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"));
|
||||
}
|
||||
let target_prop = i.own_property(target, k)?;
|
||||
let target_prop = i.own_pk(target, k)?;
|
||||
if let Some(prop) = &target_prop {
|
||||
i.temp_roots.extend(desc_values(&prop_desc(prop)));
|
||||
}
|
||||
@@ -289,18 +295,18 @@ 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<bool> {
|
||||
pub(crate) fn proxy_define_own_property(&mut self, p: ObjId, k: &PropKey, desc: &Desc) -> JsResult<bool> {
|
||||
let mut roots = desc_values(desc);
|
||||
roots.push(Value::String(Str::from_rc(k.clone())));
|
||||
roots.push(pk_root(k));
|
||||
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 Some(trap) = i.proxy_trap(handler, "defineProperty")? else { return i.define_own_pk(target, k.clone(), desc, false) };
|
||||
let desc_obj = from_desc(i, desc)?;
|
||||
i.temp_roots.push(desc_obj.clone());
|
||||
let name = i.rooted(std::slice::from_ref(&desc_obj), |i| i.key_value(k))?;
|
||||
let name = i.rooted(std::slice::from_ref(&desc_obj), |i| i.pk_value(k))?;
|
||||
if !i.call_trap(&trap, handler, &[Value::Object(target), name, desc_obj])?.truthy() {
|
||||
return Ok(false);
|
||||
}
|
||||
let target_prop = i.own_property(target, k)?;
|
||||
let target_prop = i.own_pk(target, k)?;
|
||||
let extensible = i.is_extensible(target)?;
|
||||
let setting_config_false = desc.configurable == Some(false);
|
||||
let Some(current) = target_prop else {
|
||||
@@ -330,12 +336,12 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// [[HasProperty]] of a proxy (section 9.5.7).
|
||||
pub(crate) fn proxy_has(&mut self, p: ObjId, k: &Key) -> JsResult<bool> {
|
||||
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_indexed(target, k) };
|
||||
let name = i.key_value(k)?;
|
||||
pub(crate) fn proxy_has(&mut self, p: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
self.proxy_op(p, "test a property of", &[pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "has")? else { return i.has_pk_indexed(target, k) };
|
||||
let name = i.pk_value(k)?;
|
||||
let found = i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy();
|
||||
if !found && let Some(current) = i.own_property(target, k)? {
|
||||
if !found && let Some(current) = i.own_pk(target, k)? {
|
||||
if !current.configurable() {
|
||||
return Err(i.invariant("has", "hid a non-configurable property of its target"));
|
||||
}
|
||||
@@ -348,14 +354,18 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// [[Get]] of a proxy (section 9.5.8).
|
||||
pub(crate) fn proxy_get(&mut self, p: ObjId, k: &Key, receiver: &Value, indexed: bool) -> JsResult<Value> {
|
||||
self.proxy_op(p, "read a property of", &[receiver.clone(), Value::String(Str::from_rc(k.clone()))], |i, target, handler| {
|
||||
pub(crate) fn proxy_get(&mut self, p: ObjId, k: &PropKey, receiver: &Value, indexed: bool) -> JsResult<Value> {
|
||||
self.proxy_op(p, "read a property of", &[receiver.clone(), pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "get")? else {
|
||||
return if indexed { i.get_from(target, k, receiver) } else { i.get_property_only(target, k, receiver) };
|
||||
return match k {
|
||||
PropKey::Str(name) if indexed => i.get_from(target, name, receiver),
|
||||
PropKey::Str(name) => i.get_property_only(target, name, receiver),
|
||||
PropKey::Sym(s) => i.get_sym_from(target, s, receiver),
|
||||
};
|
||||
};
|
||||
let name = i.key_value(k)?;
|
||||
let name = i.pk_value(k)?;
|
||||
let v = i.call_trap(&trap, handler, &[Value::Object(target), name, receiver.clone()])?;
|
||||
match i.own_property(target, k)? {
|
||||
match i.own_pk(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"))
|
||||
}
|
||||
@@ -368,14 +378,14 @@ 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<bool> {
|
||||
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) };
|
||||
let name = i.key_value(k)?;
|
||||
pub(crate) fn proxy_set(&mut self, p: ObjId, k: &PropKey, v: &Value, receiver: &Value) -> JsResult<bool> {
|
||||
self.proxy_op(p, "set a property of", &[v.clone(), receiver.clone(), pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "set")? else { return i.set_pk_with_receiver(target, k.clone(), v.clone(), receiver) };
|
||||
let name = i.pk_value(k)?;
|
||||
if !i.call_trap(&trap, handler, &[Value::Object(target), name, v.clone(), receiver.clone()])?.truthy() {
|
||||
return Ok(false);
|
||||
}
|
||||
match i.own_property(target, k)? {
|
||||
match i.own_pk(target, k)? {
|
||||
Some(Prop::Data { value, flags }) if flags & (CONFIGURABLE | WRITABLE) == 0 && !same_value(v, &value) => {
|
||||
Err(i.invariant("set", "set a value other than its target's non-configurable, read-only property"))
|
||||
}
|
||||
@@ -388,14 +398,14 @@ 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: &Key) -> JsResult<bool> {
|
||||
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) };
|
||||
let name = i.key_value(k)?;
|
||||
pub(crate) fn proxy_delete(&mut self, p: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
self.proxy_op(p, "delete a property of", &[pk_root(k)], |i, target, handler| {
|
||||
let Some(trap) = i.proxy_trap(handler, "deleteProperty")? else { return i.delete_pk(target, k, false) };
|
||||
let name = i.pk_value(k)?;
|
||||
if !i.call_trap(&trap, handler, &[Value::Object(target), name])?.truthy() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(current) = i.own_property(target, k)? else { return Ok(true) };
|
||||
let Some(current) = i.own_pk(target, k)? else { return Ok(true) };
|
||||
if !current.configurable() {
|
||||
return Err(i.invariant("deleteProperty", "deleted a non-configurable property of its target"));
|
||||
}
|
||||
@@ -407,23 +417,45 @@ 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.
|
||||
/// 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,
|
||||
/// which keeps the trap's order in [`HeldKeys::ordered`].
|
||||
pub(crate) fn proxy_own_keys(&mut self, p: ObjId) -> JsResult<HeldKeys> {
|
||||
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 {
|
||||
// A target that is a proxy gives its Symbols with its names.
|
||||
let mut keys = i.ecma_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))?;
|
||||
}
|
||||
return Ok(keys);
|
||||
};
|
||||
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 TrapKeys { keys, syms, ordered } = i.trap_key_list(&result, &mut held)?;
|
||||
i.check_own_keys(target, &keys, &syms)?;
|
||||
Ok(HeldKeys { keys, syms, ordered: Some(ordered), held })
|
||||
})
|
||||
}
|
||||
|
||||
/// 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<Vec<Key>> {
|
||||
/// The object's own names and its own Symbols together, from a single [[OwnPropertyKeys]]:
|
||||
/// one `ownKeys` trap call for a proxy.
|
||||
pub(crate) fn own_keys_and_symbols(&mut self, id: ObjId) -> JsResult<HeldKeys> {
|
||||
if self.is_proxy(id) {
|
||||
return self.proxy_own_keys(id);
|
||||
}
|
||||
let mut keys = self.own_keys(id)?;
|
||||
keys.syms = self.own_symbols(id)?;
|
||||
keys.held.add(self, keys.syms.len().saturating_mul(KEY_ENTRY_BYTES))?;
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// CreateListFromArrayLike (section 7.3.17) of an `ownKeys` trap's result: its names and its
|
||||
/// Symbols in the order given, refusing a value that is neither and a key given twice. Two
|
||||
/// Symbols are the same key only when they are the same Symbol.
|
||||
fn trap_key_list(&mut self, result: &Value, held: &mut HeldBytes) -> JsResult<TrapKeys> {
|
||||
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)?;
|
||||
@@ -433,63 +465,167 @@ impl Interp {
|
||||
return Err(self.throw(ErrorType::Range, "the proxy's ownKeys trap returned too many names"));
|
||||
}
|
||||
let mut keys = Vec::new();
|
||||
let mut syms = Vec::new();
|
||||
let mut ordered = Vec::new();
|
||||
let mut seen: HashSet<Key> = HashSet::new();
|
||||
// Symbols by identity: their addresses.
|
||||
let mut seen_syms: HashSet<usize> = HashSet::new();
|
||||
let mut duplicate = None;
|
||||
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")) };
|
||||
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() {
|
||||
duplicate = Some(k.clone());
|
||||
match v {
|
||||
Value::String(s) => {
|
||||
held.add(self, string_bytes(s.len()).saturating_add(3 * KEY_ENTRY_BYTES))?;
|
||||
let k = s.flat();
|
||||
if !seen.insert(k.clone()) && duplicate.is_none() {
|
||||
duplicate = Some(PropKey::Str(k.clone()));
|
||||
}
|
||||
ordered.push(PropKey::Str(k.clone()));
|
||||
keys.push(k);
|
||||
}
|
||||
Value::Symbol(s) => {
|
||||
// A Symbol read from the list stays reachable while later entries are read.
|
||||
self.temp_roots.push(Value::Symbol(s.clone()));
|
||||
held.add(self, 3 * KEY_ENTRY_BYTES)?;
|
||||
if !seen_syms.insert(s.addr()) && duplicate.is_none() {
|
||||
duplicate = Some(PropKey::Sym(s.clone()));
|
||||
}
|
||||
ordered.push(PropKey::Sym(s.clone()));
|
||||
syms.push(s);
|
||||
}
|
||||
_ => return Err(self.invariant("ownKeys", "returned a key that is neither a string nor a Symbol")),
|
||||
}
|
||||
keys.push(k);
|
||||
}
|
||||
if let Some(k) = duplicate {
|
||||
let name = String::from_utf16_lossy(&k);
|
||||
return Err(self.invariant("ownKeys", &format!("returned the name '{name}' twice")));
|
||||
let name = self.pk_name(&k)?;
|
||||
return Err(self.invariant("ownKeys", &format!("returned the key '{name}' twice")));
|
||||
}
|
||||
Ok(keys)
|
||||
Ok(TrapKeys { keys, syms, ordered })
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
/// Steps 16 to 23 of section 9.5.11: the names `keys` and the Symbols `syms` the trap gave
|
||||
/// against the target's own keys of both kinds.
|
||||
fn check_own_keys(&mut self, target: ObjId, keys: &[Key], syms: &[Sym]) -> JsResult<()> {
|
||||
let extensible = self.is_extensible(target)?;
|
||||
let target_keys = self.own_keys(target)?;
|
||||
let mut fixed = Vec::new();
|
||||
let mut configurable = Vec::new();
|
||||
for k in target_keys.iter() {
|
||||
self.use_fuel()?;
|
||||
if self.own_property(target, k)?.is_some_and(|p| !p.configurable()) {
|
||||
fixed.push(k.clone());
|
||||
} else {
|
||||
configurable.push(k.clone());
|
||||
// The target's keys in its own order (a proxy target's trap order), counted until the
|
||||
// check ends.
|
||||
let (target_keys, _held) = self.own_keys_and_symbols(target)?.into_prop_keys();
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.extend(target_keys.iter().filter_map(|k| match k {
|
||||
PropKey::Sym(s) => Some(Value::Symbol(s.clone())),
|
||||
PropKey::Str(_) => None,
|
||||
}));
|
||||
let r = (|| {
|
||||
let mut fixed = Vec::new();
|
||||
let mut configurable = Vec::new();
|
||||
for k in target_keys.iter().cloned() {
|
||||
self.use_fuel()?;
|
||||
if self.own_pk(target, &k)?.is_some_and(|p| !p.configurable()) {
|
||||
fixed.push(k);
|
||||
} else {
|
||||
configurable.push(k);
|
||||
}
|
||||
}
|
||||
if extensible && fixed.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut unchecked: HashSet<&[u16]> = keys.iter().map(|k| &**k).collect();
|
||||
let mut unchecked_syms: HashSet<usize> = syms.iter().map(Sym::addr).collect();
|
||||
for k in &fixed {
|
||||
if !take(&mut unchecked, &mut unchecked_syms, k) {
|
||||
let name = self.pk_name(k)?;
|
||||
return Err(self.invariant("ownKeys", &format!("left out the non-configurable property '{name}' of its target")));
|
||||
}
|
||||
}
|
||||
if extensible {
|
||||
return Ok(());
|
||||
}
|
||||
for k in &configurable {
|
||||
if !take(&mut unchecked, &mut unchecked_syms, k) {
|
||||
let name = self.pk_name(k)?;
|
||||
return Err(self.invariant("ownKeys", &format!("left out the property '{name}' of its non-extensible target")));
|
||||
}
|
||||
}
|
||||
if !unchecked.is_empty() || !unchecked_syms.is_empty() {
|
||||
return Err(self.invariant("ownKeys", "gave a key its non-extensible target does not have"));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
/// The value a trap is given for the key `k`: a copy of a name, or the Symbol itself.
|
||||
fn pk_value(&mut self, k: &PropKey) -> JsResult<Value> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.key_value(name),
|
||||
PropKey::Sym(s) => Ok(Value::Symbol(s.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Set]] of `k` on `o` with `receiver`, for a name or a Symbol: whether the value was set.
|
||||
pub(crate) fn set_pk_with_receiver(&mut self, o: ObjId, k: PropKey, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.set_with_receiver(o, name, v, receiver),
|
||||
PropKey::Sym(s) => self.set_sym_with_receiver(o, s, v, receiver),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Set]] (sections 9.1.9 and 9.5.9) of the Symbol `k` on `o` with `receiver`: a proxy's
|
||||
/// `set` trap, a setter found on the chain, or a data property defined on the receiver
|
||||
/// through its own [[DefineOwnProperty]]. Whether the value was set.
|
||||
pub(crate) fn set_sym_with_receiver(&mut self, o: ObjId, k: Sym, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
let mark = self.temp_roots.len();
|
||||
self.temp_roots.extend([Value::Object(o), Value::Symbol(k.clone()), v.clone(), receiver.clone()]);
|
||||
let r = self.ordinary_set_sym(o, k, v, receiver);
|
||||
self.temp_roots.truncate(mark);
|
||||
r
|
||||
}
|
||||
|
||||
fn ordinary_set_sym(&mut self, o: ObjId, k: Sym, v: Value, receiver: &Value) -> JsResult<bool> {
|
||||
let mut cur = o;
|
||||
let mut steps = 0usize;
|
||||
let own = loop {
|
||||
if self.is_proxy(cur) {
|
||||
return self.proxy_set(cur, &PropKey::Sym(k), &v, receiver);
|
||||
}
|
||||
if matches!(self.object(cur)?.class, Class::ModuleNamespace(_)) {
|
||||
return Ok(false);
|
||||
}
|
||||
if let Some(p) = self.get_own_sym(cur, &k)? {
|
||||
break p;
|
||||
}
|
||||
match self.object(cur)?.proto {
|
||||
Some(next) => {
|
||||
self.use_fuel()?;
|
||||
cur = next;
|
||||
}
|
||||
None => break Prop::Data { value: Value::Undefined, flags: OPEN },
|
||||
}
|
||||
steps += 1;
|
||||
if steps > 1_000_000 {
|
||||
return Err(Abrupt::Internal("prototype chain too long".into()));
|
||||
}
|
||||
};
|
||||
match own {
|
||||
Prop::Accessor { set: Some(s), .. } => {
|
||||
self.call(&Value::Object(s), receiver, &[v])?;
|
||||
Ok(true)
|
||||
}
|
||||
Prop::Accessor { set: None, .. } => Ok(false),
|
||||
Prop::Data { flags, .. } if flags & WRITABLE == 0 => Ok(false),
|
||||
Prop::Data { .. } => {
|
||||
let Value::Object(r) = receiver else { return Ok(false) };
|
||||
let r = *r;
|
||||
match self.get_own_sym(r, &k)? {
|
||||
Some(Prop::Accessor { .. }) => Ok(false),
|
||||
Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => Ok(false),
|
||||
Some(Prop::Data { .. }) => self.define_own_sym(r, k, &Desc { value: Some(v), ..Desc::default() }, false),
|
||||
None => self.define_own_sym(r, k, &Desc::data(v, OPEN), false),
|
||||
}
|
||||
}
|
||||
}
|
||||
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")));
|
||||
}
|
||||
}
|
||||
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")));
|
||||
}
|
||||
}
|
||||
if !unchecked.is_empty() {
|
||||
return Err(self.invariant("ownKeys", "gave a name its non-extensible target does not have"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [[Set]] (section 9.1.9) of `k` on `o` with `receiver`: a proxy's `set` trap, a setter found
|
||||
@@ -519,8 +655,13 @@ impl Interp {
|
||||
let found = self.lookup_for_set(o, &k)?;
|
||||
let own = match found {
|
||||
SetLookup::ReadOnly => return Ok(false),
|
||||
SetLookup::Ignored => return Ok(true),
|
||||
SetLookup::Proxy(p) => return self.proxy_set(p, &k, &v, receiver),
|
||||
SetLookup::TypedArray(t, n) => {
|
||||
if receiver.as_object() == Some(t) {
|
||||
crate::builtins::binary::set_element(self, t, n, &v)?;
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
SetLookup::Proxy(p) => return self.proxy_set(p, &PropKey::Str(k), &v, receiver),
|
||||
SetLookup::Found(prop) => prop,
|
||||
SetLookup::Missing => Prop::Data { value: Value::Undefined, flags: OPEN },
|
||||
};
|
||||
@@ -612,6 +753,29 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys an `ownKeys` trap gave: the names, the Symbols, and both in the trap's order.
|
||||
struct TrapKeys {
|
||||
keys: Vec<Key>,
|
||||
syms: Vec<Sym>,
|
||||
ordered: Vec<PropKey>,
|
||||
}
|
||||
|
||||
/// The key `k` as a value, to keep it reachable while a trap runs.
|
||||
fn pk_root(k: &PropKey) -> Value {
|
||||
match k {
|
||||
PropKey::Str(name) => Value::String(Str::from_rc(name.clone())),
|
||||
PropKey::Sym(s) => Value::Symbol(s.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes `k` from the keys a trap gave that are not yet matched: whether it was there.
|
||||
fn take(names: &mut HashSet<&[u16]>, syms: &mut HashSet<usize>, k: &PropKey) -> bool {
|
||||
match k {
|
||||
PropKey::Str(name) => names.remove(&**name),
|
||||
PropKey::Sym(s) => syms.remove(&s.addr()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The values a descriptor holds, to keep them reachable while more script runs.
|
||||
pub(crate) fn desc_values(desc: &Desc) -> Vec<Value> {
|
||||
let mut out: Vec<Value> = desc.value.iter().cloned().collect();
|
||||
|
||||
+240
-12
@@ -318,7 +318,7 @@ fn own_keys_reads_and_validates_the_list_before_rejecting_duplicates() {
|
||||
try { Reflect.ownKeys(p); } catch (e) { caught = e === marker; }
|
||||
Object.defineProperty(result, '2', { get: function () { reads++; return 1; } });
|
||||
var invalid = false;
|
||||
try { Reflect.ownKeys(p); } catch (e) { invalid = e instanceof TypeError && e.message.indexOf('not a string') >= 0; }
|
||||
try { Reflect.ownKeys(p); } catch (e) { invalid = e instanceof TypeError && e.message.indexOf('neither a string nor a Symbol') >= 0; }
|
||||
duplicate && caught && invalid && reads === 3",
|
||||
);
|
||||
}
|
||||
@@ -949,24 +949,183 @@ fn transparent_builtin_constructors_read_the_proxy_new_target_prototype() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_integrity_operations_reject_symbol_properties() {
|
||||
fn proxy_integrity_operations_reach_the_targets_symbol_properties() {
|
||||
truth(
|
||||
"var s = Symbol('x'), t = {}; t[s] = 1;
|
||||
var p = new Proxy(new Proxy(t, {}), {});
|
||||
var freeze = type_error(function () { Object.freeze(p); });
|
||||
var seal = type_error(function () { Object.seal(p); });
|
||||
var extensible = Object.isExtensible(t);
|
||||
Object.preventExtensions(t);
|
||||
freeze && seal && extensible && type_error(function () { Object.isFrozen(p); }) &&
|
||||
type_error(function () { Object.isSealed(p); }) && Object.getOwnPropertyDescriptor(t, s).writable",
|
||||
var before = Object.isSealed(p);
|
||||
Object.freeze(p);
|
||||
var d = Object.getOwnPropertyDescriptor(t, s);
|
||||
!before && Object.isFrozen(p) && Object.isSealed(p) && !d.writable && !d.configurable && t[s] === 1",
|
||||
);
|
||||
truth(
|
||||
"var p = new Proxy({}, {}); p[Symbol('x')] = 1;
|
||||
type_error(function () { Object.freeze(p); }) && type_error(function () { Object.isFrozen(p); })",
|
||||
"var s = Symbol('x'), p = new Proxy({}, {}); p[s] = 1;
|
||||
Object.seal(p);
|
||||
var d = Object.getOwnPropertyDescriptor(p, s);
|
||||
Object.isSealed(p) && !Object.isFrozen(p) && d.writable && !d.configurable",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_keys_on_a_proxy_reach_its_target_without_traps() {
|
||||
truth(
|
||||
"var p = new Proxy({}, { ownKeys: function () { p[Symbol('x')] = 1; return []; } });
|
||||
type_error(function () { Object.freeze(p); })",
|
||||
"var s = Symbol('s'), t = {}; t[s] = 1;
|
||||
var p = new Proxy(t, {});
|
||||
var syms = Object.getOwnPropertySymbols(p), d = Reflect.getOwnPropertyDescriptor(p, s);
|
||||
p[s] = 2;
|
||||
var other = Symbol('other'); p[other] = 3;
|
||||
Object.defineProperty(p, Symbol.iterator, { value: 4, configurable: true });
|
||||
var deleted = delete p[other];
|
||||
syms.length === 1 && syms[0] === s && d.value === 1 && t[s] === 2 && p[s] === 2 && s in p &&
|
||||
deleted && !(other in t) && t[Symbol.iterator] === 4 &&
|
||||
Object.getOwnPropertySymbols(p).length === 2 && Reflect.ownKeys(p)[1] === Symbol.iterator",
|
||||
);
|
||||
// A write through a proxy keeps the target's read-only and getter-only properties.
|
||||
truth(
|
||||
"var s = Symbol('s'), g = Symbol('g'), t = {};
|
||||
Object.defineProperty(t, s, { value: 1, writable: false, configurable: true });
|
||||
Object.defineProperty(t, g, { get: function () { return 5; }, configurable: true });
|
||||
var p = new Proxy(t, {}); p[s] = 2; p[g] = 6;
|
||||
t[s] === 1 && t[g] === 5 && !Reflect.set(p, s, 2) && !Reflect.set(p, g, 6) &&
|
||||
type_error(function () { 'use strict'; p[s] = 2; })",
|
||||
);
|
||||
// An object that inherits from a proxy sets its own property through the proxy's [[Set]].
|
||||
truth(
|
||||
"var s = Symbol('s'), t = {}, child = Object.create(new Proxy(t, {}));
|
||||
child[s] = 1;
|
||||
Object.getOwnPropertySymbols(child).length === 1 && !(s in t) && child[s] === 1",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_keys_on_a_proxy_run_its_traps() {
|
||||
truth(
|
||||
"var s = Symbol('s'), log = [];
|
||||
var p = new Proxy({}, {
|
||||
get: function (t, k, r) { log.push('get'); return k === s ? 'from trap' : undefined; },
|
||||
has: function (t, k) { log.push('has'); return k === s; },
|
||||
set: function (t, k, v) { log.push('set'); return k === s; },
|
||||
deleteProperty: function (t, k) { log.push('delete'); return k === s; },
|
||||
defineProperty: function (t, k, d) { log.push('define'); return k === s; },
|
||||
getOwnPropertyDescriptor: function (t, k) { log.push('gopd'); return undefined; }
|
||||
});
|
||||
var child = Object.create(p);
|
||||
var read = p[s] === 'from trap' && child[s] === 'from trap' && s in p && s in child;
|
||||
p[s] = 1;
|
||||
var set = Reflect.set(p, s, 1) && !Reflect.set(p, Symbol('x'), 1);
|
||||
var del = delete p[s] && Reflect.deleteProperty(p, s);
|
||||
var def = Reflect.defineProperty(p, s, { value: 1, configurable: true });
|
||||
var gopd = Reflect.getOwnPropertyDescriptor(p, s) === undefined;
|
||||
read && set && del && def && gopd &&
|
||||
log.join() === 'get,get,has,has,set,set,set,delete,delete,define,gopd'",
|
||||
);
|
||||
// A `super` write with a Symbol key that reaches a proxy is its [[Set]], with `this` as the
|
||||
// receiver; the descriptor trap does not run.
|
||||
truth(
|
||||
"var s = Symbol('s'), seen = null;
|
||||
var proto = new Proxy({}, {
|
||||
set: function (t, k, v, r) { seen = [k, v, r]; return true; },
|
||||
getOwnPropertyDescriptor: function () { throw 'descriptor'; }
|
||||
});
|
||||
class C { write() { super[s] = 3; } }
|
||||
Object.setPrototypeOf(C.prototype, proto);
|
||||
var o = new C();
|
||||
o.write();
|
||||
seen[0] === s && seen[1] === 3 && seen[2] === o",
|
||||
);
|
||||
// A Symbol write on a primitive whose prototype chain reaches a proxy is the proxy's [[Set]],
|
||||
// with the primitive as the receiver.
|
||||
truth(
|
||||
"var s = Symbol('s'), seen = null;
|
||||
Object.setPrototypeOf(Number.prototype, new Proxy({}, {
|
||||
set: function (t, k, v, r) { seen = [k, v, r]; return true; },
|
||||
getOwnPropertyDescriptor: function () { throw 'descriptor'; }
|
||||
}));
|
||||
(1)[s] = 2;
|
||||
seen[0] === s && seen[1] === 2 && seen[2] === 1",
|
||||
);
|
||||
// An outer proxy checks its trap's keys against an inner proxy target's keys in that
|
||||
// target's trap order.
|
||||
truth(
|
||||
"var s = Symbol('s'), order = [];
|
||||
var inner = new Proxy({}, {
|
||||
ownKeys: function () { return [s, 'x']; },
|
||||
getOwnPropertyDescriptor: function (t, k) { order.push(k); return undefined; }
|
||||
});
|
||||
var outer = new Proxy(inner, { ownKeys: function () { return []; } });
|
||||
Reflect.ownKeys(outer);
|
||||
order.length === 2 && order[0] === s && order[1] === 'x'",
|
||||
);
|
||||
// A trap that breaks an invariant for a Symbol key is a TypeError.
|
||||
type_errors(&[
|
||||
"var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 });
|
||||
var p = new Proxy(t, { get: function () { return 2; } }); p[s];",
|
||||
"var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 });
|
||||
var p = new Proxy(t, { has: function () { return false; } }); s in p;",
|
||||
]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_keys_traps_give_symbols_and_are_checked_against_the_targets_symbols() {
|
||||
truth(
|
||||
"var s = Symbol('s'), u = Symbol('s');
|
||||
var p = new Proxy({}, { ownKeys: function () { return [s, 'a', u]; } });
|
||||
var keys = Reflect.ownKeys(p), syms = Object.getOwnPropertySymbols(p);
|
||||
keys.length === 3 && keys[0] === s && keys[1] === 'a' && keys[2] === u &&
|
||||
syms.length === 2 && syms[0] === s && Object.getOwnPropertyNames(p).length === 1",
|
||||
);
|
||||
// `Object.defineProperties` reads the descriptors in the trap's order.
|
||||
truth(
|
||||
"var s = Symbol('s'), order = [];
|
||||
var source = new Proxy({ a: {}, [s]: {} }, {
|
||||
ownKeys: function () { return [s, 'a']; },
|
||||
getOwnPropertyDescriptor: function (t, k) { order.push(k); return Reflect.getOwnPropertyDescriptor(t, k); }
|
||||
});
|
||||
Object.defineProperties({}, source);
|
||||
order.length === 2 && order[0] === s && order[1] === 'a'",
|
||||
);
|
||||
type_errors(&[
|
||||
// The same Symbol twice.
|
||||
"var s = Symbol('s'); var p = new Proxy({}, { ownKeys: function () { return [s, s]; } }); Reflect.ownKeys(p);",
|
||||
// A value that is neither a string nor a Symbol.
|
||||
"var p = new Proxy({}, { ownKeys: function () { return [1]; } }); Reflect.ownKeys(p);",
|
||||
// A non-configurable Symbol of the target left out.
|
||||
"var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 });
|
||||
var p = new Proxy(t, { ownKeys: function () { return []; } }); Reflect.ownKeys(p);",
|
||||
// A Symbol of a non-extensible target left out.
|
||||
"var s = Symbol('s'), t = {}; t[s] = 1; Object.preventExtensions(t);
|
||||
var p = new Proxy(t, { ownKeys: function () { return []; } }); Reflect.ownKeys(p);",
|
||||
// A Symbol a non-extensible target does not have.
|
||||
"var t = Object.preventExtensions({});
|
||||
var p = new Proxy(t, { ownKeys: function () { return [Symbol('s')]; } }); Reflect.ownKeys(p);",
|
||||
]);
|
||||
// The target's non-configurable Symbol, given back, passes.
|
||||
truth(
|
||||
"var s = Symbol('s'), t = {}; Object.defineProperty(t, s, { value: 1 });
|
||||
var p = new Proxy(t, { ownKeys: function () { return [s]; } });
|
||||
Reflect.ownKeys(p)[0] === s",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revoked_proxy_is_neither_a_target_nor_a_handler() {
|
||||
type_errors(&[
|
||||
"var r = Proxy.revocable({}, {}); r.revoke(); new Proxy(r.proxy, {});",
|
||||
"var r = Proxy.revocable({}, {}); r.revoke(); new Proxy({}, r.proxy);",
|
||||
"var r = Proxy.revocable({}, {}); r.revoke(); Proxy.revocable(r.proxy, {});",
|
||||
"var r = Proxy.revocable({}, {}); r.revoke(); Proxy.revocable({}, r.proxy);",
|
||||
]);
|
||||
// A proxy that is not revoked is still a valid target and handler.
|
||||
truth("var p = new Proxy({ x: 1 }, {}); new Proxy(p, new Proxy({}, {})).x === 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_array_receiver_converts_the_value_for_an_index_it_lacks() {
|
||||
truth(
|
||||
"var a = new Uint8Array(1), reads = 0, v = { valueOf: function () { reads++; return 1; } };
|
||||
var set = Reflect.set(Object.create(a), '2', v, a);
|
||||
var other = {}, ignored = Reflect.set(Object.create(a), '2', v, other);
|
||||
set && reads === 1 && ignored && reads === 1 && !('2' in other) && a.length === 1",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1412,6 +1571,75 @@ fn proxy_key_lists_stay_charged_during_nested_descriptor_callbacks() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_keys_stay_counted_when_descriptor_traps_delete_the_target_properties() {
|
||||
use crate::builtins::native;
|
||||
use crate::heap::{HIDDEN, NativeKind, Prop, key};
|
||||
use crate::value::Value;
|
||||
|
||||
fn live_bytes(interp: &mut crate::interp::Interp, _: Value, _: &[Value], _: bool) -> crate::interp::JsResult<Value> {
|
||||
interp.collect_garbage();
|
||||
Ok(Value::Number(f64::from(u32::try_from(interp.heap.bytes).unwrap())))
|
||||
}
|
||||
|
||||
for operation in ["Object.freeze(p)", "Object.isFrozen(p)", "Object.isSealed(p)"] {
|
||||
let mut realm = es();
|
||||
realm.define_function("makeSymbol", |_| Ok(JsValue::Symbol(Some("x".repeat(65536)))));
|
||||
let interp = realm.interp();
|
||||
let probe = native(interp, "liveBytes", live_bytes, 0, NativeKind::Plain, false).unwrap();
|
||||
interp.define(interp.global, key("liveBytes"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap();
|
||||
let src = format!(
|
||||
"var t = {{}}, retained = 0, cleared = false;
|
||||
t[makeSymbol()] = 1; t[makeSymbol()] = 2;
|
||||
Object.preventExtensions(t);
|
||||
function clear() {{ Object.getOwnPropertySymbols(t).forEach(function (s) {{ delete t[s]; }}); }}
|
||||
var p = new Proxy(t, {{ getOwnPropertyDescriptor: function () {{
|
||||
if (!cleared) {{ clear(); cleared = true; }}
|
||||
retained = liveBytes(); return undefined;
|
||||
}} }});
|
||||
var baseline = liveBytes();
|
||||
{operation};
|
||||
cleared && retained > baseline - 65536 && liveBytes() < retained - 65536"
|
||||
);
|
||||
assert_eq!(realm.run(&src), Ok(JsValue::Bool(true)), "{operation}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarded_symbol_key_lists_stay_charged_until_released() {
|
||||
use crate::builtins::native;
|
||||
use crate::heap::{HIDDEN, NativeKind, Prop, key};
|
||||
use crate::interp::KEY_ENTRY_BYTES;
|
||||
use crate::value::Value;
|
||||
|
||||
fn check_list(interp: &mut crate::interp::Interp, _: Value, args: &[Value], _: bool) -> crate::interp::JsResult<Value> {
|
||||
let Value::Object(o) = args[0] else { panic!("expected an object") };
|
||||
interp.collect_garbage();
|
||||
let before = interp.heap.bytes;
|
||||
let keys = interp.own_keys_and_symbols(o)?;
|
||||
assert!(!keys.syms.is_empty());
|
||||
interp.collect_garbage();
|
||||
let retained = interp.heap.bytes;
|
||||
assert!(retained >= before + keys.syms.len() * KEY_ENTRY_BYTES);
|
||||
drop(keys);
|
||||
interp.collect_garbage();
|
||||
assert!(interp.heap.bytes < retained);
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
|
||||
let mut realm = es();
|
||||
let interp = realm.interp();
|
||||
let probe = native(interp, "checkList", check_list, 1, NativeKind::Plain, false).unwrap();
|
||||
interp.define(interp.global, key("checkList"), Prop::Data { value: Value::Object(probe), flags: HIDDEN }).unwrap();
|
||||
assert_eq!(
|
||||
realm.run(
|
||||
"var t = {}; t[Symbol('a')] = 1; t[Symbol('b')] = 2;
|
||||
checkList(t) && checkList(new Proxy(t, {})) && checkList(new Proxy(new Proxy(t, {}), {}))"
|
||||
),
|
||||
Ok(JsValue::Bool(true))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reviver_traversal_keys_stay_charged_until_the_frame_is_dropped() {
|
||||
use crate::builtins::native;
|
||||
|
||||
+77
-23
@@ -143,6 +143,7 @@ impl SymProps {
|
||||
}
|
||||
|
||||
/// A property key (section 6.1.7): a name or a Symbol.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum PropKey {
|
||||
Str(crate::heap::Key),
|
||||
Sym(Sym),
|
||||
@@ -315,24 +316,29 @@ impl Interp {
|
||||
self.reject(true, &name, why)
|
||||
}
|
||||
|
||||
/// [[GetOwnProperty]] for a Symbol key, through a proxy's `getOwnPropertyDescriptor` trap
|
||||
/// when `id` is a proxy.
|
||||
pub(crate) fn get_own_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
|
||||
self.symbol_lookup_target(id)?;
|
||||
if self.is_proxy(id) {
|
||||
return self.proxy_get_own_property(id, &PropKey::Sym(k.clone()));
|
||||
}
|
||||
Ok(self.object(id)?.syms.as_ref().and_then(|m| m.get(k)).cloned())
|
||||
}
|
||||
|
||||
/// The property `k` found on the object or its prototype chain. Each step to a prototype takes
|
||||
/// a unit of fuel. A proxy on the way is passed through to its target.
|
||||
pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
|
||||
/// The object on the chain from `id` that holds `k` with the property, or the first proxy on
|
||||
/// the way, whose traps answer the rest; `None` when no object on the chain has `k`. Each step
|
||||
/// to a prototype takes a unit of fuel.
|
||||
pub(crate) fn sym_holder(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<(ObjId, Option<Prop>)>> {
|
||||
let mut cur = Some(id);
|
||||
let mut steps = 0usize;
|
||||
while let Some(o) = cur {
|
||||
if let Some(p) = self.get_own_sym(o, k)? {
|
||||
return Ok(Some(p));
|
||||
if self.is_proxy(o) {
|
||||
return Ok(Some((o, None)));
|
||||
}
|
||||
cur = match self.symbol_lookup_target(o)? {
|
||||
Some(target) => Some(target),
|
||||
None => self.object(o)?.proto,
|
||||
};
|
||||
if let Some(p) = self.object(o)?.syms.as_ref().and_then(|m| m.get(k)).cloned() {
|
||||
return Ok(Some((o, Some(p))));
|
||||
}
|
||||
cur = self.object(o)?.proto;
|
||||
if cur.is_some() {
|
||||
self.use_fuel()?;
|
||||
}
|
||||
@@ -344,12 +350,23 @@ impl Interp {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// [[Get]] of `k` starting at `start`, with `receiver` as `this` for a getter.
|
||||
/// [[HasProperty]] of `k`, through the `has` trap of a proxy on the prototype chain.
|
||||
pub(crate) fn has_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<bool> {
|
||||
match self.sym_holder(id, k)? {
|
||||
None => Ok(false),
|
||||
Some((_, Some(_))) => Ok(true),
|
||||
Some((p, None)) => self.proxy_has(p, &PropKey::Sym(k.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// [[Get]] of `k` 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_sym_from(&mut self, start: ObjId, k: &Sym, receiver: &Value) -> JsResult<Value> {
|
||||
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, &[]),
|
||||
match self.sym_holder(start, k)? {
|
||||
None | Some((_, Some(Prop::Accessor { get: None, .. }))) => Ok(Value::Undefined),
|
||||
Some((_, Some(Prop::Data { value, .. }))) => Ok(value),
|
||||
Some((_, Some(Prop::Accessor { get: Some(g), .. }))) => self.call(&Value::Object(g), receiver, &[]),
|
||||
Some((p, None)) => self.proxy_get(p, &PropKey::Sym(k.clone()), receiver, true),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,9 +380,9 @@ impl Interp {
|
||||
self.get_sym_from(start, k, base)
|
||||
}
|
||||
|
||||
/// Adds or replaces an own property directly, keeping the heap estimate.
|
||||
/// Adds or replaces an own property directly, keeping the heap estimate. For objects the
|
||||
/// engine made, which are never proxies.
|
||||
pub(crate) fn define_sym(&mut self, id: ObjId, k: Sym, prop: Prop) -> JsResult<()> {
|
||||
self.symbol_lookup_target(id)?;
|
||||
let o = self.object_mut(id)?;
|
||||
if o.syms.get_or_insert_with(Box::default).insert(k, prop) {
|
||||
self.heap.bytes = self.heap.bytes.saturating_add(PROP_BYTES);
|
||||
@@ -375,6 +392,12 @@ impl Interp {
|
||||
|
||||
/// The default [[DefineOwnProperty]] (section 9.1.6) for a Symbol key.
|
||||
pub(crate) fn define_own_sym(&mut self, id: ObjId, k: Sym, desc: &Desc, throw: bool) -> JsResult<bool> {
|
||||
if self.is_proxy(id) {
|
||||
if !self.proxy_define_own_property(id, &PropKey::Sym(k.clone()), desc)? {
|
||||
return self.reject_sym_bool(throw, &k, "the proxy's defineProperty trap returned false");
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
let Some(current) = self.get_own_sym(id, &k)? else {
|
||||
if !self.object(id)?.extensible {
|
||||
return self.reject_sym_bool(throw, &k, "the object is not extensible");
|
||||
@@ -399,6 +422,12 @@ impl Interp {
|
||||
|
||||
/// [[Set]] (section 9.1.9) of an ordinary object for a Symbol key.
|
||||
pub(crate) fn put_sym(&mut self, id: ObjId, k: Sym, v: Value, throw: bool) -> JsResult<()> {
|
||||
if self.is_proxy(id) {
|
||||
if !self.set_sym_with_receiver(id, k.clone(), v, &Value::Object(id))? {
|
||||
return self.reject_sym(throw, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
match self.get_own_sym(id, &k)? {
|
||||
Some(Prop::Data { flags, .. }) => {
|
||||
if flags & WRITABLE == 0 {
|
||||
@@ -420,6 +449,13 @@ impl Interp {
|
||||
if matches!(self.object(object)?.class, crate::heap::Class::ModuleNamespace(_)) {
|
||||
return self.reject_sym(throw, &k, "a module namespace object is read-only");
|
||||
}
|
||||
// Past a proxy the rest is its [[Set]], with the object as the receiver.
|
||||
if self.is_proxy(object) {
|
||||
if !self.set_sym_with_receiver(object, k.clone(), v, &Value::Object(id))? {
|
||||
return self.reject_sym(throw, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(property) = self.get_own_sym(object, &k)? {
|
||||
inherited = Some(property);
|
||||
break;
|
||||
@@ -460,10 +496,18 @@ impl Interp {
|
||||
}
|
||||
_ => {
|
||||
let proto = self.primitive_proto(base, &[])?;
|
||||
if let Some(Prop::Accessor { set: Some(s), .. }) = self.find_sym(proto, &k)? {
|
||||
return self.call(&Value::Object(s), base, &[v]).map(drop);
|
||||
}
|
||||
let strict = self.strict();
|
||||
match self.sym_holder(proto, &k)? {
|
||||
Some((_, Some(Prop::Accessor { set: Some(s), .. }))) => return self.call(&Value::Object(s), base, &[v]).map(drop),
|
||||
// Past a proxy the rest is its [[Set]], with the primitive as the receiver.
|
||||
Some((p, None)) => {
|
||||
if !self.set_sym_with_receiver(p, k.clone(), v, base)? {
|
||||
return self.reject_sym(strict, &k, "the proxy did not set it");
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.reject_sym(strict, &k, "the value is a primitive")
|
||||
}
|
||||
}
|
||||
@@ -471,6 +515,14 @@ impl Interp {
|
||||
|
||||
/// [[Delete]] (section 9.1.10) for a Symbol key.
|
||||
pub(crate) fn delete_sym(&mut self, id: ObjId, k: &Sym, throw: bool) -> JsResult<bool> {
|
||||
if self.is_proxy(id) {
|
||||
let deleted = self.proxy_delete(id, &PropKey::Sym(k.clone()))?;
|
||||
if !deleted && throw {
|
||||
let key = self.sym_name(k)?;
|
||||
return Err(self.type_error(&format!("cannot delete property '{key}': the proxy's deleteProperty trap returned false")));
|
||||
}
|
||||
return Ok(deleted);
|
||||
}
|
||||
match self.get_own_sym(id, k)? {
|
||||
None => Ok(true),
|
||||
Some(p) if p.configurable() => {
|
||||
@@ -488,9 +540,11 @@ 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.
|
||||
/// 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<Vec<Sym>> {
|
||||
self.symbol_lookup_target(id)?;
|
||||
if self.is_proxy(id) {
|
||||
return Ok(self.proxy_own_keys(id)?.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 {
|
||||
@@ -511,7 +565,7 @@ impl Interp {
|
||||
pub(crate) fn has_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult<bool> {
|
||||
match k {
|
||||
PropKey::Str(name) => self.has_property(id, name),
|
||||
PropKey::Sym(s) => Ok(self.find_sym(id, s)?.is_some()),
|
||||
PropKey::Sym(s) => self.has_sym(id, s),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+13
-6
@@ -2854,7 +2854,7 @@ throws a `TypeError`, since that engine was made without the ECMAScript 2015 bui
|
||||
an engine that `#targetengine` keeps reads each run the way that run's script does. A `.js` script, a `.mjs` file,
|
||||
and a run with `module: true` also have 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 26.2), with string and Symbol property keys. 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, key lists retained by enumeration callers, and the names retained during
|
||||
a `for-in` prototype walk count against the heap limit. A trap result that breaks one of the proxy invariants,
|
||||
or any operation on a revoked proxy, throws a `TypeError`. A
|
||||
@@ -2896,9 +2896,15 @@ when reading its value; a binding removed between those checks does not select a
|
||||
The legacy `Object.prototype.reflect` getter throws `TypeError` for a proxy receiver without enumerating
|
||||
its properties or calling descriptor traps. Symbol property reads, writes, deletion, descriptor operations
|
||||
and symbol enumeration on a revoked proxy also throw `TypeError`.
|
||||
`Reflect.ownKeys` returns string keys only. Ordinary targets list array-index keys in ascending order,
|
||||
then other strings in insertion order; an array's `length` precedes its other non-index strings.
|
||||
A proxy's `ownKeys` trap determines its key order. A `for-in` prototype walk keeps the current proxy reachable
|
||||
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.
|
||||
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
|
||||
trap gives them. The trap may return strings and Symbols; any other value, or
|
||||
the same key twice (two Symbols are the same key only when they are the same Symbol), throws `TypeError`, and the
|
||||
result is checked against the target's non-configurable keys of both kinds. A `for-in` prototype walk keeps the current proxy reachable
|
||||
through key collection and its `getPrototypeOf` call, even if `ownKeys` removes it from the receiver's prototype chain.
|
||||
A `for-in` loop checks each proxy candidate's descriptor
|
||||
when iteration reaches that name. An `ownKeys` result is read and its elements are validated before duplicate
|
||||
@@ -2907,8 +2913,9 @@ Deleting a binding in a `with` scope calls the proxy's `deleteProperty`
|
||||
trap without first calling its `getOwnPropertyDescriptor` trap. Target descriptor values and accessors stay
|
||||
reachable during proxy callbacks, including callbacks that revoke a nested target proxy.
|
||||
`Reflect.set` and ordinary assignment ignore invalid numeric indices found on a typed-array prototype
|
||||
without creating a property on the receiver. `Object.freeze`, `Object.seal`, `Object.isFrozen`
|
||||
and `Object.isSealed` throw `TypeError` for a proxy when it or any of its proxy targets has symbol properties.
|
||||
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
|
||||
keys. `new Proxy` and `Proxy.revocable` throw `TypeError` when the target or the handler is a revoked proxy.
|
||||
`Reflect.set` and a write a proxy forwards return false when the lookup reaches a module namespace
|
||||
object before it finds the property. `Reflect.getOwnPropertyDescriptor`
|
||||
and forwarded proxy descriptors throw `ReferenceError` for an uninitialized namespace export. Proxy invariant
|
||||
|
||||
@@ -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. Every internal method of an object goes through one dispatch, so a proxy's traps run for property reads and writes, `in`, `delete`, `for`-`in`, `Object.keys` and the other `Object` functions, `instanceof`, calls and `new`, and when the proxy is a prototype or a `with` object; `Array.isArray`, `concat` and `JSON.stringify` treat a proxy of an array as an array. Each trap result is checked against the target's invariants (non-configurable and non-extensible targets, and `ownKeys` results with a duplicate or a value that is not a string), and a violation or an operation on a revoked proxy throws a `TypeError`. Traps take fuel and count against the limit on nested calls, the property name each trap is given counts against the heap limit, and so a trap that calls itself or a chain of proxies stops at a limit error, and a proxy given to the app in a command's params throws a `TypeError` naming it without running its traps. `script.run` gives a `.js` file, a `.mjs` file, and a run with `module: true` both globals. A `.jsx` script and a `source` string run as a script have neither in a new engine or in an engine that has not run ECMAScript 2015 code. An engine that `#targetengine` keeps gets both globals at its first ECMAScript 2015 run and keeps them for later `.jsx` runs, which still read ES5.1. A `Proxy` or `Reflect` global that an earlier run in that engine defined stays as it is, and an ECMAScript 2015 run does not replace it. `cargo xtask test262` includes the suite's Proxy and Reflect tests whose features are present. Tests: `crates/js/src/proxy_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- A realm made with `Options::es2015` also has `Proxy`, with `Proxy.revocable`, and `Reflect` with its thirteen functions (https://262.ecma-international.org/11.0/, sections 9.5, 26.1 and 26.2), with string and Symbol property keys. 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 key or a value that is neither a string nor 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. `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. `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`.
|
||||
|
||||
Reference in new issue
Block a user