CyclicModule.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. /*
  2. * Copyright (c) 2022, David Tuin <davidot@serenityos.org>
  3. * Copyright (c) 2023, networkException <networkexception@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/TypeCasts.h>
  9. #include <LibJS/CyclicModule.h>
  10. #include <LibJS/Runtime/ModuleRequest.h>
  11. #include <LibJS/Runtime/PromiseCapability.h>
  12. #include <LibJS/Runtime/PromiseConstructor.h>
  13. #include <LibJS/Runtime/VM.h>
  14. namespace JS {
  15. CyclicModule::CyclicModule(Realm& realm, StringView filename, bool has_top_level_await, Vector<ModuleRequest> requested_modules, Script::HostDefined* host_defined)
  16. : Module(realm, filename, host_defined)
  17. , m_requested_modules(move(requested_modules))
  18. , m_has_top_level_await(has_top_level_await)
  19. {
  20. }
  21. void CyclicModule::visit_edges(Cell::Visitor& visitor)
  22. {
  23. Base::visit_edges(visitor);
  24. visitor.visit(m_cycle_root);
  25. visitor.visit(m_top_level_capability);
  26. for (auto const& module : m_async_parent_modules)
  27. visitor.visit(module);
  28. for (auto const& loaded_module : m_loaded_modules)
  29. visitor.visit(loaded_module.module);
  30. }
  31. // 16.2.1.5.1 LoadRequestedModules ( [ hostDefined ] ), https://tc39.es/ecma262/#sec-LoadRequestedModules
  32. PromiseCapability& CyclicModule::load_requested_modules(JS::Realm& realm, Optional<GraphLoadingState::HostDefined> host_defined)
  33. {
  34. // 1. If hostDefined is not present, let hostDefined be EMPTY.
  35. // NOTE: The empty state is handled by hostDefined being an optional without value.
  36. // 2. Let pc be ! NewPromiseCapability(%Promise%).
  37. auto promise_capability = MUST(new_promise_capability(realm.vm(), realm.intrinsics().promise_constructor()));
  38. // 3. Let state be the GraphLoadingState Record { [[IsLoading]]: true, [[PendingModulesCount]]: 1, [[Visited]]: « », [[PromiseCapability]]: pc, [[HostDefined]]: hostDefined }.
  39. auto state = GraphLoadingState { .promise_capability = promise_capability, .is_loading = true, .pending_module_count = 1, .visited = {}, .host_defined = move(host_defined) };
  40. // 4. Perform InnerModuleLoading(state, module).
  41. inner_module_loading(state);
  42. // NOTE: This is likely a spec bug, see https://matrixlogs.bakkot.com/WHATWG/2023-02-13#L1
  43. // FIXME: 5. Return pc.[[Promise]].
  44. return promise_capability;
  45. }
  46. // 16.2.1.5.1.1 InnerModuleLoading ( state, module ), https://tc39.es/ecma262/#sec-InnerModuleLoading
  47. void CyclicModule::inner_module_loading(JS::GraphLoadingState& state)
  48. {
  49. // 1. Assert: state.[[IsLoading]] is true.
  50. VERIFY(state.is_loading);
  51. // 2. If module is a Cyclic Module Record, module.[[Status]] is NEW, and state.[[Visited]] does not contain module, then
  52. if (m_status == ModuleStatus::New && !state.visited.contains(this)) {
  53. // a. Append module to state.[[Visited]].
  54. state.visited.set(this);
  55. // b. Let requestedModulesCount be the number of elements in module.[[RequestedModules]].
  56. auto requested_modules_count = m_requested_modules.size();
  57. // c. Set state.[[PendingModulesCount]] to state.[[PendingModulesCount]] + requestedModulesCount.
  58. state.pending_module_count += requested_modules_count;
  59. // d. For each String required of module.[[RequestedModules]], do
  60. for (auto const& required : m_requested_modules) {
  61. bool found_record_in_loaded_modules = false;
  62. // i. If module.[[LoadedModules]] contains a Record whose [[Specifier]] is required, then
  63. for (auto const& record : m_loaded_modules) {
  64. if (record.specifier == required.module_specifier) {
  65. // 1. Let record be that Record.
  66. // 2. Perform InnerModuleLoading(state, record.[[Module]]).
  67. static_cast<CyclicModule&>(*record.module).inner_module_loading(state);
  68. found_record_in_loaded_modules = true;
  69. break;
  70. }
  71. }
  72. // ii. Else,
  73. if (!found_record_in_loaded_modules) {
  74. // 1. Perform HostLoadImportedModule(module, required, state.[[HostDefined]], state).
  75. vm().host_load_imported_module(realm(), NonnullGCPtr<CyclicModule>(*this), required, state.host_defined, state);
  76. // 2. NOTE: HostLoadImportedModule will call FinishLoadingImportedModule, which re-enters the graph loading process through ContinueModuleLoading.
  77. }
  78. // iii. If state.[[IsLoading]] is false, return UNUSED.
  79. if (!state.is_loading)
  80. return;
  81. }
  82. }
  83. // 3. Assert: state.[[PendingModulesCount]] ≥ 1.
  84. VERIFY(state.pending_module_count >= 1);
  85. // 4. Set state.[[PendingModulesCount]] to state.[[PendingModulesCount]] - 1.
  86. --state.pending_module_count;
  87. // 5. If state.[[PendingModulesCount]] = 0, then
  88. if (state.pending_module_count == 0) {
  89. // a. Set state.[[IsLoading]] to false.
  90. state.is_loading = false;
  91. // b. For each Cyclic Module Record loaded of state.[[Visited]], do
  92. for (auto const& loaded : state.visited) {
  93. // i. If loaded.[[Status]] is NEW, set loaded.[[Status]] to UNLINKED.
  94. if (loaded->m_status == ModuleStatus::New)
  95. loaded->m_status = ModuleStatus::Linked;
  96. }
  97. // c. Perform ! Call(state.[[PromiseCapability]].[[Resolve]], undefined, « undefined »).
  98. MUST(call(vm(), *state.promise_capability->resolve(), js_undefined(), js_undefined()));
  99. }
  100. // 6. Return unused.
  101. }
  102. // 16.2.1.5.1.2 ContinueModuleLoading ( state, moduleCompletion ), https://tc39.es/ecma262/#sec-ContinueModuleLoading
  103. void continue_module_loading(Realm& realm, GraphLoadingState& state, ThrowCompletionOr<Module*> const& module_completion)
  104. {
  105. // 1. If state.[[IsLoading]] is false, return UNUSED.
  106. if (state.is_loading)
  107. return;
  108. // 2. If moduleCompletion is a normal completion, then
  109. if (!module_completion.is_error()) {
  110. auto* module = const_cast<Module*>(module_completion.value());
  111. // a. Perform InnerModuleLoading(state, moduleCompletion.[[Value]]).
  112. static_cast<CyclicModule*>(module)->inner_module_loading(state);
  113. }
  114. // 3. Else,
  115. else {
  116. // a. Set state.[[IsLoading]] to false.
  117. state.is_loading = false;
  118. auto value = module_completion.throw_completion().value();
  119. // b. Perform ! Call(state.[[PromiseCapability]].[[Reject]], undefined, « moduleCompletion.[[Value]] »).
  120. MUST(call(realm.vm(), *state.promise_capability->reject(), js_undefined(), *value));
  121. }
  122. // 4. Return UNUSED.
  123. }
  124. // 16.2.1.5.1 Link ( ), https://tc39.es/ecma262/#sec-moduledeclarationlinking
  125. ThrowCompletionOr<void> CyclicModule::link(VM& vm)
  126. {
  127. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] link[{}]()", this);
  128. // 1. Assert: module.[[Status]] is not linking or evaluating.
  129. VERIFY(m_status != ModuleStatus::Linking && m_status != ModuleStatus::Evaluating);
  130. // 2. Let stack be a new empty List.
  131. Vector<Module*> stack;
  132. // 3. Let result be Completion(InnerModuleLinking(module, stack, 0)).
  133. auto result = inner_module_linking(vm, stack, 0);
  134. // 4. If result is an abrupt completion, then
  135. if (result.is_throw_completion()) {
  136. // a. For each Cyclic Module Record m of stack, do
  137. for (auto* module : stack) {
  138. if (is<CyclicModule>(module)) {
  139. auto& cyclic_module = static_cast<CyclicModule&>(*module);
  140. // i. Assert: m.[[Status]] is linking.
  141. VERIFY(cyclic_module.m_status == ModuleStatus::Linking);
  142. // ii. Set m.[[Status]] to unlinked.
  143. cyclic_module.m_status = ModuleStatus::Unlinked;
  144. }
  145. }
  146. // b. Assert: module.[[Status]] is unlinked.
  147. VERIFY(m_status == ModuleStatus::Unlinked);
  148. // c. Return result.
  149. return result.release_error();
  150. }
  151. // 5. Assert: module.[[Status]] is linked, evaluating-async, or evaluated.
  152. VERIFY(m_status == ModuleStatus::Linked || m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated);
  153. // 6. Assert: stack is empty.
  154. VERIFY(stack.is_empty());
  155. // 7. Return unused.
  156. return {};
  157. }
  158. // 16.2.1.5.1.1 InnerModuleLinking ( module, stack, index ), https://tc39.es/ecma262/#sec-InnerModuleLinking
  159. ThrowCompletionOr<u32> CyclicModule::inner_module_linking(VM& vm, Vector<Module*>& stack, u32 index)
  160. {
  161. // 1. If module is not a Cyclic Module Record, then
  162. // a. Perform ? module.Link().
  163. // b. Return index.
  164. // Note: Step 1, 1.a and 1.b are handled in Module.cpp
  165. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] inner_module_linking[{}](vm, {}, {})", this, DeprecatedString::join(',', stack), index);
  166. // 2. If module.[[Status]] is linking, linked, evaluating-async, or evaluated, then
  167. if (m_status == ModuleStatus::Linking || m_status == ModuleStatus::Linked || m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated) {
  168. // a. Return index.
  169. return index;
  170. }
  171. // 3. Assert: module.[[Status]] is unlinked.
  172. VERIFY(m_status == ModuleStatus::Unlinked);
  173. // 4. Set module.[[Status]] to linking.
  174. m_status = ModuleStatus::Linking;
  175. // 5. Set module.[[DFSIndex]] to index.
  176. m_dfs_index = index;
  177. // 6. Set module.[[DFSAncestorIndex]] to index.
  178. m_dfs_ancestor_index = index;
  179. // 7. Set index to index + 1.
  180. ++index;
  181. // 8. Append module to stack.
  182. stack.append(this);
  183. #if JS_MODULE_DEBUG
  184. StringBuilder request_module_names;
  185. for (auto& module_request : m_requested_modules) {
  186. request_module_names.append(module_request.module_specifier);
  187. request_module_names.append(", "sv);
  188. }
  189. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] module: {} has requested modules: [{}]", filename(), request_module_names.string_view());
  190. #endif
  191. // 9. For each String required of module.[[RequestedModules]], do
  192. for (auto& required_string : m_requested_modules) {
  193. ModuleRequest required { required_string };
  194. // a. Let requiredModule be ? HostResolveImportedModule(module, required).
  195. auto required_module = TRY(vm.host_resolve_imported_module(NonnullGCPtr<Module>(*this), required));
  196. // b. Set index to ? InnerModuleLinking(requiredModule, stack, index).
  197. index = TRY(required_module->inner_module_linking(vm, stack, index));
  198. // c. If requiredModule is a Cyclic Module Record, then
  199. if (is<CyclicModule>(*required_module)) {
  200. auto& cyclic_module = static_cast<CyclicModule&>(*required_module);
  201. // i. Assert: requiredModule.[[Status]] is either linking, linked, evaluating-async, or evaluated.
  202. VERIFY(cyclic_module.m_status == ModuleStatus::Linking || cyclic_module.m_status == ModuleStatus::Linked || cyclic_module.m_status == ModuleStatus::EvaluatingAsync || cyclic_module.m_status == ModuleStatus::Evaluated);
  203. // ii. Assert: requiredModule.[[Status]] is linking if and only if requiredModule is in stack.
  204. VERIFY((cyclic_module.m_status == ModuleStatus::Linking) == (stack.contains_slow(&cyclic_module)));
  205. // iii. If requiredModule.[[Status]] is linking, then
  206. if (cyclic_module.m_status == ModuleStatus::Linking) {
  207. // 1. Set module.[[DFSAncestorIndex]] to min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]]).
  208. m_dfs_ancestor_index = min(m_dfs_ancestor_index.value(), cyclic_module.m_dfs_ancestor_index.value());
  209. }
  210. }
  211. }
  212. // 10. Perform ? module.InitializeEnvironment().
  213. TRY(initialize_environment(vm));
  214. // 11. Assert: module occurs exactly once in stack.
  215. size_t count = 0;
  216. for (auto* module : stack) {
  217. if (module == this)
  218. count++;
  219. }
  220. VERIFY(count == 1);
  221. // 12. Assert: module.[[DFSAncestorIndex]] ≤ module.[[DFSIndex]].
  222. VERIFY(m_dfs_ancestor_index.value() <= m_dfs_index.value());
  223. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] module {} after inner_linking has dfs {} and ancestor dfs {}", filename(), m_dfs_index.value(), m_dfs_ancestor_index.value());
  224. // 13. If module.[[DFSAncestorIndex]] = module.[[DFSIndex]], then
  225. if (m_dfs_ancestor_index == m_dfs_index) {
  226. // a. Let done be false.
  227. // b. Repeat, while done is false,
  228. while (true) {
  229. // i. Let requiredModule be the last element in stack.
  230. // ii. Remove the last element of stack.
  231. auto* required_module = stack.take_last();
  232. // iii. Assert: requiredModule is a Cyclic Module Record.
  233. VERIFY(is<CyclicModule>(*required_module));
  234. // iv. Set requiredModule.[[Status]] to linked.
  235. static_cast<CyclicModule&>(*required_module).m_status = ModuleStatus::Linked;
  236. // v. If requiredModule and module are the same Module Record, set done to true.
  237. if (required_module == this)
  238. break;
  239. }
  240. }
  241. // 14. Return index.
  242. return index;
  243. }
  244. // 16.2.1.5.2 Evaluate ( ), https://tc39.es/ecma262/#sec-moduleevaluation
  245. ThrowCompletionOr<Promise*> CyclicModule::evaluate(VM& vm)
  246. {
  247. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] evaluate[{}](vm)", this);
  248. // 1. Assert: This call to Evaluate is not happening at the same time as another call to Evaluate within the surrounding agent.
  249. // FIXME: Verify this somehow
  250. // 2. Assert: module.[[Status]] is linked, evaluating-async, or evaluated.
  251. VERIFY(m_status == ModuleStatus::Linked || m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated);
  252. // NOTE: The spec does not catch the case where evaluate is called twice on a script which failed
  253. // during evaluation. This means the script is evaluated but does not have a cycle root.
  254. // In that case we first check if this module itself has a top level capability.
  255. // See also: https://github.com/tc39/ecma262/issues/2823 .
  256. if (m_top_level_capability != nullptr)
  257. return verify_cast<Promise>(m_top_level_capability->promise().ptr());
  258. // 3. If module.[[Status]] is evaluating-async or evaluated, set module to module.[[CycleRoot]].
  259. if (m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated) {
  260. // Note: This will continue this function with module.[[CycleRoot]]
  261. VERIFY(m_cycle_root);
  262. VERIFY(this != m_cycle_root);
  263. VERIFY(m_cycle_root->m_status == ModuleStatus::Linked);
  264. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] evaluate[{}](vm) deferring to cycle root at {}", this, m_cycle_root.ptr());
  265. return m_cycle_root->evaluate(vm);
  266. }
  267. // 4. If module.[[TopLevelCapability]] is not empty, then
  268. if (m_top_level_capability != nullptr) {
  269. // a. Return module.[[TopLevelCapability]].[[Promise]].
  270. return verify_cast<Promise>(m_top_level_capability->promise().ptr());
  271. }
  272. // 5. Let stack be a new empty List.
  273. Vector<Module*> stack;
  274. auto& realm = *vm.current_realm();
  275. // 6. Let capability be ! NewPromiseCapability(%Promise%).
  276. // 7. Set module.[[TopLevelCapability]] to capability.
  277. m_top_level_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  278. // 8. Let result be Completion(InnerModuleEvaluation(module, stack, 0)).
  279. auto result = inner_module_evaluation(vm, stack, 0);
  280. // 9. If result is an abrupt completion, then
  281. if (result.is_throw_completion()) {
  282. VERIFY(!m_evaluation_error.is_error());
  283. // a. For each Cyclic Module Record m of stack, do
  284. for (auto* mod : stack) {
  285. if (!is<CyclicModule>(*mod))
  286. continue;
  287. auto& cyclic_module = static_cast<CyclicModule&>(*mod);
  288. // i. Assert: m.[[Status]] is evaluating.
  289. VERIFY(cyclic_module.m_status == ModuleStatus::Evaluating);
  290. // ii. Set m.[[Status]] to evaluated.
  291. cyclic_module.m_status = ModuleStatus::Evaluated;
  292. // iii. Set m.[[EvaluationError]] to result.
  293. cyclic_module.m_evaluation_error = result.throw_completion();
  294. }
  295. // b. Assert: module.[[Status]] is evaluated.
  296. VERIFY(m_status == ModuleStatus::Evaluated);
  297. // c. Assert: module.[[EvaluationError]] is result.
  298. VERIFY(m_evaluation_error.is_error() && same_value(*m_evaluation_error.throw_completion().value(), *result.throw_completion().value()));
  299. // d. Perform ! Call(capability.[[Reject]], undefined, « result.[[Value]] »).
  300. MUST(call(vm, *m_top_level_capability->reject(), js_undefined(), *result.throw_completion().value()));
  301. }
  302. // 10. Else,
  303. else {
  304. // a. Assert: module.[[Status]] is evaluating-async or evaluated.
  305. VERIFY(m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated);
  306. // b. Assert: module.[[EvaluationError]] is empty.
  307. VERIFY(!m_evaluation_error.is_error());
  308. // c. If module.[[AsyncEvaluation]] is false, then
  309. if (!m_async_evaluation) {
  310. // i. Assert: module.[[Status]] is evaluated.
  311. VERIFY(m_status == ModuleStatus::Evaluated);
  312. // ii. Perform ! Call(capability.[[Resolve]], undefined, « undefined »).
  313. MUST(call(vm, *m_top_level_capability->resolve(), js_undefined(), js_undefined()));
  314. }
  315. // d. Assert: stack is empty.
  316. VERIFY(stack.is_empty());
  317. }
  318. // 11. Return capability.[[Promise]].
  319. return verify_cast<Promise>(m_top_level_capability->promise().ptr());
  320. }
  321. // 16.2.1.5.2.1 InnerModuleEvaluation ( module, stack, index ), https://tc39.es/ecma262/#sec-innermoduleevaluation
  322. ThrowCompletionOr<u32> CyclicModule::inner_module_evaluation(VM& vm, Vector<Module*>& stack, u32 index)
  323. {
  324. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] inner_module_evaluation[{}](vm, {}, {})", this, DeprecatedString::join(", "sv, stack), index);
  325. // Note: Step 1 is performed in Module.cpp
  326. // 2. If module.[[Status]] is evaluating-async or evaluated, then
  327. if (m_status == ModuleStatus::EvaluatingAsync || m_status == ModuleStatus::Evaluated) {
  328. // a. If module.[[EvaluationError]] is empty, return index.
  329. if (!m_evaluation_error.is_error())
  330. return index;
  331. // b. Otherwise, return ? module.[[EvaluationError]].
  332. return m_evaluation_error.throw_completion();
  333. }
  334. // 3. If module.[[Status]] is evaluating, return index.
  335. if (m_status == ModuleStatus::Evaluating)
  336. return index;
  337. // 4. Assert: module.[[Status]] is linked.
  338. VERIFY(m_status == ModuleStatus::Linked);
  339. // 5. Set module.[[Status]] to evaluating.
  340. m_status = ModuleStatus::Evaluating;
  341. // 6. Set module.[[DFSIndex]] to index.
  342. m_dfs_index = index;
  343. // 7. Set module.[[DFSAncestorIndex]] to index.
  344. m_dfs_ancestor_index = index;
  345. // 8. Set module.[[PendingAsyncDependencies]] to 0.
  346. m_pending_async_dependencies = 0;
  347. // 9. Set index to index + 1.
  348. ++index;
  349. // 10. Append module to stack.
  350. stack.append(this);
  351. // 11. For each String required of module.[[RequestedModules]], do
  352. for (auto& required : m_requested_modules) {
  353. // a. Let requiredModule be ! HostResolveImportedModule(module, required).
  354. auto* required_module = MUST(vm.host_resolve_imported_module(NonnullGCPtr<Module>(*this), required)).ptr();
  355. // b. NOTE: Link must be completed successfully prior to invoking this method, so every requested module is guaranteed to resolve successfully.
  356. // c. Set index to ? InnerModuleEvaluation(requiredModule, stack, index).
  357. index = TRY(required_module->inner_module_evaluation(vm, stack, index));
  358. // d. If requiredModule is a Cyclic Module Record, then
  359. if (!is<CyclicModule>(*required_module))
  360. continue;
  361. auto* cyclic_module = static_cast<CyclicModule*>(required_module);
  362. // i. Assert: requiredModule.[[Status]] is either evaluating, evaluating-async, or evaluated.
  363. VERIFY(cyclic_module->m_status == ModuleStatus::Evaluating || cyclic_module->m_status == ModuleStatus::EvaluatingAsync || cyclic_module->m_status == ModuleStatus::Evaluated);
  364. // ii. Assert: requiredModule.[[Status]] is evaluating if and only if requiredModule is in stack.
  365. VERIFY(cyclic_module->m_status != ModuleStatus::Evaluating || stack.contains_slow(cyclic_module));
  366. // iii. If requiredModule.[[Status]] is evaluating, then
  367. if (cyclic_module->m_status == ModuleStatus::Evaluating) {
  368. // 1. Set module.[[DFSAncestorIndex]] to min(module.[[DFSAncestorIndex]], requiredModule.[[DFSAncestorIndex]]).
  369. m_dfs_ancestor_index = min(m_dfs_ancestor_index.value(), cyclic_module->m_dfs_ancestor_index.value());
  370. }
  371. // iv. Else,
  372. else {
  373. // 1. Set requiredModule to requiredModule.[[CycleRoot]].
  374. cyclic_module = cyclic_module->m_cycle_root;
  375. // 2. Assert: requiredModule.[[Status]] is evaluating-async or evaluated.
  376. VERIFY(cyclic_module->m_status == ModuleStatus::EvaluatingAsync || cyclic_module->m_status == ModuleStatus::Evaluated);
  377. // 3. If requiredModule.[[EvaluationError]] is not empty, return ? requiredModule.[[EvaluationError]].
  378. if (cyclic_module->m_evaluation_error.is_error())
  379. return cyclic_module->m_evaluation_error.throw_completion();
  380. }
  381. // v. If requiredModule.[[AsyncEvaluation]] is true, then
  382. if (cyclic_module->m_async_evaluation) {
  383. // 1. Set module.[[PendingAsyncDependencies]] to module.[[PendingAsyncDependencies]] + 1.
  384. ++m_pending_async_dependencies.value();
  385. // 2. Append module to requiredModule.[[AsyncParentModules]].
  386. cyclic_module->m_async_parent_modules.append(this);
  387. }
  388. }
  389. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] inner_module_evaluation on {} has tla: {} and pending async dep: {} dfs: {} ancestor dfs: {}", filename(), m_has_top_level_await, m_pending_async_dependencies.value(), m_dfs_index.value(), m_dfs_ancestor_index.value());
  390. // 12. If module.[[PendingAsyncDependencies]] > 0 or module.[[HasTLA]] is true, then
  391. if (m_pending_async_dependencies.value() > 0 || m_has_top_level_await) {
  392. // a. Assert: module.[[AsyncEvaluation]] is false and was never previously set to true.
  393. VERIFY(!m_async_evaluation); // FIXME: I don't think we can check previously?
  394. // b. Set module.[[AsyncEvaluation]] to true.
  395. m_async_evaluation = true;
  396. // c. NOTE: The order in which module records have their [[AsyncEvaluation]] fields transition to true is significant. (See 16.2.1.5.2.4.)
  397. // d. If module.[[PendingAsyncDependencies]] is 0, perform ExecuteAsyncModule(module).
  398. if (m_pending_async_dependencies.value() == 0)
  399. execute_async_module(vm);
  400. }
  401. // 13. Otherwise, perform ? module.ExecuteModule().
  402. else {
  403. TRY(execute_module(vm));
  404. }
  405. // 14. Assert: module occurs exactly once in stack.
  406. auto count = 0;
  407. for (auto* module : stack) {
  408. if (module == this)
  409. count++;
  410. }
  411. VERIFY(count == 1);
  412. // 15. Assert: module.[[DFSAncestorIndex]] ≤ module.[[DFSIndex]].
  413. VERIFY(m_dfs_ancestor_index.value() <= m_dfs_index.value());
  414. // 16. If module.[[DFSAncestorIndex]] = module.[[DFSIndex]], then
  415. if (m_dfs_ancestor_index == m_dfs_index) {
  416. // a. Let done be false.
  417. bool done = false;
  418. // b. Repeat, while done is false,
  419. while (!done) {
  420. // i. Let requiredModule be the last element in stack.
  421. // ii. Remove the last element of stack.
  422. auto* required_module = stack.take_last();
  423. // iii. Assert: requiredModule is a Cyclic Module Record.
  424. VERIFY(is<CyclicModule>(*required_module));
  425. auto& cyclic_module = static_cast<CyclicModule&>(*required_module);
  426. // iv. If requiredModule.[[AsyncEvaluation]] is false, set requiredModule.[[Status]] to evaluated.
  427. if (!cyclic_module.m_async_evaluation)
  428. cyclic_module.m_status = ModuleStatus::Evaluated;
  429. // v. Otherwise, set requiredModule.[[Status]] to evaluating-async.
  430. else
  431. cyclic_module.m_status = ModuleStatus::EvaluatingAsync;
  432. // vi. If requiredModule and module are the same Module Record, set done to true.
  433. if (required_module == this)
  434. done = true;
  435. // vii. Set requiredModule.[[CycleRoot]] to module.
  436. cyclic_module.m_cycle_root = this;
  437. }
  438. }
  439. // 17. Return index.
  440. return index;
  441. }
  442. ThrowCompletionOr<void> CyclicModule::initialize_environment(VM&)
  443. {
  444. // Note: In ecma262 this is never called on a cyclic module only on SourceTextModules.
  445. // So this check is to make sure we don't accidentally call this.
  446. VERIFY_NOT_REACHED();
  447. }
  448. ThrowCompletionOr<void> CyclicModule::execute_module(VM&, GCPtr<PromiseCapability>)
  449. {
  450. // Note: In ecma262 this is never called on a cyclic module only on SourceTextModules.
  451. // So this check is to make sure we don't accidentally call this.
  452. VERIFY_NOT_REACHED();
  453. }
  454. // 16.2.1.5.2.2 ExecuteAsyncModule ( module ), https://tc39.es/ecma262/#sec-execute-async-module
  455. void CyclicModule::execute_async_module(VM& vm)
  456. {
  457. auto& realm = *vm.current_realm();
  458. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] executing async module {}", filename());
  459. // 1. Assert: module.[[Status]] is evaluating or evaluating-async.
  460. VERIFY(m_status == ModuleStatus::Evaluating || m_status == ModuleStatus::EvaluatingAsync);
  461. // 2. Assert: module.[[HasTLA]] is true.
  462. VERIFY(m_has_top_level_await);
  463. // 3. Let capability be ! NewPromiseCapability(%Promise%).
  464. auto capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  465. // 4. Let fulfilledClosure be a new Abstract Closure with no parameters that captures module and performs the following steps when called:
  466. auto fulfilled_closure = [&](VM& vm) -> ThrowCompletionOr<Value> {
  467. // a. Perform AsyncModuleExecutionFulfilled(module).
  468. async_module_execution_fulfilled(vm);
  469. // b. Return undefined.
  470. return js_undefined();
  471. };
  472. // 5. Let onFulfilled be CreateBuiltinFunction(fulfilledClosure, 0, "", « »).
  473. auto on_fulfilled = NativeFunction::create(realm, move(fulfilled_closure), 0, "");
  474. // 6. Let rejectedClosure be a new Abstract Closure with parameters (error) that captures module and performs the following steps when called:
  475. auto rejected_closure = [&](VM& vm) -> ThrowCompletionOr<Value> {
  476. auto error = vm.argument(0);
  477. // a. Perform AsyncModuleExecutionRejected(module, error).
  478. async_module_execution_rejected(vm, error);
  479. // b. Return undefined.
  480. return js_undefined();
  481. };
  482. // 7. Let onRejected be CreateBuiltinFunction(rejectedClosure, 0, "", « »).
  483. auto on_rejected = NativeFunction::create(realm, move(rejected_closure), 0, "");
  484. // 8. Perform PerformPromiseThen(capability.[[Promise]], onFulfilled, onRejected).
  485. verify_cast<Promise>(capability->promise().ptr())->perform_then(on_fulfilled, on_rejected, {});
  486. // 9. Perform ! module.ExecuteModule(capability).
  487. MUST(execute_module(vm, capability));
  488. // 10. Return unused.
  489. }
  490. // 16.2.1.5.2.3 GatherAvailableAncestors ( module, execList ), https://tc39.es/ecma262/#sec-gather-available-ancestors
  491. void CyclicModule::gather_available_ancestors(Vector<CyclicModule*>& exec_list)
  492. {
  493. // 1. For each Cyclic Module Record m of module.[[AsyncParentModules]], do
  494. for (auto module : m_async_parent_modules) {
  495. // a. If execList does not contain m and m.[[CycleRoot]].[[EvaluationError]] is empty, then
  496. if (!exec_list.contains_slow(module) && !module->m_cycle_root->m_evaluation_error.is_error()) {
  497. // i. Assert: m.[[Status]] is evaluating-async.
  498. VERIFY(module->m_status == ModuleStatus::EvaluatingAsync);
  499. // ii. Assert: m.[[EvaluationError]] is empty.
  500. VERIFY(!module->m_evaluation_error.is_error());
  501. // iii. Assert: m.[[AsyncEvaluation]] is true.
  502. VERIFY(module->m_async_evaluation);
  503. // iv. Assert: m.[[PendingAsyncDependencies]] > 0.
  504. VERIFY(module->m_pending_async_dependencies.value() > 0);
  505. // v. Set m.[[PendingAsyncDependencies]] to m.[[PendingAsyncDependencies]] - 1.
  506. module->m_pending_async_dependencies.value()--;
  507. // vi. If m.[[PendingAsyncDependencies]] = 0, then
  508. if (module->m_pending_async_dependencies.value() == 0) {
  509. // 1. Append m to execList.
  510. exec_list.append(module);
  511. // 2. If m.[[HasTLA]] is false, perform GatherAvailableAncestors(m, execList).
  512. if (!module->m_has_top_level_await)
  513. module->gather_available_ancestors(exec_list);
  514. }
  515. }
  516. }
  517. // 2. Return unused.
  518. }
  519. // 16.2.1.5.2.4 AsyncModuleExecutionFulfilled ( module ), https://tc39.es/ecma262/#sec-async-module-execution-fulfilled
  520. void CyclicModule::async_module_execution_fulfilled(VM& vm)
  521. {
  522. // 1. If module.[[Status]] is evaluated, then
  523. if (m_status == ModuleStatus::Evaluated) {
  524. // a. Assert: module.[[EvaluationError]] is not empty.
  525. VERIFY(m_evaluation_error.is_error());
  526. // b. Return unused.
  527. return;
  528. }
  529. // 2. Assert: module.[[Status]] is evaluating-async.
  530. VERIFY(m_status == ModuleStatus::EvaluatingAsync);
  531. // 3. Assert: module.[[AsyncEvaluation]] is true.
  532. VERIFY(m_async_evaluation);
  533. // 4. Assert: module.[[EvaluationError]] is empty.
  534. VERIFY(!m_evaluation_error.is_error());
  535. // 5. Set module.[[AsyncEvaluation]] to false.
  536. m_async_evaluation = false;
  537. // 6. Set module.[[Status]] to evaluated.
  538. m_status = ModuleStatus::Evaluated;
  539. // 7. If module.[[TopLevelCapability]] is not empty, then
  540. if (m_top_level_capability != nullptr) {
  541. // a. Assert: module.[[CycleRoot]] is module.
  542. VERIFY(m_cycle_root == this);
  543. // b. Perform ! Call(module.[[TopLevelCapability]].[[Resolve]], undefined, « undefined »).
  544. MUST(call(vm, *m_top_level_capability->resolve(), js_undefined(), js_undefined()));
  545. }
  546. // 8. Let execList be a new empty List.
  547. Vector<CyclicModule*> exec_list;
  548. // 9. Perform GatherAvailableAncestors(module, execList).
  549. gather_available_ancestors(exec_list);
  550. // 10. Let sortedExecList be a List whose elements are the elements of execList, in the order in which they had their [[AsyncEvaluation]] fields set to true in InnerModuleEvaluation.
  551. // FIXME: Sort the list. To do this we need to use more than an Optional<bool> to track [[AsyncEvaluation]].
  552. // 11. Assert: All elements of sortedExecList have their [[AsyncEvaluation]] field set to true, [[PendingAsyncDependencies]] field set to 0, and [[EvaluationError]] field set to empty.
  553. VERIFY(all_of(exec_list, [&](CyclicModule* module) { return module->m_async_evaluation && module->m_pending_async_dependencies.value() == 0 && !module->m_evaluation_error.is_error(); }));
  554. // 12. For each Cyclic Module Record m of sortedExecList, do
  555. for (auto* module : exec_list) {
  556. // a. If m.[[Status]] is evaluated, then
  557. if (module->m_status == ModuleStatus::Evaluated) {
  558. // i. Assert: m.[[EvaluationError]] is not empty.
  559. VERIFY(module->m_evaluation_error.is_error());
  560. }
  561. // b. Else if m.[[HasTLA]] is true, then
  562. else if (module->m_has_top_level_await) {
  563. // i. Perform ExecuteAsyncModule(m).
  564. module->execute_async_module(vm);
  565. }
  566. // c. Else,
  567. else {
  568. // i. Let result be m.ExecuteModule().
  569. auto result = module->execute_module(vm);
  570. // ii. If result is an abrupt completion, then
  571. if (result.is_throw_completion()) {
  572. // 1. Perform AsyncModuleExecutionRejected(m, result.[[Value]]).
  573. module->async_module_execution_rejected(vm, *result.throw_completion().value());
  574. }
  575. // iii. Else,
  576. else {
  577. // 1. Set m.[[Status]] to evaluated.
  578. module->m_status = ModuleStatus::Evaluated;
  579. // 2. If m.[[TopLevelCapability]] is not empty, then
  580. if (module->m_top_level_capability != nullptr) {
  581. // a. Assert: m.[[CycleRoot]] is m.
  582. VERIFY(module->m_cycle_root == module);
  583. // b. Perform ! Call(m.[[TopLevelCapability]].[[Resolve]], undefined, « undefined »).
  584. MUST(call(vm, *module->m_top_level_capability->resolve(), js_undefined(), js_undefined()));
  585. }
  586. }
  587. }
  588. }
  589. // 13. Return unused.
  590. }
  591. // 16.2.1.5.2.5 AsyncModuleExecutionRejected ( module, error ), https://tc39.es/ecma262/#sec-async-module-execution-rejected
  592. void CyclicModule::async_module_execution_rejected(VM& vm, Value error)
  593. {
  594. // 1. If module.[[Status]] is evaluated, then
  595. if (m_status == ModuleStatus::Evaluated) {
  596. // a. Assert: module.[[EvaluationError]] is not empty.
  597. VERIFY(m_evaluation_error.is_error());
  598. // b. Return unused.
  599. return;
  600. }
  601. // 2. Assert: module.[[Status]] is evaluating-async.
  602. VERIFY(m_status == ModuleStatus::EvaluatingAsync);
  603. // 3. Assert: module.[[AsyncEvaluation]] is true.
  604. VERIFY(m_async_evaluation);
  605. // 4. Assert: module.[[EvaluationError]] is empty.
  606. VERIFY(!m_evaluation_error.is_error());
  607. // 5. Set module.[[EvaluationError]] to ThrowCompletion(error)
  608. m_evaluation_error = throw_completion(error);
  609. // 6. Set module.[[Status]] to evaluated.
  610. m_status = ModuleStatus::Evaluated;
  611. // 7. For each Cyclic Module Record m of module.[[AsyncParentModules]], do
  612. for (auto module : m_async_parent_modules) {
  613. // a. Perform AsyncModuleExecutionRejected(m, error).
  614. module->async_module_execution_rejected(vm, error);
  615. }
  616. // 8. If module.[[TopLevelCapability]] is not empty, then
  617. if (m_top_level_capability != nullptr) {
  618. // a. Assert: module.[[CycleRoot]] is module.
  619. VERIFY(m_cycle_root == this);
  620. // b. Perform ! Call(module.[[TopLevelCapability]].[[Reject]], undefined, « error »).
  621. MUST(call(vm, *m_top_level_capability->reject(), js_undefined(), error));
  622. }
  623. // 9. Return unused.
  624. }
  625. }