From c021b269e7fd3ffff564c8b9b2a7414a63afc6af Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:24:03 -0800 Subject: [PATCH 1/3] 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`. From e4751813293ca576c08eb8900e88910e6e7c98d7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 01:56:22 -0800 Subject: [PATCH 2/3] 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`. From 93df144331b105009fc7fe966abd3bd8641079e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:35:00 -0800 Subject: [PATCH 3/3] JavaScript: keep Symbol keys and converted operands counted while script runs Object.defineProperties and Object.create now keep the Symbol keys of the properties object rooted until they are defined, so a getter that deletes a Symbol-keyed property already read no longer lets a collection drop the Symbol's description from the heap count. The + operator and the relational comparisons now keep the first operand's converted value rooted while the second operand's @@toPrimitive or valueOf runs, so a fresh Symbol or string from the first conversion stays counted against the heap limit. --- crates/js/src/builtins/object.rs | 10 ++++++- crates/js/src/interp.rs | 9 ++++-- crates/js/src/symbol_tests.rs | 51 ++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index 48fdbb6eda..42947c7d7a 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -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; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 3c6f73cb64..405874dc96 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -2993,7 +2993,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. @@ -3007,12 +3008,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> { + // 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. diff --git a/crates/js/src/symbol_tests.rs b/crates/js/src/symbol_tests.rs index a11c105107..6ea28e1dee 100644 --- a/crates/js/src/symbol_tests.rs +++ b/crates/js/src/symbol_tests.rs @@ -283,6 +283,57 @@ fn a_symbol_key_from_to_primitive_counts_against_the_heap_while_the_property_is_ } } +#[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'; };";