Promise.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. * Copyright (c) 2021, Linus Groh <mail@linusgroh.de>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Debug.h>
  27. #include <AK/Function.h>
  28. #include <AK/Optional.h>
  29. #include <LibJS/Runtime/Error.h>
  30. #include <LibJS/Runtime/GlobalObject.h>
  31. #include <LibJS/Runtime/JobCallback.h>
  32. #include <LibJS/Runtime/Promise.h>
  33. #include <LibJS/Runtime/PromiseJobs.h>
  34. #include <LibJS/Runtime/PromiseReaction.h>
  35. #include <LibJS/Runtime/PromiseResolvingFunction.h>
  36. namespace JS {
  37. // 27.2.4.7.1 PromiseResolve, https://tc39.es/ecma262/#sec-promise-resolve
  38. Object* promise_resolve(GlobalObject& global_object, Object& constructor, Value value)
  39. {
  40. auto& vm = global_object.vm();
  41. if (value.is_object() && is<Promise>(value.as_object())) {
  42. auto value_constructor = value.as_object().get(vm.names.constructor).value_or(js_undefined());
  43. if (vm.exception())
  44. return nullptr;
  45. if (same_value(value_constructor, &constructor))
  46. return &static_cast<Promise&>(value.as_object());
  47. }
  48. auto promise_capability = new_promise_capability(global_object, &constructor);
  49. if (vm.exception())
  50. return nullptr;
  51. [[maybe_unused]] auto result = vm.call(*promise_capability.resolve, js_undefined(), value);
  52. if (vm.exception())
  53. return nullptr;
  54. return promise_capability.promise;
  55. }
  56. Promise* Promise::create(GlobalObject& global_object)
  57. {
  58. return global_object.heap().allocate<Promise>(global_object, *global_object.promise_prototype());
  59. }
  60. Promise::Promise(Object& prototype)
  61. : Object(prototype)
  62. {
  63. }
  64. // 27.2.1.3 CreateResolvingFunctions, https://tc39.es/ecma262/#sec-createresolvingfunctions
  65. Promise::ResolvingFunctions Promise::create_resolving_functions()
  66. {
  67. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / create_resolving_functions()]", this);
  68. auto& vm = this->vm();
  69. auto* already_resolved = vm.heap().allocate_without_global_object<AlreadyResolved>();
  70. // 27.2.1.3.2 Promise Resolve Functions, https://tc39.es/ecma262/#sec-promise-resolve-functions
  71. auto* resolve_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto& global_object, auto& promise, auto& already_resolved) {
  72. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolve function was called", &promise);
  73. if (already_resolved.value) {
  74. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise is already resolved, returning undefined", &promise);
  75. return js_undefined();
  76. }
  77. already_resolved.value = true;
  78. auto resolution = vm.argument(0).value_or(js_undefined());
  79. if (resolution.is_object() && &resolution.as_object() == &promise) {
  80. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Promise can't be resolved with itself, rejecting with error", &promise);
  81. auto* self_resolution_error = TypeError::create(global_object, "Cannot resolve promise with itself");
  82. return promise.reject(self_resolution_error);
  83. }
  84. if (!resolution.is_object()) {
  85. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Resolution is not an object, fulfilling with {}", &promise, resolution);
  86. return promise.fulfill(resolution);
  87. }
  88. auto then_action = resolution.as_object().get(vm.names.then);
  89. if (vm.exception()) {
  90. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Exception while getting 'then' property, rejecting with error", &promise);
  91. auto error = vm.exception()->value();
  92. vm.clear_exception();
  93. vm.stop_unwind();
  94. return promise.reject(error);
  95. }
  96. if (!then_action.is_function()) {
  97. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Then action is not a function, fulfilling with {}", &promise, resolution);
  98. return promise.fulfill(resolution);
  99. }
  100. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating JobCallback for then action @ {}", &promise, &then_action.as_function());
  101. auto then_job_callback = make_job_callback(then_action.as_function());
  102. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Creating PromiseResolveThenableJob for thenable {}", &promise, resolution);
  103. auto* job = PromiseResolveThenableJob::create(global_object, promise, resolution, then_job_callback);
  104. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Enqueuing job @ {}", &promise, job);
  105. vm.enqueue_promise_job(*job);
  106. return js_undefined();
  107. });
  108. // 27.2.1.3.1 Promise Reject Functions, https://tc39.es/ecma262/#sec-promise-reject-functions
  109. auto* reject_function = PromiseResolvingFunction::create(global_object(), *this, *already_resolved, [](auto& vm, auto&, auto& promise, auto& already_resolved) {
  110. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / PromiseResolvingFunction]: Reject function was called", &promise);
  111. if (already_resolved.value)
  112. return js_undefined();
  113. already_resolved.value = true;
  114. auto reason = vm.argument(0).value_or(js_undefined());
  115. return promise.reject(reason);
  116. });
  117. return { *resolve_function, *reject_function };
  118. }
  119. // 27.2.1.4 FulfillPromise, https://tc39.es/ecma262/#sec-fulfillpromise
  120. Value Promise::fulfill(Value value)
  121. {
  122. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / fulfill()]: Fulfilling promise with value {}", this, value);
  123. VERIFY(m_state == State::Pending);
  124. VERIFY(!value.is_empty());
  125. m_state = State::Fulfilled;
  126. m_result = value;
  127. trigger_reactions();
  128. m_fulfill_reactions.clear();
  129. m_reject_reactions.clear();
  130. return js_undefined();
  131. }
  132. // 27.2.1.7 RejectPromise, https://tc39.es/ecma262/#sec-rejectpromise
  133. Value Promise::reject(Value reason)
  134. {
  135. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / reject()]: Rejecting promise with reason {}", this, reason);
  136. VERIFY(m_state == State::Pending);
  137. VERIFY(!reason.is_empty());
  138. auto& vm = this->vm();
  139. m_state = State::Rejected;
  140. m_result = reason;
  141. if (!m_is_handled)
  142. vm.promise_rejection_tracker(*this, RejectionOperation::Reject);
  143. trigger_reactions();
  144. m_fulfill_reactions.clear();
  145. m_reject_reactions.clear();
  146. return js_undefined();
  147. }
  148. // 27.2.1.8 TriggerPromiseReactions, https://tc39.es/ecma262/#sec-triggerpromisereactions
  149. void Promise::trigger_reactions() const
  150. {
  151. VERIFY(is_settled());
  152. auto& vm = this->vm();
  153. auto& reactions = m_state == State::Fulfilled
  154. ? m_fulfill_reactions
  155. : m_reject_reactions;
  156. for (auto& reaction : reactions) {
  157. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, &reaction, m_result);
  158. auto* job = PromiseReactionJob::create(global_object(), *reaction, m_result);
  159. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / trigger_reactions()]: Enqueuing job @ {}", this, job);
  160. vm.enqueue_promise_job(*job);
  161. }
  162. if constexpr (PROMISE_DEBUG) {
  163. if (reactions.is_empty())
  164. dbgln("[Promise @ {} / trigger_reactions()]: No reactions!", this);
  165. }
  166. }
  167. // 27.2.5.4.1 PerformPromiseThen, https://tc39.es/ecma262/#sec-performpromisethen
  168. Value Promise::perform_then(Value on_fulfilled, Value on_rejected, Optional<PromiseCapability> result_capability)
  169. {
  170. auto& vm = this->vm();
  171. Optional<JobCallback> on_fulfilled_job_callback;
  172. if (on_fulfilled.is_function()) {
  173. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_fulfilled function @ {}", this, &on_fulfilled.as_function());
  174. on_fulfilled_job_callback = make_job_callback(on_fulfilled.as_function());
  175. }
  176. Optional<JobCallback> on_rejected_job_callback;
  177. if (on_rejected.is_function()) {
  178. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Creating JobCallback for on_rejected function @ {}", this, &on_rejected.as_function());
  179. on_rejected_job_callback = make_job_callback(on_rejected.as_function());
  180. }
  181. auto* fulfill_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Fulfill, result_capability, on_fulfilled_job_callback);
  182. auto* reject_reaction = PromiseReaction::create(vm, PromiseReaction::Type::Reject, result_capability, on_rejected_job_callback);
  183. switch (m_state) {
  184. case Promise::State::Pending:
  185. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: state is State::Pending, adding fulfill/reject reactions", this);
  186. m_fulfill_reactions.append(fulfill_reaction);
  187. m_reject_reactions.append(reject_reaction);
  188. break;
  189. case Promise::State::Fulfilled: {
  190. auto value = m_result;
  191. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Fulfilled, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, fulfill_reaction, value);
  192. auto* fulfill_job = PromiseReactionJob::create(global_object(), *fulfill_reaction, value);
  193. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {}", this, fulfill_job);
  194. vm.enqueue_promise_job(*fulfill_job);
  195. break;
  196. }
  197. case Promise::State::Rejected: {
  198. auto reason = m_result;
  199. if (!m_is_handled)
  200. vm.promise_rejection_tracker(*this, RejectionOperation::Handle);
  201. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: State is State::Rejected, creating PromiseReactionJob for PromiseReaction @ {} with argument {}", this, reject_reaction, reason);
  202. auto* reject_job = PromiseReactionJob::create(global_object(), *reject_reaction, reason);
  203. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Enqueuing job @ {}", this, reject_job);
  204. vm.enqueue_promise_job(*reject_job);
  205. break;
  206. }
  207. default:
  208. VERIFY_NOT_REACHED();
  209. }
  210. m_is_handled = true;
  211. if (!result_capability.has_value()) {
  212. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: No ResultCapability, returning undefined", this);
  213. return js_undefined();
  214. }
  215. auto* promise = result_capability.value().promise;
  216. dbgln_if(PROMISE_DEBUG, "[Promise @ {} / perform_then()]: Returning Promise @ {} from ResultCapability @ {}", this, promise, &result_capability.value());
  217. return promise;
  218. }
  219. void Promise::visit_edges(Cell::Visitor& visitor)
  220. {
  221. Base::visit_edges(visitor);
  222. visitor.visit(m_result);
  223. for (auto& reaction : m_fulfill_reactions)
  224. visitor.visit(reaction);
  225. for (auto& reaction : m_reject_reactions)
  226. visitor.visit(reaction);
  227. }
  228. }