Truly independent web browser
LibJS: Iterate arrays without making iterator objects
Aliaksandr Kalenikada11dcbc399
diff --git a/Libraries/LibJS/Flap/src/hir/mod.rs b/Libraries/LibJS/Flap/src/hir/mod.rsindex 950d4eb0f48..48a5d8419bb 100644--- a/Libraries/LibJS/Flap/src/hir/mod.rs+++ b/Libraries/LibJS/Flap/src/hir/mod.rs@@ -3069,6 +3069,7 @@ fn field_width(ty: &Type, allow_pointer: bool) -> Option<FieldWidth> {| Type::ObjectPropertyIteratorCacheData| Type::ObjectPropertyIteratorCache| Type::PrototypeChainValidity+ | Type::Fuse| Type::FunctionObject| Type::ECMAScriptFunctionObject| Type::RawNativeFunctiondiff --git a/Libraries/LibJS/Flap/src/types.rs b/Libraries/LibJS/Flap/src/types.rsindex 8bd19d32f77..549861231b7 100644--- a/Libraries/LibJS/Flap/src/types.rs+++ b/Libraries/LibJS/Flap/src/types.rs@@ -216,6 +216,7 @@ define_named_types! {ObjectPropertyIteratorCacheData => "ObjectPropertyIteratorCacheData", Some(8), true;ObjectPropertyIteratorCache => "ObjectPropertyIteratorCache", Some(8), true;PrototypeChainValidity => "PrototypeChainValidity", Some(8), true;+ Fuse => "Fuse", Some(8), true;Accessor => "Accessor", Some(8), true;FunctionObject => "FunctionObject", Some(8), true;ECMAScriptFunctionObject => "ECMAScriptFunctionObject", Some(8), true;diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.Sindex f4360ba1cb0..a75ced9a255 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/aarch64.S@@ -6791,12 +6791,25 @@ asm_handler_ObjectPropertyIteratorNext_hot_end:.p2align 4asm_handler_IteratorClose:- ldr x0, [x28, #88]- ldr x1, [x0, #152]- cbz x1, .Lasm_IteratorClose.assert_failure_0- ldr w2, [x21, #24]ldr w0, [x21, #4]ldr x0, [x27, x0, lsl #3]+ lsr x9, x0, #48+ cmp x9, x22+ b.ne .Lasm_IteratorClose.ssa_block_3+ ldr x0, [x28, #8]+ ldr x0, [x0, #64]+ cbz x0, .Lasm_IteratorClose.ssa_block_1+ ldrb w9, [x0, #11]+ cbz w9, .Lasm_IteratorClose.ssa_block_1+ ldrb w9, [x21, #32]+ add x21, x21, #32+ ldr x10, [x19, x9, lsl #3]+ br x10+.Lasm_IteratorClose.ssa_block_3:+ ldr x1, [x28, #88]+ ldr x1, [x1, #152]+ cbz x1, .Lasm_IteratorClose.assert_failure_0+ ldr w2, [x21, #24]lsl x2, x2, #3adds x1, x1, x2bl CSYM(asm_try_get_by_id_cache)@@ -6811,6 +6824,84 @@ asm_handler_IteratorClose:br x10asm_handler_IteratorClose_hot_end:+.p2align 4+asm_handler_IteratorNextUnpack:+ ldr w2, [x21, #12]+ ldr x0, [x27, x2, lsl #3]+ lsr x9, x0, #48+ cmp x9, x22+ b.ne .Lasm_IteratorNextUnpack.ssa_block_1+ sxtw x0, w0+ tbz w0, #31, 1f+ b .Lasm_IteratorNextUnpack.ssa_block_1+1:+ ldr w3, [x21, #20]+ ldr x1, [x27, x3, lsl #3]+ tbz x1, #0, 1f+ b .Lasm_IteratorNextUnpack.ssa_block_1+1:+ ldr w1, [x21, #16]+ ldr x1, [x27, x1, lsl #3]+ lsr x9, x1, #48+ mov w10, #65529+ cmp x9, x10+ b.ne .Lasm_IteratorNextUnpack.ssa_block_1+ and x1, x1, #0x3ffffffffff+ add x1, x1, x24+ ldrh w4, [x1, #12]+ tbnz x4, #2, 1f+ b .Lasm_IteratorNextUnpack.ssa_block_1+1:+ tbz x4, #4, 1f+ b .Lasm_IteratorNextUnpack.ssa_block_1+1:+ ldr w4, [x1, #16]+ cmp x0, x4+ b.lo .Lasm_IteratorNextUnpack.ssa_block_7+ ldr w9, [x21, #4]+ movz x10, #0x7ffe, lsl #48+ str x10, [x27, x9, lsl #3]+ ldr w9, [x21, #8]+ movz x10, #0x1, lsl #0+ movk x10, #0x7ff9, lsl #48+ str x10, [x27, x9, lsl #3]+ movz x9, #0x1, lsl #0+ movk x9, #0x7ff9, lsl #48+ str x9, [x27, x3, lsl #3]+ ldrb w9, [x21, #24]+ add x21, x21, #24+ ldr x10, [x19, x9, lsl #3]+ br x10+.Lasm_IteratorNextUnpack.ssa_block_7:+ ldrb w3, [x1, #14]+ cmp x3, #1+ b.lo .Lasm_IteratorNextUnpack.ssa_block_1+ cmp x3, #3+ b.hs .Lasm_IteratorNextUnpack.ssa_block_1+ ldr x1, [x1, #40]+ cbz x1, .Lasm_IteratorNextUnpack.ssa_block_1+ ldur w3, [x1, #-8]+ cmp x0, x3+ b.hs .Lasm_IteratorNextUnpack.ssa_block_1+ ldr x1, [x1, x0, lsl #3]+ movz x9, #0x7ffb, lsl #48+ cmp x1, x9+ b.eq .Lasm_IteratorNextUnpack.ssa_block_1+ adds w0, w0, #1+ b.vs .Lasm_IteratorNextUnpack.ssa_block_1+ ldr w9, [x21, #4]+ str x1, [x27, x9, lsl #3]+ ldr w9, [x21, #8]+ movz x10, #0x7ff9, lsl #48+ str x10, [x27, x9, lsl #3]+ movk x0, #0x7ffa, lsl #48+ str x0, [x27, x2, lsl #3]+ ldrb w9, [x21, #24]+ add x21, x21, #24+ ldr x10, [x19, x9, lsl #3]+ br x10+asm_handler_IteratorNextUnpack_hot_end:+.p2align 4asm_handler_IsCallable:ldr w0, [x21, #8]@@ -17250,8 +17341,9 @@ asm_handler_IteratorNext_hot_end:asm_handler_IteratorNext_cold:asm_handler_IteratorNext_cold_end:-.p2align 4-asm_handler_IteratorNextUnpack:+asm_handler_IteratorNextUnpack_cold:+// Cold paths for IteratorNextUnpack+.Lasm_IteratorNextUnpack.ssa_block_1:mov x0, x20sub w1, w21, w26str w1, [x28, #64]@@ -17273,8 +17365,12 @@ asm_handler_IteratorNextUnpack:mov x2, x21add x3, sp, #0bl CSYM(asm_slow_path_iterator_next_unpack)- tbnz x0, #63, .Lasm_IteratorNextUnpack.values_exceptional_outputs_5- tbz x0, #32, .Lasm_IteratorNextUnpack.values_exceptional_outputs_5+ tbz x0, #63, 1f+ b .Lasm_IteratorNextUnpack.values_exceptional_outputs_5+1:+ tbnz x0, #32, 1f+ b .Lasm_IteratorNextUnpack.values_exceptional_outputs_5+1:ldr w12, [x21, #4]ldr x11, [sp]str x11, [x27, x12, lsl #3]@@ -17283,10 +17379,14 @@ asm_handler_IteratorNextUnpack:ldr x11, [sp, #8]str x11, [x27, x12, lsl #3].Lasm_IteratorNextUnpack.skip_output_value_7:+ ldr w12, [x21, #12]+ ldr x11, [sp, #16]+ str x11, [x27, x12, lsl #3]+.Lasm_IteratorNextUnpack.skip_output_value_8:ldr w12, [x21, #20]ldr x11, [sp, #32]str x11, [x27, x12, lsl #3]-.Lasm_IteratorNextUnpack.skip_output_value_8:+.Lasm_IteratorNextUnpack.skip_output_value_9:add sp, sp, #48add x21, x26, w0, uxtwldrb w9, [x21]@@ -17296,22 +17396,28 @@ asm_handler_IteratorNextUnpack:ldr x9, [x20]cmp x9, x28b.ne .Lasm_IteratorNextUnpack.values_restore_stack_4+ ldr w12, [x21, #12]+ ldr x11, [sp, #16]+ str x11, [x27, x12, lsl #3]+.Lasm_IteratorNextUnpack.skip_exceptional_output_10:ldr w12, [x21, #20]ldr x11, [sp, #32]str x11, [x27, x12, lsl #3]-.Lasm_IteratorNextUnpack.skip_exceptional_output_9:+.Lasm_IteratorNextUnpack.skip_exceptional_output_11:.Lasm_IteratorNextUnpack.values_restore_stack_4:add sp, sp, #48.Lasm_IteratorNextUnpack.values_call_done_0:tbz x0, #63, 1fb .Lexit1:- tbz x0, #32, .Lasm_IteratorNextUnpack.slow_path_transfer_10+ tbnz x0, #32, 1f+ b .Lasm_IteratorNextUnpack.slow_path_transfer_12+1:add x21, x26, w0, uxtwldrb w9, [x21]ldr x10, [x19, x9, lsl #3]br x10-.Lasm_IteratorNextUnpack.slow_path_transfer_10:+.Lasm_IteratorNextUnpack.slow_path_transfer_12:ldr x28, [x20]ldr x9, [x28, #88]ldr x26, [x9, #40]@@ -17320,10 +17426,7 @@ asm_handler_IteratorNextUnpack:ldrb w9, [x21]ldr x10, [x19, x9, lsl #3]br x10-asm_handler_IteratorNextUnpack_hot_end:-asm_handler_IteratorNextUnpack_cold:asm_handler_IteratorNextUnpack_cold_end:-.p2align 4asm_handler_IteratorToArray:mov x0, x20diff --git a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.Sindex aa34b4b2e9d..98ecd869f50 100644--- a/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S+++ b/Libraries/LibJS/Flap/tests/interpreter-assembly/x86_64.S@@ -6952,13 +6952,27 @@ asm_handler_ObjectPropertyIteratorNext_hot_end:.p2align 6asm_handler_IteratorClose:+ mov eax, DWORD PTR [r14 + r13 + 4]+ mov rcx, QWORD PTR [rbx + rax * 8]+ mov r11, rcx+ shr r11, 48+ cmp r11w, 32762+ jne .Lasm_IteratorClose.ssa_block_3+ mov rax, QWORD PTR [rbx - 120]+ mov rax, QWORD PTR [rax + 64]+ test rax, rax+ jz .Lasm_IteratorClose.ssa_block_1+ cmp BYTE PTR [rax + 11], 0+ jz .Lasm_IteratorClose.ssa_block_1+ add r13d, 32+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+.Lasm_IteratorClose.ssa_block_3:mov rax, QWORD PTR [rbx - 40]mov rdx, QWORD PTR [rax + 152]test rdx, rdxjz .Lasm_IteratorClose.assert_failure_0mov eax, DWORD PTR [r14 + r13 + 24]- mov ecx, DWORD PTR [r14 + r13 + 4]- mov rcx, QWORD PTR [rbx + rcx * 8]shl rax, 3add rdx, raxmov rdi, rcx@@ -6973,6 +6987,81 @@ asm_handler_IteratorClose:jmp [r12 + rax * 8]asm_handler_IteratorClose_hot_end:+.p2align 6+asm_handler_IteratorNextUnpack:+ mov edx, DWORD PTR [r14 + r13 + 12]+ mov rax, QWORD PTR [rbx + rdx * 8]+ mov r11, rax+ shr r11, 48+ cmp r11w, 32762+ jne .Lasm_IteratorNextUnpack.ssa_block_1+ movsxd rcx, eax+ test ecx, ecx+ js .Lasm_IteratorNextUnpack.ssa_block_1+ mov esi, DWORD PTR [r14 + r13 + 20]+ mov rax, QWORD PTR [rbx + rsi * 8]+ test eax, 1+ jnz .Lasm_IteratorNextUnpack.ssa_block_1+ mov eax, DWORD PTR [r14 + r13 + 16]+ mov rax, QWORD PTR [rbx + rax * 8]+ mov r11, rax+ shr r11, 48+ cmp r11w, 65529+ jne .Lasm_IteratorNextUnpack.ssa_block_1+ movabs r11, 4398046511103+ and rax, r11+ add rax, r15+ movzx edi, WORD PTR [rax + 12]+ test edi, 4+ jz .Lasm_IteratorNextUnpack.ssa_block_1+ test edi, 16+ jnz .Lasm_IteratorNextUnpack.ssa_block_1+ mov edi, DWORD PTR [rax + 16]+ cmp rcx, rdi+ jb .Lasm_IteratorNextUnpack.ssa_block_7+ movabs r11, 9222809086901354496+ mov eax, DWORD PTR [r14 + r13 + 4]+ mov QWORD PTR [rbx + rax * 8], r11+ movabs r11, 9221401712017801217+ mov eax, DWORD PTR [r14 + r13 + 8]+ mov QWORD PTR [rbx + rax * 8], r11+ movabs r11, 9221401712017801217+ mov QWORD PTR [rbx + rsi * 8], r11+ add r13d, 24+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+.Lasm_IteratorNextUnpack.ssa_block_7:+ movzx esi, BYTE PTR [rax + 14]+ cmp rsi, 1+ jb .Lasm_IteratorNextUnpack.ssa_block_1+ cmp rsi, 3+ jae .Lasm_IteratorNextUnpack.ssa_block_1+ mov rax, QWORD PTR [rax + 40]+ test rax, rax+ jz .Lasm_IteratorNextUnpack.ssa_block_1+ mov esi, DWORD PTR [rax - 8]+ cmp rcx, rsi+ jae .Lasm_IteratorNextUnpack.ssa_block_1+ mov rax, QWORD PTR [rax + rcx * 8]+ mov r11, rax+ shr r11, 48+ cmp r11w, 32763+ je .Lasm_IteratorNextUnpack.ssa_block_1+ inc ecx+ jo .Lasm_IteratorNextUnpack.ssa_block_1+ mov r11d, DWORD PTR [r14 + r13 + 4]+ mov QWORD PTR [rbx + r11 * 8], rax+ movabs r11, 9221401712017801216+ mov eax, DWORD PTR [r14 + r13 + 8]+ mov QWORD PTR [rbx + rax * 8], r11+ movabs r11, 9221683186994511872+ or rcx, r11+ mov QWORD PTR [rbx + rdx * 8], rcx+ add r13d, 24+ movzx eax, BYTE PTR [r14 + r13]+ jmp [r12 + rax * 8]+asm_handler_IteratorNextUnpack_hot_end:+.p2align 6asm_handler_IsCallable:mov eax, DWORD PTR [r14 + r13 + 8]@@ -16861,8 +16950,9 @@ asm_handler_IteratorNext_hot_end:asm_handler_IteratorNext_cold:asm_handler_IteratorNext_cold_end:-.p2align 4-asm_handler_IteratorNextUnpack:+asm_handler_IteratorNextUnpack_cold:+# Cold paths for IteratorNextUnpack+.Lasm_IteratorNextUnpack.ssa_block_1:mov DWORD PTR [rbx + -64], r13dlea rcx, [r14 + r13]sub rsp, 64@@ -16896,10 +16986,14 @@ asm_handler_IteratorNextUnpack:mov r11, QWORD PTR [rsp + 24]mov QWORD PTR [rbx + r10 * 8], r11.Lasm_IteratorNextUnpack.skip_output_value_7:+ mov r10d, DWORD PTR [rcx + 12]+ mov r11, QWORD PTR [rsp + 32]+ mov QWORD PTR [rbx + r10 * 8], r11+.Lasm_IteratorNextUnpack.skip_output_value_8:mov r10d, DWORD PTR [rcx + 20]mov r11, QWORD PTR [rsp + 48]mov QWORD PTR [rbx + r10 * 8], r11-.Lasm_IteratorNextUnpack.skip_output_value_8:+.Lasm_IteratorNextUnpack.skip_output_value_9:add rsp, 64mov r13d, eaxmovzx eax, BYTE PTR [r14 + r13]@@ -16910,22 +17004,27 @@ asm_handler_IteratorNextUnpack:add r10, 128cmp r10, rbxjne .Lasm_IteratorNextUnpack.values_restore_stack_4+ lea rcx, [r14 + r13]+ mov r10d, DWORD PTR [rcx + 12]+ mov r11, QWORD PTR [rsp + 32]+ mov QWORD PTR [rbx + r10 * 8], r11+.Lasm_IteratorNextUnpack.skip_exceptional_output_10:lea rcx, [r14 + r13]mov r10d, DWORD PTR [rcx + 20]mov r11, QWORD PTR [rsp + 48]mov QWORD PTR [rbx + r10 * 8], r11-.Lasm_IteratorNextUnpack.skip_exceptional_output_9:+.Lasm_IteratorNextUnpack.skip_exceptional_output_11:.Lasm_IteratorNextUnpack.values_restore_stack_4:add rsp, 64.Lasm_IteratorNextUnpack.values_call_done_0:test rax, raxjs .Lexitbt rax, 32- jnc .Lasm_IteratorNextUnpack.slow_path_transfer_10+ jnc .Lasm_IteratorNextUnpack.slow_path_transfer_12mov r13d, eaxmovzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]-.Lasm_IteratorNextUnpack.slow_path_transfer_10:+.Lasm_IteratorNextUnpack.slow_path_transfer_12:mov rcx, QWORD PTR [rbp - 48]mov rbx, QWORD PTR [rcx]add rbx, 128@@ -16934,10 +17033,7 @@ asm_handler_IteratorNextUnpack:mov r13d, eaxmovzx eax, BYTE PTR [r14 + r13]jmp [r12 + rax * 8]-asm_handler_IteratorNextUnpack_hot_end:-asm_handler_IteratorNextUnpack_cold:asm_handler_IteratorNextUnpack_cold_end:-.p2align 4asm_handler_IteratorToArray:mov DWORD PTR [rbx + -64], r13ddiff --git a/Libraries/LibJS/Flap/tests/interpreter-layout.conf b/Libraries/LibJS/Flap/tests/interpreter-layout.confindex 799de62cda3..159727d53cb 100644--- a/Libraries/LibJS/Flap/tests/interpreter-layout.conf+++ b/Libraries/LibJS/Flap/tests/interpreter-layout.conf@@ -248,6 +248,12 @@ const REALM_GLOBAL_OBJECT = 16field Realm.global_object Object REALM_GLOBAL_OBJECT nullable cell global_stateconst REALM_GLOBAL_DECLARATIVE_ENVIRONMENT = 24field Realm.global_declarative_environment DeclarativeEnvironment REALM_GLOBAL_DECLARATIVE_ENVIRONMENT nullable cell global_state+const REALM_ARRAY_ITERATOR_RETURN_FUSE = 64+field Realm.array_iterator_return_fuse Fuse REALM_ARRAY_ITERATOR_RETURN_FUSE nullable cell++# Fuse layout+const FUSE_INTACT = 11+field Fuse.intact bool FUSE_INTACT nonnull scalar# VM layoutconst VM_RUNNING_EXECUTION_CONTEXT = 0diff --git a/Libraries/LibJS/Interpreter/interpreter.flap b/Libraries/LibJS/Interpreter/interpreter.flapindex 5e5aa25fa01..f3413d3248a 100644--- a/Libraries/LibJS/Interpreter/interpreter.flap+++ b/Libraries/LibJS/Interpreter/interpreter.flap@@ -3700,6 +3700,7 @@ handler GetIterator(dst_iterator_done: out Operand,iterable: Operand,hint: IteratorHint,+ fast_array_mode_allowed: bool,cache: PropertyLookupCacheIndex) @cold = call_slow_path(get_iterator);@@ -4561,8 +4562,18 @@ handler IteratorClose(};# An iterator without a return method closes without doing anything, for every completion type: the- # instruction that follows a close for a throw completion throws it again. The cache of the site- # tells if the method is missing.+ # instruction that follows a close for a throw completion throws it again.++ # In fast array mode, the iterator register holds a number. The return fuse of the realm tells if array+ # iterators have a return method.+ if extract_tag(load(iterator_object)) == INT32_TAG {+ let return_fuse = exec_ctx.realm.array_iterator_return_fuse;+ guard return_fuse != 0 else slow;+ guard return_fuse.intact else slow;+ dispatch_next;+ }++ # Other iterators: the cache of the site tells if the method is missing.let executable = exec_ctx.executable;let caches: u64 = alias(executable.property_lookup_caches);let cache_index: u64 = alias(load(cache));@@ -4582,10 +4593,56 @@ handler IteratorNext(handler IteratorNextUnpack(dst_value: out Operand,dst_done: out Operand,- iterator_object: Operand,+ iterator_object: inout Operand,iterator_next: Operand,iterator_done: inout Operand-) @cold = call_slow_path(iterator_next_unpack);+) {+ let slow = || @cold {+ call_slow_path(iterator_next_unpack);+ };++ # In fast array mode, the iterator register holds the index of the next element as a number, and the next+ # register holds the array (see get_iterator() in the runtime). Holes, iterations that are done and all other+ # iterators take the slow path.+ guard let Value<i32>(index) = load(iterator_object) else slow;+ guard index >= 0 else slow;+ # NB: The done register holds a boolean.+ let iteration_done = load(iterator_done);+ branch_bits_set(iteration_done, 1, slow);+ guard let Value<Object>(array) = load(iterator_next) else slow;+ let flags = array.flags;+ guard flags has OBJECT_FLAG_HAS_MAGICAL_LENGTH else slow;+ guard flags lacks OBJECT_FLAG_MAY_INTERFERE else slow;+ let unsigned_index = assume_u32(index);++ # The array iterator reads the length of the array at each step. After the last element, the done register+ # keeps the iteration done, also if the array grows.+ if unsigned_index >= array.indexed_array_like_size {+ store(dst_value, Value<Undefined>);+ store(dst_done, Value<True>);+ store(iterator_done, Value<True>);+ dispatch_next;+ }++ let next_element = || {+ let indexed_elements = array.indexed_elements;+ guard indexed_elements != 0 else slow;+ guard unsigned_index < indexed_elements.capacity else slow;+ let value = indexed_elements[unsigned_index];+ guard value is not Value<Empty> else slow;+ guard let next_index = checked_add(index, 1) else slow;+ store(dst_value, value);+ store(dst_done, Value<False>);+ store(iterator_object, box_i32(next_index));+ dispatch_next;+ };++ match array.indexed_storage_kind {+ INDEXED_STORAGE_KIND_PACKED => next_element,+ INDEXED_STORAGE_KIND_HOLEY => next_element,+ _ => slow,+ }+}handler IteratorToArray(dst: out Operand,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs b/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rsindex b7501e7ab67..a3ce8caf4b5 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/array_iterators.rs@@ -11,6 +11,7 @@use super::Flow;use super::GraphBuilder;+use super::checks::SlowPaths;use crate::CompileFailure;use crate::bytecode::Operand;use crate::code::Repr;@@ -66,13 +67,20 @@ impl GraphBuilder<'_> {Ok(Some(Flow::Continue))}- /// Builds `IteratorNextUnpack` (`Handling::Expanded`) for array- /// iterators over the values of arrays with packed or holey elements,- /// whose next method is the builtin one: the element at the iterator's- /// index, which moves on to the next one, or done once the index reaches- /// the length of the array. Holes take the slow path, which looks them- /// up in the prototype chain. Returns `None`, having built nothing, if- /// the realm's array iterators had another next method.+ /// Builds `IteratorNextUnpack` (`Handling::Expanded`) for arrays with+ /// packed or holey elements, stepped like `%ArrayIteratorPrototype%.next`+ /// steps array iterators over their values: the element at the index,+ /// which moves on to the next one, or done once the index reaches the+ /// length of the array. Holes take the slow path, which looks them up in+ /// the prototype chain.+ ///+ /// In fast array mode (see `get_iterator()` in the runtime), the iterator+ /// operand holds the index, an int32 until the slow path makes it a+ /// double, the next operand holds the array, and the done operand tells+ /// when the iteration is done. Otherwise, array+ /// iterators whose next method is the builtin one hold the array and the+ /// index, if the realm's array iterators had that method when the+ /// snapshot was taken.pub(super) fn try_build_iterator_next_unpack(&mut self,dst_value: Operand,@@ -81,78 +89,143 @@ impl GraphBuilder<'_> {iterator_next: Operand,iterator_done: Operand,) -> Result<Option<Flow>, CompileFailure> {- let Some(builtin_next) = self.array_iterator_next() else {- return Ok(None);- };let iterator = self.read(iterator_object)?;let next = self.read(iterator_next)?;let iterator_is_done = self.read(iterator_done)?;let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;+ let (undefined, done, not_done) = (+ self.constant(value::UNDEFINED),+ self.constant(value::TRUE),+ self.constant(value::FALSE),+ );+ let kind = ElementsKind::Holey;++ // Fast array mode. NB: Iterations that are done take the slow path.+ let index = self.branch_to_next_case(&mut slow_paths, BranchCondition::NonNegativeInt32, vec![iterator], true);self.branch_to_slow_path(&mut slow_paths,BranchCondition::TaggedEquals { equal: true },- vec![next, builtin_next],+ vec![iterator_is_done, not_done],true,);- let iterator = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![iterator], true);- let iterator = self.cell_address(iterator);- let iterator = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ArrayIterator, vec![iterator], true);- let (undefined, done, not_done) = (- self.constant(value::UNDEFINED),- self.constant(value::TRUE),- self.constant(value::FALSE),+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![next], true);+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ElementsKind(kind), vec![array], true);+ let array = self.cell_address(array);+ let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::MagicalLength, vec![array], true);+ let index = self.emit(Op::UnboxInt32, vec![index], Some(Repr::Int32));+ let length = self.emit(Op::LoadElementsLength, vec![array], Some(Repr::Int32));+ let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, vec![index, length]);++ // NB: The done operand keeps the iteration done, also if the array+ // grows.+ self.block = outside;+ self.end_hot_path(&mut slow_paths, vec![undefined, done, iterator, done]);++ self.block = inside;+ let index = self.refine(BranchCondition::IndexInBounds, true, vec![index, length]);+ let element = self.load_array_iteration_element(&mut slow_paths, kind, array, index);+ // NB: The index is below the capacity, so the next one is an int32 too.+ let one = self.int32_constant(1);+ let next_index = self.emit_checked(+ Op::Int32Binary { op: BinaryOp::Add },+ vec![index, one],+ Some(Repr::Int32),);+ let next_index = self.emit(Op::BoxInt32, vec![next_index], Some(Repr::Tagged));+ self.end_hot_path(&mut slow_paths, vec![element, not_done, next_index, iterator_is_done]);++ // Array iterators. NB: Without them, the other values take the slow+ // path.+ let Some(builtin_next) = self.array_iterator_next() else {+ let outputs = self.join_hot_paths_with(slow_paths, |_, outputs| outputs);+ self.write_iterator_next_unpack_outputs(&outputs, dst_value, dst_done, iterator_object, iterator_done)?;+ return Ok(Some(Flow::Continue));+ };+ let started = self.start_next_case(&mut slow_paths);+ debug_assert!(started, "values other than indices go on to the next case");+ self.branch_to_slow_path(+ &mut slow_paths,+ BranchCondition::TaggedEquals { equal: true },+ vec![next, builtin_next],+ true,+ );+ let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::Object, vec![iterator], true);+ let object = self.cell_address(object);+ let object = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ArrayIterator, vec![object], true);// NB: Done iterators no longer have an array.- let array = self.emit(Op::LoadArrayIteratorArray, vec![iterator], Some(Repr::Tagged));+ let array = self.emit(Op::LoadArrayIteratorArray, vec![object], Some(Repr::Tagged));let (exhausted, live) = self.branch_both_ways(BranchCondition::Undefined, vec![array]);self.block = exhausted;- self.end_hot_path(&mut slow_paths, vec![undefined, done, done]);+ self.end_hot_path(&mut slow_paths, vec![undefined, done, iterator, done]);self.block = live;let array = self.refine(BranchCondition::Undefined, false, vec![array]);- let kind = ElementsKind::Holey;let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::ElementsKind(kind), vec![array], true);let array = self.cell_address(array);// NB: Array iterators iterate array-likes up to their `length`,// which only arrays keep as the size of their elements.let array = self.branch_to_slow_path(&mut slow_paths, BranchCondition::MagicalLength, vec![array], true);- let index = self.emit(Op::LoadArrayIteratorIndex, vec![iterator], Some(Repr::Int32));+ let index = self.emit(Op::LoadArrayIteratorIndex, vec![object], Some(Repr::Int32));let length = self.emit(Op::LoadElementsLength, vec![array], Some(Repr::Int32));let (inside, outside) = self.branch_both_ways(BranchCondition::IndexInBounds, vec![index, length]);// NB: The array has no element at the index, so the iterator is done.self.block = outside;- self.emit(Op::FinishArrayIterator, vec![iterator], None);- self.end_hot_path(&mut slow_paths, vec![undefined, done, done]);+ self.emit(Op::FinishArrayIterator, vec![object], None);+ self.end_hot_path(&mut slow_paths, vec![undefined, done, iterator, done]);self.block = inside;let index = self.refine(BranchCondition::IndexInBounds, true, vec![index, length]);- // NB: Holey elements below the length may be past the capacity.- // Elements are accessed through the array (see- // `element_storage_and_bound()`).- let capacity = self.emit(Op::LoadElementsCapacity, vec![array], Some(Repr::Int32));- let index = self.branch_to_slow_path(- &mut slow_paths,- BranchCondition::IndexInBounds,- vec![index, capacity],- true,- );- let element = self.load_element(kind, array, index);- let element = self.branch_if_empty(&mut slow_paths, element);+ let element = self.load_array_iteration_element(&mut slow_paths, kind, array, index);let one = self.int32_constant(1);let next_index = self.emit_checked(Op::Int32Binary { op: BinaryOp::Add },vec![index, one],Some(Repr::Int32),);- self.emit(Op::StoreArrayIteratorIndex, vec![iterator, next_index], None);- let outputs = self.join_paths(slow_paths, vec![element, not_done, iterator_is_done], |_, outputs| {- outputs- });+ self.emit(Op::StoreArrayIteratorIndex, vec![object, next_index], None);+ let outputs = self.join_paths(+ slow_paths,+ vec![element, not_done, iterator, iterator_is_done],+ |_, outputs| outputs,+ );+ self.write_iterator_next_unpack_outputs(&outputs, dst_value, dst_done, iterator_object, iterator_done)?;+ Ok(Some(Flow::Continue))+ }++ /// The element of `array` at `index`, which is below its length: holes+ /// take the slow path.+ fn load_array_iteration_element(+ &mut self,+ slow_paths: &mut SlowPaths,+ kind: ElementsKind,+ array: NodeId,+ index: NodeId,+ ) -> NodeId {+ // NB: Holey elements below the length may be past the capacity.+ // Elements are accessed through the array (see+ // `element_storage_and_bound()`).+ let capacity = self.emit(Op::LoadElementsCapacity, vec![array], Some(Repr::Int32));+ let index = self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, vec![index, capacity], true);+ let element = self.load_element(kind, array, index);+ self.branch_if_empty(slow_paths, element)+ }++ /// Writes the outputs of `IteratorNextUnpack`, in the order of the+ /// outputs of its slow path.+ fn write_iterator_next_unpack_outputs(+ &mut self,+ outputs: &[NodeId],+ dst_value: Operand,+ dst_done: Operand,+ iterator_object: Operand,+ iterator_done: Operand,+ ) -> Result<(), CompileFailure> {self.write(dst_value, outputs[0])?;self.write(dst_done, outputs[1])?;- self.write(iterator_done, outputs[2])?;- Ok(Some(Flow::Continue))+ self.write(iterator_object, outputs[2])?;+ self.write(iterator_done, outputs[3])?;+ Ok(())}}diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rsindex 652e46fda94..4dfdf8184ab 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs@@ -551,7 +551,7 @@ impl GraphBuilder<'_> {});predecessors.extend(slow.as_ref().map(|(block, _)| *block));self.join_blocks(predecessors);- debug_assert!(+ assert!(values.is_empty() || values.len() == slow_paths.output_count,"the slow path writes the same operands");diff --git a/Libraries/LibJS/Rust/generate/layout_table.rs b/Libraries/LibJS/Rust/generate/layout_table.rsindex 1e1fa15f371..203b93c9f3c 100644--- a/Libraries/LibJS/Rust/generate/layout_table.rs+++ b/Libraries/LibJS/Rust/generate/layout_table.rs@@ -377,6 +377,10 @@ pub fn generate(configuration: &LayoutConfiguration) -> LayoutWriter {field!(w, "REALM_GLOBAL_ENVIRONMENT", "Realm.global_environment", "GlobalEnvironment", Realm, global_environment, 8, "nonnull", "cell");field!(w, "REALM_GLOBAL_OBJECT", "Realm.global_object", "Object", Realm, global_object, 8, "nullable", "cell", "global_state");field!(w, "REALM_GLOBAL_DECLARATIVE_ENVIRONMENT", "Realm.global_declarative_environment", "DeclarativeEnvironment", Realm, global_declarative_environment, 8, "nullable", "cell", "global_state");+ field!(w, "REALM_ARRAY_ITERATOR_RETURN_FUSE", "Realm.array_iterator_return_fuse", "Fuse", Realm, array_iterator_return_fuse, 8, "nullable", "cell");++ w.section("Fuse layout");+ field!(w, "FUSE_INTACT", "Fuse.intact", "bool", Fuse, intact, 1, "nonnull", "scalar");w.section("VM layout");offset!(w, "VM_RUNNING_EXECUTION_CONTEXT", VmHead, running_execution_context);diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen.rs b/Libraries/LibJS/Rust/src/bytecode/codegen.rsindex 464f22e6cf8..61fd0dac4bb 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen.rs@@ -1477,6 +1477,8 @@ fn generate_yield_from(dst_iterator_done: iterator_done_property.operand(),iterable: value.operand(),hint,+ // NB: yield* passes the iterator to calls of its methods.+ fast_array_mode_allowed: false,cache,});@@ -7476,6 +7478,7 @@ fn generate_for_of_statement_inner(} else {IteratorHint::Sync} as u32,+ fast_array_mode_allowed: !is_await,cache,});@@ -8073,6 +8076,7 @@ fn generate_array_binding_pattern(dst_iterator_done: iterator_done.operand(),iterable: input_array.operand(),hint: IteratorHint::Sync as u32,+ fast_array_mode_allowed: true,cache,});diff --git a/Libraries/LibJS/Rust/src/bytecode_cache.rs b/Libraries/LibJS/Rust/src/bytecode_cache.rsindex 734b6d9672a..ccbcaa8ef8d 100644--- a/Libraries/LibJS/Rust/src/bytecode_cache.rs+++ b/Libraries/LibJS/Rust/src/bytecode_cache.rs@@ -50,7 +50,7 @@ use crate::compile::CompiledProgramBytecode;use crate::u32_from_usize;const MAGIC: &[u8; 8] = b"LBJSBC\0\0";-const FORMAT_VERSION: u32 = 27;+const FORMAT_VERSION: u32 = 28;/// The size of the source hash a blob is keyed by.pub(crate) const SOURCE_HASH_SIZE: usize = 32;const BYTECODE_ALIGNMENT: usize = 8;diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rsindex 68c134bafa1..744be8f4b8e 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/control.rs@@ -15,22 +15,25 @@ use crate::interpreter::runtime_functions::{SlowPathControl, asm_try, handle_asmuse crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::execution_context::ExecutionContext;+use crate::layout::function_object::FunctionObject;use crate::layout::object::Object;use crate::layout::value::Value;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::async_generator::AsyncGenerator;-use crate::runtime::completion::{Completion, Must, completion_type_from_bytecode};+use crate::runtime::completion::{Completion, Must, ThrowCompletionOr, completion_type_from_bytecode};use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;use crate::runtime::generator_object::GeneratorObject;use crate::runtime::iterator::{- IteratorRecord, IteratorRecordImpl, get_iterator_from_method_impl, get_iterator_impl_with_cache,- get_iterator_values, iterator_close_with_cache, iterator_hint_from_bytecode, iterator_next, iterator_step_value,+ IteratorHint, IteratorRecord, IteratorRecordImpl, get_iterator_from_method_impl, get_iterator_impl_with_cache,+ get_iterator_values, get_sync_iterator_method, iterator_close_with_cache, iterator_hint_from_bytecode,+ iterator_next, iterator_step_value,};use crate::runtime::map::Map;use crate::runtime::map_iterator::map_iteration_is_unobservable;-use crate::runtime::object::{IndexedStorageKind, IntegrityLevel};+use crate::runtime::object::{IndexedStorageKind, IntegrityLevel, PropertyKind};use crate::runtime::property_attributes::{Attribute, DEFAULT_ATTRIBUTES, PropertyAttributes};use crate::runtime::property_key::PropertyKey;use crate::runtime::realm::Realm;@@ -70,12 +73,14 @@ fn create_reference_error(vm: &Vm, realm: Gc<Realm>, message: &Utf16FlyString) -.upcast()}-/// The iterator record a slow path receives as the three registers the bytecode keeps it in.+/// The iterator record a slow path receives as the three registers the bytecode keeps it in, if they are not in fast+/// array mode (see get_iterator()).fn iterator_record_from_registers(iterator_object: Value,iterator_next: Value,iterator_done: Value,) -> IteratorRecordImpl {+ assert!(iterator_object.is_object());IteratorRecordImpl::new(Some(iterator_object.as_object()),iterator_next,@@ -373,6 +378,42 @@ pub fn new_type_error(SlowPathControl::continue_at(pc + op::NewTypeError::LENGTH)}+// NB: In fast array mode, GetIterator makes no iterator for an array whose iteration nothing can observe. The+// iterator register holds the index of the next element as a number, and the next register holds the array.+// The done register tells when the iteration is done. IteratorNextUnpack, IteratorClose and IteratorToArray step+// it like an array iterator. Other iterator records always hold an object in the iterator register.++/// The index of the next element in fast array mode, if the iterator register is in that mode.+fn fast_array_mode_index(iterator_object: Value) -> Option<f64> {+ iterator_object.is_number().then(|| iterator_object.as_f64())+}++/// The array of an iteration in fast array mode, or `None` if GetIterator must make an iterator for `iterable` whose+/// iterator method is `method`. The array iterator that the method would make has the builtin next method, and only+/// that method reads the array.+fn fast_array_mode_array(vm: &Vm, iterable: Value, method: Gc<FunctionObject>) -> Option<Gc<Object>> {+ if !iterable.is_object() {+ return None;+ }+ let realm = current_realm(vm);+ if method != realm.array_prototype_values_function() || !realm_fuses::array_iterators_have_builtin_next(&realm) {+ return None;+ }+ let array = iterable.as_object();+ array.downcast::<Array>().is_some().then_some(array)+}++/// The next step of an iteration in fast array mode at `index`, like %ArrayIteratorPrototype%.next ( ): the element+/// and the index after it, or `None` once the iteration is done.+fn fast_array_mode_step(vm: &Vm, array: &Object, index: f64) -> ThrowCompletionOr<Option<(Value, Value)>> {+ let index = index as u64;+ if index >= iterated_array_like_length(vm, array)? {+ return Ok(None);+ }+ let element = iterated_array_like_element(vm, array, index)?;+ Ok(Some((element, Value::from_f64((index + 1) as f64))))+}+pub fn get_iterator(vm: &Vm,pc: u32,@@ -381,16 +422,29 @@ pub fn get_iterator() -> SlowPathControl {let executable = vm.current_executable();let cache = executable.property_lookup_cache(instruction.cache as usize);- let iterator_record = asm_try!(- vm,- pc,- get_iterator_impl_with_cache(- vm,- values.iterable,- iterator_hint_from_bytecode(instruction.hint),- cache- )- );+ let hint = iterator_hint_from_bytecode(instruction.hint);+ if hint == IteratorHint::Async {+ let iterator_record = asm_try!(vm, pc, get_iterator_impl_with_cache(vm, values.iterable, hint, cache));+ values.dst_iterator_object = Value::from_object(iterator_record.iterator());+ values.dst_iterator_next = iterator_record.next_method();+ values.dst_iterator_done = Value::from_bool(iterator_record.done());+ return SlowPathControl::continue_at(pc + op::GetIterator::LENGTH);+ }++ let method = asm_try!(vm, pc, get_sync_iterator_method(vm, values.iterable, cache));++ // OPTIMIZATION: Calling %Array.prototype.values% and getting the next method of the array iterator it makes+ // cannot be observed, so fast array mode skips both.+ if instruction.fast_array_mode_allowed+ && let Some(array) = fast_array_mode_array(vm, values.iterable, method)+ {+ values.dst_iterator_object = Value::from_i32(0);+ values.dst_iterator_next = Value::from_object(array);+ values.dst_iterator_done = Value::FALSE;+ return SlowPathControl::continue_at(pc + op::GetIterator::LENGTH);+ }++ let iterator_record = asm_try!(vm, pc, get_iterator_from_method_impl(vm, values.iterable, method));values.dst_iterator_object = Value::from_object(iterator_record.iterator());values.dst_iterator_next = iterator_record.next_method();values.dst_iterator_done = Value::from_bool(iterator_record.done());@@ -403,15 +457,37 @@ pub fn iterator_close_slow_path(instruction: &op::IteratorClose,values: &mut op::IteratorCloseValues,) -> SlowPathControl {- let iterator_record =- iterator_record_from_registers(values.iterator_object, values.iterator_next, values.iterator_done);-let completion = Completion::new(completion_type_from_bytecode(instruction.completion_type),values.completion_value,);let executable = vm.current_executable();let cache = executable.property_lookup_cache(instruction.cache as usize);++ let iterator_record = if let Some(index) = fast_array_mode_index(values.iterator_object) {+ // NB: Without a return method, closing an array iterator does nothing.+ let realm = current_realm(vm);+ if realm_fuses::array_iterators_have_no_return(&realm) {+ return SlowPathControl::continue_at(pc + op::IteratorClose::LENGTH);+ }++ // A return method appeared during the iteration. It gets the array iterator that GetIterator would have+ // made, at the same position.+ let iterator = ArrayIterator::create(vm, realm, values.iterator_next, PropertyKind::Value);+ if values.iterator_done.as_bool() {+ iterator.array.set(Value::UNDEFINED);+ } else {+ iterator.index.set(index as u64);+ }+ IteratorRecordImpl::new(+ Some(iterator.upcast()),+ Value::UNDEFINED,+ values.iterator_done.as_bool(),+ )+ } else {+ iterator_record_from_registers(values.iterator_object, values.iterator_next, values.iterator_done)+ };+asm_try!(vm,pc,@@ -432,6 +508,26 @@ pub fn iterator_next_slow_path(vm: &Vm, pc: u32, values: &mut op::IteratorNextVa}pub fn iterator_next_unpack(vm: &Vm, pc: u32, values: &mut op::IteratorNextUnpackValues) -> SlowPathControl {+ if let Some(index) = fast_array_mode_index(values.iterator_object) {+ let step = if values.iterator_done.as_bool() {+ Ok(None)+ } else {+ fast_array_mode_step(vm, &values.iterator_next.as_object(), index)+ };+ if !matches!(step, Ok(Some(_))) {+ values.iterator_done = Value::TRUE;+ }+ if let Some((element, next_index)) = asm_try!(vm, pc, step) {+ values.dst_value = element;+ values.dst_done = Value::FALSE;+ values.iterator_object = next_index;+ } else {+ values.dst_value = Value::UNDEFINED;+ values.dst_done = Value::TRUE;+ }+ return SlowPathControl::continue_at(pc + op::IteratorNextUnpack::LENGTH);+ }+let iterator_record =iterator_record_from_registers(values.iterator_object, values.iterator_next, values.iterator_done);let iteration_result_or_error = iterator_step_value(vm, &iterator_record);@@ -451,14 +547,34 @@ pub fn iterator_next_unpack(vm: &Vm, pc: u32, values: &mut op::IteratorNextUnpac}pub fn iterator_to_array(vm: &Vm, pc: u32, values: &mut op::IteratorToArrayValues) -> SlowPathControl {+ let array = Array::create(vm, current_realm(vm), 0, None).must();+ let mut index: u64 = 0;++ if let Some(mut iterated_index) = fast_array_mode_index(values.iterator_object) {+ let was_done = values.iterator_done_property.as_bool();+ // NB: Every step either throws or reaches the end, which both make the iteration done.+ values.iterator_done_property = Value::TRUE;+ let iterated_array = values.iterator_next_method.as_object();+ while !was_done+ && let Some((element, next_index)) =+ asm_try!(vm, pc, fast_array_mode_step(vm, &iterated_array, iterated_index))+ {+ array+ .create_data_property_or_throw(vm, &PropertyKey::from_number(index), element)+ .must();+ index += 1;+ iterated_index = next_index.as_f64();+ }+ values.dst = Value::from_object(array);+ return SlowPathControl::continue_at(pc + op::IteratorToArray::LENGTH);+ }+let iterator_record = iterator_record_from_registers(values.iterator_object,values.iterator_next_method,values.iterator_done_property,);- let array = Array::create(vm, current_realm(vm), 0, None).must();- let mut index: u64 = 0;loop {let value_or_error = iterator_step_value(vm, &iterator_record);if iterator_record.done() {diff --git a/Libraries/LibJS/Rust/src/runtime/array_iterator.rs b/Libraries/LibJS/Rust/src/runtime/array_iterator.rsindex 17de124c3b8..95acb983a78 100644--- a/Libraries/LibJS/Rust/src/runtime/array_iterator.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_iterator.rs@@ -115,25 +115,8 @@ impl ArrayIterator {let kind = self.iteration_kind;// 8. If array has a [[TypedArrayName]] internal slot, then- let length = if array.is_typed_array() {- let typed_array = typed_array_of_object(&array);-- // a. Let taRecord be MakeTypedArrayWithBufferWitnessRecord(array, SEQ-CST).- let typed_array_record = make_typed_array_with_buffer_witness_record(typed_array, Order::SeqCst);-- // b. If IsTypedArrayOutOfBounds(taRecord) is true, throw a TypeError exception.- if is_typed_array_out_of_bounds(&typed_array_record) {- return vm.throw_completion(ErrorKind::TypeError, ErrorType::BufferOutOfBounds, &[&"TypedArray"]);- }-- // c. Let len be TypedArrayLength(taRecord).- u64::from(typed_array_length(&typed_array_record))- }// 9. Else,- else {- // a. Let len be ? LengthOfArrayLike(array).- length_of_array_like(vm, &array)?- };+ let length = iterated_array_like_length(vm, &array)?;// 10. If index ≥ len, thenif index >= length {@@ -162,20 +145,7 @@ impl ArrayIterator {else {// a. Let elementKey be ! ToString(indexNumber).// b. Let elementValue be ? Get(array, elementKey).- let element_value = 'element_value: {- // OPTIMIZATION: For objects that don't interfere with indexed property access, we try looking directly at storage.- // NB: The index is passed to the storage as the u32 it takes, which truncates indices past 2^32 - 1.- let storage_index = index as u32;- if !array.may_interfere_with_indexed_property_access()- && array.indexed_has(storage_index)- && let Some(element) = array.indexed_get(storage_index)- && !element.value.is_accessor()- {- break 'element_value element.value;- }-- array.get(vm, &PropertyKey::from_number(index))?- };+ let element_value = iterated_array_like_element(vm, &array, index)?;// c. If kind is VALUE, thenif kind == PropertyKind::Value {@@ -198,3 +168,55 @@ impl ArrayIterator {Ok(())}}++/// Steps 8 and 9 of %ArrayIteratorPrototype%.next ( ): the length of the array-like that an array iterator iterates.+pub fn iterated_array_like_length(vm: &Vm, array: &Object) -> ThrowCompletionOr<u64> {+ // 8. If array has a [[TypedArrayName]] internal slot, then+ if array.is_typed_array() {+ let typed_array = typed_array_of_object(array);++ // a. Let taRecord be MakeTypedArrayWithBufferWitnessRecord(array, SEQ-CST).+ let typed_array_record = make_typed_array_with_buffer_witness_record(typed_array, Order::SeqCst);++ // b. If IsTypedArrayOutOfBounds(taRecord) is true, throw a TypeError exception.+ if is_typed_array_out_of_bounds(&typed_array_record) {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::BufferOutOfBounds, &[&"TypedArray"]);+ }++ // c. Let len be TypedArrayLength(taRecord).+ return Ok(u64::from(typed_array_length(&typed_array_record)));+ }++ // 9. Else,+ // a. Let len be ? LengthOfArrayLike(array).+ length_of_array_like(vm, array)+}++/// Steps 14.a and 14.b of %ArrayIteratorPrototype%.next ( ): the element at `index` of the array-like that an array+/// iterator iterates.+pub fn iterated_array_like_element(vm: &Vm, array: &Object, index: u64) -> ThrowCompletionOr<Value> {+ // a. Let elementKey be ! ToString(indexNumber).+ // b. Let elementValue be ? Get(array, elementKey).+ // OPTIMIZATION: For objects that don't interfere with indexed property access, we try looking directly at storage.+ // NB: The index is passed to the storage as the u32 it takes, which truncates indices past 2^32 - 1.+ let storage_index = index as u32;+ if !array.may_interfere_with_indexed_property_access() {+ if array.indexed_has(storage_index) {+ if let Some(element) = array.indexed_get(storage_index)+ && !element.value.is_accessor()+ {+ return Ok(element.value);+ }+ }+ // OPTIMIZATION: A hole of an array whose prototype chain has no elements reads as undefined.+ else if array+ .as_gc()+ .downcast::<Array>()+ .is_some_and(|array| array.default_prototype_chain_intact())+ {+ return Ok(Value::UNDEFINED);+ }+ }++ array.get(vm, &PropertyKey::from_number(index))+}diff --git a/Libraries/LibJS/Rust/src/runtime/iterator.rs b/Libraries/LibJS/Rust/src/runtime/iterator.rsindex 793d7a810fd..176101af54a 100644--- a/Libraries/LibJS/Rust/src/runtime/iterator.rs+++ b/Libraries/LibJS/Rust/src/runtime/iterator.rs@@ -309,6 +309,28 @@ pub fn get_iterator_impl_with_cache(get_iterator_from_method_impl(vm, object, method)}+/// Steps 2 and 3 of GetIterator for synchronous iteration: the iterator method of `object`, through the cache+/// `iterator_method_cache`.+pub fn get_sync_iterator_method(+ vm: &Vm,+ object: Value,+ iterator_method_cache: &PropertyLookupCache,+) -> ThrowCompletionOr<Gc<FunctionObject>> {+ // 2. Else,+ // a. Let method be ? GetMethod(obj, @@iterator).+ let method = object.get_method_with_cache(+ vm,+ &PropertyKey::from(vm.well_known_symbols().iterator),+ iterator_method_cache,+ )?;++ // 3. If method is undefined, throw a TypeError exception.+ let Some(method) = method else {+ return vm.throw_completion(ErrorKind::TypeError, ErrorType::NotIterable, &[&object]);+ };+ Ok(method)+}+pub fn get_iterator(vm: &Vm, object: Value, kind: IteratorHint) -> ThrowCompletionOr<Gc<IteratorRecord>> {let iterator_record_impl = get_iterator_impl(vm, object, kind)?;Ok(IteratorRecord::create_from_impl(vm, &iterator_record_impl))diff --git a/Tests/LibJS/Bytecode/expected/destructure-array-rest.txt b/Tests/LibJS/Bytecode/expected/destructure-array-rest.txtindex 6545f82156f..5ab9a08e949 100644--- a/Tests/LibJS/Bytecode/expected/destructure-array-rest.txt+++ b/Tests/LibJS/Bytecode/expected/destructure-array-rest.txt@@ -26,7 +26,7 @@ block0:[ 8] GetLexicalEnvironment dst:reg4[ 10] NewPrimitiveArray dst:reg5, elements:[1, 2, 3][ 38] Mov dst:reg6, src:Bool(false)- [ 48] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5+ [ 48] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true[ 68] Jump target:block3block1:diff --git a/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txt b/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txtindex 258e154f8d3..1f620673a3c 100644--- a/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txt+++ b/Tests/LibJS/Bytecode/expected/destructuring-assignment-in-logical-and.txt@@ -33,7 +33,7 @@ block1:[ 40] Mov2 c0_dst:reg7, c0_src:arg0, c1_dst:reg8, c1_src:arg1[ 58] Call value_feedback:0, call_feedback:0, dst:reg6, callee:reg7, this_value:Undefined, t, arguments:[reg8][ 80] Mov dst:reg7, src:Bool(false)- [ 90] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:reg6+ [ 90] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:reg6, fast_array_mode_allowed:true[ b0] Jump target:block5block2:diff --git a/Tests/LibJS/Bytecode/expected/destructuring-assignment.txt b/Tests/LibJS/Bytecode/expected/destructuring-assignment.txtindex b46b7bed4ca..805473c60c8 100644--- a/Tests/LibJS/Bytecode/expected/destructuring-assignment.txt+++ b/Tests/LibJS/Bytecode/expected/destructuring-assignment.txt@@ -31,7 +31,7 @@ block0:[ 10] MovSrcUndefined dst:x~0[ 18] NewArray dst:reg5, elements:[Undefined][ 30] Mov dst:reg6, src:Bool(false)- [ 40] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5+ [ 40] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true[ 60] Jump target:block3block1:@@ -142,7 +142,7 @@ block0:[ 20] InitializeVariableBinding `setValue`, src:Undefined[ 38] NewPrimitiveArray dst:reg5, elements:[23][ 50] Mov dst:reg6, src:Bool(false)- [ 60] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5+ [ 60] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true[ 80] Jump target:block3block1:diff --git a/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txt b/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txtindex 27a4f8e58da..87990b3bf28 100644--- a/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txt+++ b/Tests/LibJS/Bytecode/expected/destructuring-no-base-identifier.txt@@ -14,7 +14,7 @@ block0:[ 20] SetGlobal `x`, src:reg5[ 30] NewPrimitiveArray dst:reg5, elements:[42][ 48] Mov dst:reg6, src:Bool(false)- [ 58] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5+ [ 58] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true[ 78] Jump target:block3block1:diff --git a/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txt b/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txtindex a8c439c8079..fbc53825365 100644--- a/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txt+++ b/Tests/LibJS/Bytecode/expected/for-of-cond-rhs-block-order.txt@@ -48,7 +48,7 @@ block5:[ b0] GetById value_feedback:2, dst:reg8, base:reg6, `entries` (Object.entries)[ c8] NewObject dst:reg9[ d8] Call value_feedback:3, call_feedback:0, dst:reg7, callee:reg8, this_value:reg6, Object.entries, arguments:[reg9]- [ 100] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg8, dst_iterator_done:reg6, iterable:reg7+ [ 100] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg8, dst_iterator_done:reg6, iterable:reg7, fast_array_mode_allowed:true[ 120] JumpLoop target:block2block6:@@ -61,7 +61,7 @@ block7:block8:[ 160] Mov dst:reg12, src:Bool(false)- [ 170] GetIterator dst_iterator_object:reg13, dst_iterator_next:reg14, dst_iterator_done:reg15, iterable:reg10+ [ 170] GetIterator dst_iterator_object:reg13, dst_iterator_next:reg14, dst_iterator_done:reg15, iterable:reg10, fast_array_mode_allowed:true[ 190] Jump target:block11block9:diff --git a/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txt b/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txtindex 627f6911d55..9c77e158820 100644--- a/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txt+++ b/Tests/LibJS/Bytecode/expected/for-of-continue-with-block-scope.txt@@ -28,7 +28,7 @@ block0:[ 20] CreateLexicalEnvironment dst:reg5, parent:reg4, capacity:1, is_catch_environment:false[ 38] CreateVariable `r`, is_immutable:false, is_global:false, is_strict:false[ 48] SetLexicalEnvironment environment:reg4- [ 50] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0+ [ 50] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0, fast_array_mode_allowed:true[ 70] Jump target:block2block1:diff --git a/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txt b/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txtindex 7785b682987..c8963fa54e7 100644--- a/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txt+++ b/Tests/LibJS/Bytecode/expected/for-of-iteration-env-capacity.txt@@ -11,7 +11,7 @@ block0:[ 0] Enter[ 8] GetLexicalEnvironment dst:reg4[ 10] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]- [ 38] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5+ [ 38] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true[ 58] MovSrcUndefined dst:reg5[ 60] Jump target:block2diff --git a/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt b/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txtindex b11d14e3dab..c0969a86c1b 100644--- a/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt+++ b/Tests/LibJS/Bytecode/expected/for-of-iterator-close.txt@@ -30,7 +30,7 @@ block0:[ 0] Enter[ 8] GetLexicalEnvironment dst:reg4[ 10] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]- [ 38] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5+ [ 38] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true[ 58] Jump target:block2block1:@@ -93,7 +93,7 @@ block0:[ 0] Enter[ 8] GetLexicalEnvironment dst:reg4[ 10] NewPrimitiveArray dst:reg5, elements:[1, 2, 3]- [ 38] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5+ [ 38] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true[ 58] Jump target:block2block1:@@ -149,7 +149,7 @@ block0:block1:[ 18] GetLexicalEnvironment dst:reg4- [ 20] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0+ [ 20] GetIterator dst_iterator_object:reg5, dst_iterator_next:reg6, dst_iterator_done:reg7, iterable:arg0, fast_array_mode_allowed:false[ 40] Jump target:block3block2:diff --git a/Tests/LibJS/Bytecode/expected/generator-yield-star.txt b/Tests/LibJS/Bytecode/expected/generator-yield-star.txtindex 9da9d16638b..9527484d64a 100644--- a/Tests/LibJS/Bytecode/expected/generator-yield-star.txt+++ b/Tests/LibJS/Bytecode/expected/generator-yield-star.txt@@ -25,7 +25,7 @@ block0:[ 8] Yield continuation_label:block1, value:Undefinedblock1:- [ 18] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:arg0+ [ 18] GetIterator dst_iterator_object:reg8, dst_iterator_next:reg9, dst_iterator_done:reg10, iterable:arg0, fast_array_mode_allowed:false[ 38] Mov2 c0_dst:reg6, c0_src:Int32(1), c1_dst:reg7, c1_src:Undefinedblock2:diff --git a/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txt b/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txtindex f70f755f715..c3292efff76 100644--- a/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txt+++ b/Tests/LibJS/Bytecode/expected/lexical-env-teardown.txt@@ -141,7 +141,7 @@ block0:[ 8] GetLexicalEnvironment dst:reg4[ 10] Mov dst:outer~1, src:Int32(5)[ 20] NewPrimitiveArray dst:reg5, elements:[10, 20]- [ 40] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5+ [ 40] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true[ 60] Jump target:block2block1:diff --git a/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txt b/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txtindex 377f8240971..129a877a7c5 100644--- a/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txt+++ b/Tests/LibJS/Bytecode/expected/named-class-expression-no-lhs-name-leak.txt@@ -12,7 +12,7 @@ block0:[ 8] GetLexicalEnvironment dst:reg4[ 10] NewArray dst:reg5[ 20] Mov dst:reg6, src:Bool(false)- [ 30] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5+ [ 30] GetIterator dst_iterator_object:reg7, dst_iterator_next:reg8, dst_iterator_done:reg9, iterable:reg5, fast_array_mode_allowed:true[ 50] Jump target:block3block1:diff --git a/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txt b/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txtindex 4199acdde2e..db3781aefb9 100644--- a/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txt+++ b/Tests/LibJS/Bytecode/expected/super-for-of-resolve-order.txt@@ -30,7 +30,7 @@ block0:[ 0] Enter[ 8] GetLexicalEnvironment dst:reg4[ 10] NewPrimitiveArray dst:reg5, elements:[1, 2]- [ 30] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5+ [ 30] GetIterator dst_iterator_object:reg6, dst_iterator_next:reg7, dst_iterator_done:reg8, iterable:reg5, fast_array_mode_allowed:true[ 50] Jump target:block2block1:diff --git a/Tests/LibJS/JIT/ir/overflow-check-elimination.js b/Tests/LibJS/JIT/ir/overflow-check-elimination.jsindex f78591306fe..b10e8b6fa25 100644--- a/Tests/LibJS/JIT/ir/overflow-check-elimination.js+++ b/Tests/LibJS/JIT/ir/overflow-check-elimination.js@@ -75,8 +75,8 @@ jit.compile(lookup);// CHECK: CheckBounds ({{v[0-9]+}}, #i32:256)// CHECK: Int32WrappingAdd ({{v[0-9]+}}, #i32:1)-// A branch on an index being in bounds bounds it where it holds, like the array iterator's index, which it then-// increments.+// A branch on an index being in bounds bounds it where it holds, like the index of an iteration over an array, which+// it then increments.function total(a) {let s = 0;@@ -91,7 +91,7 @@ jit.compile(total);// CHECK-PASS: bounds check elimination// CHECK: RefineIndexInBounds// CHECK: [[NEXT:v[0-9]+]]:int32 = Int32WrappingAdd ({{v[0-9]+}}, #i32:1)-// CHECK-NEXT: StoreArrayIteratorIndex ({{v[0-9]+}}, [[NEXT]])+// CHECK-NEXT: {{v[0-9]+}} = BoxInt32 ([[NEXT]])// An unsigned right shift of any int32 by at least one is a non-negative int32, like the bytes of hashes.diff --git a/Tests/LibJS/Runtime/loops/for-of-fast-array.js b/Tests/LibJS/Runtime/loops/for-of-fast-array.jsnew file mode 100644index 00000000000..5da81e94723--- /dev/null+++ b/Tests/LibJS/Runtime/loops/for-of-fast-array.js@@ -0,0 +1,335 @@+// for-of loops and array destructuring patterns step through plain arrays without making array iterators. These tests+// check that they still behave like array iterators do.++const ArrayIteratorPrototype = Object.getPrototypeOf([][Symbol.iterator]());++function collect(iterable) {+ const values = [];+ for (const value of iterable) values.push(value);+ return values;+}++function firstTwo(iterable) {+ const [first, second] = iterable;+ return [first, second];+}++function restAfterFirst(iterable) {+ const [first, ...rest] = iterable;+ return [first, rest];+}++describe("elements", () => {+ test("packed arrays", () => {+ expect(collect([1, 2, 3])).toEqual([1, 2, 3]);+ expect(collect([])).toEqual([]);+ expect(firstTwo([1, 2, 3])).toEqual([1, 2]);+ expect(firstTwo([1])).toEqual([1, undefined]);+ expect(restAfterFirst([1, 2, 3])).toEqual([1, [2, 3]]);+ expect(restAfterFirst([])).toEqual([undefined, []]);+ });++ test("holes read undefined", () => {+ expect(collect([1, , 3])).toEqual([1, undefined, 3]);+ expect(collect(new Array(3))).toEqual([undefined, undefined, undefined]);+ expect(firstTwo(new Array(5))).toEqual([undefined, undefined]);+ expect(restAfterFirst([1, , 3])).toEqual([1, [undefined, 3]]);+ });++ test("holes read the prototype chain", () => {+ Array.prototype[1] = "from Array.prototype";+ Object.prototype[2] = "from Object.prototype";+ try {+ expect(collect([0, , , 3])).toEqual([0, "from Array.prototype", "from Object.prototype", 3]);+ expect(firstTwo(new Array(2))).toEqual([undefined, "from Array.prototype"]);+ expect(restAfterFirst(new Array(3))).toEqual([+ undefined,+ ["from Array.prototype", "from Object.prototype"],+ ]);+ } finally {+ delete Array.prototype[1];+ delete Object.prototype[2];+ }+ });++ test("getters on the prototype run once per hole", () => {+ let getterCalls = 0;+ Object.defineProperty(Array.prototype, 1, {+ get() {+ ++getterCalls;+ return "from getter";+ },+ configurable: true,+ });+ try {+ let seen = "";+ for (const value of new Array(3)) seen += `${value},`;+ expect(seen).toBe("undefined,from getter,undefined,");+ expect(getterCalls).toBe(1);+ } finally {+ delete Array.prototype[1];+ }+ });++ test("subclasses of Array", () => {+ class MyArray extends Array {}+ const array = MyArray.from([1, 2, 3]);+ expect(collect(array)).toEqual([1, 2, 3]);+ expect(firstTwo(array)).toEqual([1, 2]);+ });++ test("frozen arrays", () => {+ const array = Object.freeze([1, 2, 3]);+ expect(collect(array)).toEqual([1, 2, 3]);+ expect(restAfterFirst(array)).toEqual([1, [2, 3]]);+ });+});++describe("changes during the iteration", () => {+ test("arrays that grow", () => {+ const array = [1, 2];+ const values = [];+ for (const value of array) {+ values.push(value);+ if (array.length < 4) array.push(value * 10);+ }+ expect(values).toEqual([1, 2, 10, 20]);+ });++ test("arrays that shrink", () => {+ const array = [1, 2, 3, 4];+ const values = [];+ for (const value of array) {+ values.push(value);+ array.length = 2;+ }+ expect(values).toEqual([1, 2]);+ });++ test("arrays that get holes", () => {+ const array = [1, 2, 3];+ const values = [];+ for (const value of array) {+ values.push(value);+ delete array[1];+ }+ expect(values).toEqual([1, undefined, 3]);+ });++ test("an iteration that is done stays done when the array grows", () => {+ const array = [1];+ const values = [];+ for (const value of array) values.push(value);+ array.push(2);+ expect(values).toEqual([1]);++ const [first, second, third] = array;+ expect([first, second, third]).toEqual([1, 2, undefined]);+ });++ test("next replaced during the iteration is not called", () => {+ const originalNext = ArrayIteratorPrototype.next;+ const values = [];+ try {+ for (const value of [1, 2, 3]) {+ values.push(value);+ ArrayIteratorPrototype.next = () => ({ value: "replaced", done: false });+ }+ } finally {+ ArrayIteratorPrototype.next = originalNext;+ }+ expect(values).toEqual([1, 2, 3]);+ });+});++describe("iterator methods", () => {+ test("an own iterator method of the array", () => {+ const array = [1, 2, 3];+ array[Symbol.iterator] = function* () {+ yield "own";+ };+ expect(collect(array)).toEqual(["own"]);+ expect(firstTwo(array)).toEqual(["own", undefined]);+ });++ test("an iterator getter runs once per iteration", () => {+ let getterCalls = 0;+ const array = [1, 2, 3];+ Object.defineProperty(array, Symbol.iterator, {+ get() {+ ++getterCalls;+ return Array.prototype.values;+ },+ });+ expect(collect(array)).toEqual([1, 2, 3]);+ expect(firstTwo(array)).toEqual([1, 2]);+ expect(getterCalls).toBe(2);+ });++ test("an iterator that is an array with a next property that is not callable", () => {+ const iterator = [1, 2, 3];+ iterator.next = 0;+ const iterable = { [Symbol.iterator]: () => iterator };+ expect(() => collect(iterable)).toThrow(TypeError);+ expect(() => firstTwo(iterable)).toThrow(TypeError);+ });++ test("arrays of another iteration method", () => {+ const array = [1, 2, 3];+ expect(collect(array.keys())).toEqual([0, 1, 2]);+ expect(collect(array.entries())).toEqual([+ [0, 1],+ [1, 2],+ [2, 3],+ ]);+ expect(firstTwo(array.values())).toEqual([1, 2]);+ });+});++describe("closing", () => {+ function expectClosedAt(close, expectedNextValue) {+ const receivers = [];+ ArrayIteratorPrototype.return = function () {+ receivers.push(this);+ expect(Object.getPrototypeOf(this)).toBe(ArrayIteratorPrototype);+ expect(this.next()).toEqual(expectedNextValue);+ return {};+ };+ try {+ close();+ } finally {+ delete ArrayIteratorPrototype.return;+ }+ expect(receivers).toHaveLength(1);+ }++ test("break, return and throw close at the next element", () => {+ expectClosedAt(+ () => {+ for (const value of [1, 2, 3]) break;+ },+ { value: 2, done: false }+ );+ expectClosedAt(+ () => {+ (() => {+ for (const value of [1, 2, 3]) if (value === 2) return;+ })();+ },+ { value: 3, done: false }+ );+ expectClosedAt(+ () => {+ expect(() => {+ for (const value of [1, 2, 3]) throw new Error("thrown");+ }).toThrowWithMessage(Error, "thrown");+ },+ { value: 2, done: false }+ );+ });++ test("a return method added during the iteration is called", () => {+ const receivers = [];+ try {+ for (const value of [1, 2, 3]) {+ ArrayIteratorPrototype.return = function () {+ receivers.push(this.next());+ return {};+ };+ break;+ }+ } finally {+ delete ArrayIteratorPrototype.return;+ }+ expect(receivers).toEqual([{ value: 2, done: false }]);+ });++ test("destructuring closes unless the pattern reads past the end", () => {+ expectClosedAt(+ () => {+ const [first] = [1, 2, 3];+ },+ { value: 2, done: false }+ );+ expectClosedAt(+ () => {+ const [first, second] = [1, 2];+ },+ { value: undefined, done: true }+ );++ let returnCalls = 0;+ ArrayIteratorPrototype.return = () => {+ ++returnCalls;+ return {};+ };+ try {+ const [first, second] = [1];+ const [third, ...rest] = [1, 2, 3];+ } finally {+ delete ArrayIteratorPrototype.return;+ }+ expect(returnCalls).toBe(0);+ });++ test("a throwing return method and a throwing body", () => {+ ArrayIteratorPrototype.return = () => {+ throw new Error("from return");+ };+ try {+ expect(() => {+ for (const value of [1, 2]) throw new Error("from body");+ }).toThrowWithMessage(Error, "from body");+ expect(() => {+ for (const value of [1, 2]) break;+ }).toThrowWithMessage(Error, "from return");+ } finally {+ delete ArrayIteratorPrototype.return;+ }+ });+});++describe("other consumers of iterators", () => {+ test("yield* over arrays", () => {+ function* delegate(array) {+ return yield* array;+ }+ expect([...delegate([1, 2, 3])]).toEqual([1, 2, 3]);+ const generator = delegate([1, 2, 3]);+ generator.next();+ expect(generator.return(5)).toEqual({ value: 5, done: true });+ });++ test("a generator suspended inside a for-of over an array", () => {+ function* generator(array) {+ for (const value of array) yield value * 2;+ }+ const iterator = generator([1, 2, 3]);+ expect(iterator.next()).toEqual({ value: 2, done: false });+ expect(iterator.next()).toEqual({ value: 4, done: false });+ expect(iterator.return(7)).toEqual({ value: 7, done: true });+ expect([...generator([4, 5])]).toEqual([8, 10]);+ });++ test("for await over arrays", async () => {+ const values = [];+ for await (const value of [1, Promise.resolve(2), 3]) values.push(value);+ expect(values).toEqual([1, 2, 3]);+ });++ test("nested patterns, defaults and elisions", () => {+ const [[a, b] = [9, 9], , c = 7, ...[d, e]] = [[1, 2], 0, undefined, 4, 5];+ expect([a, b, c, d, e]).toEqual([1, 2, 7, 4, 5]);+ const [x = 1, y = 2] = [];+ expect([x, y]).toEqual([1, 2]);+ });++ test("assignment patterns", () => {+ let first;+ let second;+ [first, second] = [1, 2, 3];+ expect([first, second]).toEqual([1, 2]);+ [second, first] = [first, second];+ expect([first, second]).toEqual([2, 1]);+ });+});