From e7bf7b789f773fc3482862d46949d9e75a85cb02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 16:51:11 -0800 Subject: [PATCH] Scripts: Map, Set and typed array constructors read their argument through its iterator new Map, new Set, new WeakMap and new WeakSet read their argument by index (an array, a string or an object with a length), so a generator, a Map, a Set or any other iterable was a TypeError, and an array whose @@iterator was replaced was still read by index. They now read it through GetIterator and close the iterator when adding an entry throws (ECMAScript 2015, sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1). A Map or WeakMap entry that is not an object is a TypeError. The typed array constructors and %TypedArray%.from read a source with an @@iterator method through its iterator to the end before mapping it, and any other source as an array-like object (sections 22.2.1.4 and 22.2.2.1). Map.prototype[@@iterator] is entries, Set.prototype[@@iterator] is values, %TypedArray%.prototype[@@iterator] is values, and the Map, Set and array iterators inherit %IteratorPrototype%, so for-of and spread walk them. Changed behavior: an array-like object without @@iterator passed to new Set or new Map is now a TypeError, and Uint8Array.from([1, 1], f) with an f that changes the array maps the values read before f ran. --- crates/js/src/builtins/binary.rs | 126 +++++++++++++------------- crates/js/src/builtins/collections.rs | 84 ++++++----------- crates/js/src/collections_tests.rs | 92 ++++++++++++++++++- crates/js/src/iteration.rs | 49 +++++++++- crates/js/src/lib.rs | 11 ++- docs/target-app-parity.md | 2 +- 6 files changed, 229 insertions(+), 135 deletions(-) diff --git a/crates/js/src/builtins/binary.rs b/crates/js/src/builtins/binary.rs index 39734bb088..3ec93edc07 100644 --- a/crates/js/src/builtins/binary.rs +++ b/crates/js/src/builtins/binary.rs @@ -15,12 +15,13 @@ //! every buffer's bytes are checked against the heap before they are allocated. Every element //! a method visits takes a unit of fuel, and a sort's comparisons take one each. //! -//! The language has no iterators yet, so constructing from an object reads an array or an object -//! with a `length`, by index, and `%TypedArray%.from` reads those or a string, by code point. A -//! constructor given a primitive string reads it as a length. +//! Constructing from an object that is not a buffer or a typed array, and `%TypedArray%.from`, +//! read a source with an `@@iterator` method through its iterator (a string by code point), and +//! any other source as an array-like object, by index. `%TypedArray%.prototype[@@iterator]` is +//! `values`. A constructor given a primitive string reads it as a length. -use super::collections::{for_each_item, getter, length_of, new_iter, new_proto}; -use super::{arg, array, data, method, native, require_callable, to_integer}; +use super::collections::{getter, length_of, new_iter, new_proto}; +use super::{arg, array, data, method, native, new_array, require_callable, to_integer}; use crate::heap::{Class, Elem, HIDDEN, IterKind, IterSource, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, VIEW_BYTES, View, key}; use crate::interp::{Abrupt, Desc, ErrorType, Interp, JsResult}; use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint32}; @@ -28,9 +29,6 @@ use crate::value::{Value, array_index, number_to_str, string_to_number, to_uint3 /// The longest buffer, in bytes. const MAX_BUFFER: u64 = u32::MAX as u64; -/// The bytes each item a method gathers before it writes them is charged. -const ITEM_BYTES: usize = 16; - pub(super) fn install(interp: &mut Interp) -> JsResult<()> { install_array_buffer(interp)?; install_data_view(interp)?; @@ -124,6 +122,11 @@ fn install_typed_arrays(interp: &mut Interp) -> JsResult<()> { for (name, f, length) in methods { method(interp, proto, name, f, length)?; } + // `%TypedArray%.prototype[@@iterator]` is `values` (section 22.2.3.30). + if let Some(iterator) = interp.well_known(|w| &w.iterator) { + let values = interp.get_from(proto, &key("values"), &Value::Object(proto))?; + interp.define_sym(proto, iterator, crate::heap::Prop::Data { value: values, flags: HIDDEN })?; + } // `%TypedArray%.prototype.toString` is `Array.prototype.toString` (section 22.2.3.28). let array_proto = interp.intrinsics.array_proto; let to_string = interp.get_from(array_proto, &key("toString"), &Value::Object(array_proto))?; @@ -645,21 +648,59 @@ fn typed_ctor(interp: &mut Interp, args: &[Value], constructing: bool, elem: Ele } return Ok(Value::Object(ta)); } - let len = length_of(interp, o)?; - let ta = new_typed(interp, elem, len)?; - interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, &first, len))?; - Ok(Value::Object(ta)) + // Any other object is read as TypedArrayFrom reads it (section 22.2.1.4). + typed_array_from(interp, &first, None, |interp, len| new_typed(interp, elem, len)) } -/// Writes the elements `0` to `len - 1` of the array-like object `src` to the typed array `ta`, -/// each converted with ToNumber. -fn fill_from(interp: &mut Interp, ta: ObjId, src: &Value, len: u64) -> JsResult<()> { - let Value::Object(o) = src else { return Ok(()) }; +/// TypedArrayFrom (section 22.2.2.1.1): a typed array with the values of `items`, made by `make` +/// once their number is known, each value mapped with `map` (the function and its `this`) when +/// one is given and converted with ToNumber. An `items` with an `@@iterator` method is read +/// through its iterator to the end before the typed array is made. Any other value is read as +/// an array-like object, each element read, mapped and written before the next is read. +fn typed_array_from( + interp: &mut Interp, + items: &Value, + map: Option<(&Value, &Value)>, + make: impl FnOnce(&mut Interp, u64) -> JsResult, +) -> JsResult { + let using_iterator = match interp.well_known(|w| &w.iterator) { + Some(iterator) => interp.get_value_sym(items, &iterator)?, + None => Value::Undefined, + }; + let src = if using_iterator.is_nullish() { + interp.to_object(items)? + } else { + let rec = interp.get_iterator_with(items, &using_iterator)?; + interp.rooted(&[Value::Object(rec)], |interp| { + let list = new_array(interp, 0)?; + interp.rooted(&[Value::Object(list)], |interp| interp.append_values(rec, list))?; + Ok(list) + })? + }; + let src_value = Value::Object(src); + interp.rooted(std::slice::from_ref(&src_value), |interp| { + let len = length_of(interp, src)?; + let ta = make(interp, len)?; + interp.rooted(&[Value::Object(ta)], |interp| fill_from(interp, ta, src, len, map))?; + Ok(Value::Object(ta)) + }) +} + +/// Writes the elements `0` to `len - 1` of the object `src` to the typed array `ta`, each mapped +/// with `map` when one is given and converted with ToNumber. Each element is read just before it +/// is mapped and written. +fn fill_from(interp: &mut Interp, ta: ObjId, src: ObjId, len: u64, map: Option<(&Value, &Value)>) -> JsResult<()> { let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; + let src_value = Value::Object(src); for i in 0..len { interp.use_fuel()?; #[allow(clippy::cast_precision_loss)] - let v = interp.get_from(*o, &super::key_of(i as f64), src)?; + let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; + #[allow(clippy::cast_precision_loss)] + let v = match map { + Some((f, this_arg)) => interp.call(f, this_arg, &[item, Value::Number(i as f64)])?, + None => item, + }; let n = interp.to_number(&v)?; write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); } @@ -741,54 +782,11 @@ fn typed_from(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsRe require_callable(interp, &map_fn, "the map function")?; } let this_arg = arg(args, 2); - let source = arg(args, 0); - if !matches!(source, Value::String(_)) { - // An array-like source: each element is read, mapped and written before the next is read. - let src = interp.to_object(&source)?; - let src_value = Value::Object(src); - let len = length_of(interp, src)?; + let map = mapping.then_some((&map_fn, &this_arg)); + typed_array_from(interp, &arg(args, 0), map, |interp, len| { let elem = ctor_elem(interp, &this, "from")?; - let ta = interp.rooted(std::slice::from_ref(&src_value), |interp| new_typed(interp, elem, len))?; - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - return interp.rooted(&[Value::Object(ta), src_value.clone()], |interp| { - for i in 0..len { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let item = interp.get_from(src, &super::key_of(i as f64), &src_value)?; - #[allow(clippy::cast_precision_loss)] - let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; - let n = interp.to_number(&v)?; - write(interp, &view, usize::try_from(i).unwrap_or(usize::MAX), n); - } - Ok(Value::Object(ta)) - }); - } - // A string is read by code point first, as an iterable source is, and then mapped. - let mark = interp.temp_roots.len(); - let mut held = crate::interp::HeldBytes::new(interp); - let gathered = for_each_item(interp, &source, false, |interp, item| { - held.add(interp, ITEM_BYTES)?; - interp.temp_roots.push(item); - Ok(()) - }); - let result = gathered.and_then(|()| { - let items: Vec = interp.temp_roots.get(mark..).map(<[Value]>::to_vec).unwrap_or_default(); - let elem = ctor_elem(interp, &this, "from")?; - let ta = new_typed(interp, elem, items.len() as u64)?; - interp.temp_roots.push(Value::Object(ta)); - let view = view_of(interp, ta).ok_or_else(|| Abrupt::Internal("not a typed array".into()))?; - for (i, item) in items.into_iter().enumerate() { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let v = if mapping { interp.call(&map_fn, &this_arg, &[item, Value::Number(i as f64)])? } else { item }; - let n = interp.to_number(&v)?; - write(interp, &view, i, n); - } - Ok(Value::Object(ta)) - }); - interp.temp_roots.truncate(mark); - drop(held); - result + new_typed(interp, elem, len) + }) } /// `%TypedArray%.of(...items)` (section 22.2.2.2). diff --git a/crates/js/src/builtins/collections.rs b/crates/js/src/builtins/collections.rs index 70da37c39c..2d9f6176d3 100644 --- a/crates/js/src/builtins/collections.rs +++ b/crates/js/src/builtins/collections.rs @@ -8,18 +8,20 @@ //! entries hold their key weakly: the collector removes an entry once its key is reachable only //! through it ([`crate::heap::Heap::collect`]), and they have no size and cannot be listed. //! -//! The language has no iterators yet, so the constructors read their argument by index: an -//! array or an object with a `length`, or a string by code point. Every entry added is checked -//! against the heap limit before it is added, and every entry visited takes a unit of fuel. +//! The constructors read their argument through its `@@iterator` method (GetIterator, section +//! 7.4.1), and close the iterator when adding an entry throws (IteratorClose, section 7.4.6). +//! `Map.prototype[@@iterator]` is `entries`, `Set.prototype[@@iterator]` is `values`, and the +//! iterators inherit from `%IteratorPrototype%`. Every entry added is checked against the heap +//! limit before it is added, and every entry visited takes a unit of fuel. -use super::{arg, constructor, create_at, key_of, method, native, new_array, require_callable}; +use super::{arg, constructor, create_at, method, native, new_array, require_callable}; use crate::heap::{ COLL_ENTRY_BYTES, CONFIGURABLE, Class, Coll, CollKey, IterKind, IterSource, IterState, NativeFn, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, VIEW_BYTES, WEAK_ENTRY_BYTES, WeakColl, key, string_bytes, }; use crate::interp::{Abrupt, Interp, JsResult}; use crate::string_builtins::flat_charged; -use crate::value::{Str, Value}; +use crate::value::Value; /// The ECMAScript 2015 intrinsics the built-ins make their objects with, whatever a script does /// to the globals. @@ -137,7 +139,14 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> { getter(interp, set_proto, "get size", set_size)?; // `Set.prototype.keys` is the same function object as `values` (section 23.2.3.8). let values = interp.get_from(set_proto, &key("values"), &Value::Object(set_proto))?; - interp.define(set_proto, key("keys"), Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + interp.define(set_proto, key("keys"), Prop::Data { value: values.clone(), flags: crate::heap::HIDDEN })?; + // `Map.prototype[@@iterator]` is `entries` and `Set.prototype[@@iterator]` is `values` + // (sections 23.1.3.12 and 23.2.3.11). + if let Some(iterator) = interp.well_known(|w| &w.iterator) { + let entries = interp.get_from(map_proto, &key("entries"), &Value::Object(map_proto))?; + interp.define_sym(map_proto, iterator.clone(), Prop::Data { value: entries, flags: crate::heap::HIDDEN })?; + interp.define_sym(set_proto, iterator, Prop::Data { value: values, flags: crate::heap::HIDDEN })?; + } let weak_map_proto = new_proto(interp, object_proto); interp.intrinsics.es2015.weak_map_proto = weak_map_proto; @@ -158,8 +167,12 @@ pub(super) fn install(interp: &mut Interp) -> JsResult<()> { method(interp, weak_set_proto, name, f, length)?; } + // The iterators' prototypes inherit from `%IteratorPrototype%` (sections 23.1.5.2, 23.2.5.2 + // and 22.1.5.2), whose `@@iterator` gives the iterator itself. + let iterator_proto = + interp.symbols.objects.and_then(|o| interp.heap.object(o.array_iterator_proto).and_then(|p| p.proto)).unwrap_or(object_proto); for source in [IterSource::Map, IterSource::Set, IterSource::Array] { - let proto = new_proto(interp, object_proto); + let proto = new_proto(interp, iterator_proto); let next: NativeFn = match source { IterSource::Map => map_iterator_next, IterSource::Set => set_iterator_next, @@ -209,56 +222,10 @@ pub(crate) fn length_of(interp: &mut Interp, o: ObjId) -> JsResult { Ok(if n <= 0.0 { 0 } else { n.min(9_007_199_254_740_991.0) as u64 }) } -/// Calls `f` with each item of `list`, read by index: an object's elements up to its `length`, -/// or a string's code points. Any other value is a `TypeError`, and so is an object without a -/// `length` when `need_length` is true. Each item takes a unit of fuel. -pub(crate) fn for_each_item( - interp: &mut Interp, - list: &Value, - need_length: bool, - mut f: impl FnMut(&mut Interp, Value) -> JsResult<()>, -) -> JsResult<()> { - match list { - Value::Object(o) => { - if need_length && !interp.has_property(*o, &key("length"))? { - return Err(interp.type_error("the value is not an array, a string or an object with a length")); - } - let len = length_of(interp, *o)?; - let mut i = 0u64; - while i < len { - interp.use_fuel()?; - #[allow(clippy::cast_precision_loss)] - let item = interp.get_from(*o, &key_of(i as f64), list)?; - f(interp, item)?; - i += 1; - } - Ok(()) - } - Value::String(s) => { - let units = flat_charged(interp, s)?; - let mut i = 0; - while i < units.len() { - interp.use_fuel()?; - let width = match (units.get(i), units.get(i + 1)) { - (Some(hi), Some(lo)) if (0xD800..0xDC00).contains(hi) && (0xDC00..0xE000).contains(lo) => 2, - _ => 1, - }; - let piece = units.get(i..i + width).unwrap_or_default().to_vec(); - let bytes = string_bytes(piece.len()); - interp.reserve_heap(bytes)?; - interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); - f(interp, Value::String(Str::from_units(piece)))?; - i += width; - } - Ok(()) - } - _ => Err(interp.type_error("the value is not an array, a string or an object with a length")), - } -} - -/// Adds the items of `list` to the new collection `target` with its `adder` method, as the -/// constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` reads each item -/// as a `[key, value]` entry. +/// Adds the values the iterator of `list` gives to the new collection `target` with its `adder` +/// method, as the constructors do (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1); `pairs` +/// reads each value as a `[key, value]` entry, which must be an object. When reading an entry +/// or adding it throws, the iterator is closed. fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bool) -> JsResult<()> { if list.is_nullish() { return Ok(()); @@ -268,7 +235,8 @@ fn fill(interp: &mut Interp, target: ObjId, list: &Value, adder: &str, pairs: bo let add = interp.get_from(target, &key(adder), &this)?; require_callable(interp, &add, adder)?; interp.rooted(std::slice::from_ref(&add), |interp| { - for_each_item(interp, list, true, |interp, item| { + let rec = interp.get_iterator(list)?; + interp.for_each_value(rec, |interp, item| { if !pairs { return interp.call(&add, &this, &[item]).map(drop); } diff --git a/crates/js/src/collections_tests.rs b/crates/js/src/collections_tests.rs index cbc35d3929..31230e4958 100644 --- a/crates/js/src/collections_tests.rs +++ b/crates/js/src/collections_tests.rs @@ -131,10 +131,11 @@ fn iterators_step_through_live_entries() { } #[test] -fn constructors_read_arrays_strings_and_array_likes() { +fn constructors_read_arrays_and_strings() { truth("var m = new Map([[1, 'a'], [2, 'b']]); m.size === 2 && m.get(2) === 'b'"); truth("new Set('ab\u{1F600}b').size === 3"); - truth("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'}).size === 2"); + // An object without `@@iterator` is not iterable, whatever its `length` (section 23.2.1.1). + throws("new Set({length: 3, 0: 'a', 1: 'a', 2: 'b'})", "TypeError"); truth("new Map(null).size === 0 && new Set(undefined).size === 0"); truth("Object.prototype.toString.call(new Set()) === '[object Set]' && Object.prototype.toString.call(new WeakMap()) === '[object WeakMap]'"); throws("Map()", "TypeError"); @@ -146,7 +147,8 @@ fn constructors_read_arrays_strings_and_array_likes() { truth("Uint8Array.from({}).length === 0 && new Uint8Array({}).length === 0 && DataView.length === 1 && Uint8Array.length === 3"); // `from` reads each element of an array-like source just before mapping it (section 22.2.2.1). truth("var src = {length: 2, 0: 1, 1: 1}; Uint8Array.from(src, function (v, i) { src[1] = 7; return v; }).join() === '1,7'"); - truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,14'"); + // An iterable source is read to the end before the first value is mapped (section 22.2.2.1.1). + truth("var src = [1, 1]; Uint8Array.from(src, function (v, i) { src[1] = 7; return v * 2; }).join() === '2,2'"); truth("Uint8Array.from('ab', function (v) { return v.charCodeAt(0); }).join() === '97,98'"); throws("Map.prototype.get.call({}, 1)", "TypeError"); throws("Object.getOwnPropertyDescriptor(Map.prototype, 'size').get.call(new Set())", "TypeError"); @@ -158,6 +160,86 @@ fn constructors_read_arrays_strings_and_array_likes() { truth("JSON.stringify(new Map([[1, 2]])) === '{}' && JSON.stringify(new Set([1])) === '{}'"); } +/// An iterable that gives `values` and counts the calls of its `return` method in `closed`. +const CLOSING: &str = "var closed = 0; function closing(values) { var i = 0; return { [Symbol.iterator]: function () { return this; }, \ + next: function () { return i < values.length ? { value: values[i++], done: false } : { done: true }; }, \ + return: function () { closed++; return {}; } }; }"; + +#[test] +fn constructors_read_their_argument_through_its_iterator() { + // GetIterator and IteratorStep (sections 23.1.1.1, 23.2.1.1, 23.3.1.1, 23.4.1.1 and 22.2.1.4). + truth("function* g() { yield 1; yield 2; yield 1; } var s = new Set(g()); s.size === 2 && s.has(2)"); + truth("function* g() { yield ['a', 1]; yield ['b', 2]; } new Map(g()).get('b') === 2"); + truth("function* g() { yield 3; yield 4; } new Uint8Array(g()).join() === '3,4' && Int16Array.from(g()).join() === '3,4'"); + truth(&format!("{CLOSING} var s = new Set(closing(['x', 'y'])); s.size === 2 && s.has('y') && closed === 0")); + truth(&format!( + "{CLOSING} var k = {{}}; var w = new WeakMap(closing([[k, 5]])); var ws = new WeakSet(closing([k])); w.get(k) === 5 && ws.has(k)" + )); + truth(&format!("{CLOSING} new Float64Array(closing([1.5, 2])).join() === '1.5,2' && closed === 0")); + // A string is read by code point, as its iterator reads it. + truth("new Set('\\uD83D\\uDE00\\uD83D\\uDE00').size === 1 && new Set('\\uD83D\\uDE00x').has('\\uD83D\\uDE00')"); + truth("var m = new Map([[1, 'a']]); Array.prototype.join.call(Uint8Array.from(m.keys())) === '1'"); + // An array is read through its `@@iterator`, not by index. + truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; var s = new Set(a); s.has(9) && !s.has(1)"); + truth("var a = [1, 2]; a[Symbol.iterator] = function () { return [9][Symbol.iterator](); }; new Uint8Array(a).join() === '9'"); + // An object without `@@iterator` is still read by index by the typed array constructors. + truth("new Uint8Array({length: 2, 0: 1, 1: 2}).join() === '1,2'"); + throws("new Set({ [Symbol.iterator]: 1 })", "TypeError"); + throws("new Uint8Array({ [Symbol.iterator]: 1 })", "TypeError"); +} + +#[test] +fn collections_and_typed_arrays_are_iterable() { + // Sections 23.1.3.12, 23.2.3.11 and 22.2.3.30. + truth("Map.prototype[Symbol.iterator] === Map.prototype.entries && Set.prototype[Symbol.iterator] === Set.prototype.values"); + truth("var p = Object.getPrototypeOf(Int8Array.prototype); p[Symbol.iterator] === p.values"); + truth("var m = new Map([[1, 'a'], [2, 'b']]); var out = []; for (var e of m) out.push(e.join(':')); out.join() === '1:a,2:b'"); + truth("var out = []; for (var v of new Set([3, 4])) out.push(v); for (var v of new Int8Array([5])) out.push(v); out.join() === '3,4,5'"); + truth("var m = new Map([[1, 2]]); new Map(m).get(1) === 2 && new Set(new Set([7])).has(7) && new Set(new Uint8Array([8])).has(8)"); + // The iterators inherit `%IteratorPrototype%[@@iterator]` (sections 23.1.5.2, 23.2.5.2 and 22.1.5.2). + truth("var it = new Map().keys(); it[Symbol.iterator]() === it && new Set([1]).values()[Symbol.iterator]().next().value === 1"); + truth("var it = new Int8Array([6]).values(); it[Symbol.iterator]() === it && [...new Set([1, 2]).keys()].join() === '1,2'"); +} + +#[test] +fn a_map_entry_that_is_not_an_object_closes_the_iterator() { + // Section 23.1.1.1, step 10.d. + truth(&format!("{CLOSING} var caught; try {{ new Map(closing([1])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1")); + truth(&format!( + "{CLOSING} var caught; try {{ new WeakMap(closing(['k'])); }} catch (e) {{ caught = e instanceof TypeError; }} caught && closed === 1" + )); +} + +#[test] +fn an_iterator_whose_next_throws_is_not_closed() { + let src = "var closed = 0; var it = { [Symbol.iterator]: function () { return this; }, \ + next: function () { throw new RangeError('next'); }, return: function () { closed++; return {}; } };"; + for make in ["new Set(it)", "new Map(it)", "new WeakSet(it)", "new Uint8Array(it)", "Uint8Array.from(it)"] { + truth(&format!( + "{src} var caught; try {{ {make}; }} catch (e) {{ caught = e instanceof RangeError && e.message === 'next'; }} caught && closed === 0" + )); + } +} + +#[test] +fn a_throwing_adder_closes_the_iterator() { + // IteratorClose (section 7.4.6) keeps the adder's exception, even when `return` throws too. + for (ctor, adder) in [("Set", "add"), ("Map", "set"), ("WeakSet", "add"), ("WeakMap", "set")] { + let src = format!( + "{CLOSING} var o = {{}}; {ctor}.prototype.{adder} = function () {{ throw new RangeError('adder'); }}; var caught; \ + try {{ new {ctor}(closing([[o, 1], [o, 2]])); }} catch (e) {{ caught = e instanceof RangeError && e.message === 'adder'; }}" + ); + truth(&format!("{src} caught && closed === 1")); + let throwing = src.replace("closed++; return {};", "closed++; throw new TypeError('return');"); + truth(&format!("{throwing} caught && closed === 1")); + } + // A Map entry whose `0` getter throws closes the iterator as well. + truth(&format!( + "{CLOSING} var bad = {{ get 0() {{ throw new RangeError('key'); }} }}; var caught; \ + try {{ new Map(closing([bad])); }} catch (e) {{ caught = e.message === 'key'; }} caught && closed === 1" + )); +} + // ---- WeakMap and WeakSet ---- #[test] @@ -220,7 +302,9 @@ fn collections_of_millions_end_at_the_limits() { assert_eq!(limit(&heap, "var m = new Map(); for (var i = 0; ; i++) m.set(i, i);"), LimitKind::Heap); assert_eq!(limit(&heap, "var s = new Set(); for (var i = 0; ; i++) s.add('k' + i);"), LimitKind::Heap); let fuel = Limits { fuel: 100_000, ..Limits::default() }; - assert_eq!(limit(&fuel, "new Set({length: 1e15})"), LimitKind::Fuel); + let endless = "{ [Symbol.iterator]: function () { return { next: function () { return { value: 1, done: false }; } }; } }"; + assert_eq!(limit(&fuel, &format!("new Set({endless})")), LimitKind::Fuel); + assert_eq!(limit(&fuel, &format!("new Uint8Array({endless})")), LimitKind::Fuel); let m = "var m = new Map(); for (var i = 0; i < 1000; i++) m.set(i, i); m.forEach(function () { for (;;) {} });"; assert_eq!(limit(&fuel, m), LimitKind::Fuel); } diff --git a/crates/js/src/iteration.rs b/crates/js/src/iteration.rs index eac1d4abe6..c0ce093ebb 100644 --- a/crates/js/src/iteration.rs +++ b/crates/js/src/iteration.rs @@ -59,7 +59,12 @@ impl Interp { Some(_) => Value::Undefined, None => return self.walk_record(v), }; - if !self.is_callable(&method) { + self.get_iterator_with(v, &method) + } + + /// GetIterator (section 7.4.1) with `method`, the `@@iterator` method already read from `v`. + pub(crate) fn get_iterator_with(&mut self, v: &Value, method: &Value) -> JsResult { + if !self.is_callable(method) { let what = match v { Value::Undefined => "undefined", Value::Null => "null", @@ -67,7 +72,7 @@ impl Interp { }; return Err(self.type_error(&format!("{what} is not iterable"))); } - let iterator = self.call(&method, v, &[])?; + let iterator = self.call(method, v, &[])?; if !matches!(iterator, Value::Object(_)) { return Err(self.type_error("the iterator is not an object")); } @@ -187,6 +192,41 @@ impl Interp { }) } + /// Calls `f` with each value the iterator of `rec` gives, until it is done. When `f` throws, + /// the iterator is closed ([`Interp::iter_close_after_throw`]) and the exception is thrown + /// again; when a step throws, the iterator is not closed. `rec` and each value are kept + /// reachable while `f` runs. + pub(crate) fn for_each_value(&mut self, rec: ObjId, mut f: impl FnMut(&mut Self, Value) -> JsResult<()>) -> JsResult<()> { + self.rooted(&[Value::Object(rec)], |i| { + while let Some(v) = i.iter_next(rec)? { + match i.rooted(std::slice::from_ref(&v), |i| f(i, v.clone())) { + Ok(()) => {} + Err(Abrupt::Throw(reason)) => return Err(i.iter_close_after_throw(rec, reason)), + Err(other) => return Err(other), + } + } + Ok(()) + }) + } + + /// IteratorClose (section 7.4.6) with the exception `reason`: closes the iterator of `rec` + /// unless it is done, and gives back `reason` to throw, with the position it was thrown from. + /// What closing it throws is dropped, the lookup of `return` included (ECMA-262 2023 section + /// 7.4.8, steps 4 to 6); running out of fuel, heap or time is not. + pub(crate) fn iter_close_after_throw(&mut self, rec: ObjId, reason: Value) -> Abrupt { + let site = self.throw_site.clone(); + let mark = self.thrown_mark; + match self.rooted(std::slice::from_ref(&reason), |i| i.iter_close(rec)) { + Ok(()) | Err(Abrupt::Throw(_)) => { + self.throw_site = site; + self.thrown_mark = mark; + self.passing = reason.clone(); + Abrupt::Throw(reason) + } + Err(other) => other, + } + } + /// `value` → `record`. pub(crate) fn op_get_iterator(&mut self) -> JsResult<()> { let v = self.peek(0)?; @@ -227,8 +267,9 @@ impl Interp { self.append_values(rec, a) } - /// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack. - fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> { + /// Appends the values the iterator of `rec` gives to the array `a`; both are on the stack or + /// otherwise kept reachable. + pub(crate) fn append_values(&mut self, rec: ObjId, a: ObjId) -> JsResult<()> { while let Some(v) = self.iter_next(rec)? { let Class::Array { length, .. } = &self.object(a)?.class else { return internal("not an array") }; let i = *length; diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 346f21eb58..1f2863ed2d 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -103,10 +103,13 @@ //! entries added while it runs; `WeakMap` and `WeakSet` (23.3 and 23.4), whose entries the //! collector removes once their keys are unreachable; and `ArrayBuffer`, `DataView` and the nine //! typed arrays (24.1, 24.2 and 22.2). `keys`, `values` and `entries` give iterator objects with -//! a `next` method. Until the language has iterators, the collection constructors and -//! `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by -//! index. A typed array constructor reads an array or an object with a `length` the same way, and -//! converts a first argument that is not an object to a length. A buffer longer than the heap +//! a `next` method, and `Map`, `Set` and the typed arrays are iterable. The collection +//! constructors read their argument through its `@@iterator` method (sections 23.1.1.1 to +//! 23.4.1.1), so an object without one is a `TypeError`, and a `Map` entry that is not an object +//! is a `TypeError` too. A typed array constructor given an object that is not a buffer or a typed +//! array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator +//! and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1). A +//! typed array constructor converts a first argument that is not an object to a length. A buffer longer than the heap //! limit is a `RangeError`, and its bytes are checked against the heap before they are allocated. #![forbid(unsafe_code)] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ca31fe8761..00301edd48 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1184,7 +1184,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), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 7,000 of 7,070 runs pass (the 35 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `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 `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. Until the language has iterators, the collection constructors and `%TypedArray%.from` read an array, a string (by code point) or an object with a `length`, by index, and a typed array constructor reads an array or an object with a `length` the same way and converts a first argument that is not an object to a length; these rules are VectorCraft's own. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. A typed array constructor given an object that is not a buffer or a typed array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator to the end before mapping it, and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1); a typed array constructor converts a first argument that is not an object to a length. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - 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 made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.