AsyncGenerator.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/AsyncGenerator.h>
  8. #include <LibJS/Runtime/AsyncGeneratorPrototype.h>
  9. #include <LibJS/Runtime/AsyncGeneratorRequest.h>
  10. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  11. #include <LibJS/Runtime/GlobalObject.h>
  12. #include <LibJS/Runtime/PromiseConstructor.h>
  13. namespace JS {
  14. GC_DEFINE_ALLOCATOR(AsyncGenerator);
  15. ThrowCompletionOr<GC::Ref<AsyncGenerator>> AsyncGenerator::create(Realm& realm, Value initial_value, ECMAScriptFunctionObject* generating_function, NonnullOwnPtr<ExecutionContext> execution_context)
  16. {
  17. auto& vm = realm.vm();
  18. // This is "g1.prototype" in figure-2 (https://tc39.es/ecma262/img/figure-2.png)
  19. auto generating_function_prototype = TRY(generating_function->get(vm.names.prototype));
  20. auto generating_function_prototype_object = TRY(generating_function_prototype.to_object(vm));
  21. auto object = realm.create<AsyncGenerator>(realm, generating_function_prototype_object, move(execution_context));
  22. object->m_generating_function = generating_function;
  23. object->m_previous_value = initial_value;
  24. return object;
  25. }
  26. AsyncGenerator::AsyncGenerator(Realm&, Object& prototype, NonnullOwnPtr<ExecutionContext> context)
  27. : Object(ConstructWithPrototypeTag::Tag, prototype)
  28. , m_async_generator_context(move(context))
  29. {
  30. }
  31. AsyncGenerator::~AsyncGenerator() = default;
  32. void AsyncGenerator::visit_edges(Cell::Visitor& visitor)
  33. {
  34. Base::visit_edges(visitor);
  35. for (auto const& request : m_async_generator_queue) {
  36. if (request.completion.value().has_value())
  37. visitor.visit(*request.completion.value());
  38. visitor.visit(request.capability);
  39. }
  40. visitor.visit(m_generating_function);
  41. visitor.visit(m_previous_value);
  42. visitor.visit(m_current_promise);
  43. m_async_generator_context->visit_edges(visitor);
  44. }
  45. // 27.6.3.4 AsyncGeneratorEnqueue ( generator, completion, promiseCapability ), https://tc39.es/ecma262/#sec-asyncgeneratorenqueue
  46. void AsyncGenerator::async_generator_enqueue(Completion completion, GC::Ref<PromiseCapability> promise_capability)
  47. {
  48. // 1. Let request be AsyncGeneratorRequest { [[Completion]]: completion, [[Capability]]: promiseCapability }.
  49. auto request = AsyncGeneratorRequest { .completion = move(completion), .capability = promise_capability };
  50. // 2. Append request to generator.[[AsyncGeneratorQueue]].
  51. m_async_generator_queue.append(move(request));
  52. // 3. Return unused.
  53. }
  54. void AsyncGenerator::set_async_generator_state(Badge<AsyncGeneratorPrototype>, AsyncGenerator::State value)
  55. {
  56. m_async_generator_state = value;
  57. }
  58. // 27.7.5.3 Await ( value ), https://tc39.es/ecma262/#await
  59. ThrowCompletionOr<void> AsyncGenerator::await(Value value)
  60. {
  61. auto& vm = this->vm();
  62. auto& realm = *vm.current_realm();
  63. // 1. Let asyncContext be the running execution context.
  64. auto& async_context = vm.running_execution_context();
  65. // 2. Let promise be ? PromiseResolve(%Promise%, value).
  66. auto* promise_object = TRY(promise_resolve(vm, realm.intrinsics().promise_constructor(), value));
  67. // 3. Let fulfilledClosure be a new Abstract Closure with parameters (v) that captures asyncContext and performs the
  68. // following steps when called:
  69. auto fulfilled_closure = [this, &async_context](VM& vm) -> ThrowCompletionOr<Value> {
  70. auto value = vm.argument(0);
  71. // a. Let prevContext be the running execution context.
  72. auto& prev_context = vm.running_execution_context();
  73. // FIXME: b. Suspend prevContext.
  74. // c. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  75. TRY(vm.push_execution_context(async_context, {}));
  76. // d. Resume the suspended evaluation of asyncContext using NormalCompletion(v) as the result of the operation that
  77. // suspended it.
  78. execute(vm, normal_completion(value));
  79. // e. Assert: When we reach this step, asyncContext has already been removed from the execution context stack and
  80. // prevContext is the currently running execution context.
  81. VERIFY(&vm.running_execution_context() == &prev_context);
  82. // f. Return undefined.
  83. return js_undefined();
  84. };
  85. // 4. Let onFulfilled be CreateBuiltinFunction(fulfilledClosure, 1, "", « »).
  86. auto on_fulfilled = NativeFunction::create(realm, move(fulfilled_closure), 1, "");
  87. // 5. Let rejectedClosure be a new Abstract Closure with parameters (reason) that captures asyncContext and performs the
  88. // following steps when called:
  89. auto rejected_closure = [this, &async_context](VM& vm) -> ThrowCompletionOr<Value> {
  90. auto reason = vm.argument(0);
  91. // a. Let prevContext be the running execution context.
  92. auto& prev_context = vm.running_execution_context();
  93. // FIXME: b. Suspend prevContext.
  94. // c. Push asyncContext onto the execution context stack; asyncContext is now the running execution context.
  95. TRY(vm.push_execution_context(async_context, {}));
  96. // d. Resume the suspended evaluation of asyncContext using ThrowCompletion(reason) as the result of the operation that
  97. // suspended it.
  98. execute(vm, throw_completion(reason));
  99. // e. Assert: When we reach this step, asyncContext has already been removed from the execution context stack and
  100. // prevContext is the currently running execution context.
  101. VERIFY(&vm.running_execution_context() == &prev_context);
  102. // f. Return undefined.
  103. return js_undefined();
  104. };
  105. // 6. Let onRejected be CreateBuiltinFunction(rejectedClosure, 1, "", « »).
  106. auto on_rejected = NativeFunction::create(realm, move(rejected_closure), 1, "");
  107. // 7. Perform PerformPromiseThen(promise, onFulfilled, onRejected).
  108. m_current_promise = verify_cast<Promise>(promise_object);
  109. m_current_promise->perform_then(on_fulfilled, on_rejected, {});
  110. // 8. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the
  111. // execution context stack as the running execution context.
  112. vm.pop_execution_context();
  113. // NOTE: None of these are necessary. 10-12 are handled by step d of the above lambdas.
  114. // 9. Let callerContext be the running execution context.
  115. // 10. Resume callerContext passing empty. If asyncContext is ever resumed again, let completion be the Completion Record with which it is resumed.
  116. // 11. Assert: If control reaches here, then asyncContext is the running execution context again.
  117. // 12. Return completion.
  118. return {};
  119. }
  120. void AsyncGenerator::execute(VM& vm, Completion completion)
  121. {
  122. while (true) {
  123. // Loosely based on step 4 of https://tc39.es/ecma262/#sec-asyncgeneratorstart
  124. VERIFY(completion.value().has_value());
  125. auto generated_value = [](Value value) -> Value {
  126. if (value.is_object())
  127. return value.as_object().get_without_side_effects("result");
  128. return value.is_empty() ? js_undefined() : value;
  129. };
  130. auto generated_continuation = [&](Value value) -> Optional<size_t> {
  131. if (value.is_object()) {
  132. auto number_value = value.as_object().get_without_side_effects("continuation");
  133. if (number_value.is_null())
  134. return {};
  135. return static_cast<size_t>(number_value.as_double());
  136. }
  137. return {};
  138. };
  139. auto generated_is_await = [](Value value) -> bool {
  140. if (value.is_object())
  141. return value.as_object().get_without_side_effects("isAwait").as_bool();
  142. return false;
  143. };
  144. auto& realm = *vm.current_realm();
  145. auto completion_object = Object::create(realm, nullptr);
  146. completion_object->define_direct_property(vm.names.type, Value(to_underlying(completion.type())), default_attributes);
  147. completion_object->define_direct_property(vm.names.value, completion.value().value(), default_attributes);
  148. auto& bytecode_interpreter = vm.bytecode_interpreter();
  149. auto const continuation_address = generated_continuation(m_previous_value);
  150. // We should never enter `execute` again after the generator is complete.
  151. VERIFY(continuation_address.has_value());
  152. auto next_result = bytecode_interpreter.run_executable(*m_generating_function->bytecode_executable(), continuation_address, completion_object);
  153. auto result_value = move(next_result.value);
  154. if (!result_value.is_throw_completion()) {
  155. m_previous_value = result_value.release_value();
  156. auto value = generated_value(m_previous_value);
  157. bool is_await = generated_is_await(m_previous_value);
  158. if (is_await) {
  159. auto await_result = this->await(value);
  160. if (await_result.is_throw_completion()) {
  161. completion = await_result.release_error();
  162. continue;
  163. }
  164. return;
  165. }
  166. }
  167. bool done = result_value.is_throw_completion() || !generated_continuation(m_previous_value).has_value();
  168. if (!done) {
  169. // 27.6.3.8 AsyncGeneratorYield ( value ), https://tc39.es/ecma262/#sec-asyncgeneratoryield
  170. // 1. Let genContext be the running execution context.
  171. // 2. Assert: genContext is the execution context of a generator.
  172. // 3. Let generator be the value of the Generator component of genContext.
  173. // 4. Assert: GetGeneratorKind() is async.
  174. // NOTE: genContext is `m_async_generator_context`, generator is `this`.
  175. // 5. Let completion be NormalCompletion(value).
  176. auto value = generated_value(m_previous_value);
  177. auto yield_completion = normal_completion(value);
  178. // 6. Assert: The execution context stack has at least two elements.
  179. VERIFY(vm.execution_context_stack().size() >= 2);
  180. // 7. Let previousContext be the second to top element of the execution context stack.
  181. auto& previous_context = vm.execution_context_stack().at(vm.execution_context_stack().size() - 2);
  182. // 8. Let previousRealm be previousContext's Realm.
  183. auto previous_realm = previous_context->realm;
  184. // 9. Perform AsyncGeneratorCompleteStep(generator, completion, false, previousRealm).
  185. complete_step(yield_completion, false, previous_realm.ptr());
  186. // 10. Let queue be generator.[[AsyncGeneratorQueue]].
  187. auto& queue = m_async_generator_queue;
  188. // 11. If queue is not empty, then
  189. if (!queue.is_empty()) {
  190. // a. NOTE: Execution continues without suspending the generator.
  191. // b. Let toYield be the first element of queue.
  192. auto& to_yield = queue.first();
  193. // c. Let resumptionValue be Completion(toYield.[[Completion]]).
  194. completion = Completion(to_yield.completion);
  195. // d. Return ? AsyncGeneratorUnwrapYieldResumption(resumptionValue).
  196. // NOTE: AsyncGeneratorUnwrapYieldResumption is performed inside the continuation block inside the generator,
  197. // so we just need to enter the generator again.
  198. continue;
  199. }
  200. // 12. Else,
  201. else {
  202. // a. Set generator.[[AsyncGeneratorState]] to suspendedYield.
  203. m_async_generator_state = State::SuspendedYield;
  204. // b. Remove genContext from the execution context stack and restore the execution context that is at the top of the
  205. // execution context stack as the running execution context.
  206. vm.pop_execution_context();
  207. // c. Let callerContext be the running execution context.
  208. // d. Resume callerContext passing undefined. If genContext is ever resumed again, let resumptionValue be the Completion Record with which it is resumed.
  209. // e. Assert: If control reaches here, then genContext is the running execution context again.
  210. // f. Return ? AsyncGeneratorUnwrapYieldResumption(resumptionValue).
  211. // NOTE: e-f are performed whenever someone calls `execute` again.
  212. return;
  213. }
  214. }
  215. // 27.6.3.2 AsyncGeneratorStart ( generator, generatorBody ), https://tc39.es/ecma262/#sec-asyncgeneratorstart
  216. // 4.e. Assert: If we return here, the async generator either threw an exception or performed either an implicit or explicit return.
  217. // 4.f. Remove acGenContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.
  218. vm.pop_execution_context();
  219. // 4.g. Set acGenerator.[[AsyncGeneratorState]] to completed.
  220. m_async_generator_state = State::Completed;
  221. // 4.h. If result.[[Type]] is normal, set result to NormalCompletion(undefined).
  222. // 4.i. If result.[[Type]] is return, set result to NormalCompletion(result.[[Value]]).
  223. Completion result;
  224. if (!result_value.is_throw_completion()) {
  225. result = normal_completion(generated_value(m_previous_value));
  226. } else {
  227. result = result_value.release_error();
  228. }
  229. // 4.j. Perform AsyncGeneratorCompleteStep(acGenerator, result, true).
  230. complete_step(result, true);
  231. // 4.k. Perform AsyncGeneratorDrainQueue(acGenerator).
  232. drain_queue();
  233. // 4.l. Return undefined.
  234. return;
  235. }
  236. }
  237. // 27.6.3.6 AsyncGeneratorResume ( generator, completion ), https://tc39.es/ecma262/#sec-asyncgeneratorresume
  238. ThrowCompletionOr<void> AsyncGenerator::resume(VM& vm, Completion completion)
  239. {
  240. // 1. Assert: generator.[[AsyncGeneratorState]] is either suspendedStart or suspendedYield.
  241. VERIFY(m_async_generator_state == State::SuspendedStart || m_async_generator_state == State::SuspendedYield);
  242. // 2. Let genContext be generator.[[AsyncGeneratorContext]].
  243. auto& generator_context = m_async_generator_context;
  244. // 3. Let callerContext be the running execution context.
  245. auto const& caller_context = vm.running_execution_context();
  246. // FIXME: 4. Suspend callerContext.
  247. // 5. Set generator.[[AsyncGeneratorState]] to executing.
  248. m_async_generator_state = State::Executing;
  249. // 6. Push genContext onto the execution context stack; genContext is now the running execution context.
  250. TRY(vm.push_execution_context(*generator_context, {}));
  251. // 7. Resume the suspended evaluation of genContext using completion as the result of the operation that suspended
  252. // it. Let result be the Completion Record returned by the resumed computation.
  253. // 8. Assert: result is never an abrupt completion.
  254. execute(vm, completion);
  255. // 9. Assert: When we return here, genContext has already been removed from the execution context stack and
  256. // callerContext is the currently running execution context.
  257. VERIFY(&vm.running_execution_context() == &caller_context);
  258. // 10. Return unused.
  259. return {};
  260. }
  261. // 27.6.3.9 AsyncGeneratorAwaitReturn ( generator ), https://tc39.es/ecma262/#sec-asyncgeneratorawaitreturn
  262. // With unmerged broken promise fixup from https://github.com/tc39/ecma262/pull/2683
  263. void AsyncGenerator::await_return()
  264. {
  265. auto& vm = this->vm();
  266. auto& realm = *vm.current_realm();
  267. // 1. Let queue be generator.[[AsyncGeneratorQueue]].
  268. auto& queue = m_async_generator_queue;
  269. // 2. Assert: queue is not empty.
  270. VERIFY(!queue.is_empty());
  271. // 3. Let next be the first element of queue.
  272. auto& next = m_async_generator_queue.first();
  273. // 4. Let completion be Completion(next.[[Completion]]).
  274. auto completion = Completion(next.completion);
  275. // 5. Assert: completion.[[Type]] is return.
  276. VERIFY(completion.type() == Completion::Type::Return);
  277. // 6. Let promiseCompletion be Completion(PromiseResolve(%Promise%, _completion_.[[Value]])).
  278. auto promise_completion = promise_resolve(vm, realm.intrinsics().promise_constructor(), completion.value().value());
  279. // 7. If promiseCompletion is an abrupt completion, then
  280. if (promise_completion.is_throw_completion()) {
  281. // a. Set generator.[[AsyncGeneratorState]] to completed.
  282. m_async_generator_state = State::Completed;
  283. // b. Perform AsyncGeneratorCompleteStep(generator, promiseCompletion, true).
  284. complete_step(promise_completion.release_error(), true);
  285. // c. Perform AsyncGeneratorDrainQueue(generator).
  286. drain_queue();
  287. // d. Return unused.
  288. return;
  289. }
  290. // 8. Assert: promiseCompletion.[[Type]] is normal.
  291. VERIFY(!promise_completion.is_throw_completion());
  292. // 9. Let promise be promiseCompletion.[[Value]].
  293. auto* promise = promise_completion.release_value();
  294. // 10. Let fulfilledClosure be a new Abstract Closure with parameters (value) that captures generator and performs
  295. // the following steps when called:
  296. auto fulfilled_closure = [this](VM& vm) -> ThrowCompletionOr<Value> {
  297. // a. Set generator.[[AsyncGeneratorState]] to completed.
  298. m_async_generator_state = State::Completed;
  299. // b. Let result be NormalCompletion(value).
  300. auto result = normal_completion(vm.argument(0));
  301. // c. Perform AsyncGeneratorCompleteStep(generator, result, true).
  302. complete_step(result, true);
  303. // d. Perform AsyncGeneratorDrainQueue(generator).
  304. drain_queue();
  305. // e. Return undefined.
  306. return js_undefined();
  307. };
  308. // 11. Let onFulfilled be CreateBuiltinFunction(fulfilledClosure, 1, "", « »).
  309. auto on_fulfilled = NativeFunction::create(realm, move(fulfilled_closure), 1, "");
  310. // 12. Let rejectedClosure be a new Abstract Closure with parameters (reason) that captures generator and performs
  311. // the following steps when called:
  312. auto rejected_closure = [this](VM& vm) -> ThrowCompletionOr<Value> {
  313. // a. Set generator.[[AsyncGeneratorState]] to completed.
  314. m_async_generator_state = State::Completed;
  315. // b. Let result be ThrowCompletion(reason).
  316. auto result = throw_completion(vm.argument(0));
  317. // c. Perform AsyncGeneratorCompleteStep(generator, result, true).
  318. complete_step(result, true);
  319. // d. Perform AsyncGeneratorDrainQueue(generator).
  320. drain_queue();
  321. // e. Return undefined.
  322. return js_undefined();
  323. };
  324. // 13. Let onRejected be CreateBuiltinFunction(rejectedClosure, 1, "", « »).
  325. auto on_rejected = NativeFunction::create(realm, move(rejected_closure), 1, "");
  326. // 14. Perform PerformPromiseThen(promise, onFulfilled, onRejected).
  327. // NOTE: await_return should only be called when the generator is in SuspendedStart or Completed state,
  328. // so an await shouldn't be running currently, so it should be safe to overwrite m_current_promise.
  329. m_current_promise = verify_cast<Promise>(promise);
  330. m_current_promise->perform_then(on_fulfilled, on_rejected, {});
  331. // 15. Return unused.
  332. return;
  333. }
  334. // 27.6.3.5 AsyncGeneratorCompleteStep ( generator, completion, done [ , realm ] ), https://tc39.es/ecma262/#sec-asyncgeneratorcompletestep
  335. void AsyncGenerator::complete_step(Completion completion, bool done, Realm* realm)
  336. {
  337. auto& vm = this->vm();
  338. // 1. Assert: generator.[[AsyncGeneratorQueue]] is not empty.
  339. VERIFY(!m_async_generator_queue.is_empty());
  340. // 2. Let next be the first element of generator.[[AsyncGeneratorQueue]].
  341. // 3. Remove the first element from generator.[[AsyncGeneratorQueue]].
  342. auto next = m_async_generator_queue.take_first();
  343. // 4. Let promiseCapability be next.[[Capability]].
  344. auto promise_capability = next.capability;
  345. // 5. Let value be completion.[[Value]].
  346. auto value = completion.value().value();
  347. // 6. If completion.[[Type]] is throw, then
  348. if (completion.type() == Completion::Type::Throw) {
  349. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « value »).
  350. MUST(call(vm, *promise_capability->reject(), js_undefined(), value));
  351. }
  352. // 7. Else,
  353. else {
  354. // a. Assert: completion.[[Type]] is normal.
  355. VERIFY(completion.type() == Completion::Type::Normal);
  356. GC::Ptr<Object> iterator_result;
  357. // b. If realm is present, then
  358. if (realm) {
  359. // i. Let oldRealm be the running execution context's Realm.
  360. auto old_realm = vm.running_execution_context().realm;
  361. // ii. Set the running execution context's Realm to realm.
  362. vm.running_execution_context().realm = realm;
  363. // iii. Let iteratorResult be CreateIterResultObject(value, done).
  364. iterator_result = create_iterator_result_object(vm, value, done);
  365. // iv. Set the running execution context's Realm to oldRealm.
  366. vm.running_execution_context().realm = old_realm;
  367. }
  368. // c. Else,
  369. else {
  370. // i. Let iteratorResult be CreateIterResultObject(value, done).
  371. iterator_result = create_iterator_result_object(vm, value, done);
  372. }
  373. VERIFY(iterator_result);
  374. // d. Perform ! Call(promiseCapability.[[Resolve]], undefined, « iteratorResult »).
  375. MUST(call(vm, *promise_capability->resolve(), js_undefined(), iterator_result));
  376. }
  377. // 8. Return unused.
  378. }
  379. // 27.6.3.10 AsyncGeneratorDrainQueue ( generator ), https://tc39.es/ecma262/#sec-asyncgeneratordrainqueue
  380. void AsyncGenerator::drain_queue()
  381. {
  382. // 1. Assert: generator.[[AsyncGeneratorState]] is completed.
  383. VERIFY(m_async_generator_state == State::Completed);
  384. // 2. Let queue be generator.[[AsyncGeneratorQueue]].
  385. auto& queue = m_async_generator_queue;
  386. // 3. If queue is empty, return unused.
  387. if (queue.is_empty())
  388. return;
  389. // 4. Let done be false.
  390. bool done = false;
  391. // 5. Repeat, while done is false,
  392. while (!done) {
  393. // a. Let next be the first element of queue.
  394. auto& next = m_async_generator_queue.first();
  395. // b. Let completion be Completion(next.[[Completion]]).
  396. auto completion = Completion(next.completion);
  397. // c. If completion.[[Type]] is return, then
  398. if (completion.type() == Completion::Type::Return) {
  399. // i. Set generator.[[AsyncGeneratorState]] to awaiting-return.
  400. m_async_generator_state = State::AwaitingReturn;
  401. // ii. Perform AsyncGeneratorAwaitReturn(generator).
  402. await_return();
  403. // iii. Set done to true.
  404. done = true;
  405. }
  406. // d. Else,
  407. else {
  408. // i. If completion.[[Type]] is normal, then
  409. if (completion.type() == Completion::Type::Normal) {
  410. // 1. Set completion to NormalCompletion(undefined).
  411. completion = normal_completion(js_undefined());
  412. }
  413. // ii. Perform AsyncGeneratorCompleteStep(generator, completion, true).
  414. complete_step(completion, true);
  415. // iii. If queue is empty, set done to true.
  416. if (queue.is_empty())
  417. done = true;
  418. }
  419. }
  420. // 6. Return unused.
  421. }
  422. }