CyclicModule.cpp 39 KB

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