Browse Source

LibJS: Annotate Promise implementation with spec comments

I wanted to do this for a long time. The guts of Promise are pretty
complex, and it's easier to understand with the spec right next to it.
Also found a couple of issues along the way :^)
Linus Groh 3 years ago
parent
commit
01c2570678

+ 163 - 5
Userland/Libraries/LibJS/Runtime/Promise.cpp

@@ -22,13 +22,24 @@ namespace JS {
 ThrowCompletionOr<Object*> promise_resolve(GlobalObject& global_object, Object& constructor, Value value)
 ThrowCompletionOr<Object*> promise_resolve(GlobalObject& global_object, Object& constructor, Value value)
 {
 {
     auto& vm = global_object.vm();
     auto& vm = global_object.vm();
+
+    // 1. If IsPromise(x) is true, then
     if (value.is_object() && is<Promise>(value.as_object())) {
     if (value.is_object() && is<Promise>(value.as_object())) {
+        // a. Let xConstructor be ? Get(x, "constructor").
         auto value_constructor = TRY(value.as_object().get(vm.names.constructor));
         auto value_constructor = TRY(value.as_object().get(vm.names.constructor));
+
+        // b. If SameValue(xConstructor, C) is true, return x.
         if (same_value(value_constructor, &constructor))
         if (same_value(value_constructor, &constructor))
             return &static_cast<Promise&>(value.as_object());
             return &static_cast<Promise&>(value.as_object());
     }
     }
+
+    // 2. Let promiseCapability be ? NewPromiseCapability(C).
     auto promise_capability = TRY(new_promise_capability(global_object, &constructor));
     auto promise_capability = TRY(new_promise_capability(global_object, &constructor));
+
+    // 3. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »).
     (void)TRY(vm.call(*promise_capability.resolve, js_undefined(), value));
     (void)TRY(vm.call(*promise_capability.resolve, js_undefined(), value));
+
+    // 4. Return promiseCapability.[[Promise]].
     return promise_capability.promise;
     return promise_capability.promise;
 }
 }
 
 
@@ -37,6 +48,7 @@ Promise* Promise::create(GlobalObject& global_object)
     return global_object.heap().allocate<Promise>(global_object, *global_object.promise_prototype());
     return global_object.heap().allocate<Promise>(global_object, *global_object.promise_prototype());
 }
 }
 
 
+// 27.2 Promise Objects, https://tc39.es/ecma262/#sec-promise-objects
 Promise::Promise(Object& prototype)
 Promise::Promise(Object& prototype)
     : Object(prototype)
     : Object(prototype)
 {
 {
@@ -48,59 +60,122 @@ Promise::ResolvingFunctions Promise::create_resolving_functions()
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / create_resolving_functions()]", this);
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / create_resolving_functions()]", this);
     auto& vm = this->vm();
     auto& vm = this->vm();
 
 
+    // 1. Let alreadyResolved be the Record { [[Value]]: false }.
     auto* already_resolved = vm.heap().allocate_without_global_object<AlreadyResolved>();
     auto* already_resolved = vm.heap().allocate_without_global_object<AlreadyResolved>();
 
 
+    // 2. Let stepsResolve be the algorithm steps defined in Promise Resolve Functions.
+    // 3. Let lengthResolve be the number of non-optional parameters of the function definition in Promise Resolve Functions.
+    // 4. Let resolve be ! CreateBuiltinFunction(stepsResolve, lengthResolve, "", « [[Promise]], [[AlreadyResolved]] »).
+    // 5. Set resolve.[[Promise]] to promise.
+    // 6. Set resolve.[[AlreadyResolved]] to alreadyResolved.
+
     // 27.2.1.3.2 Promise Resolve Functions, https://tc39.es/ecma262/#sec-promise-resolve-functions
     // 27.2.1.3.2 Promise Resolve Functions, https://tc39.es/ecma262/#sec-promise-resolve-functions
     auto* resolve_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto& global_object, auto& promise, auto& already_resolved) {
     auto* resolve_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto& global_object, auto& promise, auto& already_resolved) {
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolve function was called", &promise);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolve function was called", &promise);
+
+        auto resolution = vm.argument(0);
+
+        // 1. Let F be the active function object.
+        // 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
+        // 3. Let promise be F.[[Promise]].
+
+        // 4. Let alreadyResolved be F.[[AlreadyResolved]].
+        // 5. If alreadyResolved.[[Value]] is true, return undefined.
         if (already_resolved.value) {
         if (already_resolved.value) {
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise is already resolved, returning undefined", &promise);
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise is already resolved, returning undefined", &promise);
             return js_undefined();
             return js_undefined();
         }
         }
+
+        // 6. Set alreadyResolved.[[Value]] to true.
         already_resolved.value = true;
         already_resolved.value = true;
-        auto resolution = vm.argument(0);
+
+        // 7. If SameValue(resolution, promise) is true, then
         if (resolution.is_object() && &resolution.as_object() == &promise) {
         if (resolution.is_object() && &resolution.as_object() == &promise) {
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise can't be resolved with itself, rejecting with error", &promise);
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise can't be resolved with itself, rejecting with error", &promise);
+
+            // a. Let selfResolutionError be a newly created TypeError object.
             auto* self_resolution_error = TypeError::create(global_object, "Cannot resolve promise with itself");
             auto* self_resolution_error = TypeError::create(global_object, "Cannot resolve promise with itself");
+
+            // b. Return RejectPromise(promise, selfResolutionError).
             return promise.reject(self_resolution_error);
             return promise.reject(self_resolution_error);
         }
         }
+
+        // 8. If Type(resolution) is not Object, then
         if (!resolution.is_object()) {
         if (!resolution.is_object()) {
+            // a. Return FulfillPromise(promise, resolution).
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolution is not an object, fulfilling with {}", &promise, resolution);
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolution is not an object, fulfilling with {}", &promise, resolution);
             return promise.fulfill(resolution);
             return promise.fulfill(resolution);
         }
         }
+
+        // 9. Let then be Get(resolution, "then").
         auto then = resolution.as_object().get(vm.names.then);
         auto then = resolution.as_object().get(vm.names.then);
+
+        // 10. If then is an abrupt completion, then
         if (then.is_throw_completion()) {
         if (then.is_throw_completion()) {
+            // a. Return RejectPromise(promise, then.[[Value]]).
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Exception while getting 'then' property, rejecting with error", &promise);
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Exception while getting 'then' property, rejecting with error", &promise);
             vm.clear_exception();
             vm.clear_exception();
             vm.stop_unwind();
             vm.stop_unwind();
             return promise.reject(then.throw_completion().value());
             return promise.reject(then.throw_completion().value());
         }
         }
+
+        // 11. Let thenAction be then.[[Value]].
         auto then_action = then.release_value();
         auto then_action = then.release_value();
+
+        // 12. If IsCallable(thenAction) is false, then
         if (!then_action.is_function()) {
         if (!then_action.is_function()) {
+            // a. Return FulfillPromise(promise, resolution).
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Then action is not a function, fulfilling with {}", &promise, resolution);
             dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Then action is not a function, fulfilling with {}", &promise, resolution);
             return promise.fulfill(resolution);
             return promise.fulfill(resolution);
         }
         }
+
+        // 13. Let thenJobCallback be HostMakeJobCallback(thenAction).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating JobCallback for then action @ {}", &promise, &then_action.as_function());
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating JobCallback for then action @ {}", &promise, &then_action.as_function());
         auto then_job_callback = make_job_callback(then_action.as_function());
         auto then_job_callback = make_job_callback(then_action.as_function());
+
+        // 14. Let job be NewPromiseResolveThenableJob(promise, resolution, thenJobCallback).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating PromiseResolveThenableJob for thenable {}", &promise, resolution);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating PromiseResolveThenableJob for thenable {}", &promise, resolution);
         auto* job = PromiseResolveThenableJob::create(global_object, promise, resolution, then_job_callback);
         auto* job = PromiseResolveThenableJob::create(global_object, promise, resolution, then_job_callback);
+
+        // 15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Enqueuing job @ {}", &promise, job);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Enqueuing job @ {}", &promise, job);
         vm.enqueue_promise_job(*job);
         vm.enqueue_promise_job(*job);
+
+        // 16. Return undefined.
         return js_undefined();
         return js_undefined();
     });
     });
     resolve_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
     resolve_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
 
 
+    // 7. Let stepsReject be the algorithm steps defined in Promise Reject Functions.
+    // 8. Let lengthReject be the number of non-optional parameters of the function definition in Promise Reject Functions.
+    // 9. Let reject be ! CreateBuiltinFunction(stepsReject, lengthReject, "", « [[Promise]], [[AlreadyResolved]] »).
+    // 10. Set reject.[[Promise]] to promise.
+    // 11. Set reject.[[AlreadyResolved]] to alreadyResolved.
+
     // 27.2.1.3.1 Promise Reject Functions, https://tc39.es/ecma262/#sec-promise-reject-functions
     // 27.2.1.3.1 Promise Reject Functions, https://tc39.es/ecma262/#sec-promise-reject-functions
     auto* reject_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto&, auto& promise, auto& already_resolved) {
     auto* reject_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto&, auto& promise, auto& already_resolved) {
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Reject function was called", &promise);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Reject function was called", &promise);
+
+        auto reason = vm.argument(0);
+
+        // 1. Let F be the active function object.
+        // 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
+        // 3. Let promise be F.[[Promise]].
+
+        // 4. Let alreadyResolved be F.[[AlreadyResolved]].
+        // 5. If alreadyResolved.[[Value]] is true, return undefined.
         if (already_resolved.value)
         if (already_resolved.value)
             return js_undefined();
             return js_undefined();
+
+        // 6. Set alreadyResolved.[[Value]] to true.
         already_resolved.value = true;
         already_resolved.value = true;
-        auto reason = vm.argument(0);
+
+        // 7. Return RejectPromise(promise, reason).
         return promise.reject(reason);
         return promise.reject(reason);
     });
     });
     reject_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
     reject_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
 
 
+    // 12. Return the Record { [[Resolve]]: resolve, [[Reject]]: reject }.
     return { *resolve_function, *reject_function };
     return { *resolve_function, *reject_function };
 }
 }
 
 
@@ -108,10 +183,24 @@ Promise::ResolvingFunctions Promise::create_resolving_functions()
 Value Promise::fulfill(Value value)
 Value Promise::fulfill(Value value)
 {
 {
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / fulfill()]: Fulfilling promise with value {}", this, value);
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / fulfill()]: Fulfilling promise with value {}", this, value);
+
+    // 1. Assert: The value of promise.[[PromiseState]] is pending.
     VERIFY(m_state == State::Pending);
     VERIFY(m_state == State::Pending);
     VERIFY(!value.is_empty());
     VERIFY(!value.is_empty());
-    m_state = State::Fulfilled;
+
+    // 2. Let reactions be promise.[[PromiseFulfillReactions]].
+    // NOTE: This is a noop, we do these steps in a slightly different order.
+
+    // 3. Set promise.[[PromiseResult]] to value.
     m_result = value;
     m_result = value;
+
+    // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
+    // 5. Set promise.[[PromiseRejectReactions]] to undefined.
+
+    // 6. Set promise.[[PromiseState]] to fulfilled.
+    m_state = State::Fulfilled;
+
+    // 7. Return TriggerPromiseReactions(reactions, value).
     trigger_reactions();
     trigger_reactions();
     m_fulfill_reactions.clear();
     m_fulfill_reactions.clear();
     m_reject_reactions.clear();
     m_reject_reactions.clear();
@@ -121,14 +210,31 @@ Value Promise::fulfill(Value value)
 // 27.2.1.7 RejectPromise ( promise, reason ), https://tc39.es/ecma262/#sec-rejectpromise
 // 27.2.1.7 RejectPromise ( promise, reason ), https://tc39.es/ecma262/#sec-rejectpromise
 Value Promise::reject(Value reason)
 Value Promise::reject(Value reason)
 {
 {
+
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / reject()]: Rejecting promise with reason {}", this, reason);
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / reject()]: Rejecting promise with reason {}", this, reason);
+    auto& vm = this->vm();
+
+    // 1. Assert: The value of promise.[[PromiseState]] is pending.
     VERIFY(m_state == State::Pending);
     VERIFY(m_state == State::Pending);
     VERIFY(!reason.is_empty());
     VERIFY(!reason.is_empty());
-    auto& vm = this->vm();
-    m_state = State::Rejected;
+
+    // 2. Let reactions be promise.[[PromiseRejectReactions]].
+    // NOTE: This is a noop, we do these steps in a slightly different order.
+
+    // 3. Set promise.[[PromiseResult]] to reason.
     m_result = reason;
     m_result = reason;
+
+    // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
+    // 5. Set promise.[[PromiseRejectReactions]] to undefined.
+
+    // 6. Set promise.[[PromiseState]] to rejected.
+    m_state = State::Rejected;
+
+    // 7. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "reject").
     if (!m_is_handled)
     if (!m_is_handled)
         vm.promise_rejection_tracker(*this, RejectionOperation::Reject);
         vm.promise_rejection_tracker(*this, RejectionOperation::Reject);
+
+    // 8. Return TriggerPromiseReactions(reactions, reason).
     trigger_reactions();
     trigger_reactions();
     m_fulfill_reactions.clear();
     m_fulfill_reactions.clear();
     m_reject_reactions.clear();
     m_reject_reactions.clear();
@@ -143,16 +249,24 @@ void Promise::trigger_reactions() const
     auto& reactions = m_state == State::Fulfilled
     auto& reactions = m_state == State::Fulfilled
         ? m_fulfill_reactions
         ? m_fulfill_reactions
         : m_reject_reactions;
         : m_reject_reactions;
+
+    // 1. For each element reaction of reactions, do
     for (auto& reaction : reactions) {
     for (auto& reaction : reactions) {
+        // a. Let job be NewPromiseReactionJob(reaction, argument).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, &reaction, m_result);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, &reaction, m_result);
         auto* job = PromiseReactionJob::create(global_object(), *reaction, m_result);
         auto* job = PromiseReactionJob::create(global_object(), *reaction, m_result);
+
+        // b. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Enqueuing job @ {}", this, job);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Enqueuing job @ {}", this, job);
         vm.enqueue_promise_job(*job);
         vm.enqueue_promise_job(*job);
     }
     }
+
     if constexpr (PROMISE_DEBUG) {
     if constexpr (PROMISE_DEBUG) {
         if (reactions.is_empty())
         if (reactions.is_empty())
             dbgln("[Promise @ {} / trigger_reactions()]: No reactions!", this);
             dbgln("[Promise @ {} / trigger_reactions()]: No reactions!", this);
     }
     }
+
+    // 2. Return undefined.
 }
 }
 
 
 // 27.2.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] ), https://tc39.es/ecma262/#sec-performpromisethen
 // 27.2.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] ), https://tc39.es/ecma262/#sec-performpromisethen
@@ -160,41 +274,79 @@ Value Promise::perform_then(Value on_fulfilled, Value on_rejected, Optional<Prom
 {
 {
     auto& vm = this->vm();
     auto& vm = this->vm();
 
 
+    // 1. Assert: IsPromise(promise) is true.
+    // 2. If resultCapability is not present, then
+    //     a. Set resultCapability to undefined.
+
+    // 3. If IsCallable(onFulfilled) is false, then
+    //     a. Let onFulfilledJobCallback be empty.
     Optional<JobCallback> on_fulfilled_job_callback;
     Optional<JobCallback> on_fulfilled_job_callback;
+
+    // 4. Else,
     if (on_fulfilled.is_function()) {
     if (on_fulfilled.is_function()) {
+        // a. Let onFulfilledJobCallback be HostMakeJobCallback(onFulfilled).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_fulfilled function @ {}", this, &on_fulfilled.as_function());
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_fulfilled function @ {}", this, &on_fulfilled.as_function());
         on_fulfilled_job_callback = make_job_callback(on_fulfilled.as_function());
         on_fulfilled_job_callback = make_job_callback(on_fulfilled.as_function());
     }
     }
 
 
+    // 5. If IsCallable(onRejected) is false, then
+    //     a. Let onRejectedJobCallback be empty.
     Optional<JobCallback> on_rejected_job_callback;
     Optional<JobCallback> on_rejected_job_callback;
+
+    // 6. Else,
     if (on_rejected.is_function()) {
     if (on_rejected.is_function()) {
+        // a. Let onRejectedJobCallback be HostMakeJobCallback(onRejected).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_rejected function @ {}", this, &on_rejected.as_function());
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_rejected function @ {}", this, &on_rejected.as_function());
         on_rejected_job_callback = make_job_callback(on_rejected.as_function());
         on_rejected_job_callback = make_job_callback(on_rejected.as_function());
     }
     }
 
 
+    // 7. Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Fulfill, [[Handler]]: onFulfilledJobCallback }.
     auto* fulfill_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Fulfill, result_capability, on_fulfilled_job_callback);
     auto* fulfill_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Fulfill, result_capability, on_fulfilled_job_callback);
+
+    // 8. Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Reject, [[Handler]]: onRejectedJobCallback }.
     auto* reject_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Reject, result_capability, on_rejected_job_callback);
     auto* reject_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Reject, result_capability, on_rejected_job_callback);
 
 
     switch (m_state) {
     switch (m_state) {
+    // 9. If promise.[[PromiseState]] is pending, then
     case Promise::State::Pending:
     case Promise::State::Pending:
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: state is State::Pending, adding fulfill/reject reactions", this);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: state is State::Pending, adding fulfill/reject reactions", this);
+
+        // a. Append fulfillReaction as the last element of the List that is promise.[[PromiseFulfillReactions]].
         m_fulfill_reactions.append(fulfill_reaction);
         m_fulfill_reactions.append(fulfill_reaction);
+
+        // b. Append rejectReaction as the last element of the List that is promise.[[PromiseRejectReactions]].
         m_reject_reactions.append(reject_reaction);
         m_reject_reactions.append(reject_reaction);
         break;
         break;
+    // 10. Else if promise.[[PromiseState]] is fulfilled, then
     case Promise::State::Fulfilled: {
     case Promise::State::Fulfilled: {
+        // a. Let value be promise.[[PromiseResult]].
         auto value = m_result;
         auto value = m_result;
+
+        // b. Let fulfillJob be NewPromiseReactionJob(fulfillReaction, value).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Fulfilled, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, fulfill_reaction, value);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Fulfilled, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, fulfill_reaction, value);
         auto* fulfill_job = PromiseReactionJob::create(global_object(), *fulfill_reaction, value);
         auto* fulfill_job = PromiseReactionJob::create(global_object(), *fulfill_reaction, value);
+
+        // c. Perform HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]]).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {}", this, fulfill_job);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {}", this, fulfill_job);
         vm.enqueue_promise_job(*fulfill_job);
         vm.enqueue_promise_job(*fulfill_job);
         break;
         break;
     }
     }
+    // 11. Else,
     case Promise::State::Rejected: {
     case Promise::State::Rejected: {
+        // a. Assert: The value of promise.[[PromiseState]] is rejected.
+
+        // b. Let reason be promise.[[PromiseResult]].
         auto reason = m_result;
         auto reason = m_result;
+
+        // c. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "handle").
         if (!m_is_handled)
         if (!m_is_handled)
             vm.promise_rejection_tracker(*this, RejectionOperation::Handle);
             vm.promise_rejection_tracker(*this, RejectionOperation::Handle);
+
+        // d. Let rejectJob be NewPromiseReactionJob(rejectReaction, reason).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Rejected, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, reject_reaction, reason);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Rejected, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, reject_reaction, reason);
         auto* reject_job = PromiseReactionJob::create(global_object(), *reject_reaction, reason);
         auto* reject_job = PromiseReactionJob::create(global_object(), *reject_reaction, reason);
+
+        // e. Perform HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]]).
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {}", this, reject_job);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {}", this, reject_job);
         vm.enqueue_promise_job(*reject_job);
         vm.enqueue_promise_job(*reject_job);
         break;
         break;
@@ -203,12 +355,18 @@ Value Promise::perform_then(Value on_fulfilled, Value on_rejected, Optional<Prom
         VERIFY_NOT_REACHED();
         VERIFY_NOT_REACHED();
     }
     }
 
 
+    // 12. Set promise.[[PromiseIsHandled]] to true.
     m_is_handled = true;
     m_is_handled = true;
 
 
+    // 13. If resultCapability is undefined, then
     if (!result_capability.has_value()) {
     if (!result_capability.has_value()) {
+        // a. Return undefined.
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: No ResultCapability, returning undefined", this);
         dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: No ResultCapability, returning undefined", this);
         return js_undefined();
         return js_undefined();
     }
     }
+
+    // 14. Else,
+    //     a. Return resultCapability.[[Promise]].
     auto* promise = result_capability.value().promise;
     auto* promise = result_capability.value().promise;
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Returning Promise @ {} from ResultCapability @ {}", this, promise, &result_capability.value());
     dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Returning Promise @ {} from ResultCapability @ {}", this, promise, &result_capability.value());
     return promise;
     return promise;

+ 6 - 5
Userland/Libraries/LibJS/Runtime/Promise.h

@@ -53,11 +53,12 @@ private:
 
 
     void trigger_reactions() const;
     void trigger_reactions() const;
 
 
-    State m_state { State::Pending };
-    Value m_result;
-    Vector<PromiseReaction*> m_fulfill_reactions;
-    Vector<PromiseReaction*> m_reject_reactions;
-    bool m_is_handled { false };
+    // 27.2.6 Properties of Promise Instances, https://tc39.es/ecma262/#sec-properties-of-promise-instances
+    State m_state { State::Pending };             // [[PromiseState]]
+    Value m_result;                               // [[PromiseResult]]
+    Vector<PromiseReaction*> m_fulfill_reactions; // [[PromiseFulfillReactions]]
+    Vector<PromiseReaction*> m_reject_reactions;  // [[PromiseRejectReactions]]
+    bool m_is_handled { false };                  // [[PromiseIsHandled]]
 };
 };
 
 
 }
 }

+ 173 - 5
Userland/Libraries/LibJS/Runtime/PromiseConstructor.cpp

@@ -27,10 +27,14 @@ static ThrowCompletionOr<Value> get_promise_resolve(GlobalObject& global_object,
     VERIFY(constructor.is_constructor());
     VERIFY(constructor.is_constructor());
     auto& vm = global_object.vm();
     auto& vm = global_object.vm();
 
 
+    // 1. Let promiseResolve be ? Get(promiseConstructor, "resolve").
     auto promise_resolve = TRY(constructor.get(global_object, vm.names.resolve));
     auto promise_resolve = TRY(constructor.get(global_object, vm.names.resolve));
+
+    // 2. If IsCallable(promiseResolve) is false, throw a TypeError exception.
     if (!promise_resolve.is_function())
     if (!promise_resolve.is_function())
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, promise_resolve.to_string_without_side_effects());
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, promise_resolve.to_string_without_side_effects());
 
 
+    // 3. Return promiseResolve.
     return promise_resolve;
     return promise_resolve;
 }
 }
 
 
@@ -38,13 +42,19 @@ static ThrowCompletionOr<Value> get_promise_resolve(GlobalObject& global_object,
 #define TRY_OR_REJECT(vm, capability, expression)                                                         \
 #define TRY_OR_REJECT(vm, capability, expression)                                                         \
     ({                                                                                                    \
     ({                                                                                                    \
         auto _temporary_result = (expression);                                                            \
         auto _temporary_result = (expression);                                                            \
+        /* 1. If value is an abrupt completion, then */                                                   \
         if (_temporary_result.is_error()) {                                                               \
         if (_temporary_result.is_error()) {                                                               \
             vm.clear_exception();                                                                         \
             vm.clear_exception();                                                                         \
             vm.stop_unwind();                                                                             \
             vm.stop_unwind();                                                                             \
                                                                                                           \
                                                                                                           \
+            /* a. Perform ? Call(capability.[[Reject]], undefined, « value.[[Value]] »). */             \
             (void)vm.call(*capability.reject, js_undefined(), _temporary_result.release_error().value()); \
             (void)vm.call(*capability.reject, js_undefined(), _temporary_result.release_error().value()); \
+                                                                                                          \
+            /* b. Return capability.[[Promise]]. */                                                       \
             return capability.promise;                                                                    \
             return capability.promise;                                                                    \
         }                                                                                                 \
         }                                                                                                 \
+                                                                                                          \
+        /* 2. Else if value is a Completion Record, set value to value.[[Value]]. */                      \
         _temporary_result.release_value();                                                                \
         _temporary_result.release_value();                                                                \
     })
     })
 
 
@@ -78,40 +88,70 @@ static ThrowCompletionOr<Value> perform_promise_common(GlobalObject& global_obje
     VERIFY(constructor.is_constructor());
     VERIFY(constructor.is_constructor());
     VERIFY(promise_resolve.is_function());
     VERIFY(promise_resolve.is_function());
 
 
+    // 1. Let values be a new empty List.
     auto* values = vm.heap().allocate_without_global_object<PromiseValueList>();
     auto* values = vm.heap().allocate_without_global_object<PromiseValueList>();
+
+    // 2. Let remainingElementsCount be the Record { [[Value]]: 1 }.
     auto* remaining_elements_count = vm.heap().allocate_without_global_object<RemainingElements>(1);
     auto* remaining_elements_count = vm.heap().allocate_without_global_object<RemainingElements>(1);
+
+    // 3. Let index be 0.
     size_t index = 0;
     size_t index = 0;
 
 
+    // 4. Repeat,
     while (true) {
     while (true) {
+        // a. Let next be IteratorStep(iteratorRecord).
         auto next_or_error = iterator_step(global_object, iterator_record);
         auto next_or_error = iterator_step(global_object, iterator_record);
+
+        // b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
+        // c. ReturnIfAbrupt(next).
         if (next_or_error.is_throw_completion()) {
         if (next_or_error.is_throw_completion()) {
             set_iterator_record_complete(global_object, iterator_record);
             set_iterator_record_complete(global_object, iterator_record);
             return next_or_error.release_error();
             return next_or_error.release_error();
         }
         }
         auto* next = next_or_error.release_value();
         auto* next = next_or_error.release_value();
 
 
+        // d. If next is false, then
         if (!next) {
         if (!next) {
+            // i. Set iteratorRecord.[[Done]] to true.
             set_iterator_record_complete(global_object, iterator_record);
             set_iterator_record_complete(global_object, iterator_record);
 
 
-            if (--remaining_elements_count->value == 0)
+            // ii. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
+            // iii. If remainingElementsCount.[[Value]] is 0, then
+            if (--remaining_elements_count->value == 0) {
+                // 1-2/3. are handled in `end_of_list`
                 return TRY(end_of_list(*values));
                 return TRY(end_of_list(*values));
+            }
+
+            // iv. Return resultCapability.[[Promise]].
             return result_capability.promise;
             return result_capability.promise;
         }
         }
 
 
+        // e. Let nextValue be IteratorValue(next).
         auto next_value_or_error = iterator_value(global_object, *next);
         auto next_value_or_error = iterator_value(global_object, *next);
+
+        // f. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
+        // g. ReturnIfAbrupt(nextValue).
         if (next_value_or_error.is_throw_completion()) {
         if (next_value_or_error.is_throw_completion()) {
             set_iterator_record_complete(global_object, iterator_record);
             set_iterator_record_complete(global_object, iterator_record);
             return next_value_or_error.release_error();
             return next_value_or_error.release_error();
         }
         }
         auto next_value = next_value_or_error.release_value();
         auto next_value = next_value_or_error.release_value();
 
 
+        // h. Append undefined to values.
         values->values().append(js_undefined());
         values->values().append(js_undefined());
 
 
+        // i. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »).
         auto next_promise = TRY(vm.call(promise_resolve.as_function(), constructor, next_value));
         auto next_promise = TRY(vm.call(promise_resolve.as_function(), constructor, next_value));
 
 
+        // j-q. are handled in `invoke_element_function`
+
+        // r. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] + 1.
         ++remaining_elements_count->value;
         ++remaining_elements_count->value;
 
 
+        // s. Perform ? Invoke(nextPromise, "then", « ... »).
         TRY(invoke_element_function(*values, *remaining_elements_count, next_promise, index));
         TRY(invoke_element_function(*values, *remaining_elements_count, next_promise, index));
+
+        // t. Set index to index + 1.
         ++index;
         ++index;
     }
     }
 }
 }
@@ -124,16 +164,28 @@ static ThrowCompletionOr<Value> perform_promise_all(GlobalObject& global_object,
     return perform_promise_common(
     return perform_promise_common(
         global_object, iterator_record, constructor, result_capability, promise_resolve,
         global_object, iterator_record, constructor, result_capability, promise_resolve,
         [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
         [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
+            // 1. Let valuesArray be ! CreateArrayFromList(values).
             auto values_array = Array::create_from(global_object, values.values());
             auto values_array = Array::create_from(global_object, values.values());
 
 
+            // 2. Perform ? Call(resultCapability.[[Resolve]], undefined, « valuesArray »).
             TRY(vm.call(*result_capability.resolve, js_undefined(), values_array));
             TRY(vm.call(*result_capability.resolve, js_undefined(), values_array));
 
 
+            // iv. Return resultCapability.[[Promise]].
             return Value(result_capability.promise);
             return Value(result_capability.promise);
         },
         },
         [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
         [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
+            // j. Let steps be the algorithm steps defined in Promise.all Resolve Element Functions.
+            // k. Let length be the number of non-optional parameters of the function definition in Promise.all Resolve Element Functions.
+            // l. Let onFulfilled be ! CreateBuiltinFunction(steps, length, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
+            // m. Set onFulfilled.[[AlreadyCalled]] to false.
+            // n. Set onFulfilled.[[Index]] to index.
+            // o. Set onFulfilled.[[Values]] to values.
+            // p. Set onFulfilled.[[Capability]] to resultCapability.
+            // q. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
             auto* on_fulfilled = PromiseAllResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
             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);
             on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
 
 
+            // s. Perform ? Invoke(nextPromise, "then", « onFulfilled, resultCapability.[[Reject]] »).
             return next_promise.invoke(global_object, vm.names.then, on_fulfilled, result_capability.reject);
             return next_promise.invoke(global_object, vm.names.then, on_fulfilled, result_capability.reject);
         });
         });
 }
 }
@@ -153,12 +205,30 @@ static ThrowCompletionOr<Value> perform_promise_all_settled(GlobalObject& global
             return Value(result_capability.promise);
             return Value(result_capability.promise);
         },
         },
         [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
         [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
+            // j. Let stepsFulfilled be the algorithm steps defined in Promise.allSettled Resolve Element Functions.
+            // k. Let lengthFulfilled be the number of non-optional parameters of the function definition in Promise.allSettled Resolve Element Functions.
+            // l. Let onFulfilled be ! CreateBuiltinFunction(stepsFulfilled, lengthFulfilled, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
+            // m. Let alreadyCalled be the Record { [[Value]]: false }.
+            // n. Set onFulfilled.[[AlreadyCalled]] to alreadyCalled.
+            // o. Set onFulfilled.[[Index]] to index.
+            // p. Set onFulfilled.[[Values]] to values.
+            // q. Set onFulfilled.[[Capability]] to resultCapability.
+            // r. Set onFulfilled.[[RemainingElements]] to remainingElementsCount.
             auto* on_fulfilled = PromiseAllSettledResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
             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);
             on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
 
 
+            // s. Let stepsRejected be the algorithm steps defined in Promise.allSettled Reject Element Functions.
+            // t. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.allSettled Reject Element Functions.
+            // u. Let onRejected be ! CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], [[RemainingElements]] »).
+            // v. Set onRejected.[[AlreadyCalled]] to alreadyCalled.
+            // w. Set onRejected.[[Index]] to index.
+            // x. Set onRejected.[[Values]] to values.
+            // y. Set onRejected.[[Capability]] to resultCapability.
+            // z. Set onRejected.[[RemainingElements]] to remainingElementsCount.
             auto* on_rejected = PromiseAllSettledRejectElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
             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);
             on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
 
 
+            // ab. Perform ? Invoke(nextPromise, "then", « onFulfilled, onRejected »).
             return next_promise.invoke(global_object, vm.names.then, on_fulfilled, on_rejected);
             return next_promise.invoke(global_object, vm.names.then, on_fulfilled, on_rejected);
         });
         });
 }
 }
@@ -171,18 +241,30 @@ static ThrowCompletionOr<Value> perform_promise_any(GlobalObject& global_object,
     return perform_promise_common(
     return perform_promise_common(
         global_object, iterator_record, constructor, result_capability, promise_resolve,
         global_object, iterator_record, constructor, result_capability, promise_resolve,
         [&](PromiseValueList& errors) -> ThrowCompletionOr<Value> {
         [&](PromiseValueList& errors) -> ThrowCompletionOr<Value> {
-            auto errors_array = Array::create_from(global_object, errors.values());
-
+            // 1. Let error be a newly created AggregateError object.
             auto* error = AggregateError::create(global_object);
             auto* error = AggregateError::create(global_object);
+
+            // 2. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: ! CreateArrayFromList(errors) }).
+            auto* errors_array = Array::create_from(global_object, errors.values());
             MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
             MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
 
 
+            // 3. Return ThrowCompletion(error).
             vm.throw_exception(global_object, error);
             vm.throw_exception(global_object, error);
             return throw_completion(error);
             return throw_completion(error);
         },
         },
         [&](PromiseValueList& errors, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
         [&](PromiseValueList& errors, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
+            // j. Let stepsRejected be the algorithm steps defined in Promise.any Reject Element Functions.
+            // k. Let lengthRejected be the number of non-optional parameters of the function definition in Promise.any Reject Element Functions.
+            // l. Let onRejected be ! CreateBuiltinFunction(stepsRejected, lengthRejected, "", « [[AlreadyCalled]], [[Index]], [[Errors]], [[Capability]], [[RemainingElements]] »).
+            // m. Set onRejected.[[AlreadyCalled]] to false.
+            // n. Set onRejected.[[Index]] to index.
+            // o. Set onRejected.[[Errors]] to errors.
+            // p. Set onRejected.[[Capability]] to resultCapability.
+            // q. Set onRejected.[[RemainingElements]] to remainingElementsCount.
             auto* on_rejected = PromiseAnyRejectElementFunction::create(global_object, index, errors, result_capability, remaining_elements_count);
             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);
             on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
 
 
+            // s. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], onRejected »).
             return next_promise.invoke(global_object, vm.names.then, result_capability.resolve, on_rejected);
             return next_promise.invoke(global_object, vm.names.then, result_capability.resolve, on_rejected);
         });
         });
 }
 }
@@ -195,9 +277,11 @@ static ThrowCompletionOr<Value> perform_promise_race(GlobalObject& global_object
     return perform_promise_common(
     return perform_promise_common(
         global_object, iterator_record, constructor, result_capability, promise_resolve,
         global_object, iterator_record, constructor, result_capability, promise_resolve,
         [&](PromiseValueList&) -> ThrowCompletionOr<Value> {
         [&](PromiseValueList&) -> ThrowCompletionOr<Value> {
+            // ii. Return resultCapability.[[Promise]].
             return Value(result_capability.promise);
             return Value(result_capability.promise);
         },
         },
         [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
         [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
+            // i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »).
             return next_promise.invoke(global_object, vm.names.then, result_capability.resolve, result_capability.reject);
             return next_promise.invoke(global_object, vm.names.then, result_capability.resolve, result_capability.reject);
         });
         });
 }
 }
@@ -232,6 +316,8 @@ void PromiseConstructor::initialize(GlobalObject& global_object)
 ThrowCompletionOr<Value> PromiseConstructor::call()
 ThrowCompletionOr<Value> PromiseConstructor::call()
 {
 {
     auto& vm = this->vm();
     auto& vm = this->vm();
+
+    // 1. If NewTarget is undefined, throw a TypeError exception.
     return vm.throw_completion<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.Promise);
     return vm.throw_completion<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.Promise);
 }
 }
 
 
@@ -242,127 +328,209 @@ ThrowCompletionOr<Object*> PromiseConstructor::construct(FunctionObject& new_tar
     auto& global_object = this->global_object();
     auto& global_object = this->global_object();
 
 
     auto executor = vm.argument(0);
     auto executor = vm.argument(0);
+
+    // 2. If IsCallable(executor) is false, throw a TypeError exception.
     if (!executor.is_function())
     if (!executor.is_function())
         return vm.throw_completion<TypeError>(global_object, ErrorType::PromiseExecutorNotAFunction);
         return vm.throw_completion<TypeError>(global_object, ErrorType::PromiseExecutorNotAFunction);
 
 
+    // 3. Let promise be ? OrdinaryCreateFromConstructor(NewTarget, "%Promise.prototype%", « [[PromiseState]], [[PromiseResult]], [[PromiseFulfillReactions]], [[PromiseRejectReactions]], [[PromiseIsHandled]] »).
+    // 4. Set promise.[[PromiseState]] to pending.
+    // 5. Set promise.[[PromiseFulfillReactions]] to a new empty List.
+    // 6. Set promise.[[PromiseRejectReactions]] to a new empty List.
+    // 7. Set promise.[[PromiseIsHandled]] to false.
     auto* promise = TRY(ordinary_create_from_constructor<Promise>(global_object, new_target, &GlobalObject::promise_prototype));
     auto* promise = TRY(ordinary_create_from_constructor<Promise>(global_object, new_target, &GlobalObject::promise_prototype));
 
 
+    // 8. Let resolvingFunctions be CreateResolvingFunctions(promise).
     auto [resolve_function, reject_function] = promise->create_resolving_functions();
     auto [resolve_function, reject_function] = promise->create_resolving_functions();
 
 
+    // 9. Let completion be Call(executor, undefined, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »).
     (void)vm.call(executor.as_function(), js_undefined(), &resolve_function, &reject_function);
     (void)vm.call(executor.as_function(), js_undefined(), &resolve_function, &reject_function);
+
+    // 10. If completion is an abrupt completion, then
     if (auto* exception = vm.exception()) {
     if (auto* exception = vm.exception()) {
         vm.clear_exception();
         vm.clear_exception();
         vm.stop_unwind();
         vm.stop_unwind();
+
+        // a. Perform ? Call(resolvingFunctions.[[Reject]], undefined, « completion.[[Value]] »).
         TRY(vm.call(reject_function, js_undefined(), exception->value()));
         TRY(vm.call(reject_function, js_undefined(), exception->value()));
     }
     }
+
+    // 11. Return promise.
     return promise;
     return promise;
 }
 }
 
 
 // 27.2.4.1 Promise.all ( iterable ), https://tc39.es/ecma262/#sec-promise.all
 // 27.2.4.1 Promise.all ( iterable ), https://tc39.es/ecma262/#sec-promise.all
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all)
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all)
 {
 {
+    // 1. Let C be the this value.
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
 
 
+    // 2. Let promiseCapability be ? NewPromiseCapability(C).
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
 
 
+    // 3. Let promiseResolve be GetPromiseResolve(C).
+    // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
+
+    // 5. Let iteratorRecord be GetIterator(iterable).
+    // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
 
 
+    // 7. Let result be PerformPromiseAll(iteratorRecord, C, promiseCapability, promiseResolve).
     auto result = perform_promise_all(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
     auto result = perform_promise_all(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
+
+    // 8. If result is an abrupt completion, then
     if (result.is_error()) {
     if (result.is_error()) {
+        // a. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
         if (!iterator_record_is_complete(global_object, *iterator_record))
         if (!iterator_record_is_complete(global_object, *iterator_record))
             result = iterator_close(*iterator_record, result.release_error());
             result = iterator_close(*iterator_record, result.release_error());
 
 
+        // b. IfAbruptRejectPromise(result, promiseCapability).
         TRY_OR_REJECT(vm, promise_capability, result);
         TRY_OR_REJECT(vm, promise_capability, result);
     }
     }
 
 
+    // 9. Return Completion(result).
     return result.release_value();
     return result.release_value();
 }
 }
 
 
 // 27.2.4.2 Promise.allSettled ( iterable ), https://tc39.es/ecma262/#sec-promise.allsettled
 // 27.2.4.2 Promise.allSettled ( iterable ), https://tc39.es/ecma262/#sec-promise.allsettled
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled)
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::all_settled)
 {
 {
+    // 1. Let C be the this value.
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
 
 
+    // 2. Let promiseCapability be ? NewPromiseCapability(C).
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
 
 
+    // 3. Let promiseResolve be GetPromiseResolve(C).
+    // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
+
+    // 5. Let iteratorRecord be GetIterator(iterable).
+    // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
 
 
+    // 7. Let result be PerformPromiseAllSettled(iteratorRecord, C, promiseCapability, promiseResolve).
     auto result = perform_promise_all_settled(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
     auto result = perform_promise_all_settled(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
+
+    // 8. If result is an abrupt completion, then
     if (result.is_error()) {
     if (result.is_error()) {
+        // a. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
         if (!iterator_record_is_complete(global_object, *iterator_record))
         if (!iterator_record_is_complete(global_object, *iterator_record))
             result = iterator_close(*iterator_record, result.release_error());
             result = iterator_close(*iterator_record, result.release_error());
 
 
+        // b. IfAbruptRejectPromise(result, promiseCapability).
         TRY_OR_REJECT(vm, promise_capability, result);
         TRY_OR_REJECT(vm, promise_capability, result);
     }
     }
 
 
+    // 9. Return Completion(result).
     return result.release_value();
     return result.release_value();
 }
 }
 
 
 // 27.2.4.3 Promise.any ( iterable ), https://tc39.es/ecma262/#sec-promise.any
 // 27.2.4.3 Promise.any ( iterable ), https://tc39.es/ecma262/#sec-promise.any
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any)
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::any)
 {
 {
+    // 1. Let C be the this value.
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
 
 
+    // 2. Let promiseCapability be ? NewPromiseCapability(C).
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
 
 
+    // 3. Let promiseResolve be GetPromiseResolve(C).
+    // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
+
+    // 5. Let iteratorRecord be GetIterator(iterable).
+    // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
 
 
+    // 7. Let result be PerformPromiseAny(iteratorRecord, C, promiseCapability, promiseResolve).
     auto result = perform_promise_any(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
     auto result = perform_promise_any(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
+
+    // 8. If result is an abrupt completion, then
     if (result.is_error()) {
     if (result.is_error()) {
+        // a. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
         if (!iterator_record_is_complete(global_object, *iterator_record))
         if (!iterator_record_is_complete(global_object, *iterator_record))
             result = iterator_close(*iterator_record, result.release_error());
             result = iterator_close(*iterator_record, result.release_error());
 
 
+        // b. IfAbruptRejectPromise(result, promiseCapability).
         TRY_OR_REJECT(vm, promise_capability, result);
         TRY_OR_REJECT(vm, promise_capability, result);
     }
     }
 
 
+    // 9. Return Completion(result).
     return result.release_value();
     return result.release_value();
 }
 }
 
 
 // 27.2.4.5 Promise.race ( iterable ), https://tc39.es/ecma262/#sec-promise.race
 // 27.2.4.5 Promise.race ( iterable ), https://tc39.es/ecma262/#sec-promise.race
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race)
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::race)
 {
 {
+    // 1. Let C be the this value.
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
 
 
+    // 2. Let promiseCapability be ? NewPromiseCapability(C).
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
 
 
+    // 3. Let promiseResolve be GetPromiseResolve(C).
+    // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability).
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
     auto promise_resolve = TRY_OR_REJECT(vm, promise_capability, get_promise_resolve(global_object, constructor));
+
+    // 5. Let iteratorRecord be GetIterator(iterable).
+    // 6. IfAbruptRejectPromise(iteratorRecord, promiseCapability).
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
     auto* iterator_record = TRY_OR_REJECT(vm, promise_capability, get_iterator(global_object, vm.argument(0)));
 
 
+    // 7. Let result be PerformPromiseRace(iteratorRecord, C, promiseCapability, promiseResolve).
     auto result = perform_promise_race(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
     auto result = perform_promise_race(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
+
+    // 8. If result is an abrupt completion, then
     if (result.is_error()) {
     if (result.is_error()) {
+        // a. If iteratorRecord.[[Done]] is false, set result to IteratorClose(iteratorRecord, result).
         if (!iterator_record_is_complete(global_object, *iterator_record))
         if (!iterator_record_is_complete(global_object, *iterator_record))
             result = iterator_close(*iterator_record, result.release_error());
             result = iterator_close(*iterator_record, result.release_error());
 
 
+        // b. IfAbruptRejectPromise(result, promiseCapability).
         TRY_OR_REJECT(vm, promise_capability, result);
         TRY_OR_REJECT(vm, promise_capability, result);
     }
     }
 
 
+    // 9. Return Completion(result).
     return result.release_value();
     return result.release_value();
 }
 }
 
 
 // 27.2.4.6 Promise.reject ( r ), https://tc39.es/ecma262/#sec-promise.reject
 // 27.2.4.6 Promise.reject ( r ), https://tc39.es/ecma262/#sec-promise.reject
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::reject)
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::reject)
 {
 {
+    auto reason = vm.argument(0);
+
+    // 1. Let C be the this value.
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
     auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
+
+    // 2. Let promiseCapability be ? NewPromiseCapability(C).
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
     auto promise_capability = TRY(new_promise_capability(global_object, constructor));
-    auto reason = vm.argument(0);
+
+    // 3. Perform ? Call(promiseCapability.[[Reject]], undefined, « r »).
     [[maybe_unused]] auto result = TRY(vm.call(*promise_capability.reject, js_undefined(), reason));
     [[maybe_unused]] auto result = TRY(vm.call(*promise_capability.reject, js_undefined(), reason));
+
+    // 4. Return promiseCapability.[[Promise]].
     return promise_capability.promise;
     return promise_capability.promise;
 }
 }
 
 
 // 27.2.4.7 Promise.resolve ( x ), https://tc39.es/ecma262/#sec-promise.resolve
 // 27.2.4.7 Promise.resolve ( x ), https://tc39.es/ecma262/#sec-promise.resolve
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::resolve)
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::resolve)
 {
 {
-    auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
     auto value = vm.argument(0);
     auto value = vm.argument(0);
+
+    // 1. Let C be the this value.
+    // 2. If Type(C) is not Object, throw a TypeError exception.
+    // FIXME: Don't coerce to object!
+    auto* constructor = TRY(vm.this_value(global_object).to_object(global_object));
+
+    // 3. Return ? PromiseResolve(C, x).
     return TRY(promise_resolve(global_object, *constructor, value));
     return TRY(promise_resolve(global_object, *constructor, value));
 }
 }
 
 
 // 27.2.4.8 get Promise [ @@species ], https://tc39.es/ecma262/#sec-get-promise-@@species
 // 27.2.4.8 get Promise [ @@species ], https://tc39.es/ecma262/#sec-get-promise-@@species
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::symbol_species_getter)
 JS_DEFINE_NATIVE_FUNCTION(PromiseConstructor::symbol_species_getter)
 {
 {
+    // 1. Return the this value.
     return vm.this_value(global_object);
     return vm.this_value(global_object);
 }
 }
 
 

+ 52 - 8
Userland/Libraries/LibJS/Runtime/PromiseJobs.cpp

@@ -29,47 +29,78 @@ PromiseReactionJob::PromiseReactionJob(PromiseReaction& reaction, Value argument
 ThrowCompletionOr<Value> PromiseReactionJob::call()
 ThrowCompletionOr<Value> PromiseReactionJob::call()
 {
 {
     auto& vm = this->vm();
     auto& vm = this->vm();
+
+    // a. Let promiseCapability be reaction.[[Capability]].
     auto& promise_capability = m_reaction.capability();
     auto& promise_capability = m_reaction.capability();
+
+    // b. Let type be reaction.[[Type]].
     auto type = m_reaction.type();
     auto type = m_reaction.type();
+
+    // c. Let handler be reaction.[[Handler]].
     auto handler = m_reaction.handler();
     auto handler = m_reaction.handler();
+
     Value handler_result;
     Value handler_result;
+
+    // d. If handler is empty, then
     if (!handler.has_value()) {
     if (!handler.has_value()) {
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Handler is empty", this);
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Handler is empty", this);
-        switch (type) {
-        case PromiseReaction::Type::Fulfill:
+
+        // i. If type is Fulfill, let handlerResult be NormalCompletion(argument).
+        if (type == PromiseReaction::Type::Fulfill) {
             dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Reaction type is Type::Fulfill, setting handler result to {}", this, m_argument);
             dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Reaction type is Type::Fulfill, setting handler result to {}", this, m_argument);
             handler_result = m_argument;
             handler_result = m_argument;
-            break;
-        case PromiseReaction::Type::Reject:
+        }
+        // ii. Else,
+        else {
+            // 1. Assert: type is Reject.
+            VERIFY(type == PromiseReaction::Type::Reject);
+
+            // 2. Let handlerResult be ThrowCompletion(argument).
+            // NOTE: handler_result is set to exception value further below
             dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Reaction type is Type::Reject, throwing exception with argument {}", this, m_argument);
             dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Reaction type is Type::Reject, throwing exception with argument {}", this, m_argument);
             vm.throw_exception(global_object(), m_argument);
             vm.throw_exception(global_object(), m_argument);
-            // handler_result is set to exception value further below
-            break;
         }
         }
-    } else {
+    }
+    // e. Else, let handlerResult be HostCallJobCallback(handler, undefined, « argument »).
+    else {
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Calling handler callback {} @ {} with argument {}", this, handler.value().callback->class_name(), handler.value().callback, m_argument);
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Calling handler callback {} @ {} with argument {}", this, handler.value().callback->class_name(), handler.value().callback, m_argument);
         handler_result = call_job_callback(vm, handler.value(), js_undefined(), m_argument);
         handler_result = call_job_callback(vm, handler.value(), js_undefined(), m_argument);
     }
     }
 
 
+    // f. If promiseCapability is undefined, then
     if (!promise_capability.has_value()) {
     if (!promise_capability.has_value()) {
+        // i. Assert: handlerResult is not an abrupt completion.
+        VERIFY(!vm.exception());
+
+        // ii. Return NormalCompletion(empty).
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Reaction has no PromiseCapability, returning empty value", this);
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Reaction has no PromiseCapability, returning empty value", this);
         // TODO: This can't return an empty value at the moment, because the implicit conversion to Completion would fail.
         // TODO: This can't return an empty value at the moment, because the implicit conversion to Completion would fail.
         //       Change it back when this is using completions (`return normal_completion({})`)
         //       Change it back when this is using completions (`return normal_completion({})`)
         return js_undefined();
         return js_undefined();
     }
     }
 
 
+    // g. Assert: promiseCapability is a PromiseCapability Record.
+
+    // h. If handlerResult is an abrupt completion, then
     if (vm.exception()) {
     if (vm.exception()) {
         handler_result = vm.exception()->value();
         handler_result = vm.exception()->value();
         vm.clear_exception();
         vm.clear_exception();
         vm.stop_unwind();
         vm.stop_unwind();
+
+        // i. Let status be Call(promiseCapability.[[Reject]], undefined, « handlerResult.[[Value]] »).
         auto* reject_function = promise_capability.value().reject;
         auto* reject_function = promise_capability.value().reject;
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Calling PromiseCapability's reject function @ {}", this, reject_function);
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Calling PromiseCapability's reject function @ {}", this, reject_function);
         return vm.call(*reject_function, js_undefined(), handler_result);
         return vm.call(*reject_function, js_undefined(), handler_result);
-    } else {
+    }
+    // i. Else,
+    else {
+        // i. Let status be Call(promiseCapability.[[Resolve]], undefined, « handlerResult.[[Value]] »).
         auto* resolve_function = promise_capability.value().resolve;
         auto* resolve_function = promise_capability.value().resolve;
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Calling PromiseCapability's resolve function @ {}", this, resolve_function);
         dbgln_if(PROMISE_DEBUG, "[PromiseReactionJob @ {}]: Calling PromiseCapability's resolve function @ {}", this, resolve_function);
         return vm.call(*resolve_function, js_undefined(), handler_result);
         return vm.call(*resolve_function, js_undefined(), handler_result);
     }
     }
+
+    // j. Return Completion(status).
 }
 }
 
 
 void PromiseReactionJob::visit_edges(Visitor& visitor)
 void PromiseReactionJob::visit_edges(Visitor& visitor)
@@ -97,16 +128,29 @@ PromiseResolveThenableJob::PromiseResolveThenableJob(Promise& promise_to_resolve
 ThrowCompletionOr<Value> PromiseResolveThenableJob::call()
 ThrowCompletionOr<Value> PromiseResolveThenableJob::call()
 {
 {
     auto& vm = this->vm();
     auto& vm = this->vm();
+
+    // a. Let resolvingFunctions be CreateResolvingFunctions(promiseToResolve).
     auto [resolve_function, reject_function] = m_promise_to_resolve.create_resolving_functions();
     auto [resolve_function, reject_function] = m_promise_to_resolve.create_resolving_functions();
+
+    // b. Let thenCallResult be HostCallJobCallback(then, thenable, « resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]] »).
     dbgln_if(PROMISE_DEBUG, "[PromiseResolveThenableJob @ {}]: Calling then job callback for thenable {}", this, &m_thenable);
     dbgln_if(PROMISE_DEBUG, "[PromiseResolveThenableJob @ {}]: Calling then job callback for thenable {}", this, &m_thenable);
     auto then_call_result = call_job_callback(vm, m_then, m_thenable, &resolve_function, &reject_function);
     auto then_call_result = call_job_callback(vm, m_then, m_thenable, &resolve_function, &reject_function);
+
+    // c. If thenCallResult is an abrupt completion, then
     if (vm.exception()) {
     if (vm.exception()) {
         auto error = vm.exception()->value();
         auto error = vm.exception()->value();
         vm.clear_exception();
         vm.clear_exception();
         vm.stop_unwind();
         vm.stop_unwind();
+
+        // i. Let status be Call(resolvingFunctions.[[Reject]], undefined, « thenCallResult.[[Value]] »).
+        // FIXME: Actually do this... not sure why we don't? :yakfused:
+
+        // ii. Return Completion(status).
         dbgln_if(PROMISE_DEBUG, "[PromiseResolveThenableJob @ {}]: An exception was thrown, returning error {}", this, error);
         dbgln_if(PROMISE_DEBUG, "[PromiseResolveThenableJob @ {}]: An exception was thrown, returning error {}", this, error);
         return error;
         return error;
     }
     }
+
+    // d. Return Completion(thenCallResult).
     dbgln_if(PROMISE_DEBUG, "[PromiseResolveThenableJob @ {}]: Returning then call result {}", this, then_call_result);
     dbgln_if(PROMISE_DEBUG, "[PromiseResolveThenableJob @ {}]: Returning then call result {}", this, then_call_result);
     return then_call_result;
     return then_call_result;
 }
 }

+ 60 - 8
Userland/Libraries/LibJS/Runtime/PromisePrototype.cpp

@@ -38,66 +38,118 @@ void PromisePrototype::initialize(GlobalObject& global_object)
 // 27.2.5.4 Promise.prototype.then ( onFulfilled, onRejected ), https://tc39.es/ecma262/#sec-promise.prototype.then
 // 27.2.5.4 Promise.prototype.then ( onFulfilled, onRejected ), https://tc39.es/ecma262/#sec-promise.prototype.then
 JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::then)
 JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::then)
 {
 {
-    auto* promise = TRY(typed_this_object(global_object));
     auto on_fulfilled = vm.argument(0);
     auto on_fulfilled = vm.argument(0);
     auto on_rejected = vm.argument(1);
     auto on_rejected = vm.argument(1);
+
+    // 1. Let promise be the this value.
+    // 2. If IsPromise(promise) is false, throw a TypeError exception.
+    auto* promise = TRY(typed_this_object(global_object));
+
+    // 3. Let C be ? SpeciesConstructor(promise, %Promise%).
     auto* constructor = TRY(species_constructor(global_object, *promise, *global_object.promise_constructor()));
     auto* constructor = TRY(species_constructor(global_object, *promise, *global_object.promise_constructor()));
+
+    // 4. Let resultCapability be ? NewPromiseCapability(C).
     auto result_capability = TRY(new_promise_capability(global_object, constructor));
     auto result_capability = TRY(new_promise_capability(global_object, constructor));
+
+    // 5. Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability).
     return promise->perform_then(on_fulfilled, on_rejected, result_capability);
     return promise->perform_then(on_fulfilled, on_rejected, result_capability);
 }
 }
 
 
 // 27.2.5.1 Promise.prototype.catch ( onRejected ), https://tc39.es/ecma262/#sec-promise.prototype.catch
 // 27.2.5.1 Promise.prototype.catch ( onRejected ), https://tc39.es/ecma262/#sec-promise.prototype.catch
 JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::catch_)
 JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::catch_)
 {
 {
-    auto this_value = vm.this_value(global_object);
     auto on_rejected = vm.argument(0);
     auto on_rejected = vm.argument(0);
+
+    // 1. Let promise be the this value.
+    auto this_value = vm.this_value(global_object);
+
+    // 2. Return ? Invoke(promise, "then", « undefined, onRejected »).
     return TRY(this_value.invoke(global_object, vm.names.then, js_undefined(), on_rejected));
     return TRY(this_value.invoke(global_object, vm.names.then, js_undefined(), on_rejected));
 }
 }
 
 
 // 27.2.5.3 Promise.prototype.finally ( onFinally ), https://tc39.es/ecma262/#sec-promise.prototype.finally
 // 27.2.5.3 Promise.prototype.finally ( onFinally ), https://tc39.es/ecma262/#sec-promise.prototype.finally
 JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::finally)
 JS_DEFINE_NATIVE_FUNCTION(PromisePrototype::finally)
 {
 {
+    auto on_finally = vm.argument(0);
+
+    // 1. Let promise be the this value.
+    // 2. If Type(promise) is not Object, throw a TypeError exception.
+    // FIXME: Don't coerce to object!
     auto* promise = TRY(vm.this_value(global_object).to_object(global_object));
     auto* promise = TRY(vm.this_value(global_object).to_object(global_object));
+
+    // 3. Let C be ? SpeciesConstructor(promise, %Promise%).
     auto* constructor = TRY(species_constructor(global_object, *promise, *global_object.promise_constructor()));
     auto* constructor = TRY(species_constructor(global_object, *promise, *global_object.promise_constructor()));
+
+    // 4. Assert: IsConstructor(C) is true.
+    VERIFY(constructor);
+
     Value then_finally;
     Value then_finally;
     Value catch_finally;
     Value catch_finally;
-    auto on_finally = vm.argument(0);
+
+    // 5. If IsCallable(onFinally) is false, then
     if (!on_finally.is_function()) {
     if (!on_finally.is_function()) {
+        // a. Let thenFinally be onFinally.
         then_finally = on_finally;
         then_finally = on_finally;
+
+        // b. Let catchFinally be onFinally.
         catch_finally = on_finally;
         catch_finally = on_finally;
-    } else {
-        // 27.2.5.3.1 Then Finally Functions, https://tc39.es/ecma262/#sec-thenfinallyfunctions
+    }
+    // 6. Else,
+    else {
+        // a. Let thenFinallyClosure be a new Abstract Closure with parameters (value) that captures onFinally and C and performs the following steps when called:
+        // b. Let thenFinally be ! CreateBuiltinFunction(thenFinallyClosure, 1, "", « »).
         auto* then_finally_function = NativeFunction::create(global_object, "", [constructor_handle = make_handle(constructor), on_finally_handle = make_handle(&on_finally.as_function())](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
         auto* then_finally_function = NativeFunction::create(global_object, "", [constructor_handle = make_handle(constructor), on_finally_handle = make_handle(&on_finally.as_function())](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
             auto& constructor = const_cast<FunctionObject&>(*constructor_handle.cell());
             auto& constructor = const_cast<FunctionObject&>(*constructor_handle.cell());
             auto& on_finally = const_cast<FunctionObject&>(*on_finally_handle.cell());
             auto& on_finally = const_cast<FunctionObject&>(*on_finally_handle.cell());
             auto value = vm.argument(0);
             auto value = vm.argument(0);
+
+            // i. Let result be ? Call(onFinally, undefined).
             auto result = TRY(vm.call(on_finally, js_undefined()));
             auto result = TRY(vm.call(on_finally, js_undefined()));
+
+            // ii. Let promise be ? PromiseResolve(C, result).
             auto* promise = TRY(promise_resolve(global_object, constructor, result));
             auto* promise = TRY(promise_resolve(global_object, constructor, result));
+
+            // iii. Let returnValue be a new Abstract Closure with no parameters that captures value and performs the following steps when called:
+            // iv. Let valueThunk be ! CreateBuiltinFunction(returnValue, 0, "", « »).
             auto* value_thunk = NativeFunction::create(global_object, "", [value](auto&, auto&) -> ThrowCompletionOr<Value> {
             auto* value_thunk = NativeFunction::create(global_object, "", [value](auto&, auto&) -> ThrowCompletionOr<Value> {
+                // 1. Return value.
                 return value;
                 return value;
             });
             });
+
+            // v. Return ? Invoke(promise, "then", « valueThunk »).
             return TRY(Value(promise).invoke(global_object, vm.names.then, value_thunk));
             return TRY(Value(promise).invoke(global_object, vm.names.then, value_thunk));
         });
         });
         then_finally_function->define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
         then_finally_function->define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
+        then_finally = Value(then_finally_function);
 
 
-        // 27.2.5.3.2 Catch Finally Functions, https://tc39.es/ecma262/#sec-catchfinallyfunctions
+        // c. Let catchFinallyClosure be a new Abstract Closure with parameters (reason) that captures onFinally and C and performs the following steps when called:
+        // d. Let catchFinally be ! CreateBuiltinFunction(catchFinallyClosure, 1, "", « »).
         auto* catch_finally_function = NativeFunction::create(global_object, "", [constructor_handle = make_handle(constructor), on_finally_handle = make_handle(&on_finally.as_function())](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
         auto* catch_finally_function = NativeFunction::create(global_object, "", [constructor_handle = make_handle(constructor), on_finally_handle = make_handle(&on_finally.as_function())](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
             auto& constructor = const_cast<FunctionObject&>(*constructor_handle.cell());
             auto& constructor = const_cast<FunctionObject&>(*constructor_handle.cell());
             auto& on_finally = const_cast<FunctionObject&>(*on_finally_handle.cell());
             auto& on_finally = const_cast<FunctionObject&>(*on_finally_handle.cell());
             auto reason = vm.argument(0);
             auto reason = vm.argument(0);
+
+            // i. Let result be ? Call(onFinally, undefined).
             auto result = TRY(vm.call(on_finally, js_undefined()));
             auto result = TRY(vm.call(on_finally, js_undefined()));
+
+            // ii. Let promise be ? PromiseResolve(C, result).
             auto* promise = TRY(promise_resolve(global_object, constructor, result));
             auto* promise = TRY(promise_resolve(global_object, constructor, result));
+
+            // iv. Let thrower be ! CreateBuiltinFunction(throwReason, 0, "", « »).
             auto* thrower = NativeFunction::create(global_object, "", [reason](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
             auto* thrower = NativeFunction::create(global_object, "", [reason](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
+                // 1. Return ThrowCompletion(reason).
                 vm.throw_exception(global_object, reason);
                 vm.throw_exception(global_object, reason);
                 return throw_completion(reason);
                 return throw_completion(reason);
             });
             });
+
+            // v. Return ? Invoke(promise, "then", « thrower »).
             return TRY(Value(promise).invoke(global_object, vm.names.then, thrower));
             return TRY(Value(promise).invoke(global_object, vm.names.then, thrower));
         });
         });
         catch_finally_function->define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
         catch_finally_function->define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
-
-        then_finally = Value(then_finally_function);
         catch_finally = Value(catch_finally_function);
         catch_finally = Value(catch_finally_function);
     }
     }
+
+    // 7. Return ? Invoke(promise, "then", « thenFinally, catchFinally »).
     return TRY(Value(promise).invoke(global_object, vm.names.then, then_finally, catch_finally));
     return TRY(Value(promise).invoke(global_object, vm.names.then, then_finally, catch_finally));
 }
 }
 
 

+ 27 - 5
Userland/Libraries/LibJS/Runtime/PromiseReaction.cpp

@@ -16,41 +16,63 @@ namespace JS {
 ThrowCompletionOr<PromiseCapability> new_promise_capability(GlobalObject& global_object, Value constructor)
 ThrowCompletionOr<PromiseCapability> new_promise_capability(GlobalObject& global_object, Value constructor)
 {
 {
     auto& vm = global_object.vm();
     auto& vm = global_object.vm();
+
+    // 1. If IsConstructor(C) is false, throw a TypeError exception.
     if (!constructor.is_constructor())
     if (!constructor.is_constructor())
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, constructor.to_string_without_side_effects());
 
 
+    // 2. NOTE: C is assumed to be a constructor function that supports the parameter conventions of the Promise constructor (see 27.2.3.1).
+
+    // 3. Let promiseCapability be the PromiseCapability Record { [[Promise]]: undefined, [[Resolve]]: undefined, [[Reject]]: undefined }.
+    // FIXME: This should not be stack-allocated, the executor function below can be captured and outlive it!
+    //        See https://discord.com/channels/830522505605283862/886211697843531866/900081190621569154 for some discussion.
     struct {
     struct {
         Value resolve { js_undefined() };
         Value resolve { js_undefined() };
         Value reject { js_undefined() };
         Value reject { js_undefined() };
     } promise_capability_functions;
     } promise_capability_functions;
 
 
-    // 27.2.1.5.1 GetCapabilitiesExecutor Functions, https://tc39.es/ecma262/#sec-getcapabilitiesexecutor-functions
+    // 4. Let executorClosure be a new Abstract Closure with parameters (resolve, reject) that captures promiseCapability and performs the following steps when called:
+    // 5. Let executor be ! CreateBuiltinFunction(executorClosure, 2, "", « »).
     auto* executor = NativeFunction::create(global_object, "", [&promise_capability_functions](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
     auto* executor = NativeFunction::create(global_object, "", [&promise_capability_functions](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
         auto resolve = vm.argument(0);
         auto resolve = vm.argument(0);
         auto reject = vm.argument(1);
         auto reject = vm.argument(1);
+
         // No idea what other engines say here.
         // No idea what other engines say here.
-        if (!promise_capability_functions.resolve.is_undefined()) {
+        // a. If promiseCapability.[[Resolve]] is not undefined, throw a TypeError exception.
+        if (!promise_capability_functions.resolve.is_undefined())
             return vm.template throw_completion<TypeError>(global_object, ErrorType::GetCapabilitiesExecutorCalledMultipleTimes);
             return vm.template throw_completion<TypeError>(global_object, ErrorType::GetCapabilitiesExecutorCalledMultipleTimes);
-        }
-        if (!promise_capability_functions.reject.is_undefined()) {
+
+        // b. If promiseCapability.[[Reject]] is not undefined, throw a TypeError exception.
+        if (!promise_capability_functions.reject.is_undefined())
             return vm.template throw_completion<TypeError>(global_object, ErrorType::GetCapabilitiesExecutorCalledMultipleTimes);
             return vm.template throw_completion<TypeError>(global_object, ErrorType::GetCapabilitiesExecutorCalledMultipleTimes);
-        }
+
+        // c. Set promiseCapability.[[Resolve]] to resolve.
         promise_capability_functions.resolve = resolve;
         promise_capability_functions.resolve = resolve;
+
+        // d. Set promiseCapability.[[Reject]] to reject.
         promise_capability_functions.reject = reject;
         promise_capability_functions.reject = reject;
+
+        // e. Return undefined.
         return js_undefined();
         return js_undefined();
     });
     });
     executor->define_direct_property(vm.names.length, Value(2), Attribute::Configurable);
     executor->define_direct_property(vm.names.length, Value(2), Attribute::Configurable);
     executor->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
     executor->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
 
 
+    // 6. Let promise be ? Construct(C, « executor »).
     MarkedValueList arguments(vm.heap());
     MarkedValueList arguments(vm.heap());
     arguments.append(executor);
     arguments.append(executor);
     auto* promise = TRY(construct(global_object, constructor.as_function(), move(arguments)));
     auto* promise = TRY(construct(global_object, constructor.as_function(), move(arguments)));
 
 
+    // 7. If IsCallable(promiseCapability.[[Resolve]]) is false, throw a TypeError exception.
     if (!promise_capability_functions.resolve.is_function())
     if (!promise_capability_functions.resolve.is_function())
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, promise_capability_functions.resolve.to_string_without_side_effects());
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, promise_capability_functions.resolve.to_string_without_side_effects());
+
+    // 8. If IsCallable(promiseCapability.[[Reject]]) is false, throw a TypeError exception.
     if (!promise_capability_functions.reject.is_function())
     if (!promise_capability_functions.reject.is_function())
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, promise_capability_functions.reject.to_string_without_side_effects());
         return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, promise_capability_functions.reject.to_string_without_side_effects());
 
 
+    // 9. Set promiseCapability.[[Promise]] to promise.
+    // 10. Return promiseCapability.
     return PromiseCapability {
     return PromiseCapability {
         promise,
         promise,
         &promise_capability_functions.resolve.as_function(),
         &promise_capability_functions.resolve.as_function(),

+ 41 - 4
Userland/Libraries/LibJS/Runtime/PromiseResolvingElementFunctions.cpp

@@ -63,13 +63,20 @@ Value PromiseAllResolveElementFunction::resolve_element()
     auto& vm = this->vm();
     auto& vm = this->vm();
     auto& global_object = this->global_object();
     auto& global_object = this->global_object();
 
 
+    // 8. Set values[index] to x.
     m_values.values()[m_index] = vm.argument(0);
     m_values.values()[m_index] = vm.argument(0);
 
 
+    // 9. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
+    // 10. If remainingElementsCount.[[Value]] is 0, then
     if (--m_remaining_elements.value == 0) {
     if (--m_remaining_elements.value == 0) {
-        auto values_array = Array::create_from(global_object, m_values.values());
+        // a. Let valuesArray be ! CreateArrayFromList(values).
+        auto* values_array = Array::create_from(global_object, m_values.values());
+
+        // b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
         return TRY_OR_DISCARD(vm.call(*m_capability.resolve, js_undefined(), values_array));
         return TRY_OR_DISCARD(vm.call(*m_capability.resolve, js_undefined(), values_array));
     }
     }
 
 
+    // 11. Return undefined.
     return js_undefined();
     return js_undefined();
 }
 }
 
 
@@ -88,17 +95,29 @@ Value PromiseAllSettledResolveElementFunction::resolve_element()
     auto& vm = this->vm();
     auto& vm = this->vm();
     auto& global_object = this->global_object();
     auto& global_object = this->global_object();
 
 
+    // 9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
     auto* object = Object::create(global_object, global_object.object_prototype());
     auto* object = Object::create(global_object, global_object.object_prototype());
+
+    // 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "fulfilled").
     MUST(object->create_data_property_or_throw(vm.names.status, js_string(vm, "fulfilled"sv)));
     MUST(object->create_data_property_or_throw(vm.names.status, js_string(vm, "fulfilled"sv)));
+
+    // 11. Perform ! CreateDataPropertyOrThrow(obj, "value", x).
     MUST(object->create_data_property_or_throw(vm.names.value, vm.argument(0)));
     MUST(object->create_data_property_or_throw(vm.names.value, vm.argument(0)));
 
 
+    // 12. Set values[index] to obj.
     m_values.values()[m_index] = object;
     m_values.values()[m_index] = object;
 
 
+    // 13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
+    // 14. If remainingElementsCount.[[Value]] is 0, then
     if (--m_remaining_elements.value == 0) {
     if (--m_remaining_elements.value == 0) {
-        auto values_array = Array::create_from(global_object, m_values.values());
+        // a. Let valuesArray be ! CreateArrayFromList(values).
+        auto* values_array = Array::create_from(global_object, m_values.values());
+
+        // b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
         return TRY_OR_DISCARD(vm.call(*m_capability.resolve, js_undefined(), values_array));
         return TRY_OR_DISCARD(vm.call(*m_capability.resolve, js_undefined(), values_array));
     }
     }
 
 
+    // 15. Return undefined.
     return js_undefined();
     return js_undefined();
 }
 }
 
 
@@ -117,17 +136,29 @@ Value PromiseAllSettledRejectElementFunction::resolve_element()
     auto& vm = this->vm();
     auto& vm = this->vm();
     auto& global_object = this->global_object();
     auto& global_object = this->global_object();
 
 
+    // 9. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
     auto* object = Object::create(global_object, global_object.object_prototype());
     auto* object = Object::create(global_object, global_object.object_prototype());
+
+    // 10. Perform ! CreateDataPropertyOrThrow(obj, "status", "rejected").
     MUST(object->create_data_property_or_throw(vm.names.status, js_string(vm, "rejected"sv)));
     MUST(object->create_data_property_or_throw(vm.names.status, js_string(vm, "rejected"sv)));
+
+    // 11. Perform ! CreateDataPropertyOrThrow(obj, "reason", x).
     MUST(object->create_data_property_or_throw(vm.names.reason, vm.argument(0)));
     MUST(object->create_data_property_or_throw(vm.names.reason, vm.argument(0)));
 
 
+    // 12. Set values[index] to obj.
     m_values.values()[m_index] = object;
     m_values.values()[m_index] = object;
 
 
+    // 13. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
+    // 14. If remainingElementsCount.[[Value]] is 0, then
     if (--m_remaining_elements.value == 0) {
     if (--m_remaining_elements.value == 0) {
+        // a. Let valuesArray be ! CreateArrayFromList(values).
         auto values_array = Array::create_from(global_object, m_values.values());
         auto values_array = Array::create_from(global_object, m_values.values());
+
+        // b. Return ? Call(promiseCapability.[[Resolve]], undefined, « valuesArray »).
         return TRY_OR_DISCARD(vm.call(*m_capability.resolve, js_undefined(), values_array));
         return TRY_OR_DISCARD(vm.call(*m_capability.resolve, js_undefined(), values_array));
     }
     }
 
 
+    // 15. Return undefined.
     return js_undefined();
     return js_undefined();
 }
 }
 
 
@@ -146,14 +177,20 @@ Value PromiseAnyRejectElementFunction::resolve_element()
     auto& vm = this->vm();
     auto& vm = this->vm();
     auto& global_object = this->global_object();
     auto& global_object = this->global_object();
 
 
+    // 8. Set errors[index] to x.
     m_values.values()[m_index] = vm.argument(0);
     m_values.values()[m_index] = vm.argument(0);
 
 
+    // 9. Set remainingElementsCount.[[Value]] to remainingElementsCount.[[Value]] - 1.
+    // 10. If remainingElementsCount.[[Value]] is 0, then
     if (--m_remaining_elements.value == 0) {
     if (--m_remaining_elements.value == 0) {
-        auto errors_array = Array::create_from(global_object, m_values.values());
-
+        // a. Let error be a newly created AggregateError object.
         auto* error = AggregateError::create(global_object);
         auto* error = AggregateError::create(global_object);
+
+        // b. Perform ! DefinePropertyOrThrow(error, "errors", PropertyDescriptor { [[Configurable]]: true, [[Enumerable]]: false, [[Writable]]: true, [[Value]]: ! CreateArrayFromList(errors) }).
+        auto errors_array = Array::create_from(global_object, m_values.values());
         MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
         MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
 
 
+        // c. Return ? Call(promiseCapability.[[Reject]], undefined, « error »).
         return TRY_OR_DISCARD(vm.call(*m_capability.reject, js_undefined(), error));
         return TRY_OR_DISCARD(vm.call(*m_capability.reject, js_undefined(), error));
     }
     }