CyclicModule.cpp 39 KB

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