CyclicModule.cpp 34 KB

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