summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibJS/Runtime/PromiseConstructor.cpp
blob: 3a71cae95fa4674dada2b046c1973091ff94a6b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/*
 * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/Function.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Runtime/AbstractOperations.h>
#include <LibJS/Runtime/AggregateError.h>
#include <LibJS/Runtime/Array.h>
#include <LibJS/Runtime/Error.h>
#include <LibJS/Runtime/FunctionObject.h>
#include <LibJS/Runtime/GlobalObject.h>
#include <LibJS/Runtime/IteratorOperations.h>
#include <LibJS/Runtime/Promise.h>
#include <LibJS/Runtime/PromiseConstructor.h>
#include <LibJS/Runtime/PromiseReaction.h>
#include <LibJS/Runtime/PromiseResolvingElementFunctions.h>
#include <LibJS/Runtime/TemporaryClearException.h>

namespace JS {

// 27.2.4.1.1 GetPromiseResolve ( promiseConstructor ), https://tc39.es/ecma262/#sec-getpromiseresolve
static Value get_promise_resolve(GlobalObject& global_object, Value constructor)
{
    VERIFY(constructor.is_constructor());
    auto& vm = global_object.vm();

    auto promise_resolve = TRY_OR_DISCARD(constructor.get(global_object, vm.names.resolve));
    if (!promise_resolve.is_function()) {
        vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, promise_resolve.to_string_without_side_effects());
        return {};
    }

    return promise_resolve;
}

// 27.2.1.1.1 IfAbruptRejectPromise ( value, capability ), https://tc39.es/ecma262/#sec-ifabruptrejectpromise
static Optional<Value> if_abrupt_reject_promise(GlobalObject& global_object, Value, PromiseCapability capability)
{
    auto& vm = global_object.vm();

    if (auto* exception = vm.exception()) {
        vm.clear_exception();
        vm.stop_unwind();

        (void)vm.call(*capability.reject, js_undefined(), exception->value());
        return capability.promise;
    }

    return {};
}

static bool iterator_record_is_complete(GlobalObject& global_object, Object& iterator_record)
{
    auto& vm = global_object.vm();

    // FIXME: Create a native iterator structure with the [[Done]] internal slot. For now, temporarily clear
    //        the exception so we can access the "done" property on the iterator object.
    TemporaryClearException clear_exception(vm);
    return iterator_complete(global_object, iterator_record);
}

static void set_iterator_record_complete(GlobalObject& global_object, Object& iterator_record)
{
    auto& vm = global_object.vm();

    // FIXME: Create a native iterator structure with the [[Done]] internal slot. For now, temporarily clear
    //        the exception so we can access the "done" property on the iterator object.
    TemporaryClearException clear_exception(vm);
    MUST(iterator_record.set(vm.names.done, Value(true), Object::ShouldThrowExceptions::No));
}

using EndOfElementsCallback = Function<Value(PromiseValueList&)>;
using InvokeElementFunctionCallback = Function<void(PromiseValueList&, RemainingElements&, Value, size_t)>;

static Value perform_promise_common(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve, EndOfElementsCallback end_of_list, InvokeElementFunctionCallback invoke_element_function)
{
    auto& vm = global_object.vm();

    VERIFY(constructor.is_constructor());
    VERIFY(promise_resolve.is_function());

    auto* values = vm.heap().allocate_without_global_object<PromiseValueList>();
    auto* remaining_elements_count = vm.heap().allocate_without_global_object<RemainingElements>(1);
    size_t index = 0;

    while (true) {
        auto* next = iterator_step(global_object, iterator_record);
        if (vm.exception()) {
            set_iterator_record_complete(global_object, iterator_record);
            return {};
        }

        if (!next) {
            set_iterator_record_complete(global_object, iterator_record);
            if (vm.exception())
                return {};

            if (--remaining_elements_count->value == 0)
                return end_of_list(*values);
            return result_capability.promise;
        }

        auto next_value = iterator_value(global_object, *next);
        if (vm.exception()) {
            set_iterator_record_complete(global_object, iterator_record);
            return {};
        }

        values->values().append(js_undefined());

        auto next_promise = TRY_OR_DISCARD(vm.call(promise_resolve.as_function(), constructor, next_value));

        ++remaining_elements_count->value;

        invoke_element_function(*values, *remaining_elements_count, next_promise, index);
        if (vm.exception())
            return {};

        ++index;
    }
}

// 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseall
static Value perform_promise_all(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
{
    auto& vm = global_object.vm();

    return perform_promise_common(
        global_object, iterator_record, constructor, result_capability, promise_resolve,
        [&](PromiseValueList& values) -> Value {
            auto values_array = Array::create_from(global_object, values.values());

            (void)vm.call(*result_capability.resolve, js_undefined(), values_array);
            if (vm.exception())
                return {};

            return result_capability.promise;
        },
        [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
            auto* on_fulfilled = PromiseAllResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
            on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);

            (void)next_promise.invoke(global_object, vm.names.then, on_fulfilled, result_capability.reject);
        });
}

// 27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseallsettled
static Value perform_promise_all_settled(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
{
    auto& vm = global_object.vm();

    return perform_promise_common(
        global_object, iterator_record, constructor, result_capability, promise_resolve,
        [&](PromiseValueList& values) -> Value {
            auto values_array = Array::create_from(global_object, values.values());

            (void)vm.call(*result_capability.resolve, js_undefined(), values_array);
            if (vm.exception())
                return {};

            return result_capability.promise;
        },
        [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
            auto* on_fulfilled = PromiseAllSettledResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
            on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);

            auto* on_rejected = PromiseAllSettledRejectElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
            on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);

            (void)next_promise.invoke(global_object, vm.names.then, on_fulfilled, on_rejected);
        });
}

// 27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseany
static Value perform_promise_any(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
{
    auto& vm = global_object.vm();

    return perform_promise_common(
        global_object, iterator_record, constructor, result_capability, promise_resolve,
        [&](PromiseValueList& errors) -> Value {
            auto errors_array = Array::create_from(global_object, errors.values());

            auto* error = AggregateError::create(global_object);
            MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));

            vm.throw_exception(global_object, error);
            return {};
        },
        [&](PromiseValueList& errors, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
            auto* on_rejected = PromiseAnyRejectElementFunction::create(global_object, index, errors, result_capability, remaining_elements_count);
            on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);

            (void)next_promise.invoke(global_object, vm.names.then, result_capability.resolve, on_rejected);
        });
}

// 27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiserace
static Value perform_promise_race(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
{
    auto& vm = global_object.vm();

    return perform_promise_common(
        global_object, iterator_record, constructor, result_capability, promise_resolve,
        [&](PromiseValueList&) -> Value {
            return result_capability.promise;
        },
        [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
            (void)next_promise.invoke(global_object, vm.names.then, result_capability.resolve, result_capability.reject);
        });
}

PromiseConstructor::PromiseConstructor(GlobalObject& global_object)
    : NativeFunction(vm().names.Promise.as_string(), *global_object.function_prototype())
{
}

void PromiseConstructor::initialize(GlobalObject& global_object)
{
    auto& vm = this->vm();
    NativeFunction::initialize(global_object);

    // 27.2.4.4 Promise.prototype, https://tc39.es/ecma262/#sec-promise.prototype
    define_direct_property(vm.names.prototype, global_object.promise_prototype(), 0);

    u8 attr = Attribute::Writable | Attribute::Configurable;
    define_native_function(vm.names.all, all, 1, attr);
    define_native_function(vm.names.allSettled, all_settled, 1, attr);
    define_native_function(vm.names.any, any, 1, attr);
    define_native_function(vm.names.race, race, 1, attr);
    define_native_function(vm.names.reject, reject, 1, attr);
    define_native_function(vm.names.resolve, resolve, 1, attr);

    define_native_accessor(*vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);

    define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
}

// 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
Value PromiseConstructor::call()
{
    auto& vm = this->vm();
    vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.Promise);
    return {};
}

// 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
Value PromiseConstructor::construct(FunctionObject& new_target)
{
    auto& vm = this->vm();
    auto& global_object = this->global_object();

    auto executor = vm.argument(0);
    if (!executor.is_function()) {
        vm.throw_exception<TypeError>(global_object, ErrorType::PromiseExecutorNotAFunction);
        return {};
    }

    auto* promise = TRY_OR_DISCARD(ordinary_create_from_constructor<Promise>(global_object, new_target, &GlobalObject::promise_prototype));

    auto [resolve_function, reject_function] = promise->create_resolving_functions();

    (void)vm.call(executor.as_function(), js_undefined(), &resolve_function, &reject_function);
    if (auto* exception = vm.exception()) {
        vm.clear_exception();
        vm.stop_unwind();
        (void)vm.call(reject_function, js_undefined(), exception->value());
    }
    return promise;
}

// 27.2.4.1 Promise.all ( iterable ), https://tc39.es/ecma262/#sec-promise.all
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all)
{
    auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));

    auto promise_capability = new_promise_capability(global_object, constructor);
    if (vm.exception())
        return {};

    auto promise_resolve = get_promise_resolve(global_object, constructor);
    if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto iterator_record = get_iterator(global_object, vm.argument(0));
    if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto result = perform_promise_all(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
    if (vm.exception()) {
        if (!iterator_record_is_complete(global_object, *iterator_record))
            iterator_close(*iterator_record);

        auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
        return abrupt.value();
    }

    return result;
}

// 27.2.4.2 Promise.allSettled ( iterable ), https://tc39.es/ecma262/#sec-promise.allsettled
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled)
{
    auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));

    auto promise_capability = new_promise_capability(global_object, constructor);
    if (vm.exception())
        return {};

    auto promise_resolve = get_promise_resolve(global_object, constructor);
    if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto iterator_record = get_iterator(global_object, vm.argument(0));
    if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto result = perform_promise_all_settled(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
    if (vm.exception()) {
        if (!iterator_record_is_complete(global_object, *iterator_record))
            iterator_close(*iterator_record);

        auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
        return abrupt.value();
    }

    return result;
}

// 27.2.4.3 Promise.any ( iterable ), https://tc39.es/ecma262/#sec-promise.any
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any)
{
    auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));

    auto promise_capability = new_promise_capability(global_object, constructor);
    if (vm.exception())
        return {};

    auto promise_resolve = get_promise_resolve(global_object, constructor);
    if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto iterator_record = get_iterator(global_object, vm.argument(0));
    if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto result = perform_promise_any(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
    if (vm.exception()) {
        if (!iterator_record_is_complete(global_object, *iterator_record))
            iterator_close(*iterator_record);

        auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
        return abrupt.value();
    }

    return result;
}

// 27.2.4.5 Promise.race ( iterable ), https://tc39.es/ecma262/#sec-promise.race
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race)
{
    auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));

    auto promise_capability = new_promise_capability(global_object, constructor);
    if (vm.exception())
        return {};

    auto promise_resolve = get_promise_resolve(global_object, constructor);
    if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto iterator_record = get_iterator(global_object, vm.argument(0));
    if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record, promise_capability); abrupt.has_value())
        return abrupt.value();

    auto result = perform_promise_race(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
    if (vm.exception()) {
        if (!iterator_record_is_complete(global_object, *iterator_record))
            iterator_close(*iterator_record);

        auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
        return abrupt.value();
    }

    return result;
}

// 27.2.4.6 Promise.reject ( r ), https://tc39.es/ecma262/#sec-promise.reject
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::reject)
{
    auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
    auto promise_capability = new_promise_capability(global_object, constructor);
    if (vm.exception())
        return {};
    auto reason = vm.argument(0);
    [[maybe_unused]] auto result = TRY_OR_DISCARD(vm.call(*promise_capability.reject, js_undefined(), reason));
    return promise_capability.promise;
}

// 27.2.4.7 Promise.resolve ( x ), https://tc39.es/ecma262/#sec-promise.resolve
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::resolve)
{
    auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
    auto value = vm.argument(0);
    return promise_resolve(global_object, *constructor, value);
}

// 27.2.4.8 get Promise [ @@species ], https://tc39.es/ecma262/#sec-get-promise-@@species
JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::symbol_species_getter)
{
    return vm.this_value(global_object);
}

}