Promise.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /*
  2. * Copyright (c) 2021-2022, 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. Perform RejectPromise(promise, selfResolutionError).
  79. promise.reject(self_resolution_error);
  80. // c. Return undefined.
  81. return js_undefined();
  82. }
  83. // 8. If Type(resolution) is not Object, then
  84. if (!resolution.is_object()) {
  85. // a. Perform FulfillPromise(promise, resolution).
  86. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolution is not an object, fulfilling with {}", &promise, resolution);
  87. promise.fulfill(resolution);
  88. // b. Return undefined.
  89. return js_undefined();
  90. }
  91. // 9. Let then be Completion(Get(resolution, "then")).
  92. auto then = resolution.as_object().get(vm.names.then);
  93. // 10. If then is an abrupt completion, then
  94. if (then.is_throw_completion()) {
  95. // a. Perform RejectPromise(promise, then.[[Value]]).
  96. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Exception while getting 'then' property, rejecting with error", &promise);
  97. promise.reject(*then.throw_completion().value());
  98. // b. Return undefined.
  99. return js_undefined();
  100. }
  101. // 11. Let thenAction be then.[[Value]].
  102. auto then_action = then.release_value();
  103. // 12. If IsCallable(thenAction) is false, then
  104. if (!then_action.is_function()) {
  105. // a. Perform FulfillPromise(promise, resolution).
  106. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Then action is not a function, fulfilling with {}", &promise, resolution);
  107. promise.fulfill(resolution);
  108. // b. Return undefined.
  109. return js_undefined();
  110. }
  111. // 13. Let thenJobCallback be HostMakeJobCallback(thenAction).
  112. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating JobCallback for then action @ {}", &promise, &then_action.as_function());
  113. auto then_job_callback = vm.host_make_job_callback(then_action.as_function());
  114. // 14. Let job be NewPromiseResolveThenableJob(promise, resolution, thenJobCallback).
  115. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating PromiseResolveThenableJob for thenable {}", &promise, resolution);
  116. auto [job, realm] = create_promise_resolve_thenable_job(global_object, promise, resolution, move(then_job_callback));
  117. // 15. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  118. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Enqueuing job @ {} in realm {}", &promise, &job, realm);
  119. vm.host_enqueue_promise_job(move(job), realm);
  120. // 16. Return undefined.
  121. return js_undefined();
  122. });
  123. resolve_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  124. // 7. Let stepsReject be the algorithm steps defined in Promise Reject Functions.
  125. // 8. Let lengthReject be the number of non-optional parameters of the function definition in Promise Reject Functions.
  126. // 9. Let reject be CreateBuiltinFunction(stepsReject, lengthReject, "", « [[Promise]], [[AlreadyResolved]] »).
  127. // 10. Set reject.[[Promise]] to promise.
  128. // 11. Set reject.[[AlreadyResolved]] to alreadyResolved.
  129. // 27.2.1.3.1 Promise Reject Functions, https://tc39.es/ecma262/#sec-promise-reject-functions
  130. auto* reject_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto&, auto& promise, auto& already_resolved) {
  131. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Reject function was called", &promise);
  132. auto reason = vm.argument(0);
  133. // 1. Let F be the active function object.
  134. // 2. Assert: F has a [[Promise]] internal slot whose value is an Object.
  135. // 3. Let promise be F.[[Promise]].
  136. // 4. Let alreadyResolved be F.[[AlreadyResolved]].
  137. // 5. If alreadyResolved.[[Value]] is true, return undefined.
  138. if (already_resolved.value)
  139. return js_undefined();
  140. // 6. Set alreadyResolved.[[Value]] to true.
  141. already_resolved.value = true;
  142. // 7. Perform RejectPromise(promise, reason).
  143. promise.reject(reason);
  144. // 8. Return undefined.
  145. return js_undefined();
  146. });
  147. reject_function->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  148. // 12. Return the Record { [[Resolve]]: resolve, [[Reject]]: reject }.
  149. return { *resolve_function, *reject_function };
  150. }
  151. // 27.2.1.4 FulfillPromise ( promise, value ), https://tc39.es/ecma262/#sec-fulfillpromise
  152. void Promise::fulfill(Value value)
  153. {
  154. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / fulfill()]: Fulfilling promise with value {}", this, value);
  155. // 1. Assert: The value of promise.[[PromiseState]] is pending.
  156. VERIFY(m_state == State::Pending);
  157. VERIFY(!value.is_empty());
  158. // 2. Let reactions be promise.[[PromiseFulfillReactions]].
  159. // NOTE: This is a noop, we do these steps in a slightly different order.
  160. // 3. Set promise.[[PromiseResult]] to value.
  161. m_result = value;
  162. // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
  163. // 5. Set promise.[[PromiseRejectReactions]] to undefined.
  164. // 6. Set promise.[[PromiseState]] to fulfilled.
  165. m_state = State::Fulfilled;
  166. // 7. Perform TriggerPromiseReactions(reactions, value).
  167. trigger_reactions();
  168. m_fulfill_reactions.clear();
  169. m_reject_reactions.clear();
  170. // 8. Return unused.
  171. }
  172. // 27.2.1.7 RejectPromise ( promise, reason ), https://tc39.es/ecma262/#sec-rejectpromise
  173. void Promise::reject(Value reason)
  174. {
  175. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / reject()]: Rejecting promise with reason {}", this, reason);
  176. auto& vm = this->vm();
  177. // 1. Assert: The value of promise.[[PromiseState]] is pending.
  178. VERIFY(m_state == State::Pending);
  179. VERIFY(!reason.is_empty());
  180. // 2. Let reactions be promise.[[PromiseRejectReactions]].
  181. // NOTE: This is a noop, we do these steps in a slightly different order.
  182. // 3. Set promise.[[PromiseResult]] to reason.
  183. m_result = reason;
  184. // 4. Set promise.[[PromiseFulfillReactions]] to undefined.
  185. // 5. Set promise.[[PromiseRejectReactions]] to undefined.
  186. // 6. Set promise.[[PromiseState]] to rejected.
  187. m_state = State::Rejected;
  188. // 7. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "reject").
  189. if (!m_is_handled)
  190. vm.host_promise_rejection_tracker(*this, RejectionOperation::Reject);
  191. // 8. Perform TriggerPromiseReactions(reactions, reason).
  192. trigger_reactions();
  193. m_fulfill_reactions.clear();
  194. m_reject_reactions.clear();
  195. // 9. Return unused.
  196. }
  197. // 27.2.1.8 TriggerPromiseReactions ( reactions, argument ), https://tc39.es/ecma262/#sec-triggerpromisereactions
  198. void Promise::trigger_reactions() const
  199. {
  200. VERIFY(is_settled());
  201. auto& vm = this->vm();
  202. auto& reactions = m_state == State::Fulfilled
  203. ? m_fulfill_reactions
  204. : m_reject_reactions;
  205. // 1. For each element reaction of reactions, do
  206. for (auto& reaction : reactions) {
  207. // a. Let job be NewPromiseReactionJob(reaction, argument).
  208. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, &reaction, m_result);
  209. auto [job, realm] = create_promise_reaction_job(global_object(), *reaction, m_result);
  210. // b. Perform HostEnqueuePromiseJob(job.[[Job]], job.[[Realm]]).
  211. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Enqueuing job @ {} in realm {}", this, &job, realm);
  212. vm.host_enqueue_promise_job(move(job), realm);
  213. }
  214. if constexpr (PROMISE_DEBUG) {
  215. if (reactions.is_empty())
  216. dbgln("[Promise @ {} / trigger_reactions()]: No reactions!", this);
  217. }
  218. // 2. Return unused.
  219. }
  220. // 27.2.5.4.1 PerformPromiseThen ( promise, onFulfilled, onRejected [ , resultCapability ] ), https://tc39.es/ecma262/#sec-performpromisethen
  221. Value Promise::perform_then(Value on_fulfilled, Value on_rejected, Optional<PromiseCapability> result_capability)
  222. {
  223. auto& vm = this->vm();
  224. // 1. Assert: IsPromise(promise) is true.
  225. // 2. If resultCapability is not present, then
  226. // a. Set resultCapability to undefined.
  227. // 3. If IsCallable(onFulfilled) is false, then
  228. // a. Let onFulfilledJobCallback be empty.
  229. Optional<JobCallback> on_fulfilled_job_callback;
  230. // 4. Else,
  231. if (on_fulfilled.is_function()) {
  232. // a. Let onFulfilledJobCallback be HostMakeJobCallback(onFulfilled).
  233. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_fulfilled function @ {}", this, &on_fulfilled.as_function());
  234. on_fulfilled_job_callback = vm.host_make_job_callback(on_fulfilled.as_function());
  235. }
  236. // 5. If IsCallable(onRejected) is false, then
  237. // a. Let onRejectedJobCallback be empty.
  238. Optional<JobCallback> on_rejected_job_callback;
  239. // 6. Else,
  240. if (on_rejected.is_function()) {
  241. // a. Let onRejectedJobCallback be HostMakeJobCallback(onRejected).
  242. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_rejected function @ {}", this, &on_rejected.as_function());
  243. on_rejected_job_callback = vm.host_make_job_callback(on_rejected.as_function());
  244. }
  245. // 7. Let fulfillReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Fulfill, [[Handler]]: onFulfilledJobCallback }.
  246. auto* fulfill_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Fulfill, result_capability, move(on_fulfilled_job_callback));
  247. // 8. Let rejectReaction be the PromiseReaction { [[Capability]]: resultCapability, [[Type]]: Reject, [[Handler]]: onRejectedJobCallback }.
  248. auto* reject_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Reject, result_capability, move(on_rejected_job_callback));
  249. switch (m_state) {
  250. // 9. If promise.[[PromiseState]] is pending, then
  251. case Promise::State::Pending:
  252. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: state is State::Pending, adding fulfill/reject reactions", this);
  253. // a. Append fulfillReaction as the last element of the List that is promise.[[PromiseFulfillReactions]].
  254. m_fulfill_reactions.append(fulfill_reaction);
  255. // b. Append rejectReaction as the last element of the List that is promise.[[PromiseRejectReactions]].
  256. m_reject_reactions.append(reject_reaction);
  257. break;
  258. // 10. Else if promise.[[PromiseState]] is fulfilled, then
  259. case Promise::State::Fulfilled: {
  260. // a. Let value be promise.[[PromiseResult]].
  261. auto value = m_result;
  262. // b. Let fulfillJob be NewPromiseReactionJob(fulfillReaction, value).
  263. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Fulfilled, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, fulfill_reaction, value);
  264. auto [fulfill_job, realm] = create_promise_reaction_job(global_object(), *fulfill_reaction, value);
  265. // c. Perform HostEnqueuePromiseJob(fulfillJob.[[Job]], fulfillJob.[[Realm]]).
  266. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &fulfill_job, realm);
  267. vm.host_enqueue_promise_job(move(fulfill_job), realm);
  268. break;
  269. }
  270. // 11. Else,
  271. case Promise::State::Rejected: {
  272. // a. Assert: The value of promise.[[PromiseState]] is rejected.
  273. // b. Let reason be promise.[[PromiseResult]].
  274. auto reason = m_result;
  275. // c. If promise.[[PromiseIsHandled]] is false, perform HostPromiseRejectionTracker(promise, "handle").
  276. if (!m_is_handled)
  277. vm.host_promise_rejection_tracker(*this, RejectionOperation::Handle);
  278. // d. Let rejectJob be NewPromiseReactionJob(rejectReaction, reason).
  279. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Rejected, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, reject_reaction, reason);
  280. auto [reject_job, realm] = create_promise_reaction_job(global_object(), *reject_reaction, reason);
  281. // e. Perform HostEnqueuePromiseJob(rejectJob.[[Job]], rejectJob.[[Realm]]).
  282. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {} in realm {}", this, &reject_job, realm);
  283. vm.host_enqueue_promise_job(move(reject_job), realm);
  284. break;
  285. }
  286. default:
  287. VERIFY_NOT_REACHED();
  288. }
  289. // 12. Set promise.[[PromiseIsHandled]] to true.
  290. m_is_handled = true;
  291. // 13. If resultCapability is undefined, then
  292. if (!result_capability.has_value()) {
  293. // a. Return undefined.
  294. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: No ResultCapability, returning undefined", this);
  295. return js_undefined();
  296. }
  297. // 14. Else,
  298. // a. Return resultCapability.[[Promise]].
  299. auto* promise = result_capability.value().promise;
  300. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Returning Promise @ {} from ResultCapability @ {}", this, promise, &result_capability.value());
  301. return promise;
  302. }
  303. void Promise::visit_edges(Cell::Visitor& visitor)
  304. {
  305. Base::visit_edges(visitor);
  306. visitor.visit(m_result);
  307. for (auto& reaction : m_fulfill_reactions)
  308. visitor.visit(reaction);
  309. for (auto& reaction : m_reject_reactions)
  310. visitor.visit(reaction);
  311. }
  312. }