Truly independent web browser
LibJS: Iterate arrays without iterators in builtins that take iterables
Andreas Klingf5aaac98fcb7
diff --git a/Libraries/LibJS/Rust/src/jit/intrinsics.rs b/Libraries/LibJS/Rust/src/jit/intrinsics.rsindex 5afea2829b8..8d9e319ccb6 100644--- a/Libraries/LibJS/Rust/src/jit/intrinsics.rs+++ b/Libraries/LibJS/Rust/src/jit/intrinsics.rs@@ -218,23 +218,8 @@ pub extern "C" fn libjs_jit_open_array_iteration(vm: &Vm, iterable: u64) -> u64if array.downcast::<Array>().is_none() {return Value::EMPTY.0;}- // NB: The array inherits the iterator method from %Array.prototype%, which holds it as a data property, unless it- // has an own @@iterator. Arrays without named properties have none.let realm = vm.current_realm().expect("JIT code runs in a realm");- if !realm_watchpoints::array_iterators_have_builtin_next(vm, realm) {- return Value::EMPTY.0;- }- if array.prototype() != Some(realm.array_prototype())- || !realm_watchpoints::arrays_have_builtin_iterator_method(vm, realm)- {- return Value::EMPTY.0;- }- let shape = array.shape();- if shape.property_count() != 0- && shape- .lookup(&PropertyKey::from(vm.well_known_symbols().iterator))- .is_some()- {+ if !realm_watchpoints::array_is_iterated_unobservably(vm, realm, &array) {return Value::EMPTY.0;}iterable.0diff --git a/Libraries/LibJS/Rust/src/runtime/array_constructor.rs b/Libraries/LibJS/Rust/src/runtime/array_constructor.rsindex eb4b96ab9e1..62e9b030b27 100644--- a/Libraries/LibJS/Rust/src/runtime/array_constructor.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_constructor.rs@@ -32,6 +32,7 @@ use crate::runtime::object::ShouldThrowExceptions;use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, PropertyAttributes};use crate::runtime::property_key::PropertyKey;use crate::runtime::realm::Realm;+use crate::runtime::realm_watchpoints;use crate::runtime::regexp_constructor::is_raw_native_function_running;use crate::runtime::set::Set;use crate::runtime::set_iterator::set_iteration_is_unobservable;@@ -41,12 +42,24 @@ use crate::runtime::value_conversions::MAX_ARRAY_LIKE_INDEX;static SYMBOL_SPECIES_GETTER: RawNativeFunctionPointer = raw_native!(ArrayConstructor::symbol_species_getter);// OPTIMIZATION: Without a mapper, unobservable collection iteration can copy storage directly.-fn array_from_set_or_map(+fn array_from_array_set_or_map(vm: &Vm,realm: Gc<Realm>,items: Gc<Object>,using_iterator: Gc<FunctionObject>,) -> Option<Gc<Array>> {+ if let Some(source) = items.downcast::<Array>() {+ if using_iterator != realm.array_prototype_values_function()+ || !source.is_simple_packed_array()+ || !realm_watchpoints::array_iterators_have_builtin_next(vm, realm)+ {+ return None;+ }++ let array = Array::create(vm, realm, 0, None).must();+ array.indexed_append_packed_elements_of(&source);+ return Some(array);+ }if let Some(set) = items.downcast::<Set>() {if !set_iteration_is_unobservable(vm, realm, using_iterator) || set.set_size() >= u32::MAX as usize {return None;@@ -311,7 +324,7 @@ impl ArrayConstructor {if constructor_is_intrinsic_array&& mapfn.is_none()&& items.is_object()- && let Some(array) = array_from_set_or_map(vm, realm, items.as_object(), using_iterator)+ && let Some(array) = array_from_array_set_or_map(vm, realm, items.as_object(), using_iterator){return Ok(Value::from_object(array));}diff --git a/Libraries/LibJS/Rust/src/runtime/iterator.rs b/Libraries/LibJS/Rust/src/runtime/iterator.rsindex 7fe4b659abe..b703598771d 100644--- a/Libraries/LibJS/Rust/src/runtime/iterator.rs+++ b/Libraries/LibJS/Rust/src/runtime/iterator.rs@@ -20,13 +20,18 @@ use crate::layout::function_object::FunctionObject;use crate::layout::object::Object;use crate::layout::value::Value;use crate::runtime::abstract_operations::{call, call_function_object};+use crate::runtime::array::Array;+use crate::runtime::array_iterator::{ArrayIterator, iterated_array_like_element, iterated_array_like_length};use crate::runtime::async_from_sync_iterator_prototype::create_async_from_sync_iterator;use crate::runtime::completion::{Completion, ThrowCompletionOr};use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;-use crate::runtime::object::{MayInterfereWithIndexedPropertyAccess, ShouldThrowExceptions, allocate_object};+use crate::runtime::object::{+ MayInterfereWithIndexedPropertyAccess, PropertyKind, ShouldThrowExceptions, allocate_object,+};use crate::runtime::property_key::PropertyKey;use crate::runtime::realm::Realm;+use crate::runtime::realm_watchpoints;pub use libjs_abi::IteratorHint;@@ -756,6 +761,44 @@ pub fn setter_that_ignores_prototype_properties(Ok(())}+/// get_iterator_values() for an array that is iterated with the array iterators of `realm` without anything observing+/// them (see `realm_watchpoints::array_is_iterated_unobservably()`).+fn get_array_values(+ vm: &Vm,+ realm: Gc<Realm>,+ array: Gc<Object>,+ mut callback: impl FnMut(Value) -> Option<Completion>,+) -> Completion {+ let mut index = 0;+ loop {+ let length = match iterated_array_like_length(vm, &array) {+ Ok(length) => length,+ Err(throw) => return throw.into(),+ };+ if index >= length {+ return Completion::normal(Value::UNDEFINED);+ }+ let value = match iterated_array_like_element(vm, &array, index) {+ Ok(value) => value,+ Err(throw) => return throw.into(),+ };+ index += 1;++ if let Some(completion) = callback(value) {+ if realm_watchpoints::array_iterators_have_no_return(vm, realm) {+ return completion;+ }+ // NB: The callback gave array iterators a return method. The iterator that it gets as its this value is+ // one that nothing saw before, so it may be made now.+ let iterator = ArrayIterator::create(vm, realm, Value::from_object(array), PropertyKind::Value);+ iterator.index.set(index);+ // NB: IteratorClose does not use the next method.+ let iterator_record = IteratorRecordImpl::new(Some(iterator.upcast()), Value::UNDEFINED, false);+ return iterator_close(vm, &iterator_record, completion);+ }+ }+}+// Non-standard/// Iterates `iterable`, handing each value to `callback`, and closes the iterator with the completion the callback/// returns to stop early.@@ -764,6 +807,16 @@ pub fn get_iterator_values(iterable: Value,mut callback: impl FnMut(Value) -> Option<Completion>,) -> Completion {+ // OPTIMIZATION: Nothing can observe the iterator of an array that is iterated with the array iterators of the+ // realm, so its elements are read like the iterator would read them, without making it.+ if iterable.is_object()+ && iterable.as_object().downcast::<Array>().is_some()+ && let Some(realm) = vm.current_realm()+ && realm_watchpoints::array_is_iterated_unobservably(vm, realm, &iterable.as_object())+ {+ return get_array_values(vm, realm, iterable.as_object(), callback);+ }+let iterator_record = match get_iterator_impl(vm, iterable, IteratorHint::Sync) {Ok(iterator_record) => iterator_record,Err(throw) => return throw.into(),diff --git a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rsindex 29a83a3f68e..d0b3a12120a 100644--- a/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs+++ b/Libraries/LibJS/Rust/src/runtime/realm_watchpoints.rs@@ -273,3 +273,22 @@ fn watch_array_iterator_method(vm: &Vm, realm: Gc<Realm>) -> Option<Gc<Watchpoin}watch_intrinsics(vm, &[array_prototype], &[(array_prototype, iterator_key)])}++/// Whether `array` is iterated with the array iterators of `realm` without anything observing them: it inherits+/// %Array.prototype%[@@iterator] of the realm, which is its %Array.prototype.values%, and the iterators have the+/// builtin `next` method.+pub fn array_is_iterated_unobservably(vm: &Vm, realm: Gc<Realm>, array: &Object) -> bool {+ if array.prototype() != Some(realm.array_prototype())+ || !array_iterators_have_builtin_next(vm, realm)+ || !arrays_have_builtin_iterator_method(vm, realm)+ {+ return false;+ }+ // NB: The array inherits the iterator method from %Array.prototype%, which holds it as a data property, unless it+ // has an own @@iterator. Arrays without named properties have none.+ let shape = array.shape();+ shape.property_count() == 0+ || shape+ .lookup(&PropertyKey::from(vm.well_known_symbols().iterator))+ .is_none()+}diff --git a/Tests/LibJS/Runtime/iterators/watchpoints/builtins-iterating-arrays.js b/Tests/LibJS/Runtime/iterators/watchpoints/builtins-iterating-arrays.jsnew file mode 100644index 00000000000..7375fb6c09c--- /dev/null+++ b/Tests/LibJS/Runtime/iterators/watchpoints/builtins-iterating-arrays.js@@ -0,0 +1,107 @@+const originalIterator = Array.prototype[Symbol.iterator];+const arrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());+const originalNext = arrayIteratorPrototype.next;++test("builtins iterate arrays like their iterators do", () => {+ expect([...new Set([1, 2, 2, 3])]).toEqual([1, 2, 3]);+ expect([+ ...new Map([+ [1, "a"],+ [2, "b"],+ ]),+ ]).toEqual([+ [1, "a"],+ [2, "b"],+ ]);+ expect(Object.fromEntries([["a", 1]])).toEqual({ a: 1 });+ expect(Array.from([1, 2, 3])).toEqual([1, 2, 3]);+ expect(Array.from([1, , 3])).toEqual([1, undefined, 3]);+ const source = [1, 2];+ const copy = Array.from(source);+ copy.push(3);+ expect(source).toEqual([1, 2]);+});++test("a replaced @@iterator of Array.prototype is used", () => {+ Array.prototype[Symbol.iterator] = function* () {+ yield "replaced";+ };+ try {+ expect([...new Set([1, 2])]).toEqual(["replaced"]);+ expect(Array.from([1, 2])).toEqual(["replaced"]);+ } finally {+ Array.prototype[Symbol.iterator] = originalIterator;+ }+});++test("an own @@iterator of an array is used", () => {+ const array = [1, 2];+ array[Symbol.iterator] = function* () {+ yield "own";+ };+ expect([...new Set(array)]).toEqual(["own"]);+ expect(Array.from(array)).toEqual(["own"]);+});++test("a replaced next of array iterators is called", () => {+ let calls = 0;+ arrayIteratorPrototype.next = function () {+ ++calls;+ return originalNext.call(this);+ };+ try {+ expect([...new Set([1, 2])]).toEqual([1, 2]);+ expect(Array.from([1, 2])).toEqual([1, 2]);+ expect(calls).toBe(6);+ } finally {+ arrayIteratorPrototype.next = originalNext;+ }+});++test("holes read the prototype chain", () => {+ Array.prototype[1] = "from prototype";+ try {+ expect([...new Set([1, , 3])]).toEqual([1, "from prototype", 3]);+ expect(Array.from([1, , 3])).toEqual([1, "from prototype", 3]);+ } finally {+ delete Array.prototype[1];+ }+});++test("adders see the array grow while it is iterated", () => {+ const array = [1, 2];+ class GrowingSet extends Set {+ add(value) {+ if (value < 4) array.push(value + 2);+ return super.add(value);+ }+ }+ expect([...new GrowingSet(array)]).toEqual([1, 2, 3, 4, 5]);+});++test("an iterator return method added while iterating is called on an abrupt completion", () => {+ let returnCalls = 0;+ class ThrowingSet extends Set {+ add(value) {+ if (value === 1) {+ arrayIteratorPrototype.return = function () {+ ++returnCalls;+ expect(Object.getPrototypeOf(this)).toBe(arrayIteratorPrototype);+ return {};+ };+ return this;+ }+ throw new Error("adder failed");+ }+ }+ try {+ expect(() => new ThrowingSet([1, 2])).toThrowWithMessage(Error, "adder failed");+ expect(returnCalls).toBe(1);+ } finally {+ delete arrayIteratorPrototype.return;+ }+});++test("an entry that is not an object throws", () => {+ expect(() => new Map([1])).toThrow(TypeError);+});