Merge branch feat/js-es2015-symbol-iterators into feat/js-es2015-for-of-destructuring

# Conflicts:
#	crates/js/src/lib.rs
#	docs/target-app-parity.md
This commit is contained in:
dotCooCoo committed 2026-11-22 06:18:50 -08:00
commit 51565e30cc
14 files changed
+392 -72

No files matched your search

+8 -28
View File
@@ -565,41 +565,21 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K
/// ToNumber of a Number object, or ToString of a String object (of either when `as_string` is
/// set), as section 15.12.3 applies them in Str step 4, step 4.b.ii and step 5. Returns `None`
/// for any other value. When the method that [[DefaultValue]] (section 8.12.8) calls first is not
/// found on the object or on its prototype chain before the object's standard prototype, the
/// result is the object's [[PrimitiveValue]] (sections 8.6.2 and 9.9), the value that
/// `Number.prototype.valueOf` (15.7.4.4), `Number.prototype.toString` (15.7.4.2) and
/// `String.prototype.toString` (15.5.4.2) return. Otherwise ToPrimitive calls the method found.
/// for any other value. The conversion is ToPrimitive (section 9.1) with the Number or String
/// hint, so `valueOf` and `toString` are looked up along the object's whole prototype chain, and
/// in a realm with [`crate::Options::es2015`] an `@@toPrimitive` method on the object is called
/// first (ECMA-262 11th edition, section 7.1.1).
fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult<Option<Value>> {
let Value::Object(o) = v else { return Ok(None) };
let (primitive, proto, string) = match interp.heap.object(*o).map(|x| &x.class) {
Some(Class::Number(n)) => (Value::Number(*n), interp.intrinsics.number_proto, as_string),
Some(Class::String(s)) => (Value::String(s.clone()), interp.intrinsics.string_proto, true),
let string = match interp.heap.object(*o).map(|x| &x.class) {
Some(Class::Number(_)) => as_string,
Some(Class::String(_)) => true,
_ => return Ok(None),
};
let (hint, name) = if string { (Hint::String, "toString") } else { (Hint::Number, "valueOf") };
let p = if reaches_prototype(interp, *o, proto, name)? { primitive } else { interp.to_primitive(v, hint)? };
let p = interp.to_primitive(v, if string { Hint::String } else { Hint::Number })?;
Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) }))
}
/// Whether looking up `name` from `o` reaches the object `proto` on the prototype chain before
/// any object on the way, `proto` included, has its own property `name`.
fn reaches_prototype(interp: &mut Interp, o: ObjId, proto: ObjId, name: &str) -> JsResult<bool> {
let k = key(name);
let mut cur = Some(o);
while let Some(id) = cur {
interp.use_fuel()?;
if interp.get_own_property(id, &k)?.is_some() {
return Ok(false);
}
if id == proto {
return Ok(true);
}
cur = interp.heap.object(id).and_then(|x| x.proto);
}
Ok(false)
}
/// Quote (section 15.12.3): the string in double quotes with the characters JSON escapes.
fn write_quoted(interp: &mut Interp, out: &mut Builder, s: &[u16]) -> JsResult<()> {
out.push_units(interp, &[QUOTE])?;
+9 -1
View File
@@ -198,7 +198,15 @@ fn define_all(interp: &mut Interp, o: ObjId, props: &Value) -> JsResult<()> {
interp.temp_roots.push(Value::Object(p));
let r = (|| {
let mut descs = Vec::new();
for k in own_prop_keys(interp, p)? {
let keys = own_prop_keys(interp, p)?;
// A getter can delete a Symbol-keyed property already read, so the Symbols stay rooted
// until they are defined on `o`.
for k in &keys {
if let PropKey::Sym(s) = k {
interp.temp_roots.push(Value::Symbol(s.clone()));
}
}
for k in keys {
interp.use_fuel()?;
if !interp.get_own_pk(p, &k)?.is_some_and(|prop| prop.enumerable()) {
continue;
+27 -5
View File
@@ -1,12 +1,12 @@
//! `Symbol` (ECMA-262 11th edition, section 19.4, <https://262.ecma-international.org/11.0/>):
//! the constructor with `Symbol.for`, `Symbol.keyFor` and the well-known Symbols, the methods of
//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10) and
//! `Function.prototype[@@hasInstance]` (section 19.2.3.6). Installed in a realm with
//! [`crate::Options::es2015`] only.
//! `Symbol.prototype`, `Object.getOwnPropertySymbols` (section 19.1.2.10),
//! `Function.prototype[@@hasInstance]` (section 19.2.3.6) and `Date.prototype[@@toPrimitive]`
//! (section 20.4.4.45). Installed in a realm with [`crate::Options::es2015`] only.
use super::{arg, constructor, create_at, data, method, native, new_array};
use crate::heap::{CONFIGURABLE, Class, NativeFn, NativeKind, ObjId, Object, Prop, SYMBOL_BYTES, string_bytes};
use crate::interp::{Interp, JsResult};
use crate::interp::{Hint, Interp, JsResult};
use crate::symbol::{Es2015Objects, REGISTRY_ENTRY_BYTES, Sym, WellKnown};
use crate::value::{Str, Value};
@@ -37,7 +37,9 @@ pub(super) fn install(interp: &mut Interp, object_ctor: ObjId) -> JsResult<()> {
let getter = native(interp, "get description", description, 0, NativeKind::Plain, false)?;
interp.define(proto, crate::heap::key("description"), Prop::Accessor { get: Some(getter), set: None, flags: CONFIGURABLE })?;
interp.define_sym(proto, to_string_tag, Prop::Data { value: Value::str("Symbol"), flags: CONFIGURABLE })?;
sym_method(interp, proto, to_primitive, "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?;
sym_method(interp, proto, to_primitive.clone(), "[Symbol.toPrimitive]", symbol_to_primitive, 1, CONFIGURABLE)?;
let date_proto = interp.intrinsics.date_proto;
sym_method(interp, date_proto, to_primitive, "[Symbol.toPrimitive]", date_to_primitive, 1, CONFIGURABLE)?;
method(interp, object_ctor, "getOwnPropertySymbols", get_own_property_symbols, 1)?;
let function_proto = interp.intrinsics.function_proto;
@@ -138,6 +140,26 @@ fn symbol_to_primitive(interp: &mut Interp, this: Value, _: &[Value], _: bool) -
this_symbol(interp, &this, "[Symbol.toPrimitive]").map(Value::Symbol)
}
/// `Date.prototype[@@toPrimitive](hint)` (section 20.4.4.45): OrdinaryToPrimitive of any object,
/// `toString` first for the hints `"string"` and `"default"` and `valueOf` first for `"number"`.
/// Any other hint, or a `this` that is not an object, throws a `TypeError`.
fn date_to_primitive(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let Value::Object(o) = this else {
return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was called on a value that is not an object"));
};
// The longest hint has 7 units, so a longer string is refused before it is flattened.
let name = match arg(args, 0) {
Value::String(s) if s.len() <= 7 => String::from_utf16_lossy(&s.flat()),
_ => String::new(),
};
let hint = match name.as_str() {
"string" | "default" => Hint::String,
"number" => Hint::Number,
_ => return Err(interp.type_error("Date.prototype[Symbol.toPrimitive] was given a hint that is not \"string\", \"number\" or \"default\"")),
};
interp.ordinary_to_primitive(o, &this, hint)
}
/// `Object.getOwnPropertySymbols(o)` (section 19.1.2.10): the object's own Symbol keys in the
/// order they were added.
fn get_own_property_symbols(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
+4
View File
@@ -684,6 +684,10 @@ fn json_stringify_unwraps_number_string_and_boolean_objects() {
assert_eq!(string("Object.prototype.valueOf = function () { return 9; }; JSON.stringify(Object(3))"), "3");
assert_eq!(string("Object.getPrototypeOf(Object(1)).valueOf = function () { return 4; }; JSON.stringify(Object(3))"), "4");
assert_eq!(string("Object.getPrototypeOf(Object('')).toString = function () { return 'q'; }; JSON.stringify(Object('abc'))"), "\"q\"");
// Once the own prototype's method is deleted, the lookup goes on to Object.prototype.
let over = "Object.prototype.toString = function () { return '7'; };";
assert_eq!(string(&format!("{over} delete String.prototype.toString; JSON.stringify(Object('abc'))")), "\"7\"");
assert_eq!(string(&format!("{over} delete Number.prototype.valueOf; delete Number.prototype.toString; JSON.stringify(Object(3))")), "7");
}
#[test]
+1 -1
View File
@@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option<u32> {
}
}
/// The value of the digit values `digits` in `radix` (8 or 16), rounded once to the nearest number
/// The value of the digit values `digits` in `radix` (2, 8 or 16), rounded once to the nearest number
/// with ties to even (sections 7.8.3 and 9.3.1), or `None` when there are no digits. Digits are
/// kept exactly in a `u128` while they fit; past that, each later digit counts only for its
/// position and for whether any of the dropped bits is set.
+16 -1
View File
@@ -269,6 +269,14 @@ impl Interp {
return Err(self.data_error(r, ErrorType::Type, &what));
}
};
// Each Symbol key the scan may visit takes a unit of fuel first.
let syms = self.object(id)?.syms.as_ref().map_or(0, |m| m.len());
if syms > 0 {
crate::regexp_vm::use_fuel_n(self, syms as u64)?;
}
if self.object(id)?.syms.as_ref().is_some_and(|m| m.iter().any(|(_, p)| p.enumerable())) {
return Err(self.data_error(r, ErrorType::Type, "has a Symbol-keyed property, not plain data"));
}
r.ancestors.push(id);
let out = match shape {
Shape::Array(length) => self.read_array(id, length, r),
@@ -529,7 +537,14 @@ impl Interp {
/// `v` as the string `String(v)` gives, within the limits of a crossing.
fn read_text(&mut self, v: &Value, r: &mut Reading) -> JsResult<Data> {
let s = self.to_str(v)?;
let s = match v {
// `String(symbol)` gives `Symbol(description)` (ECMA-262 11th edition, section 21.1.1.1).
Value::Symbol(k) => match self.descriptive_string(k)? {
Value::String(s) => s,
_ => return Err(Abrupt::Internal("a Symbol's descriptive string is not a string".into())),
},
_ => self.to_str(v)?,
};
self.charge_reading(r, s.len().saturating_mul(3).saturating_add(2))?;
Ok(Data::String(s.to_rust_string()))
}
+39
View File
@@ -325,6 +325,45 @@ fn a_text_function_takes_each_argument_as_string_gives_it() {
assert!(e.message.contains("no text"), "{}", e.message);
}
#[test]
fn a_symbol_crosses_as_the_text_string_gives_it_and_never_as_data() {
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 10_000_000, ..Limits::default() });
let seen = with_take(&mut r);
let texts: Rc<RefCell<Vec<Data>>> = Rc::default();
let log = texts.clone();
let f: HostFunction = Rc::new(move |args| {
log.borrow_mut().extend(args);
Ok(Data::Undefined)
});
r.define_host_object("text", vec![("of".into(), HostItem::TextFunction(f))]).unwrap();
r.run("text.of(Symbol('tag'), Symbol())").unwrap();
assert_eq!(texts.borrow().as_slice(), [Data::String("Symbol(tag)".into()), Data::String("Symbol()".into())]);
// An enumerable Symbol-keyed property is refused; one that is not enumerable is left out.
let probe = "var e = 'none'; var v = {a: 1}; v[Symbol('k')] = 2; try { host.take(v); } catch (x) { e = x.name + '|' + x.message; } e";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("TypeError|") && out.contains("has a Symbol-keyed property"), "{out}");
let probe = "var e = 'none'; var v = [1]; v[Symbol('k')] = 2; try { host.take({list: v}); } catch (x) { e = x.name + '|' + x.message; } e";
let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") };
assert!(out.starts_with("TypeError|") && out.contains(".list has a Symbol-keyed property"), "{out}");
assert!(seen.borrow().is_empty(), "the function ran");
r.run("var v = {a: 1}; Object.defineProperty(v, Symbol('k'), {value: 2}); host.take(v);").unwrap();
assert_eq!(seen.borrow().as_slice(), [Data::Object(vec![("a".into(), Data::Number(1.0))])]);
}
#[test]
fn checking_the_symbol_keys_of_a_value_takes_fuel() {
// Making the 20,000 hidden keys takes well under 3,000,000 units; the 500 crossings check
// 10,000,000 keys.
let mut r = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 3_000_000, ..Limits::default() });
with_take(&mut r);
let src = "var v = {}; for (var i = 0; i < 20000; i++) Object.defineProperty(v, Symbol(), {value: i}); \
for (var j = 0; j < 500; j++) host.take(v);";
match r.run(src) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
}
#[test]
fn errors_from_the_host_can_be_caught_and_an_abort_cannot() {
let mut r = realm(1_000_000);
+32 -14
View File
@@ -3343,11 +3343,20 @@ impl Interp {
if let Some(r) = self.exotic_to_primitive(*o, v, hint)? {
return Ok(r);
}
// Without a hint, a Date object converts as with the String hint.
let date = hint == Hint::Default && matches!(self.heap.object(*o).map(|ob| &ob.class), Some(Class::Date(_)));
self.ordinary_to_primitive(*o, v, hint)
}
/// [[DefaultValue]] (section 8.12.8) of the object `o`, which is `v`: ToPrimitive without the
/// `@@toPrimitive` method.
pub(crate) fn ordinary_to_primitive(&mut self, o: ObjId, v: &Value, hint: Hint) -> JsResult<Value> {
// Without a hint, a Date object converts as with the String hint. In a realm with
// `Options::es2015`, `Date.prototype[@@toPrimitive]` picks that order for a Date instead,
// and OrdinaryToPrimitive treats a missing hint as the Number hint (ECMA-262 11th edition,
// sections 7.1.1.1 and 20.4.4.45).
let date = hint == Hint::Default && !self.options.es2015 && matches!(self.heap.object(o).map(|ob| &ob.class), Some(Class::Date(_)));
let order = if hint == Hint::String || date { ["toString", "valueOf"] } else { ["valueOf", "toString"] };
for name in order {
let f = self.get_from(*o, &key(name), v)?;
let f = self.get_from(o, &key(name), v)?;
if self.is_callable(&f) {
let r = self.call(&f, v, &[])?;
if !matches!(r, Value::Object(_)) {
@@ -3358,6 +3367,8 @@ impl Interp {
Err(self.type_error("cannot convert the object to a primitive value"))
}
/// ToNumber (section 9.3). In a realm with [`crate::Options::es2015`], a string may also be a
/// `0b` or `0o` literal (ECMA-262 11th edition, section 7.1.3.1).
#[allow(clippy::wrong_self_convention)]
pub(crate) fn to_number(&mut self, v: &Value) -> JsResult<f64> {
Ok(match v {
@@ -3365,7 +3376,7 @@ impl Interp {
Value::Null => 0.0,
Value::Bool(b) => f64::from(u8::from(*b)),
Value::Number(n) => *n,
Value::String(s) => string_to_number(&flat_charged(self, s)?),
Value::String(s) => string_to_number(&flat_charged(self, s)?, self.options.es2015),
Value::Symbol(_) => return Err(self.type_error("cannot convert a Symbol value to a number")),
Value::Object(_) => {
let p = self.to_primitive(v, Hint::Number)?;
@@ -3549,7 +3560,8 @@ impl Interp {
return self.xml_concat(a, b);
}
let pa = self.to_primitive(a, Hint::Default)?;
let pb = self.to_primitive(b, Hint::Default)?;
// The right side's conversion can run script, so the left side's result stays counted.
let pb = self.rooted(std::slice::from_ref(&pa), |i| i.to_primitive(b, Hint::Default))?;
if matches!(pa, Value::String(_)) || matches!(pb, Value::String(_)) {
// Both are primitives, so this converts them without running script code; a Symbol
// throws.
@@ -3563,12 +3575,14 @@ impl Interp {
/// The abstract relational comparison `x < y` (section 11.8.5): `None` when either side is
/// NaN.
fn less_than(&mut self, x: &Value, y: &Value, left_first: bool) -> JsResult<Option<bool>> {
// The second conversion can run script, so the first one's result stays counted.
let (px, py) = if left_first {
let px = self.to_primitive(x, Hint::Number)?;
(px, self.to_primitive(y, Hint::Number)?)
let py = self.rooted(std::slice::from_ref(&px), |i| i.to_primitive(y, Hint::Number))?;
(px, py)
} else {
let py = self.to_primitive(y, Hint::Number)?;
(self.to_primitive(x, Hint::Number)?, py)
(self.rooted(std::slice::from_ref(&py), |i| i.to_primitive(x, Hint::Number))?, py)
};
if let (Value::String(a), Value::String(b)) = (&px, &py) {
// Both stay rooted, so the first copy is still counted while the second is made.
@@ -3602,7 +3616,7 @@ impl Interp {
| (Value::Symbol(_), Value::Symbol(_))
| (Value::Object(_), Value::Object(_)) => return Ok(strict_eq(&x, &y)),
(Value::Number(n), Value::String(s)) | (Value::String(s), Value::Number(n)) => {
return Ok(*n == string_to_number(&flat_charged(self, s)?));
return Ok(*n == string_to_number(&flat_charged(self, s)?, self.options.es2015));
}
(Value::Bool(v), _) => x = Value::Number(f64::from(u8::from(*v))),
(_, Value::Bool(v)) => y = Value::Number(f64::from(u8::from(*v))),
@@ -3672,9 +3686,10 @@ impl Interp {
}
}
/// A host value as a JavaScript value. A string is charged to the heap, and one that does not
/// fit in it ends the run with the heap limit. Everything the caller still needs must be
/// reachable from the roots.
/// A host value as a JavaScript value. A string or a Symbol's description is charged to the
/// heap before it is built, and one that does not fit in it ends the run with the heap limit.
/// A Symbol in a realm without [`crate::Options::es2015`] throws a `TypeError`. Everything the
/// caller still needs must be reachable from the roots.
#[allow(clippy::wrong_self_convention)]
pub(crate) fn from_js_value(&mut self, v: crate::JsValue) -> JsResult<Value> {
Ok(match v {
@@ -3689,12 +3704,15 @@ impl Interp {
Value::str(&s)
}
crate::JsValue::Object(_) => Value::Object(self.new_object()),
crate::JsValue::Symbol(_) if !self.options.es2015 => {
return Err(self.type_error("a host function returned a Symbol in a realm without Symbol"));
}
crate::JsValue::Symbol(description) => {
let units: Option<Vec<u16>> = description.map(|d| d.encode_utf16().collect());
let bytes = crate::heap::SYMBOL_BYTES + units.as_ref().map_or(0, |u| string_bytes(u.len()));
let bytes = crate::heap::SYMBOL_BYTES + description.as_ref().map_or(0, |d| string_bytes(d.encode_utf16().count()));
self.reserve_heap(bytes)?;
self.heap.bytes += bytes;
Value::Symbol(crate::symbol::Sym::new(units.map(Str::from_units), false))
let description = description.map(|d| Str::from_units(d.encode_utf16().collect()));
Value::Symbol(crate::symbol::Sym::new(description, false))
}
})
}
+10 -6
View File
@@ -68,10 +68,13 @@
//! `hasInstance`, `toPrimitive` and `toStringTag` with the hooks ToPrimitive, `instanceof` and
//! `Object.prototype.toString` read, Symbol-keyed properties with `Object.getOwnPropertySymbols`,
//! and iterator objects with a `next` method from `Array.prototype.values`, `keys`, `entries` and
//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object. A
//! Symbol converted to a string or a number without `String(symbol)` or `toString` throws a
//! `TypeError`. Every iterator step takes fuel, and every Symbol and registry entry counts against
//! the heap limit.
//! `@@iterator`, `String.prototype[@@iterator]` (by code point) and every `arguments` object.
//! `Date.prototype[@@toPrimitive]` converts a Date without a hint as with the String hint, and an
//! object without an `@@toPrimitive` method, a Date included, converts without a hint as with the
//! Number hint. A Symbol converted to a string or a number without `String(symbol)` or `toString` throws a
//! `TypeError`. A string converts to a number in the `0b` and `0o` forms as well. Every iterator
//! step and every prototype a Symbol-keyed lookup passes takes fuel, and every Symbol and registry
//! entry counts against the heap limit.
#![forbid(unsafe_code)]
pub mod ast;
@@ -135,8 +138,9 @@ pub struct Options {
/// computed property names. Off, they are syntax errors and the language is ES5.1's. Code a
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
/// On, a realm also has the later editions' built-ins this engine has: `Symbol` with
/// Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects. Off, a
/// realm has the ES5.1 built-ins only, as the app's scripts expect.
/// Symbol-keyed properties and the iterators of arrays, strings and `arguments` objects, with
/// `0b` and `0o` strings converting to numbers. Off, a realm has the ES5.1 built-ins only, as
/// the app's scripts expect.
pub es2015: bool,
}
+2 -1
View File
@@ -110,7 +110,8 @@ impl Interrupt {
}
/// A value passed between a script and the host. An object is given by its class name, and a
/// Symbol by its description; a Symbol the host passes in is a new Symbol each time.
/// Symbol by its description; a Symbol the host passes in is a new Symbol each time, and one a
/// host function returns in a realm without [`Options::es2015`] throws a `TypeError`.
#[derive(Clone, Debug, PartialEq)]
pub enum JsValue {
Undefined,
+33 -7
View File
@@ -127,6 +127,7 @@ impl SymProps {
let (_, prop) = self.entries.get_mut(i)?.take()?;
if self.entries.len() > 16 && self.index.len() * 2 < self.entries.len() {
self.entries.retain(Option::is_some);
self.entries.shrink_to_fit();
self.index = self.entries.iter().enumerate().filter_map(|(i, e)| e.as_ref().map(|(k, _)| (k.clone(), i))).collect();
}
Some(prop)
@@ -238,10 +239,10 @@ impl Interp {
Value::Symbol(s) => f(self, PropKey::Sym(s.clone())),
Value::Object(_) => {
let p = self.to_primitive(v, Hint::String)?;
if let Value::Symbol(s) = p {
return f(self, PropKey::Sym(s));
}
self.rooted(std::slice::from_ref(&p), |i| i.with_key(&p, |i, k| f(i, PropKey::Str(k))))
self.rooted(std::slice::from_ref(&p), |i| match &p {
Value::Symbol(s) => f(i, PropKey::Sym(s.clone())),
_ => i.with_key(&p, |i, k| f(i, PropKey::Str(k))),
})
}
_ => self.with_key(v, |i, k| f(i, PropKey::Str(k))),
}
@@ -304,8 +305,9 @@ impl Interp {
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.
pub(crate) fn find_sym(&self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
/// The property `k` found on the object or its prototype chain. Each step to a prototype takes
/// a unit of fuel.
pub(crate) fn find_sym(&mut self, id: ObjId, k: &Sym) -> JsResult<Option<Prop>> {
let mut cur = Some(id);
let mut steps = 0usize;
while let Some(o) = cur {
@@ -313,6 +315,9 @@ impl Interp {
return Ok(Some(p));
}
cur = self.object(o)?.proto;
if cur.is_some() {
self.use_fuel()?;
}
steps += 1;
if steps > 1_000_000 {
return Err(crate::interp::Abrupt::Internal("prototype chain too long".into()));
@@ -464,7 +469,7 @@ impl Interp {
}
}
pub(crate) fn has_pk(&self, id: ObjId, k: &PropKey) -> JsResult<bool> {
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()),
@@ -579,3 +584,24 @@ impl Interp {
}
}
}
#[cfg(test)]
mod tests {
use super::{Sym, SymProps};
use crate::heap::{OPEN, Prop};
use crate::value::Value;
#[test]
fn removing_most_symbol_keys_gives_back_their_room_and_keeps_the_order() {
let mut m = SymProps::default();
let keys: Vec<Sym> = (0..100).map(|_| Sym::new(None, false)).collect();
for k in &keys {
m.insert(k.clone(), Prop::Data { value: Value::Undefined, flags: OPEN });
}
for k in &keys[..90] {
m.remove(k);
}
assert!(m.entries.capacity() < 64, "{}", m.entries.capacity());
assert_eq!(m.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>(), keys[90..]);
}
}
+180
View File
@@ -219,6 +219,186 @@ fn an_array_iterator_keeps_its_object_while_reading_its_length_runs_script() {
assert_eq!(string(src), "x false true");
}
#[test]
fn binary_and_octal_strings_are_numbers_in_an_es2015_realm_only() {
for length in ["0b10", "0o2", "2"] {
let src = format!(
"var it = Array.prototype.values.call({{0: 'first', 1: 'second', length: '{length}'}}); \
var a = it.next(), b = it.next(); a.value + ' ' + b.value + ' ' + it.next().done"
);
assert_eq!(string(&src), "first second true", "{length}");
}
truth("Number('0b101') === 5 && +'0O17' === 15 && '0b11' == 3 && isNaN('0b2') && isNaN('-0o1')");
let src = "isNaN(Number('0b10')) && isNaN(+'0o2') && '0b1' != 1";
assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(src), Ok(JsValue::Bool(true)));
}
#[test]
fn json_calls_the_to_primitive_method_of_a_wrapper() {
let hook = "w[Symbol.toPrimitive] = function (hint) { return hint === 'number' ? 2 : 'b'; };";
truth(&format!("var w = new String('x'); {hook} JSON.stringify(w) === '\"b\"'"));
truth(&format!("var w = new String('x'); delete String.prototype.toString; {hook} JSON.stringify(w) === '\"b\"'"));
truth(&format!("var w = new String('x'); {hook} JSON.stringify({{a: 1, b: 2}}, [w]) === '{{\"b\":2}}'"));
truth(&format!("var w = new Number(5); {hook} JSON.stringify([w], null, w) === '[\\n 2\\n]'"));
truth("JSON.stringify([new String('x'), new Number(1)], null, new Number(1)) === '[\\n \"x\",\\n 1\\n]'");
// A `@@toPrimitive` getter that deletes the prototype's method and gives `undefined` sends the
// lookup on to `Object.prototype`.
let getter = |method: &str| {
format!(
"Object.defineProperty(w, Symbol.toPrimitive, {{ get: function () {{ delete Object.getPrototypeOf(w).{method}; return undefined; }} }});"
)
};
let over = "Object.prototype.toString = function () { return '7'; };";
truth(&format!("var w = new String('x'); {over} {} JSON.stringify(w) === '\"7\"'", getter("toString")));
truth(&format!("var w = new Number(3); {over} delete Number.prototype.toString; {} JSON.stringify(w) === '7'", getter("valueOf")));
}
#[test]
fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_used() {
// `mk(n)` makes a string of `n` units. The key's accessor deletes itself from
// `Object.prototype`, so when the key is a Symbol only the read or write holds it and its
// description of 2,000,000 units, and then makes a string of 1,500,000 units. With `keep`
// (1,000,000 units) and a description still counted, that string does not fit; without one it
// does.
let src = |key: &str, access: &str| {
format!(
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
var keep = mk(1000000), made = null; \
function use() {{ var p = Object.prototype; delete p[Object.getOwnPropertySymbols(p)[0] || 'k']; \
made = mk(1500000); return 0; }} \
var w = {{}}; w[Symbol.toPrimitive] = function () {{ var k = {key}; \
Object.defineProperty(Object.prototype, k, {{ configurable: true, get: use, set: use }}); return k; }}; \
{access}; made.length"
)
};
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
for access in ["({})[w]", "({})[w] = 1", "({})[w]++"] {
// A name as the key leaves the Symbol and its description to the collector, and the string
// fits.
assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 'k')", access)), Ok(JsValue::Number(1_500_000.0)), "{access}");
match es2015(limits()).run(&src("Symbol(mk(2000000))", access)) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{access}: {other:?}"),
}
}
}
#[test]
fn define_properties_keeps_a_symbol_key_counted_after_a_getter_deletes_it() {
// The second Symbol-keyed descriptor's getter deletes the first property, drops `s` and makes
// a string of 1,500,000 units. With `keep` (1,000,000 units) and the first Symbol's
// description of 2,000,000 units still counted, that string does not fit; with a short
// description it does.
let src = |description: &str, define: &str| {
format!(
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
var keep = mk(1000000), made = null, s = Symbol({description}), props = {{}}; \
props[s] = {{ value: 1, enumerable: true }}; \
Object.defineProperty(props, Symbol('t'), {{ enumerable: true, get: function () {{ \
delete props[s]; s = null; made = mk(1500000); return {{ value: 2 }}; }} }}); \
var o = {define}; o[Object.getOwnPropertySymbols(o)[0]] + ' ' + made.length"
)
};
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
for define in ["Object.defineProperties({}, props)", "Object.create(null, props)"] {
assert_eq!(es2015(limits()).run(&src("'d'", define)), Ok(JsValue::String("1 1500000".into())), "{define}");
match es2015(limits()).run(&src("mk(2000000)", define)) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{define}: {other:?}"),
}
}
}
#[test]
fn an_operator_keeps_the_first_operand_converted_while_it_converts_the_second() {
// `a` converts to a Symbol with a description of 2,000,000 units that nothing else holds, and
// `b`'s conversion makes a string of 1,500,000 units. With `keep` (1,000,000 units) and the
// description still counted, that string does not fit; when `a` gives a number it does.
let src = |first: &str, op: &str| {
format!(
"function mk(n) {{ return new Array(n + 1).join('x'); }} \
var keep = mk(1000000), made = null; \
var a = {{}}; a[Symbol.toPrimitive] = function () {{ return {first}; }}; \
var b = {{}}; b[Symbol.toPrimitive] = function () {{ made = mk(1500000); return 1; }}; \
try {{ a {op} b; }} catch (e) {{ if (!(e instanceof TypeError)) throw e; }} \
made.length === 1500000"
)
};
let limits = || Limits { heap_bytes: 8 << 20, fuel: 50_000_000, ..Limits::default() };
for op in ["+", "<", ">", "<=", ">="] {
assert_eq!(es2015(limits()).run(&src("(Symbol(mk(2000000)), 0)", op)), Ok(JsValue::Bool(true)), "{op}");
match es2015(limits()).run(&src("Symbol(mk(2000000))", op)) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{op}: {other:?}"),
}
}
}
#[test]
fn date_objects_convert_through_their_to_primitive_method() {
let date = "var d = new Date(0); d.valueOf = function () { return 7; }; d.toString = function () { return 'date'; };";
truth(&format!("{date} d + 1 === 'date1' && d * 1 === 7 && String(d) === 'date' && (d == 'date')"));
// Without a method, a Date converts with `valueOf` first when no hint is given.
// The inherited method is read-only, so an assignment does not shadow it.
truth(&format!("{date} d[Symbol.toPrimitive] = null; d + 1 === 'date1'"));
truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: null }}); d + 1 === 8"));
truth(&format!("{date} Object.defineProperty(d, Symbol.toPrimitive, {{ value: undefined }}); d + 1 === 8 && String(d) === 'date'"));
truth(&format!("{date} delete Date.prototype[Symbol.toPrimitive]; d + 1 === 8 && d == 7"));
// The method itself, on any object.
truth(
"var m = Date.prototype[Symbol.toPrimitive], p = Object.getOwnPropertyDescriptor(Date.prototype, Symbol.toPrimitive); \
typeof m === 'function' && m.length === 1 && !p.writable && !p.enumerable && p.configurable",
);
let o = "var o = { valueOf: function () { return 7; }, toString: function () { return 's'; } }, m = Date.prototype[Symbol.toPrimitive];";
truth(&format!("{o} m.call(o, 'number') === 7 && m.call(o, 'string') === 's' && m.call(o, 'default') === 's'"));
for call in ["m.call(o)", "m.call(o, 'other')", "m.call(o, new String('number'))", "m.call(1, 'number')", "m.call(o, 'defaultx')"] {
throws(&format!("{o} {call}"), "TypeError");
}
// A realm without the option keeps the String-hint order for a Date.
let src = format!("{date} d + 1 === 'date1' && d * 1 === 7");
assert_eq!(Realm::with_options(Options::default(), Limits::default()).run(&src), Ok(JsValue::Bool(true)));
}
#[test]
fn a_host_function_returns_a_symbol_only_in_an_es2015_realm() {
let symbol = |_: &[JsValue]| -> Result<JsValue, String> { Ok(JsValue::Symbol(Some("from host".into()))) };
let mut realm = es2015(Limits::default());
realm.define_function("make", symbol);
assert_eq!(realm.run("var s = make(); typeof s === 'symbol' && String(s) === 'Symbol(from host)' && s !== make()"), Ok(JsValue::Bool(true)));
let mut realm = Realm::with_options(Options::default(), Limits::default());
realm.define_function("make", symbol);
let src = "try { make(); 'none'; } catch (e) { (e instanceof TypeError) + ' ' + typeof Symbol; }";
assert_eq!(realm.run(src), Ok(JsValue::String("true undefined".into())));
}
#[test]
fn a_host_symbol_description_counts_against_the_heap_before_it_is_made() {
let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() });
realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1 << 20)))));
match realm.run("make()") {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. }) => {}
other => panic!("{other:?}"),
}
let mut realm = es2015(Limits { heap_bytes: 1 << 20, ..Limits::default() });
realm.define_function("make", |_| Ok(JsValue::Symbol(Some("d".repeat(1_000)))));
assert_eq!(realm.run("make().description.length"), Ok(JsValue::Number(1_000.0)));
}
#[test]
fn a_symbol_lookup_takes_fuel_for_each_prototype() {
// Building the chain takes about 20,000 units; each lookup of an absent Symbol walks all 2,000
// prototypes, so the 100 lookups take 200,000 more.
let src = "var s = Symbol(), o = {}; for (var i = 0; i < 2000; i++) o = Object.create(o); \
for (var j = 0; j < 100; j++) s in o;";
match es2015(Limits { fuel: 150_000, ..Limits::default() }).run(src) {
Err(RunError { kind: RunErrorKind::Limit(LimitKind::Fuel), .. }) => {}
other => panic!("{other:?}"),
}
let src = "var s = Symbol(), root = {}, o = root; root[s] = 'found'; for (var i = 0; i < 50; i++) o = Object.create(o); \
o[s] === 'found' && s in o && !o.hasOwnProperty(s)";
truth(src);
}
#[test]
fn iterator_steps_take_fuel() {
let mut realm = es2015(Limits { fuel: 5_000, ..Limits::default() });
+30 -7
View File
@@ -263,9 +263,10 @@ pub(crate) fn is_str_space(u: u16) -> bool {
crate::chars::is_whitespace(u32::from(u)) || crate::chars::is_line_terminator(u32::from(u))
}
/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, NaN for
/// anything else.
pub(crate) fn string_to_number(units: &[u16]) -> f64 {
/// ToNumber applied to a string (section 9.3.1): the StringNumericLiteral grammar, with the `0b`
/// and `0o` literals of ECMA-262 11th edition, section 7.1.3.1, as well when `binary_octal` is
/// set; NaN for anything else.
pub(crate) fn string_to_number(units: &[u16], binary_octal: bool) -> f64 {
let start = units.iter().position(|&u| !is_str_space(u)).unwrap_or(units.len());
let end = units.iter().rposition(|&u| !is_str_space(u)).map_or(start, |i| i + 1);
let Some(text) = units.get(start..end) else { return f64::NAN };
@@ -279,6 +280,15 @@ pub(crate) fn string_to_number(units: &[u16]) -> f64 {
}
return crate::chars::radix_value(hex.bytes().filter_map(|b| crate::chars::hex_value(u32::from(b))), 16).unwrap_or(f64::NAN);
}
if binary_octal {
for (prefix, radix) in [("0b", 2), ("0B", 2), ("0o", 8), ("0O", 8)] {
let Some(digits) = s.strip_prefix(prefix) else { continue };
if digits.is_empty() || !digits.chars().all(|c| c.is_digit(radix)) {
return f64::NAN;
}
return crate::chars::radix_value(digits.chars().filter_map(|c| c.to_digit(radix)), radix).unwrap_or(f64::NAN);
}
}
let (sign, body) = match s.as_bytes().first() {
Some(b'+') => (1.0, &s[1..]),
Some(b'-') => (-1.0, &s[1..]),
@@ -386,19 +396,32 @@ mod tests {
("-Infinity", f64::NEG_INFINITY),
];
for (s, want) in cases {
assert_eq!(string_to_number(&u(s)), *want, "{s:?}");
assert_eq!(string_to_number(&u(s), false), *want, "{s:?}");
}
for s in ["inf", "nan", "1_0", "0x", "1e", ".", "--1", "0x-1", "infinity", "1 2"] {
assert!(string_to_number(&u(s)).is_nan(), "{s:?}");
assert!(string_to_number(&u(s), false).is_nan(), "{s:?}");
}
}
#[test]
fn binary_and_octal_strings_convert_only_when_asked() {
for (s, want) in [("0b10", 2.0), ("0B11", 3.0), (" 0o17 ", 15.0), ("0O7", 7.0), ("0x10", 16.0), ("2", 2.0)] {
assert_eq!(string_to_number(&u(s), true), want, "{s:?}");
}
for s in ["0b", "0b2", "0o8", "-0b1", "+0o1", "0b1.0", "0o"] {
assert!(string_to_number(&u(s), true).is_nan(), "{s:?}");
}
for s in ["0b10", "0o2"] {
assert!(string_to_number(&u(s), false).is_nan(), "{s:?}");
}
}
#[test]
fn hex_strings_round_once_to_the_nearest_number() {
assert_eq!(string_to_number(&u("0xc83ce80553ee648")), 0xc83_ce80_553e_e648_u64 as f64);
assert_eq!(string_to_number(&u("0xc83ce80553ee648"), false), 0xc83_ce80_553e_e648_u64 as f64);
// 2^136 + 2^83 + 1: a set bit past 128 bits rounds the half-way case up.
let digits = format!("0x1{}8{}1", "0".repeat(13), "0".repeat(19));
assert_eq!(string_to_number(&u(&digits)), 2f64.powi(136) + 2f64.powi(84));
assert_eq!(string_to_number(&u(&digits), false), 2f64.powi(136) + 2f64.powi(84));
}
#[test]
+1 -1
View File
@@ -1083,7 +1083,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- `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), 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: 6,798 of 6,866 runs pass (the 34 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,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs `.jsx` scripts in, has none of these names. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm without the option, including the one the app runs `.jsx` scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: 164 of 216 runs pass (6 passed before), and the 52 others expect a configurable function `length` and a function `name` property. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`.
- With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator that threw, or whose `next()` said it was done, is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: 609 of 617 runs pass (529 before, most of them negative parse tests); the 8 others expect a function given as a default to take the name of its binding, a `name` property `vectorcraft-js` does not set. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
- Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report <path>]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`.
- With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`.