CyclicModule.cpp 39 KB

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