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