Skip to content

Truly independent web browser

LibJS: Add realm fuses for the array iterator protocol

Aliaksandr Kalenik6a3e490c0157
diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rs
index b42d014c878..c274f9ebf38 100644
--- a/Libraries/LibJS/JIT/Rust/src/code.rs
+++ b/Libraries/LibJS/JIT/Rust/src/code.rs
@@ -140,6 +140,9 @@ pub enum Dependency {
/// The shape stays stable: no object leaves it, so objects that have it
/// keep it while other code runs.
StableShape(CellId),
+ /// The fuse cell stays intact: the properties of the intrinsics of its
+ /// realm that it watches do not change.
+ Fuse(CellId),
}
/// A point of compiled code where the runtime may translate its state into
diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rs
index daf916a9a8f..ee77b5a25e4 100644
--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs
+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs
@@ -739,7 +739,6 @@ define_static_property_lookup_cache_sites! {
IteratorValueValue,
IteratorCloseReturn,
ArrayAppendIteratorMethod,
- ArrayAppendNextMethod,
CreateArrayIteratorOwnIteratorMethod,
CreateArrayIteratorIteratorMethod,
CreateArrayIteratorNextMethod,
diff --git a/Libraries/LibJS/Rust/src/gc/class_id.rs b/Libraries/LibJS/Rust/src/gc/class_id.rs
index 656fbeb529f..6f352718731 100644
--- a/Libraries/LibJS/Rust/src/gc/class_id.rs
+++ b/Libraries/LibJS/Rust/src/gc/class_id.rs
@@ -32,6 +32,7 @@ define_class_ids! {
Accessor,
Shape,
PrototypeChainValidity,
+ Fuse,
DescriptorArray,
ValueStorage,
PrivateEnvironment,
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
index c5d1127f5f4..68c134bafa1 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs
@@ -10,7 +10,6 @@ use ak::{Utf16FlyString, Utf16String};
use crate::bytecode::executable::StaticPropertyLookupCacheSite;
use crate::bytecode::op;
-use crate::bytecode::property_access::get_own_property_without_side_effects;
use crate::debugger::PauseReason;
use crate::interpreter::runtime_functions::{SlowPathControl, asm_try, handle_asm_exception};
use crate::interpreter::vm::Vm;
@@ -35,6 +34,7 @@ use crate::runtime::object::{IndexedStorageKind, IntegrityLevel};
use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, PropertyAttributes};
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
+use crate::runtime::realm_fuses;
use crate::runtime::regexp_object::RegExpObject;
use crate::runtime::set::Set;
use crate::runtime::set_iterator::set_iteration_is_unobservable;
@@ -212,30 +212,15 @@ pub fn array_append(
// OPTIMIZATION: The original array iterator has no observable side effects, so a packed
// array can be appended in bulk if its next method is also unchanged.
- let original_iterator_method = current_realm(vm).array_prototype_values_function();
+ let realm = current_realm(vm);
if let Some(rhs_array) = rhs_array
- && iterator_method == original_iterator_method
+ && iterator_method == realm.array_prototype_values_function()
&& rhs_array.is_simple_packed_array()
+ && realm_fuses::array_iterators_have_builtin_next(&realm)
+ && rhs_array.indexed_packed_element_count() <= u32::MAX - lhs_size
{
- let iterator_prototype = current_realm(vm).array_iterator_prototype();
-
- // NB: Inspect the intrinsic prototype's own property without invoking it. Using get()
- // here would call an accessor with the prototype as its receiver, whereas the
- // iterator protocol calls it with the newly created iterator as its receiver.
- // Accessors and replacement methods therefore take the generic path below.
- let next_method = get_own_property_without_side_effects(
- &iterator_prototype,
- &vm.names.next,
- vm.static_property_lookup_cache(StaticPropertyLookupCacheSite::ArrayAppendNextMethod),
- );
- if next_method.is_function()
- && next_method.as_function().as_native_function().is_some()
- && next_method.as_function().is_array_prototype_next_builtin()
- && rhs_array.indexed_packed_element_count() <= u32::MAX - lhs_size
- {
- lhs_array.indexed_append_packed_elements_of(&rhs_array);
- return SlowPathControl::continue_at(pc + op::ArrayAppend::LENGTH);
- }
+ lhs_array.indexed_append_packed_elements_of(&rhs_array);
+ return SlowPathControl::continue_at(pc + op::ArrayAppend::LENGTH);
}
// OPTIMIZATION: Iterating a Set or Map with its original iteration functions cannot be observed, and no
diff --git a/Libraries/LibJS/Rust/src/jit/dependencies.rs b/Libraries/LibJS/Rust/src/jit/dependencies.rs
index 3c9244b6caa..5bf0d850fee 100644
--- a/Libraries/LibJS/Rust/src/jit/dependencies.rs
+++ b/Libraries/LibJS/Rust/src/jit/dependencies.rs
@@ -29,6 +29,7 @@ use crate::layout::cell::Gc;
use crate::layout::environment::DeclarativeEnvironment;
use crate::layout::object::Object;
use crate::layout::shape::PrototypeChainValidity;
+use crate::runtime::realm_fuses::Fuse;
use crate::runtime::shape::Shape;
/// Installed code that depends on something, as its executable and its id. Once the executable died or has other
@@ -77,7 +78,8 @@ impl Dependents {
Dependency::StableShape(shape) => shape_of(*shape).set_has_dependent_code(),
Dependency::PrototypeChainValid(_)
| Dependency::GlobalPropertyUnassigned { .. }
- | Dependency::NoHtmlDdaObjects => {}
+ | Dependency::NoHtmlDdaObjects
+ | Dependency::Fuse(_) => {}
}
code.entry(*dependency).or_default().push(DependentCode {
executable: weak_executable.clone(),
@@ -168,6 +170,10 @@ pub fn holds(vm: &Vm, dependency: &Dependency) -> bool {
}
Dependency::NoHtmlDdaObjects => !vm.jit.htmldda_objects_exist(),
Dependency::StableShape(shape) => shape_of(*shape).is_stable(),
+ Dependency::Fuse(fuse) => {
+ // SAFETY: Code that depends on the cell embeds it, which keeps it alive.
+ unsafe { &*(fuse.0 as *const Fuse) }.is_intact()
+ }
}
}
diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rs
index b6f337694a8..29f9421266e 100644
--- a/Libraries/LibJS/Rust/src/jit/disabled.rs
+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs
@@ -228,6 +228,7 @@ pub mod dependencies {
GlobalDeclarations { environment: CellId, serial: u64 },
GlobalBindingUnassigned { environment: CellId, index: u32 },
StableShape(CellId),
+ Fuse(CellId),
}
pub struct Dependents;
diff --git a/Libraries/LibJS/Rust/src/layout/realm.rs b/Libraries/LibJS/Rust/src/layout/realm.rs
index 377944f50c0..f1353ab443d 100644
--- a/Libraries/LibJS/Rust/src/layout/realm.rs
+++ b/Libraries/LibJS/Rust/src/layout/realm.rs
@@ -21,5 +21,18 @@ pub struct Realm {
pub intrinsics: Cell<Option<Gc<Intrinsics>>>,
/// [[HostDefined]]: a cell of the embedder, such as the settings object of a web realm.
pub host_defined: ForeignCellSlot,
+ /// Intact while %ArrayIteratorPrototype% has its original `next` (see `runtime::realm_fuses`).
+ pub array_iterator_next_fuse: Cell<Option<Gc<Fuse>>>,
+ /// Intact while array iterators of the realm have no `return` method (see `runtime::realm_fuses`).
+ pub array_iterator_return_fuse: Cell<Option<Gc<Fuse>>>,
pub storage: RealmStorage,
}
+
+/// A flag that stays set until a property of an intrinsic that it watches changes (see `runtime::realm_fuses`).
+#[repr(C)]
+pub struct Fuse {
+ pub header: CellHeader,
+ pub intact: Cell<bool>,
+ /// Keeps the cell at the minimum cell size.
+ pub padding: usize,
+}
diff --git a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
index 165ff7f543f..de680681bbc 100644
--- a/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
+++ b/Libraries/LibJS/Rust/src/runtime/intrinsics.rs
@@ -111,6 +111,7 @@ use crate::runtime::property_attributes::{Attribute, PropertyAttributes};
use crate::runtime::property_key::{PropertyKey, StringMayBeNumber};
use crate::runtime::proxy_constructor::ProxyConstructor;
use crate::runtime::realm::Realm;
+use crate::runtime::realm_fuses;
use crate::runtime::reflect_object::ReflectObject;
use crate::runtime::regexp_constructor::RegExpConstructor;
use crate::runtime::regexp_prototype::RegExpPrototype;
@@ -1087,6 +1088,8 @@ impl Intrinsics {
// 3. Perform AddRestrictedFunctionProperties(realmRec.[[Intrinsics]].[[%Function.prototype%]], realmRec).
add_restricted_function_properties(vm, &realm.intrinsics().function_prototype(vm), realm);
+ realm_fuses::arm(vm, realm);
+
// 4. Return unused.
intrinsics
}
diff --git a/Libraries/LibJS/Rust/src/runtime/mod.rs b/Libraries/LibJS/Rust/src/runtime/mod.rs
index 3f22e884b14..1934d6319b2 100644
--- a/Libraries/LibJS/Rust/src/runtime/mod.rs
+++ b/Libraries/LibJS/Rust/src/runtime/mod.rs
@@ -143,6 +143,7 @@ pub mod proxy_constructor;
pub mod proxy_object;
pub mod raw_json_object;
pub mod realm;
+pub mod realm_fuses;
pub mod reference;
pub mod reflect_object;
pub mod regexp_constructor;
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index a950459d0d7..514e8df36bd 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -52,6 +52,7 @@ use crate::runtime::property_attributes::{DEFAULT_ATTRIBUTES, PropertyAttributes
use crate::runtime::property_descriptor::{PropertyDescriptor, to_property_descriptor};
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
+use crate::runtime::realm_fuses;
use crate::runtime::shape::{AssignCopy, Shape};
use crate::runtime::symbol::Symbol;
use crate::runtime::value::{PreferredType, is_strictly_equal, same_value};
@@ -2831,6 +2832,8 @@ impl Object {
remove_intrinsic_accessor(vm, self, property_key);
}
+ realm_fuses::note_property_change(vm, self, property_key);
+
if attributes != metadata.attributes {
let shape = self.shape();
if shape.is_dictionary() {
@@ -2870,6 +2873,8 @@ impl Object {
return None;
}
+ realm_fuses::note_property_change(vm, self, property_key);
+
if !self.shape().is_dictionary()
&& self.shape().property_count() >= MAX_TRANSITIONS_BEFORE_CONVERTING_TO_DICTIONARY
{
@@ -2903,6 +2908,8 @@ impl Object {
let metadata = self.shape().lookup(property_key).expect("the object has the property");
+ realm_fuses::note_property_change(vm, self, property_key);
+
// NB: Deleting the property moves those after it to the slots before them.
if self.has_global_object_flag() {
crate::jit::dependencies::note_global_object_slot_assignments(
@@ -2938,6 +2945,7 @@ impl Object {
if self.prototype() == new_prototype {
return;
}
+ realm_fuses::note_prototype_change(vm, self);
self.shape
.set(self.shape().create_prototype_transition(vm, new_prototype));
}
diff --git a/Libraries/LibJS/Rust/src/runtime/object_constructor.rs b/Libraries/LibJS/Rust/src/runtime/object_constructor.rs
index 9d09807c3c2..424696a3c24 100644
--- a/Libraries/LibJS/Rust/src/runtime/object_constructor.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object_constructor.rs
@@ -30,6 +30,7 @@ use crate::runtime::property_attributes::{Attribute, PropertyAttributes};
use crate::runtime::property_descriptor::{from_property_descriptor, to_property_descriptor};
use crate::runtime::property_key::PropertyKey;
use crate::runtime::realm::Realm;
+use crate::runtime::realm_fuses;
use crate::runtime::value::same_value;
use crate::utf16::utf16_formatted;
@@ -788,6 +789,7 @@ fn try_assign_from_shape(vm: &Vm, target: &Object, source: &Object) -> ThrowComp
&& metadata.attributes.is_writable()
&& !target.get_direct(metadata.offset).is_accessor()
{
+ realm_fuses::note_property_change(vm, target, &property_key);
target.put_direct(metadata.offset, value);
continue;
}
diff --git a/Libraries/LibJS/Rust/src/runtime/realm.rs b/Libraries/LibJS/Rust/src/runtime/realm.rs
index 45cc7e7122a..08de4afb151 100644
--- a/Libraries/LibJS/Rust/src/runtime/realm.rs
+++ b/Libraries/LibJS/Rust/src/runtime/realm.rs
@@ -46,6 +46,8 @@ unsafe impl Trace for Realm {
self.global_declarative_environment.trace(visitor);
self.host_defined.trace(visitor);
self.storage.embedder_data.trace(visitor);
+ self.array_iterator_next_fuse.trace(visitor);
+ self.array_iterator_return_fuse.trace(visitor);
}
}
@@ -119,6 +121,8 @@ impl Realm {
global_environment: Cell::new(None),
intrinsics: Cell::new(None),
host_defined: ForeignCellSlot::empty(),
+ array_iterator_next_fuse: Cell::new(None),
+ array_iterator_return_fuse: Cell::new(None),
storage: RealmStorage::default(),
})
}
diff --git a/Libraries/LibJS/Rust/src/runtime/realm_fuses.rs b/Libraries/LibJS/Rust/src/runtime/realm_fuses.rs
new file mode 100644
index 00000000000..0b7eb3a5dd2
--- /dev/null
+++ b/Libraries/LibJS/Rust/src/runtime/realm_fuses.rs
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Fuses: flags of a realm that stay set while some properties of its intrinsics are as the realm made them. Fast
+//! paths that skip steps of the iterator protocol rely on them instead of looking up those properties every time.
+//!
+//! - `array_iterator_next_fuse`: %ArrayIteratorPrototype% has its own `next`, the builtin of the realm. Any change of
+//! that property pops it, also a write of the same value: caches write only to slots that the runtime wrote to
+//! before, so the first write pops the fuse before a cache can write to the slot.
+//! - `array_iterator_return_fuse`: array iterators have no `return` method. A `return` property on
+//! %ArrayIteratorPrototype%, %IteratorPrototype% or %Object.prototype%, or a new prototype of one of the first two,
+//! pops it. %Object.prototype% has an immutable prototype.
+//!
+//! A fuse never becomes intact again. Popping it invalidates the JIT code that depends on it.
+
+use core::cell::Cell;
+
+use crate::gc::class::{GcCell, define_cell};
+use crate::gc::visitor::{Trace, Visitor};
+use crate::interpreter::vm::Vm;
+use crate::jit::dependencies::{CellId, Dependency};
+use crate::layout::cell::{CellHeader, Gc};
+use crate::layout::object::Object;
+use crate::runtime::property_key::PropertyKey;
+use crate::runtime::realm::Realm;
+
+pub use crate::layout::realm::Fuse;
+
+define_cell!(Fuse, Other);
+
+// SAFETY: A fuse holds no cells.
+unsafe impl Trace for Fuse {
+ fn trace(&self, _: &mut Visitor) {}
+}
+
+impl Fuse {
+ fn create(vm: &Vm) -> Gc<Fuse> {
+ vm.heap().allocate(Fuse {
+ header: CellHeader::for_class(Self::CLASS),
+ intact: Cell::new(true),
+ padding: 0,
+ })
+ }
+
+ pub fn is_intact(&self) -> bool {
+ self.intact.get()
+ }
+
+ fn pop(&self, vm: &Vm) {
+ if !self.is_intact() {
+ return;
+ }
+ self.intact.set(false);
+ crate::jit::dependencies::invalidate_dependents(vm, Dependency::Fuse(CellId(core::ptr::from_ref(self) as u64)));
+ }
+}
+
+/// Sets the fuses of a realm whose intrinsics were just created. Until then, changes of the watched properties do not
+/// pop anything, since creating the intrinsics defines them.
+pub fn arm(vm: &Vm, realm: Gc<Realm>) {
+ // NB: Prototype shapes belong to one object each, so that caches of other objects never write to the slots of
+ // the watched objects.
+ realm.array_iterator_prototype().convert_to_prototype_if_needed(vm);
+ realm
+ .intrinsics()
+ .iterator_prototype(vm)
+ .convert_to_prototype_if_needed(vm);
+ realm.object_prototype().convert_to_prototype_if_needed(vm);
+
+ realm.array_iterator_next_fuse.set(Some(Fuse::create(vm)));
+ realm.array_iterator_return_fuse.set(Some(Fuse::create(vm)));
+}
+
+/// Whether array iterators of the realm have its builtin `next` method.
+pub fn array_iterators_have_builtin_next(realm: &Realm) -> bool {
+ realm
+ .array_iterator_next_fuse
+ .get()
+ .is_some_and(|fuse| fuse.is_intact())
+}
+
+/// Whether array iterators of the realm have no `return` method.
+pub fn array_iterators_have_no_return(realm: &Realm) -> bool {
+ realm
+ .array_iterator_return_fuse
+ .get()
+ .is_some_and(|fuse| fuse.is_intact())
+}
+
+/// Notes that property `key` of `object` changes: it is added, written, deleted or gets other attributes.
+#[inline(always)]
+pub fn note_property_change(vm: &Vm, object: &Object, key: &PropertyKey) {
+ if *key == vm.names.next || *key == vm.names.return_ {
+ note_watched_property_change(vm, object, key);
+ }
+}
+
+#[cold]
+fn note_watched_property_change(vm: &Vm, object: &Object, key: &PropertyKey) {
+ let realm = object.shape().realm();
+ if *key == vm.names.next {
+ if let Some(fuse) = realm.array_iterator_next_fuse.get()
+ && is(object, realm.array_iterator_prototype())
+ {
+ fuse.pop(vm);
+ }
+ return;
+ }
+ if let Some(fuse) = realm.array_iterator_return_fuse.get()
+ && (is_prototype_of_array_iterators(vm, &realm, object) || is(object, realm.object_prototype()))
+ {
+ fuse.pop(vm);
+ }
+}
+
+/// Notes that the prototype of `object` changes.
+pub fn note_prototype_change(vm: &Vm, object: &Object) {
+ let realm = object.shape().realm();
+ if let Some(fuse) = realm.array_iterator_return_fuse.get()
+ && is_prototype_of_array_iterators(vm, &realm, object)
+ {
+ fuse.pop(vm);
+ }
+}
+
+/// Whether `object` is %ArrayIteratorPrototype% or %IteratorPrototype% of the realm, whose fuses are armed.
+fn is_prototype_of_array_iterators(vm: &Vm, realm: &Realm, object: &Object) -> bool {
+ is(object, realm.array_iterator_prototype()) || is(object, realm.intrinsics().iterator_prototype(vm))
+}
+
+/// Whether `object` is `intrinsic`. NB: The hooks also see objects that are not allocated yet.
+fn is(object: &Object, intrinsic: Gc<Object>) -> bool {
+ core::ptr::eq(object, intrinsic.as_ptr())
+}
diff --git a/Tests/LibJS/Runtime/iterators/fuses/next-accessor.js b/Tests/LibJS/Runtime/iterators/fuses/next-accessor.js
new file mode 100644
index 00000000000..28826adcd2c
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/next-accessor.js
@@ -0,0 +1,55 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const originalNext = ArrayIteratorPrototype.next;
+
+function spread(array) {
+ return [...array];
+}
+
+function destructure(array) {
+ const [first, second] = array;
+ return [first, second];
+}
+
+function collect(array) {
+ const values = [];
+ for (const value of array) values.push(value);
+ return values;
+}
+
+function compileIteration() {
+ for (const f of [spread, destructure, collect]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let nextCalls = 0;
+function countingNext() {
+ ++nextCalls;
+ return originalNext.call(this);
+}
+
+function expectCountingNext() {
+ nextCalls = 0;
+ expect(spread([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(4);
+ expect(destructure([1, 2, 3])).toEqual([1, 2]);
+ expect(nextCalls).toBe(6);
+ expect(collect([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(10);
+}
+
+test("array iteration gets next from an accessor on %ArrayIteratorPrototype%", () => {
+ compileIteration();
+ let getterCalls = 0;
+ Object.defineProperty(ArrayIteratorPrototype, "next", {
+ get() {
+ ++getterCalls;
+ return countingNext;
+ },
+ configurable: true,
+ });
+ expectCountingNext();
+ expect(getterCalls).toBe(3);
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/next-assignment-of-same-value.js b/Tests/LibJS/Runtime/iterators/fuses/next-assignment-of-same-value.js
new file mode 100644
index 00000000000..ee08d8d640c
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/next-assignment-of-same-value.js
@@ -0,0 +1,53 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const originalNext = ArrayIteratorPrototype.next;
+
+function spread(array) {
+ return [...array];
+}
+
+function destructure(array) {
+ const [first, second] = array;
+ return [first, second];
+}
+
+function collect(array) {
+ const values = [];
+ for (const value of array) values.push(value);
+ return values;
+}
+
+function compileIteration() {
+ for (const f of [spread, destructure, collect]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let nextCalls = 0;
+function countingNext() {
+ ++nextCalls;
+ return originalNext.call(this);
+}
+
+function expectCountingNext() {
+ nextCalls = 0;
+ expect(spread([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(4);
+ expect(destructure([1, 2, 3])).toEqual([1, 2]);
+ expect(nextCalls).toBe(6);
+ expect(collect([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(10);
+}
+
+function setNext(next) {
+ ArrayIteratorPrototype.next = next;
+}
+
+test("array iteration calls a next method assigned after the same method was assigned again", () => {
+ compileIteration();
+ for (let i = 0; i < 100; ++i) setNext(originalNext);
+ expect(spread([1, 2, 3])).toEqual([1, 2, 3]);
+ setNext(countingNext);
+ expectCountingNext();
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/next-assignment.js b/Tests/LibJS/Runtime/iterators/fuses/next-assignment.js
new file mode 100644
index 00000000000..47fcaa71ce1
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/next-assignment.js
@@ -0,0 +1,47 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const originalNext = ArrayIteratorPrototype.next;
+
+function spread(array) {
+ return [...array];
+}
+
+function destructure(array) {
+ const [first, second] = array;
+ return [first, second];
+}
+
+function collect(array) {
+ const values = [];
+ for (const value of array) values.push(value);
+ return values;
+}
+
+function compileIteration() {
+ for (const f of [spread, destructure, collect]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let nextCalls = 0;
+function countingNext() {
+ ++nextCalls;
+ return originalNext.call(this);
+}
+
+function expectCountingNext() {
+ nextCalls = 0;
+ expect(spread([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(4);
+ expect(destructure([1, 2, 3])).toEqual([1, 2]);
+ expect(nextCalls).toBe(6);
+ expect(collect([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(10);
+}
+
+test("array iteration calls a next method assigned to %ArrayIteratorPrototype%", () => {
+ compileIteration();
+ ArrayIteratorPrototype.next = countingNext;
+ expectCountingNext();
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/next-deletion.js b/Tests/LibJS/Runtime/iterators/fuses/next-deletion.js
new file mode 100644
index 00000000000..bba1280e26f
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/next-deletion.js
@@ -0,0 +1,49 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const originalNext = ArrayIteratorPrototype.next;
+
+function spread(array) {
+ return [...array];
+}
+
+function destructure(array) {
+ const [first, second] = array;
+ return [first, second];
+}
+
+function collect(array) {
+ const values = [];
+ for (const value of array) values.push(value);
+ return values;
+}
+
+function compileIteration() {
+ for (const f of [spread, destructure, collect]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let nextCalls = 0;
+function countingNext() {
+ ++nextCalls;
+ return originalNext.call(this);
+}
+
+function expectCountingNext() {
+ nextCalls = 0;
+ expect(spread([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(4);
+ expect(destructure([1, 2, 3])).toEqual([1, 2]);
+ expect(nextCalls).toBe(6);
+ expect(collect([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(10);
+}
+
+test("array iteration throws without a next method on %ArrayIteratorPrototype%", () => {
+ compileIteration();
+ delete ArrayIteratorPrototype.next;
+ expect(() => spread([1, 2, 3])).toThrow(TypeError);
+ expect(() => destructure([1, 2, 3])).toThrow(TypeError);
+ expect(() => collect([1, 2, 3])).toThrow(TypeError);
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/next-object-assign.js b/Tests/LibJS/Runtime/iterators/fuses/next-object-assign.js
new file mode 100644
index 00000000000..9c28e0bbe28
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/next-object-assign.js
@@ -0,0 +1,47 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const originalNext = ArrayIteratorPrototype.next;
+
+function spread(array) {
+ return [...array];
+}
+
+function destructure(array) {
+ const [first, second] = array;
+ return [first, second];
+}
+
+function collect(array) {
+ const values = [];
+ for (const value of array) values.push(value);
+ return values;
+}
+
+function compileIteration() {
+ for (const f of [spread, destructure, collect]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let nextCalls = 0;
+function countingNext() {
+ ++nextCalls;
+ return originalNext.call(this);
+}
+
+function expectCountingNext() {
+ nextCalls = 0;
+ expect(spread([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(4);
+ expect(destructure([1, 2, 3])).toEqual([1, 2]);
+ expect(nextCalls).toBe(6);
+ expect(collect([1, 2, 3])).toEqual([1, 2, 3]);
+ expect(nextCalls).toBe(10);
+}
+
+test("array iteration calls a next method that Object.assign writes to %ArrayIteratorPrototype%", () => {
+ compileIteration();
+ Object.assign(ArrayIteratorPrototype, { next: countingNext });
+ expectCountingNext();
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/return-from-new-prototype-of-array-iterator-prototype.js b/Tests/LibJS/Runtime/iterators/fuses/return-from-new-prototype-of-array-iterator-prototype.js
new file mode 100644
index 00000000000..0951ee7fda4
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/return-from-new-prototype-of-array-iterator-prototype.js
@@ -0,0 +1,42 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const IteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);
+
+function destructure(array) {
+ const [first] = array;
+ return first;
+}
+
+function breakAfterFirst(array) {
+ for (const value of array) return value;
+}
+
+function compileIteration() {
+ for (const f of [destructure, breakAfterFirst]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let returnCalls = 0;
+function recordingReturn() {
+ ++returnCalls;
+ expect(Object.getPrototypeOf(this)).toBe(ArrayIteratorPrototype);
+ expect(this.next()).toEqual({ value: 2, done: false });
+ return {};
+}
+
+function expectRecordingReturn() {
+ returnCalls = 0;
+ expect(destructure([1, 2, 3])).toBe(1);
+ expect(breakAfterFirst([1, 2, 3])).toBe(1);
+ expect(returnCalls).toBe(2);
+}
+
+test("closing an array iterator calls a return method of a new prototype of %ArrayIteratorPrototype%", () => {
+ compileIteration();
+ const prototype = Object.create(IteratorPrototype);
+ prototype.return = recordingReturn;
+ Object.setPrototypeOf(ArrayIteratorPrototype, prototype);
+ expectRecordingReturn();
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/return-from-new-prototype-of-iterator-prototype.js b/Tests/LibJS/Runtime/iterators/fuses/return-from-new-prototype-of-iterator-prototype.js
new file mode 100644
index 00000000000..c6e1100f394
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/return-from-new-prototype-of-iterator-prototype.js
@@ -0,0 +1,40 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const IteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);
+
+function destructure(array) {
+ const [first] = array;
+ return first;
+}
+
+function breakAfterFirst(array) {
+ for (const value of array) return value;
+}
+
+function compileIteration() {
+ for (const f of [destructure, breakAfterFirst]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let returnCalls = 0;
+function recordingReturn() {
+ ++returnCalls;
+ expect(Object.getPrototypeOf(this)).toBe(ArrayIteratorPrototype);
+ expect(this.next()).toEqual({ value: 2, done: false });
+ return {};
+}
+
+function expectRecordingReturn() {
+ returnCalls = 0;
+ expect(destructure([1, 2, 3])).toBe(1);
+ expect(breakAfterFirst([1, 2, 3])).toBe(1);
+ expect(returnCalls).toBe(2);
+}
+
+test("closing an array iterator calls a return method of a new prototype of %IteratorPrototype%", () => {
+ compileIteration();
+ Object.setPrototypeOf(IteratorPrototype, { return: recordingReturn });
+ expectRecordingReturn();
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/return-getter.js b/Tests/LibJS/Runtime/iterators/fuses/return-getter.js
new file mode 100644
index 00000000000..f3d3c9856b2
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/return-getter.js
@@ -0,0 +1,48 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const IteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);
+
+function destructure(array) {
+ const [first] = array;
+ return first;
+}
+
+function breakAfterFirst(array) {
+ for (const value of array) return value;
+}
+
+function compileIteration() {
+ for (const f of [destructure, breakAfterFirst]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let returnCalls = 0;
+function recordingReturn() {
+ ++returnCalls;
+ expect(Object.getPrototypeOf(this)).toBe(ArrayIteratorPrototype);
+ expect(this.next()).toEqual({ value: 2, done: false });
+ return {};
+}
+
+function expectRecordingReturn() {
+ returnCalls = 0;
+ expect(destructure([1, 2, 3])).toBe(1);
+ expect(breakAfterFirst([1, 2, 3])).toBe(1);
+ expect(returnCalls).toBe(2);
+}
+
+test("closing an array iterator gets return from an accessor", () => {
+ compileIteration();
+ let getterCalls = 0;
+ Object.defineProperty(IteratorPrototype, "return", {
+ get() {
+ ++getterCalls;
+ return recordingReturn;
+ },
+ configurable: true,
+ });
+ expectRecordingReturn();
+ expect(getterCalls).toBe(2);
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/return-on-array-iterator-prototype.js b/Tests/LibJS/Runtime/iterators/fuses/return-on-array-iterator-prototype.js
new file mode 100644
index 00000000000..f91c850d14c
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/return-on-array-iterator-prototype.js
@@ -0,0 +1,40 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const IteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);
+
+function destructure(array) {
+ const [first] = array;
+ return first;
+}
+
+function breakAfterFirst(array) {
+ for (const value of array) return value;
+}
+
+function compileIteration() {
+ for (const f of [destructure, breakAfterFirst]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let returnCalls = 0;
+function recordingReturn() {
+ ++returnCalls;
+ expect(Object.getPrototypeOf(this)).toBe(ArrayIteratorPrototype);
+ expect(this.next()).toEqual({ value: 2, done: false });
+ return {};
+}
+
+function expectRecordingReturn() {
+ returnCalls = 0;
+ expect(destructure([1, 2, 3])).toBe(1);
+ expect(breakAfterFirst([1, 2, 3])).toBe(1);
+ expect(returnCalls).toBe(2);
+}
+
+test("closing an array iterator calls a return method on %ArrayIteratorPrototype%", () => {
+ compileIteration();
+ ArrayIteratorPrototype.return = recordingReturn;
+ expectRecordingReturn();
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/return-on-iterator-prototype.js b/Tests/LibJS/Runtime/iterators/fuses/return-on-iterator-prototype.js
new file mode 100644
index 00000000000..f67cd5ea1e4
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/return-on-iterator-prototype.js
@@ -0,0 +1,40 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const IteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);
+
+function destructure(array) {
+ const [first] = array;
+ return first;
+}
+
+function breakAfterFirst(array) {
+ for (const value of array) return value;
+}
+
+function compileIteration() {
+ for (const f of [destructure, breakAfterFirst]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let returnCalls = 0;
+function recordingReturn() {
+ ++returnCalls;
+ expect(Object.getPrototypeOf(this)).toBe(ArrayIteratorPrototype);
+ expect(this.next()).toEqual({ value: 2, done: false });
+ return {};
+}
+
+function expectRecordingReturn() {
+ returnCalls = 0;
+ expect(destructure([1, 2, 3])).toBe(1);
+ expect(breakAfterFirst([1, 2, 3])).toBe(1);
+ expect(returnCalls).toBe(2);
+}
+
+test("closing an array iterator calls a return method on %IteratorPrototype%", () => {
+ compileIteration();
+ IteratorPrototype.return = recordingReturn;
+ expectRecordingReturn();
+});
diff --git a/Tests/LibJS/Runtime/iterators/fuses/return-on-object-prototype.js b/Tests/LibJS/Runtime/iterators/fuses/return-on-object-prototype.js
new file mode 100644
index 00000000000..76665e18edc
--- /dev/null
+++ b/Tests/LibJS/Runtime/iterators/fuses/return-on-object-prototype.js
@@ -0,0 +1,44 @@
+const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());
+const IteratorPrototype = Object.getPrototypeOf(ArrayIteratorPrototype);
+
+function destructure(array) {
+ const [first] = array;
+ return first;
+}
+
+function breakAfterFirst(array) {
+ for (const value of array) return value;
+}
+
+function compileIteration() {
+ for (const f of [destructure, breakAfterFirst]) {
+ if (typeof jit !== "undefined") jit.prepare(f);
+ for (let i = 0; i < 10; ++i) f([1, 2, 3]);
+ if (typeof jit !== "undefined") expect(jit.compile(f)).toBe(jit.enabled);
+ }
+}
+
+let returnCalls = 0;
+function recordingReturn() {
+ ++returnCalls;
+ expect(Object.getPrototypeOf(this)).toBe(ArrayIteratorPrototype);
+ expect(this.next()).toEqual({ value: 2, done: false });
+ return {};
+}
+
+function expectRecordingReturn() {
+ returnCalls = 0;
+ expect(destructure([1, 2, 3])).toBe(1);
+ expect(breakAfterFirst([1, 2, 3])).toBe(1);
+ expect(returnCalls).toBe(2);
+}
+
+test("closing an array iterator calls a return method on Object.prototype", () => {
+ compileIteration();
+ Object.defineProperty(Object.prototype, "return", { value: recordingReturn, configurable: true, writable: true });
+ try {
+ expectRecordingReturn();
+ } finally {
+ delete Object.prototype.return;
+ }
+});