PromiseConstructor.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Function.h>
  7. #include <LibJS/Interpreter.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/AggregateError.h>
  10. #include <LibJS/Runtime/Array.h>
  11. #include <LibJS/Runtime/Error.h>
  12. #include <LibJS/Runtime/FunctionObject.h>
  13. #include <LibJS/Runtime/GlobalObject.h>
  14. #include <LibJS/Runtime/IteratorOperations.h>
  15. #include <LibJS/Runtime/Promise.h>
  16. #include <LibJS/Runtime/PromiseConstructor.h>
  17. #include <LibJS/Runtime/PromiseReaction.h>
  18. #include <LibJS/Runtime/PromiseResolvingElementFunctions.h>
  19. #include <LibJS/Runtime/TemporaryClearException.h>
  20. namespace JS {
  21. // 27.2.4.1.1 GetPromiseResolve ( promiseConstructor ), https://tc39.es/ecma262/#sec-getpromiseresolve
  22. static Value get_promise_resolve(GlobalObject& global_object, Value constructor)
  23. {
  24. VERIFY(constructor.is_constructor());
  25. auto& vm = global_object.vm();
  26. auto promise_resolve = TRY_OR_DISCARD(constructor.get(global_object, vm.names.resolve));
  27. if (!promise_resolve.is_function()) {
  28. vm.throw_exception<TypeError>(global_object, ErrorType::NotAFunction, promise_resolve.to_string_without_side_effects());
  29. return {};
  30. }
  31. return promise_resolve;
  32. }
  33. // 27.2.1.1.1 IfAbruptRejectPromise ( value, capability ), https://tc39.es/ecma262/#sec-ifabruptrejectpromise
  34. template<typename ValueType>
  35. static Optional<Value> if_abrupt_reject_promise(GlobalObject& global_object, ValueType const& value_or_error, PromiseCapability capability)
  36. {
  37. auto& vm = global_object.vm();
  38. // FIXME: This is temporary multi-type support. When all callers to this method are transformed
  39. // to use ThrowCompletionOr, the 'else' clause (and template) can be dropped.
  40. if constexpr (requires { value_or_error.is_throw_completion(); }) {
  41. if (value_or_error.is_throw_completion()) {
  42. vm.clear_exception();
  43. vm.stop_unwind();
  44. (void)vm.call(*capability.reject, js_undefined(), value_or_error.throw_completion().value());
  45. return capability.promise;
  46. }
  47. } else {
  48. if (auto* exception = vm.exception()) {
  49. vm.clear_exception();
  50. vm.stop_unwind();
  51. (void)vm.call(*capability.reject, js_undefined(), exception->value());
  52. return capability.promise;
  53. }
  54. }
  55. return {};
  56. }
  57. static bool iterator_record_is_complete(GlobalObject& global_object, Object& iterator_record)
  58. {
  59. auto& vm = global_object.vm();
  60. // FIXME: Create a native iterator structure with the [[Done]] internal slot. For now, temporarily clear
  61. // the exception so we can access the "done" property on the iterator object.
  62. TemporaryClearException clear_exception(vm);
  63. return MUST(iterator_complete(global_object, iterator_record));
  64. }
  65. static void set_iterator_record_complete(GlobalObject& global_object, Object& iterator_record)
  66. {
  67. auto& vm = global_object.vm();
  68. // FIXME: Create a native iterator structure with the [[Done]] internal slot. For now, temporarily clear
  69. // the exception so we can access the "done" property on the iterator object.
  70. TemporaryClearException clear_exception(vm);
  71. MUST(iterator_record.set(vm.names.done, Value(true), Object::ShouldThrowExceptions::No));
  72. }
  73. using EndOfElementsCallback = Function<ThrowCompletionOr<Value>(PromiseValueList&)>;
  74. using InvokeElementFunctionCallback = Function<void(PromiseValueList&, RemainingElements&, Value, size_t)>;
  75. static Value perform_promise_common(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve, EndOfElementsCallback end_of_list, InvokeElementFunctionCallback invoke_element_function)
  76. {
  77. auto& vm = global_object.vm();
  78. VERIFY(constructor.is_constructor());
  79. VERIFY(promise_resolve.is_function());
  80. auto* values = vm.heap().allocate_without_global_object<PromiseValueList>();
  81. auto* remaining_elements_count = vm.heap().allocate_without_global_object<RemainingElements>(1);
  82. size_t index = 0;
  83. while (true) {
  84. auto next_or_error = iterator_step(global_object, iterator_record);
  85. if (next_or_error.is_throw_completion()) {
  86. set_iterator_record_complete(global_object, iterator_record);
  87. return {};
  88. }
  89. auto* next = next_or_error.release_value();
  90. if (!next) {
  91. set_iterator_record_complete(global_object, iterator_record);
  92. if (vm.exception())
  93. return {};
  94. if (--remaining_elements_count->value == 0)
  95. return TRY_OR_DISCARD(end_of_list(*values));
  96. return result_capability.promise;
  97. }
  98. auto next_value = iterator_value(global_object, *next);
  99. if (vm.exception()) {
  100. set_iterator_record_complete(global_object, iterator_record);
  101. return {};
  102. }
  103. values->values().append(js_undefined());
  104. auto next_promise = TRY_OR_DISCARD(vm.call(promise_resolve.as_function(), constructor, next_value));
  105. ++remaining_elements_count->value;
  106. invoke_element_function(*values, *remaining_elements_count, next_promise, index);
  107. if (vm.exception())
  108. return {};
  109. ++index;
  110. }
  111. }
  112. // 27.2.4.1.2 PerformPromiseAll ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseall
  113. static Value perform_promise_all(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  114. {
  115. auto& vm = global_object.vm();
  116. return perform_promise_common(
  117. global_object, iterator_record, constructor, result_capability, promise_resolve,
  118. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  119. auto values_array = Array::create_from(global_object, values.values());
  120. TRY(vm.call(*result_capability.resolve, js_undefined(), values_array));
  121. return Value(result_capability.promise);
  122. },
  123. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  124. auto* on_fulfilled = PromiseAllResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
  125. on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  126. (void)next_promise.invoke(global_object, vm.names.then, on_fulfilled, result_capability.reject);
  127. });
  128. }
  129. // 27.2.4.2.1 PerformPromiseAllSettled ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseallsettled
  130. static Value perform_promise_all_settled(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  131. {
  132. auto& vm = global_object.vm();
  133. return perform_promise_common(
  134. global_object, iterator_record, constructor, result_capability, promise_resolve,
  135. [&](PromiseValueList& values) -> ThrowCompletionOr<Value> {
  136. auto values_array = Array::create_from(global_object, values.values());
  137. TRY(vm.call(*result_capability.resolve, js_undefined(), values_array));
  138. return Value(result_capability.promise);
  139. },
  140. [&](PromiseValueList& values, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  141. auto* on_fulfilled = PromiseAllSettledResolveElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
  142. on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  143. auto* on_rejected = PromiseAllSettledRejectElementFunction::create(global_object, index, values, result_capability, remaining_elements_count);
  144. on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  145. (void)next_promise.invoke(global_object, vm.names.then, on_fulfilled, on_rejected);
  146. });
  147. }
  148. // 27.2.4.3.1 PerformPromiseAny ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiseany
  149. static Value perform_promise_any(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  150. {
  151. auto& vm = global_object.vm();
  152. return perform_promise_common(
  153. global_object, iterator_record, constructor, result_capability, promise_resolve,
  154. [&](PromiseValueList& errors) -> ThrowCompletionOr<Value> {
  155. auto errors_array = Array::create_from(global_object, errors.values());
  156. auto* error = AggregateError::create(global_object);
  157. MUST(error->define_property_or_throw(vm.names.errors, { .value = errors_array, .writable = true, .enumerable = false, .configurable = true }));
  158. vm.throw_exception(global_object, error);
  159. return throw_completion(error);
  160. },
  161. [&](PromiseValueList& errors, RemainingElements& remaining_elements_count, Value next_promise, size_t index) {
  162. auto* on_rejected = PromiseAnyRejectElementFunction::create(global_object, index, errors, result_capability, remaining_elements_count);
  163. on_rejected->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  164. (void)next_promise.invoke(global_object, vm.names.then, result_capability.resolve, on_rejected);
  165. });
  166. }
  167. // 27.2.4.5.1 PerformPromiseRace ( iteratorRecord, constructor, resultCapability, promiseResolve ), https://tc39.es/ecma262/#sec-performpromiserace
  168. static Value perform_promise_race(GlobalObject& global_object, Object& iterator_record, Value constructor, PromiseCapability result_capability, Value promise_resolve)
  169. {
  170. auto& vm = global_object.vm();
  171. return perform_promise_common(
  172. global_object, iterator_record, constructor, result_capability, promise_resolve,
  173. [&](PromiseValueList&) -> ThrowCompletionOr<Value> {
  174. return Value(result_capability.promise);
  175. },
  176. [&](PromiseValueList&, RemainingElements&, Value next_promise, size_t) {
  177. (void)next_promise.invoke(global_object, vm.names.then, result_capability.resolve, result_capability.reject);
  178. });
  179. }
  180. PromiseConstructor::PromiseConstructor(GlobalObject& global_object)
  181. : NativeFunction(vm().names.Promise.as_string(), *global_object.function_prototype())
  182. {
  183. }
  184. void PromiseConstructor::initialize(GlobalObject& global_object)
  185. {
  186. auto& vm = this->vm();
  187. NativeFunction::initialize(global_object);
  188. // 27.2.4.4 Promise.prototype, https://tc39.es/ecma262/#sec-promise.prototype
  189. define_direct_property(vm.names.prototype, global_object.promise_prototype(), 0);
  190. u8 attr = Attribute::Writable | Attribute::Configurable;
  191. define_old_native_function(vm.names.all, all, 1, attr);
  192. define_old_native_function(vm.names.allSettled, all_settled, 1, attr);
  193. define_old_native_function(vm.names.any, any, 1, attr);
  194. define_old_native_function(vm.names.race, race, 1, attr);
  195. define_old_native_function(vm.names.reject, reject, 1, attr);
  196. define_old_native_function(vm.names.resolve, resolve, 1, attr);
  197. define_old_native_accessor(*vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable);
  198. define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  199. }
  200. // 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
  201. Value PromiseConstructor::call()
  202. {
  203. auto& vm = this->vm();
  204. vm.throw_exception<TypeError>(global_object(), ErrorType::ConstructorWithoutNew, vm.names.Promise);
  205. return {};
  206. }
  207. // 27.2.3.1 Promise ( executor ), https://tc39.es/ecma262/#sec-promise-executor
  208. Value PromiseConstructor::construct(FunctionObject& new_target)
  209. {
  210. auto& vm = this->vm();
  211. auto& global_object = this->global_object();
  212. auto executor = vm.argument(0);
  213. if (!executor.is_function()) {
  214. vm.throw_exception<TypeError>(global_object, ErrorType::PromiseExecutorNotAFunction);
  215. return {};
  216. }
  217. auto* promise = TRY_OR_DISCARD(ordinary_create_from_constructor<Promise>(global_object, new_target, &GlobalObject::promise_prototype));
  218. auto [resolve_function, reject_function] = promise->create_resolving_functions();
  219. (void)vm.call(executor.as_function(), js_undefined(), &resolve_function, &reject_function);
  220. if (auto* exception = vm.exception()) {
  221. vm.clear_exception();
  222. vm.stop_unwind();
  223. (void)vm.call(reject_function, js_undefined(), exception->value());
  224. }
  225. return promise;
  226. }
  227. // 27.2.4.1 Promise.all ( iterable ), https://tc39.es/ecma262/#sec-promise.all
  228. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::all)
  229. {
  230. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  231. auto promise_capability = new_promise_capability(global_object, constructor);
  232. if (vm.exception())
  233. return {};
  234. auto promise_resolve = get_promise_resolve(global_object, constructor);
  235. if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
  236. return abrupt.value();
  237. auto iterator_record_or_error = get_iterator(global_object, vm.argument(0));
  238. if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record_or_error, promise_capability); abrupt.has_value())
  239. return abrupt.value();
  240. auto* iterator_record = iterator_record_or_error.release_value();
  241. auto result = perform_promise_all(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  242. if (vm.exception()) {
  243. if (!iterator_record_is_complete(global_object, *iterator_record))
  244. iterator_close(*iterator_record);
  245. auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
  246. return abrupt.value();
  247. }
  248. return result;
  249. }
  250. // 27.2.4.2 Promise.allSettled ( iterable ), https://tc39.es/ecma262/#sec-promise.allsettled
  251. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::all_settled)
  252. {
  253. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  254. auto promise_capability = new_promise_capability(global_object, constructor);
  255. if (vm.exception())
  256. return {};
  257. auto promise_resolve = get_promise_resolve(global_object, constructor);
  258. if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
  259. return abrupt.value();
  260. auto iterator_record_or_error = get_iterator(global_object, vm.argument(0));
  261. if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record_or_error, promise_capability); abrupt.has_value())
  262. return abrupt.value();
  263. auto* iterator_record = iterator_record_or_error.release_value();
  264. auto result = perform_promise_all_settled(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  265. if (vm.exception()) {
  266. if (!iterator_record_is_complete(global_object, *iterator_record))
  267. iterator_close(*iterator_record);
  268. auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
  269. return abrupt.value();
  270. }
  271. return result;
  272. }
  273. // 27.2.4.3 Promise.any ( iterable ), https://tc39.es/ecma262/#sec-promise.any
  274. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::any)
  275. {
  276. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  277. auto promise_capability = new_promise_capability(global_object, constructor);
  278. if (vm.exception())
  279. return {};
  280. auto promise_resolve = get_promise_resolve(global_object, constructor);
  281. if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
  282. return abrupt.value();
  283. auto iterator_record_or_error = get_iterator(global_object, vm.argument(0));
  284. if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record_or_error, promise_capability); abrupt.has_value())
  285. return abrupt.value();
  286. auto* iterator_record = iterator_record_or_error.release_value();
  287. auto result = perform_promise_any(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  288. if (vm.exception()) {
  289. if (!iterator_record_is_complete(global_object, *iterator_record))
  290. iterator_close(*iterator_record);
  291. auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
  292. return abrupt.value();
  293. }
  294. return result;
  295. }
  296. // 27.2.4.5 Promise.race ( iterable ), https://tc39.es/ecma262/#sec-promise.race
  297. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::race)
  298. {
  299. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  300. auto promise_capability = new_promise_capability(global_object, constructor);
  301. if (vm.exception())
  302. return {};
  303. auto promise_resolve = get_promise_resolve(global_object, constructor);
  304. if (auto abrupt = if_abrupt_reject_promise(global_object, promise_resolve, promise_capability); abrupt.has_value())
  305. return abrupt.value();
  306. auto iterator_record_or_error = get_iterator(global_object, vm.argument(0));
  307. if (auto abrupt = if_abrupt_reject_promise(global_object, iterator_record_or_error, promise_capability); abrupt.has_value())
  308. return abrupt.value();
  309. auto* iterator_record = iterator_record_or_error.release_value();
  310. auto result = perform_promise_race(global_object, *iterator_record, constructor, promise_capability, promise_resolve);
  311. if (vm.exception()) {
  312. if (!iterator_record_is_complete(global_object, *iterator_record))
  313. iterator_close(*iterator_record);
  314. auto abrupt = if_abrupt_reject_promise(global_object, result, promise_capability);
  315. return abrupt.value();
  316. }
  317. return result;
  318. }
  319. // 27.2.4.6 Promise.reject ( r ), https://tc39.es/ecma262/#sec-promise.reject
  320. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::reject)
  321. {
  322. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  323. auto promise_capability = new_promise_capability(global_object, constructor);
  324. if (vm.exception())
  325. return {};
  326. auto reason = vm.argument(0);
  327. [[maybe_unused]] auto result = TRY_OR_DISCARD(vm.call(*promise_capability.reject, js_undefined(), reason));
  328. return promise_capability.promise;
  329. }
  330. // 27.2.4.7 Promise.resolve ( x ), https://tc39.es/ecma262/#sec-promise.resolve
  331. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::resolve)
  332. {
  333. auto* constructor = TRY_OR_DISCARD(vm.this_value(global_object).to_object(global_object));
  334. auto value = vm.argument(0);
  335. return promise_resolve(global_object, *constructor, value);
  336. }
  337. // 27.2.4.8 get Promise [ @@species ], https://tc39.es/ecma262/#sec-get-promise-@@species
  338. JS_DEFINE_OLD_NATIVE_FUNCTION(PromiseConstructor::symbol_species_getter)
  339. {
  340. return vm.this_value(global_object);
  341. }
  342. }