From c021b269e7fd3ffff564c8b9b2a7414a63afc6af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:24:03 -0800 Subject: [PATCH] JavaScript: tighten Symbol conversions, lookups and host crossings in ES2015 realms - A string in `0b` or `0o` form converts to a number in a realm with `Options::es2015`, so an array iterator over an object whose length is "0b10" visits two elements. Realms without the option still read such strings as NaN. - `JSON.stringify` calls a String or Number object's `@@toPrimitive` method before using its stored value, for the value itself, a replacer list entry and the `space` argument. - A host function that returns a Symbol in a realm without the option throws a `TypeError`. A Symbol's description is charged to the heap before it is built. - A text function takes a Symbol as `String(symbol)` gives it, and a data function refuses an object or array with an enumerable Symbol-keyed property; checking the keys takes fuel. - A Symbol-keyed lookup takes a unit of fuel for each prototype it passes, and removing most of an object's Symbol keys releases their storage. --- crates/js/src/builtins/json.rs | 8 ++++- crates/js/src/chars.rs | 2 +- crates/js/src/host.rs | 17 ++++++++- crates/js/src/host_tests.rs | 39 +++++++++++++++++++++ crates/js/src/interp.rs | 32 +++++++++++------ crates/js/src/lib.rs | 10 +++--- crates/js/src/realm.rs | 3 +- crates/js/src/symbol.rs | 32 +++++++++++++++-- crates/js/src/symbol_tests.rs | 64 ++++++++++++++++++++++++++++++++++ crates/js/src/value.rs | 37 ++++++++++++++++---- docs/target-app-parity.md | 2 +- 11 files changed, 217 insertions(+), 29 deletions(-) diff --git a/crates/js/src/builtins/json.rs b/crates/js/src/builtins/json.rs index 6f659922b2..6fc8544e9d 100644 --- a/crates/js/src/builtins/json.rs +++ b/crates/js/src/builtins/json.rs @@ -570,6 +570,8 @@ fn resolve_rooted(interp: &mut Interp, settings: &Settings, holder: ObjId, k: &K /// 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). 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) { @@ -578,7 +580,11 @@ fn unwrap_primitive(interp: &mut Interp, v: &Value, as_string: bool) -> JsResult _ => 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 = 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)?, + }; Ok(Some(if string { Value::String(interp.to_str(&p)?) } else { Value::Number(interp.to_number(&p)?) })) } diff --git a/crates/js/src/chars.rs b/crates/js/src/chars.rs index 61b9a7f318..60df43513c 100644 --- a/crates/js/src/chars.rs +++ b/crates/js/src/chars.rs @@ -123,7 +123,7 @@ pub fn hex_value(c: u32) -> Option { } } -/// 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. diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 967d5e3656..a57abaea06 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -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 { - 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())) } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..9fb7acc503 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -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>> = 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); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 13ac5cd834..742e31330f 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2776,11 +2776,17 @@ impl Interp { if let Some(r) = self.exotic_to_primitive(*o, v, hint)? { return Ok(r); } + 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 { // 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(_))); + let date = hint == Hint::Default && 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(_)) { @@ -2791,6 +2797,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 { Ok(match v { @@ -2798,7 +2806,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)?; @@ -3035,7 +3043,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))), @@ -3105,9 +3113,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 { Ok(match v { @@ -3122,12 +3131,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> = 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)) } }) } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index c5e45af08f..4cdb639c85 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -55,8 +55,9 @@ //! 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. +//! `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; @@ -113,8 +114,9 @@ pub struct Options { /// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins. pub e4x: bool, /// Give a realm 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. + /// 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, } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 08d9913948..ae3021dada 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -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, diff --git a/crates/js/src/symbol.rs b/crates/js/src/symbol.rs index 2c25ebd099..34fd489fa3 100644 --- a/crates/js/src/symbol.rs +++ b/crates/js/src/symbol.rs @@ -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) @@ -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> { + /// 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> { 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 { + pub(crate) fn has_pk(&mut self, id: ObjId, k: &PropKey) -> JsResult { 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 = (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::>(), keys[90..]); + } +} diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index d877e04106..5e372bdafd 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -219,6 +219,70 @@ 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]'"); +} + +#[test] +fn a_host_function_returns_a_symbol_only_in_an_es2015_realm() { + let symbol = |_: &[JsValue]| -> Result { 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() }); diff --git a/crates/js/src/value.rs b/crates/js/src/value.rs index 66005773e2..4911c6e36b 100644 --- a/crates/js/src/value.rs +++ b/crates/js/src/value.rs @@ -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] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3264973bf5..2579945202 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`. 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 scripts in, has none of these names. 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. 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`.