Promise.cpp 18 KB

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