CyclicModule.cpp 34 KB

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