LibJS: Replace Array.fromAsync with a native JavaScript implementation

This allows us to use the bytecode implementation of await, which
correctly suspends execution contexts and handles completion
injections.

This gains us 4 test262 tests around mutating Array.fromAsync's
iterable whilst it's suspended as well.

This is also one step towards removing spin_until, which the
non-bytecode implementation of await uses.

```
Duration:
     -5.98s

Summary:
    Diff Tests:
        +4     -4 

Diff Tests:
    [...]/Array/fromAsync/asyncitems-array-add-to-singleton.js  -> 
    [...]/Array/fromAsync/asyncitems-array-add.js               -> 
    [...]/Array/fromAsync/asyncitems-array-mutate.js            -> 
    [...]/Array/fromAsync/asyncitems-array-remove.js            -> 
```
This commit is contained in:
Luke Wilde 2025-11-06 19:20:29 +00:00 committed by Andreas Kling
parent a63b0cfaba
commit 0eceee0a05
Notes: github-actions[bot] 2025-11-30 10:56:04 +00:00
15 changed files with 942 additions and 233 deletions

View file

@ -40,7 +40,7 @@ void ArrayConstructor::initialize(Realm& realm)
u8 attr = Attribute::Writable | Attribute::Configurable;
define_native_function(realm, vm.names.from, from, 1, attr);
define_native_function(realm, vm.names.fromAsync, from_async, 1, attr);
define_native_javascript_backed_function(vm.names.fromAsync, realm.intrinsics().from_async_array_constructor_function(), 1, attr);
define_native_function(realm, vm.names.isArray, is_array, 1, attr);
define_native_function(realm, vm.names.of, of, 0, attr);
@ -284,236 +284,6 @@ JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from)
return array;
}
// 2.1.1.1 Array.fromAsync ( asyncItems [ , mapfn [ , thisArg ] ] ), https://tc39.es/proposal-array-from-async/#sec-array.fromAsync
JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from_async)
{
auto& realm = *vm.current_realm();
auto async_items = vm.argument(0);
auto mapfn = vm.argument(1);
auto this_arg = vm.argument(2);
// 1. Let C be the this value.
auto constructor = vm.this_value();
// 2. Let promiseCapability be ! NewPromiseCapability(%Promise%).
auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
// 3. Let fromAsyncClosure be a new Abstract Closure with no parameters that captures C, mapfn, and thisArg and performs the following steps when called:
auto from_async_closure = GC::create_function(realm.heap(), [constructor, mapfn, this_arg, &vm, &realm, async_items]() mutable -> Completion {
bool mapping;
// a. If mapfn is undefined, let mapping be false.
if (mapfn.is_undefined()) {
mapping = false;
}
// b. Else,
else {
// i. If IsCallable(mapfn) is false, throw a TypeError exception.
if (!mapfn.is_function())
return vm.throw_completion<TypeError>(ErrorType::NotAFunction, mapfn.to_string_without_side_effects());
// ii. Let mapping be true.
mapping = true;
}
// c. Let usingAsyncIterator be ? GetMethod(asyncItems, @@asyncIterator).
auto using_async_iterator = TRY(async_items.get_method(vm, vm.well_known_symbol_async_iterator()));
GC::Ptr<FunctionObject> using_sync_iterator;
// d. If usingAsyncIterator is undefined, then
if (!using_async_iterator) {
// i. Let usingSyncIterator be ? GetMethod(asyncItems, @@iterator).
using_sync_iterator = TRY(async_items.get_method(vm, vm.well_known_symbol_iterator()));
}
// e. Let iteratorRecord be undefined.
GC::Ptr<IteratorRecord> iterator_record;
// f. If usingAsyncIterator is not undefined, then
if (using_async_iterator) {
// i. Set iteratorRecord to ? GetIterator(asyncItems, async, usingAsyncIterator).
// FIXME: The Array.from proposal is out of date - it should be using GetIteratorFromMethod.
iterator_record = TRY(get_iterator_from_method(vm, async_items, *using_async_iterator));
}
// g. Else if usingSyncIterator is not undefined, then
else if (using_sync_iterator) {
// i. Set iteratorRecord to ? CreateAsyncFromSyncIterator(GetIterator(asyncItems, sync, usingSyncIterator)).
// FIXME: The Array.from proposal is out of date - it should be using GetIteratorFromMethod.
auto iterator_record_impl = create_async_from_sync_iterator(vm, TRY(get_iterator_from_method(vm, async_items, *using_sync_iterator)));
iterator_record = vm.heap().allocate<IteratorRecord>(iterator_record_impl.iterator, iterator_record_impl.next_method, iterator_record_impl.done);
}
// h. If iteratorRecord is not undefined, then
if (iterator_record) {
GC::Ptr<Object> array;
// i. If IsConstructor(C) is true, then
if (constructor.is_constructor()) {
// 1. Let A be ? Construct(C).
array = TRY(JS::construct(vm, constructor.as_function()));
}
// ii. Else,
else {
// i. Let A be ! ArrayCreate(0).
array = MUST(Array::create(realm, 0));
}
// iii. Let k be 0.
// iv. Repeat,
for (size_t k = 0;; ++k) {
// 1. If k ≥ 2^53 - 1, then
if (k >= MAX_ARRAY_LIKE_INDEX) {
// a. Let error be ThrowCompletion(a newly created TypeError object).
auto error = vm.throw_completion<TypeError>(ErrorType::ArrayMaxSize);
// b. Return ? AsyncIteratorClose(iteratorRecord, error).
return TRY(async_iterator_close(vm, *iterator_record, move(error)));
}
// 2. Let Pk be ! ToString(𝔽(k)).
auto property_key = PropertyKey { k };
// FIXME: There seems to be a bug here where we are not respecting array mutation. After resolving the first entry, the
// iterator should also take into account any other changes which are made to async_items (which does not seem to
// be happening).
// 3. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
auto next_result = TRY(JS::call(vm, iterator_record->next_method, iterator_record->iterator));
// 4. Set nextResult to ? Await(nextResult).
next_result = TRY(await(vm, next_result));
// 5. If nextResult is not an Object, throw a TypeError exception.
if (!next_result.is_object())
return vm.throw_completion<TypeError>(ErrorType::IterableNextBadReturn);
// 6. Let done be ? IteratorComplete(nextResult).
auto done = TRY(JS::iterator_complete(vm, next_result.as_object()));
// 7. If done is true,
if (done) {
// a. Perform ? Set(A, "length", 𝔽(k), true).
TRY(array->set(vm.names.length, Value(k), Object::ShouldThrowExceptions::Yes));
// b. Return Completion Record { [[Type]]: return, [[Value]]: A, [[Target]]: empty }.
return Completion { Completion::Type::Return, array };
}
// 8. Let nextValue be ? IteratorValue(nextResult).
auto next_value = TRY(iterator_value(vm, next_result.as_object()));
Value mapped_value;
// 9. If mapping is true, then
if (mapping) {
// a. Let mappedValue be Call(mapfn, thisArg, « nextValue, 𝔽(k) »).
auto mapped_value_or_error = JS::call(vm, mapfn, this_arg, next_value, Value(k));
// b. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
if (mapped_value_or_error.is_error()) {
TRY(async_iterator_close(vm, *iterator_record, mapped_value_or_error));
return mapped_value_or_error;
}
// c. Set mappedValue to Await(mappedValue).
mapped_value_or_error = await(vm, mapped_value_or_error.value());
// d. IfAbruptCloseAsyncIterator(mappedValue, iteratorRecord).
if (mapped_value_or_error.is_error()) {
TRY(async_iterator_close(vm, *iterator_record, mapped_value_or_error));
return mapped_value_or_error;
}
mapped_value = mapped_value_or_error.value();
}
// 10. Else, let mappedValue be nextValue.
else {
mapped_value = next_value;
}
// 11. Let defineStatus be CreateDataPropertyOrThrow(A, Pk, mappedValue).
auto define_status = array->create_data_property_or_throw(property_key, mapped_value);
// 12. If defineStatus is an abrupt completion, return ? AsyncIteratorClose(iteratorRecord, defineStatus).
if (define_status.is_error())
return TRY(iterator_close(vm, *iterator_record, define_status.release_error()));
// 13. Set k to k + 1.
}
}
// k. Else,
else {
// i. NOTE: asyncItems is neither an AsyncIterable nor an Iterable so assume it is an array-like object.
// ii. Let arrayLike be ! ToObject(asyncItems).
auto array_like = MUST(async_items.to_object(vm));
// iii. Let len be ? LengthOfArrayLike(arrayLike).
auto length = TRY(length_of_array_like(vm, array_like));
GC::Ptr<Object> array;
// iv. If IsConstructor(C) is true, then
if (constructor.is_constructor()) {
// 1. Let A be ? Construct(C, « 𝔽(len) »).
array = TRY(JS::construct(vm, constructor.as_function(), Value(length)));
}
// v. Else,
else {
// 1. Let A be ? ArrayCreate(len).
array = TRY(Array::create(realm, length));
}
// vi. Let k be 0.
// vii. Repeat, while k < len,
for (size_t k = 0; k < length; ++k) {
// 1. Let Pk be ! ToString(𝔽(k)).
auto property_key = PropertyKey { k };
// 2. Let kValue be ? Get(arrayLike, Pk).
auto k_value = TRY(array_like->get(property_key));
// 3. Set kValue to ? Await(kValue).
k_value = TRY(await(vm, k_value));
Value mapped_value;
// 4. If mapping is true, then
if (mapping) {
// a. Let mappedValue be ? Call(mapfn, thisArg, « kValue, 𝔽(k) »).
mapped_value = TRY(JS::call(vm, mapfn, this_arg, k_value, Value(k)));
// b. Set mappedValue to ? Await(mappedValue).
mapped_value = TRY(await(vm, mapped_value));
}
// 5. Else, let mappedValue be kValue.
else {
mapped_value = k_value;
}
// 6. Perform ? CreateDataPropertyOrThrow(A, Pk, mappedValue).
TRY(array->create_data_property_or_throw(property_key, mapped_value));
// 7. Set k to k + 1.
}
// viii. Perform ? Set(A, "length", 𝔽(len), true).
TRY(array->set(vm.names.length, Value(length), Object::ShouldThrowExceptions::Yes));
// ix. Return Completion Record { [[Type]]: return, [[Value]]: A, [[Target]]: empty }.
return Completion { Completion::Type::Return, array };
}
});
// 4. Perform AsyncFunctionStart(promiseCapability, fromAsyncClosure).
async_function_start(vm, promise_capability, *from_async_closure);
// 5. Return promiseCapability.[[Promise]].
return promise_capability->promise();
}
// 23.1.2.2 Array.isArray ( arg ), https://tc39.es/ecma262/#sec-array.isarray
JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::is_array)
{