Promise.cpp 17 KB

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