From e4751813293ca576c08eb8900e88910e6e7c98d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:56:22 -0800 Subject: [PATCH] JavaScript: Date.prototype[@@toPrimitive] and ToPrimitive fixes in ES2015 realms In a realm with `Options::es2015`, `Date.prototype[Symbol.toPrimitive]` converts with `toString` first for the hints "string" and "default" and with `valueOf` first for "number" (ECMA-262 11th edition, section 20.4.4.45). An object without an `@@toPrimitive` method, a Date whose own method is `null` or `undefined` included, converts without a hint with `valueOf` first (section 7.1.1.1), so `d + 1` gives 8 when `valueOf` returns 7. A realm without the option keeps the ES5 order for a Date. `JSON.stringify` converts a Number or String object with ToPrimitive. A `valueOf` or `toString` deleted from the object's own prototype is now looked up further along the chain, so `Object.prototype.toString` is called instead of the stored primitive value being returned. A Symbol that an object's `@@toPrimitive` method gives as a property key is rooted while the property is read or incremented, so it and its description still count against the heap when a getter starts a collection. --- crates/js/src/builtins/json.rs | 42 ++++----------------- crates/js/src/builtins/symbol.rs | 32 +++++++++++++--- crates/js/src/builtins_tests.rs | 4 ++ crates/js/src/interp.rs | 7 +++- crates/js/src/lib.rs | 6 ++- crates/js/src/symbol.rs | 8 ++-- crates/js/src/symbol_tests.rs | 65 ++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 8 files changed, 118 insertions(+), 48 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 6fc8544e9d..e01a47b085 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -565,47 +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. -/// An `@@toPrimitive` method on the object, in a realm with [`crate::Options::es2015`], is called -/// before either (ECMA-262 11th edition, section 7.1.1). +/// 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> { 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 = match interp.exotic_to_primitive(*o, v, hint)? { - Some(p) => p, - None if reaches_prototype(interp, *o, proto, name)? => primitive, - None => interp.ordinary_to_primitive(*o, 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 { - 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])?; diff --git a/crates/js/src/builtins/symbol.rs b/crates/js/src/builtins/symbol.rs index f0afe7b2f8..b671f51e42 100644 --- a/crates/js/src/builtins/symbol.rs +++ b/crates/js/src/builtins/symbol.rs @@ -1,12 +1,12 @@ //! `Symbol` (ECMA-262 11th edition, section 19.4, ): //! 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 { + 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 { diff --git a/crates/js/src/builtins_tests.rs b/crates/js/src/builtins_tests.rs index 0a70e80433..c009dddc9a 100644 --- a/crates/js/src/builtins_tests.rs +++ b/crates/js/src/builtins_tests.rs @@ -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] diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 742e31330f..3c6f73cb64 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2782,8 +2782,11 @@ impl Interp { /// [[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 { - // 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(_))); + // 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)?; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 4cdb639c85..4b02563e08 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -53,8 +53,10 @@ //! `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 +//! `@@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. diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 34fd489fa3..e89bbeb9f4 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -239,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))), } diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index 5e372bdafd..a11c105107 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -241,6 +241,71 @@ fn json_calls_the_to_primitive_method_of_a_wrapper() { 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 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] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 2579945202..48ce92a005 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1082,7 +1082,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`. 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. 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 scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `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 scripts in, has none of these names, and a host function that returns a Symbol there throws a `TypeError`. The language does not have `for`-`of`, spread or destructuring yet, so scripts call `next()` themselves. `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`. - 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 ]` 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`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`.