Promise.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/Function.h>
  8. #include <AK/Optional.h>
  9. #include <AK/TypeCasts.h>
  10. #include <LibJS/Runtime/Error.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/JobCallback.h>
  13. #include <LibJS/Runtime/Promise.h>
  14. #include <LibJS/Runtime/PromiseJobs.h>
  15. #include <LibJS/Runtime/PromiseReaction.h>
  16. #include <LibJS/Runtime/PromiseResolvingFunction.h>
  17. namespace JS {
  18. // 27.2.4.7.1 PromiseResolve ( C, x ), https://tc39.es/ecma262/#sec-promise-resolve
  19. ThrowCompletionOr<Object*> promise_resolve(GlobalObject& global_object, Object& constructor, Value value)
  20. {
  21. auto& vm = global_object.vm();
  22. // 1. If IsPromise(x) is true, then
  23. if (value.is_object() && is<Promise>(value.as_object())) {
  24. // a. Let xConstructor be ? Get(x, "constructor").
  25. auto value_constructor = TRY(value.as_object().get(vm.names.constructor));
  26. // b. If SameValue(xConstructor, C) is true, return x.
  27. if (same_value(value_constructor, &constructor))
  28. return &static_cast<Promise&>(value.as_object());
  29. }
  30. // 2. Let promiseCapability be ? NewPromiseCapability(C).
  31. auto promise_capability = TRY(new_promise_capability(global_object, &constructor));
  32. // 3. Perform ? Call(promiseCapability.[[Resolve]], undefined, « x »).
  33. (void)TRY(call(global_object, *promise_capability.resolve, js_undefined(), value));
  34. // 4. Return promiseCapability.[[Promise]].
  35. return promise_capability.promise;
  36. }
  37. Promise* Promise::create(GlobalObject& global_object)
  38. {
  39. return global_object.heap().allocate<Promise>(global_object, *global_object.promise_prototype());
  40. }
  41. // 27.2 Promise Objects, https://tc39.es/ecma262/#sec-promise-objects
  42. Promise::Promise(Object& prototype)
  43. : Object(prototype)
  44. {
  45. }
  46. // 27.2.1.3 CreateResolvingFunctions ( promise ), https://tc39.es/ecma262/#sec-createresolvingfunctions
  47. Promise::ResolvingFunctions Promise::create_resolving_functions()
  48. {
  49. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / create_resolving_functions()]", this);
  50. auto& vm = this->vm();
  51. // 1. Let alreadyResolved be the Record { [[Value]]: false }.
  52. auto* already_resolved = vm.heap().allocate_without_global_object<AlreadyResolved>();
  53. // 2. Let stepsResolve be the algorithm steps defined in Promise Resolve Functions.
  54. // 3. Let lengthResolve be the number of non-optional parameters of the function definition in Promise Resolve Functions.
  55. // 4. Let resolve be ! CreateBuiltinFunction(stepsResolve, lengthResolve, "", « [[Promise]], [[AlreadyResolved]] »).
  56. // 5. Set resolve.[[Promise]] to promise.
  57. // 6. Set resolve.[[AlreadyResolved]] to alreadyResolved.
  58. // 27.2.1.3.2 Promise Resolve Functions, https://tc39.es/ecma262/#sec-promise-resolve-functions
  59. auto* resolve_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto& global_object, auto& promise, auto& already_resolved) {
  60. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolve function was called", &promise);
  61. auto resolution = vm.argument(0);
  62. // 1. Let F be the active function object.
  63. // 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  64. // 3. Let promise be F.[[Promise]].
  65. // 4. Let alreadyResolved be F.[[AlreadyResolved]].
  66. // 5. If alreadyResolved.[[Value]] is true, return undefined.
  67. if (already_resolved.value) {
  68. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise is already resolved, returning undefined", &promise);
  69. return js_undefined();
  70. }
  71. // 6. Set alreadyResolved.[[Value]] to true.
  72. already_resolved.value = true;
  73. // 7. If SameValue(resolution, promise) is true, then
  74. if (resolution.is_object() && &resolution.as_object() == &promise) {
  75. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise can't be resolved with itself, rejecting with error", &promise);
  76. // a. Let selfResolutionError be a newly created TypeError object.
  77. auto* self_resolution_error = TypeError::create(global_object, "Cannot resolve promise with itself");
  78. // b. Return RejectPromise(promise, selfResolutionError).
  79. return promise.reject(self_resolution_error);
  80. }
  81. // 8. If Type(resolution) is not Object, then
  82. if (!resolution.is_object()) {
  83. // a. Return FulfillPromise(promise, resolution).
  84. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolution is not an object, fulfilling with {}", &promise, resolution);
  85. return promise.fulfill(resolution);
  86. }
  87. // 9. Let then be Get(resolution, "then").
  88. auto then = resolution.as_object().get(vm.names.then);
  89. // 10. If then is an abrupt completion, then
  90. if (then.is_throw_completion()) {
  91. // a. Return RejectPromise(promise, then.[[Value]]).
  92. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Exception while getting 'then' property, rejecting with error", &promise);
  93. return promise.reject(*then.throw_completion().value());
  94. }
  95. // 11. Let thenAction be then.[[Value]].
  96. auto then_action = then.release_value();
  97. // 12. If IsCallable(thenAction) is false, then
  98. if (!then_action.is_function()) {
  99. // a. Return FulfillPromise(promise, resolution).
  100. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Then action is not a function, fulfilling with {}", &promise, resolution);
  101. return promise.fulfill(resolution);
  102. }
  103. // 13. Let thenJobCallback be HostMakeJobCallback(thenAction).
  104. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating JobCallback for then action @ {}", &promise, &then_action.as_function());
  105. auto then_job_callback = vm.host_make_job_callback(then_action.as_function());
  106. // 14. Let job be NewPromiseResolveThenableJob(promise, resolution, thenJobCallback).
  107. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating PromiseResolveThenableJob for thenable {}", &promise, resolution);
  108. auto [job, realm] = create_promise_resolve_thenable_job(global_object, promise, resolution, move(then_job_callback));
  109. // 15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  110. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Enqueuing job @ {} in realm {}", &promise, &job, realm);
  111. vm.host_enqueue_promise_job(move(job), realm);
  112. // 16. Return undefined.
  113. return js_undefined();
  114. });
  115. resolve_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  116. // 7. Let stepsReject be the algorithm steps defined in Promise Reject Functions.
  117. // 8. Let lengthReject be the number of non-optional parameters of the function definition in Promise Reject Functions.
  118. // 9. Let reject be ! CreateBuiltinFunction(stepsReject, lengthReject, "", « [[Promise]], [[AlreadyResolved]] »).
  119. // 10. Set reject.[[Promise]] to promise.
  120. // 11. Set reject.[[AlreadyResolved]] to alreadyResolved.
  121. // 27.2.1.3.1 Promise Reject Functions, https://tc39.es/ecma262/#sec-promise-reject-functions
  122. auto* reject_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto&, auto& promise, auto& already_resolved) {
  123. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Reject function was called", &promise);
  124. auto reason = vm.argument(0);
  125. // 1. Let F be the active function object.
  126. // 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  127. // 3. Let promise be F.[[Promise]].
  128. // 4. Let alreadyResolved be F.[[AlreadyResolved]].
  129. // 5. If alreadyResolved.[[Value]] is true, return undefined.
  130. if (already_resolved.value)
  131. return js_undefined();
  132. // 6. Set alreadyResolved.[[Value]] to true.
  133. already_resolved.value = true;
  134. // 7. Return RejectPromise(promise, reason).
  135. return promise.reject(reason);
  136. });
  137. reject_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  138. // 12. Return the Record { [[Resolve]]: resolve, [[Reject]]: reject }.
  139. return { *resolve_function, *reject_function };
  140. }
  141. // 27.2.1.4 FulfillPromise ( promise, value ), https://tc39.es/ecma262/#sec-fulfillpromise
  142. Value Promise::fulfill(Value value)
  143. {
  144. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / fulfill()]: Fulfilling promise with value {}", this, value);
  145. // 1. Assert: The value of promise.[[PromiseState]] is pending.
  146. VERIFY(m_state == State::Pending);
  147. VERIFY(!value.is_empty());
  148. // 2. Let reactions be promise.[[PromiseFulfillReactions]].
  149. // NOTE: This is a noop, we do these steps in a slightly different order.
  150. // 3. Set promise.[[PromiseResult]] to value.
  151. m_result = value;
  152. // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
  153. // 5. Set promise.[[PromiseRejectReactions]] to undefined.
  154. // 6. Set promise.[[PromiseState]] to fulfilled.
  155. m_state = State::Fulfilled;
  156. // 7. Return TriggerPromiseReactions(reactions, value).
  157. trigger_reactions();
  158. m_fulfill_reactions.clear();
  159. m_reject_reactions.clear();
  160. return js_undefined();
  161. }
  162. // 27.2.1.7 RejectPromise ( promise, reason ), https://tc39.es/ecma262/#sec-rejectpromise
  163. Value Promise::reject(Value reason)
  164. {
  165. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / reject()]: Rejecting promise with reason {}", this, reason);
  166. auto& vm = this->vm();
  167. // 1. Assert: The value of promise.[[PromiseState]] is pending.
  168. VERIFY(m_state == State::Pending);
  169. VERIFY(!reason.is_empty());
  170. // 2. Let reactions be promise.[[PromiseRejectReactions]].
  171. // NOTE: This is a noop, we do these steps in a slightly different order.
  172. // 3. Set promise.[[PromiseResult]] to reason.
  173. m_result = reason;
  174. // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
  175. // 5. Set promise.[[PromiseRejectReactions]] to undefined.
  176. // 6. Set promise.[[PromiseState]] to rejected.
  177. m_state = State::Rejected;
  178. // 7. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "reject").
  179. if (!m_is_handled)
  180. vm.host_promise_rejection_tracker(*this, RejectionOperation::Reject);
  181. // 8. Return TriggerPromiseReactions(reactions, reason).
  182. trigger_reactions();
  183. m_fulfill_reactions.clear();
  184. m_reject_reactions.clear();
  185. return js_undefined();
  186. }
  187. // 27.2.1.8 TriggerPromiseReactions ( reactions, argument ), https://tc39.es/ecma262/#sec-triggerpromisereactions
  188. void Promise::trigger_reactions() const
  189. {
  190. VERIFY(is_settled());
  191. auto& vm = this->vm();
  192. auto& reactions = m_state == State::Fulfilled
  193. ? m_fulfill_reactions
  194. : m_reject_reactions;
  195. // 1. For each element reaction of reactions, do
  196. for (auto& reaction : reactions) {
  197. // a. Let job be NewPromiseReactionJob(reaction, argument).
  198. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, &reaction, m_result);
  199. auto [job, realm] = create_promise_reaction_job(global_object(), *reaction, m_result);
  200. // b. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  201. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Enqueuing job @ {} in realm {}", this, &job, realm);
  202. vm.host_enqueue_promise_job(move(job), realm);
  203. }
  204. if constexpr (PROMISE_DEBUG) {
  205. if (reactions.is_empty())
  206. dbgln("[Promise @ {} / trigger_reactions()]: No reactions!", this);
  207. }
  208. // 2. Return undefined.
  209. }
  210. // 27.2.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] ), https://tc39.es/ecma262/#sec-performpromisethen
  211. Value Promise::perform_then(Value on_fulfilled, Value on_rejected, Optional<PromiseCapability> result_capability)
  212. {
  213. auto& vm = this->vm();
  214. // 1. Assert: IsPromise(promise) is true.
  215. // 2. If resultCapability is not present, then
  216. // a. Set resultCapability to undefined.
  217. // 3. If IsCallable(onFulfilled) is false, then
  218. // a. Let onFulfilledJobCallback be empty.
  219. Optional<JobCallback> on_fulfilled_job_callback;
  220. // 4. Else,
  221. if (on_fulfilled.is_function()) {
  222. // a. Let onFulfilledJobCallback be HostMakeJobCallback(onFulfilled).
  223. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_fulfilled function @ {}", this, &on_fulfilled.as_function());
  224. on_fulfilled_job_callback = vm.host_make_job_callback(on_fulfilled.as_function());
  225. }
  226. // 5. If IsCallable(onRejected) is false, then
  227. // a. Let onRejectedJobCallback be empty.
  228. Optional<JobCallback> on_rejected_job_callback;
  229. // 6. Else,
  230. if (on_rejected.is_function()) {
  231. // a. Let onRejectedJobCallback be HostMakeJobCallback(onRejected).
  232. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_rejected function @ {}", this, &on_rejected.as_function());
  233. on_rejected_job_callback = vm.host_make_job_callback(on_rejected.as_function());
  234. }
  235. // 7. Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Fulfill, [[Handler]]: onFulfilledJobCallback }.
  236. auto* fulfill_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Fulfill, result_capability, move(on_fulfilled_job_callback));
  237. // 8. Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Reject, [[Handler]]: onRejectedJobCallback }.
  238. auto* reject_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Reject, result_capability, move(on_rejected_job_callback));
  239. switch (m_state) {
  240. // 9. If promise.[[PromiseState]] is pending, then
  241. case Promise::State::Pending:
  242. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: state is State::Pending, adding fulfill/reject reactions", this);
  243. // a. Append fulfillReaction as the last element of the List that is promise.[[PromiseFulfillReactions]].
  244. m_fulfill_reactions.append(fulfill_reaction);
  245. // b. Append rejectReaction as the last element of the List that is promise.[[PromiseRejectReactions]].
  246. m_reject_reactions.append(reject_reaction);
  247. break;
  248. // 10. Else if promise.[[PromiseState]] is fulfilled, then
  249. case Promise::State::Fulfilled: {
  250. // a. Let value be promise.[[PromiseResult]].
  251. auto value = m_result;
  252. // b. Let fulfillJob be NewPromiseReactionJob(fulfillReaction, value).
  253. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Fulfilled, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, fulfill_reaction, value);
  254. auto [fulfill_job, realm] = create_promise_reaction_job(global_object(), *fulfill_reaction, value);
  255. // c. Perform HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]]).
  256. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &fulfill_job, realm);
  257. vm.host_enqueue_promise_job(move(fulfill_job), realm);
  258. break;
  259. }
  260. // 11. Else,
  261. case Promise::State::Rejected: {
  262. // a. Assert: The value of promise.[[PromiseState]] is rejected.
  263. // b. Let reason be promise.[[PromiseResult]].
  264. auto reason = m_result;
  265. // c. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "handle").
  266. if (!m_is_handled)
  267. vm.host_promise_rejection_tracker(*this, RejectionOperation::Handle);
  268. // d. Let rejectJob be NewPromiseReactionJob(rejectReaction, reason).
  269. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Rejected, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, reject_reaction, reason);
  270. auto [reject_job, realm] = create_promise_reaction_job(global_object(), *reject_reaction, reason);
  271. // e. Perform HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]]).
  272. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &reject_job, realm);
  273. vm.host_enqueue_promise_job(move(reject_job), realm);
  274. break;
  275. }
  276. default:
  277. VERIFY_NOT_REACHED();
  278. }
  279. // 12. Set promise.[[PromiseIsHandled]] to true.
  280. m_is_handled = true;
  281. // 13. If resultCapability is undefined, then
  282. if (!result_capability.has_value()) {
  283. // a. Return undefined.
  284. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: No ResultCapability, returning undefined", this);
  285. return js_undefined();
  286. }
  287. // 14. Else,
  288. // a. Return resultCapability.[[Promise]].
  289. auto* promise = result_capability.value().promise;
  290. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Returning Promise @ {} from ResultCapability @ {}", this, promise, &result_capability.value());
  291. return promise;
  292. }
  293. void Promise::visit_edges(Cell::Visitor& visitor)
  294. {
  295. Base::visit_edges(visitor);
  296. visitor.visit(m_result);
  297. for (auto& reaction : m_fulfill_reactions)
  298. visitor.visit(reaction);
  299. for (auto& reaction : m_reject_reactions)
  300. visitor.visit(reaction);
  301. }
  302. }