SourceTextModule.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, David Tuin <davidot@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/QuickSort.h>
  8. #include <LibJS/Interpreter.h>
  9. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  10. #include <LibJS/Runtime/ModuleEnvironment.h>
  11. #include <LibJS/SourceTextModule.h>
  12. namespace JS {
  13. // 16.2.1.3 Static Semantics: ModuleRequests, https://tc39.es/ecma262/#sec-static-semantics-modulerequests
  14. static Vector<FlyString> module_requests(Program const& program)
  15. {
  16. // A List of all the ModuleSpecifier strings used by the module represented by this record to request the importation of a module.
  17. // Note: The List is source text occurrence ordered!
  18. struct RequestedModuleAndSourceIndex {
  19. FlyString requested_module;
  20. u64 source_index;
  21. bool operator<(RequestedModuleAndSourceIndex const& rhs) const
  22. {
  23. return source_index < rhs.source_index;
  24. }
  25. };
  26. Vector<RequestedModuleAndSourceIndex> requested_modules_with_indices;
  27. for (auto const& import_statement : program.imports()) {
  28. requested_modules_with_indices.append({ import_statement.module_request().module_specifier.view(),
  29. import_statement.source_range().start.offset });
  30. }
  31. for (auto const& export_statement : program.exports()) {
  32. for (auto const& export_entry : export_statement.entries()) {
  33. if (!export_entry.is_module_request())
  34. continue;
  35. requested_modules_with_indices.append({ export_entry.module_request().module_specifier.view(),
  36. export_statement.source_range().start.offset });
  37. }
  38. }
  39. quick_sort(requested_modules_with_indices);
  40. Vector<FlyString> requested_modules_in_source_order;
  41. requested_modules_in_source_order.ensure_capacity(requested_modules_with_indices.size());
  42. for (auto& module : requested_modules_with_indices) {
  43. requested_modules_in_source_order.append(module.requested_module);
  44. }
  45. return requested_modules_in_source_order;
  46. }
  47. SourceTextModule::SourceTextModule(Realm& realm, StringView filename, bool has_top_level_await, NonnullRefPtr<Program> body, Vector<FlyString> requested_modules,
  48. Vector<ImportEntry> import_entries, Vector<ExportEntry> local_export_entries,
  49. Vector<ExportEntry> indirect_export_entries, Vector<ExportEntry> star_export_entries,
  50. RefPtr<ExportStatement> default_export)
  51. : CyclicModule(realm, filename, has_top_level_await, move(requested_modules))
  52. , m_ecmascript_code(move(body))
  53. , m_execution_context(realm.heap())
  54. , m_import_entries(move(import_entries))
  55. , m_local_export_entries(move(local_export_entries))
  56. , m_indirect_export_entries(move(indirect_export_entries))
  57. , m_star_export_entries(move(star_export_entries))
  58. , m_default_export(move(default_export))
  59. {
  60. }
  61. // 16.2.1.6.1 ParseModule ( sourceText, realm, hostDefined ), https://tc39.es/ecma262/#sec-parsemodule
  62. Result<NonnullRefPtr<SourceTextModule>, Vector<Parser::Error>> SourceTextModule::parse(StringView source_text, Realm& realm, StringView filename)
  63. {
  64. // 1. Let body be ParseText(sourceText, Module).
  65. auto parser = Parser(Lexer(source_text, filename), Program::Type::Module);
  66. auto body = parser.parse_program();
  67. // 2. If body is a List of errors, return body.
  68. if (parser.has_errors())
  69. return parser.errors();
  70. // 3. Let requestedModules be the ModuleRequests of body.
  71. auto requested_modules = module_requests(*body);
  72. // 4. Let importEntries be ImportEntries of body.
  73. Vector<ImportEntry> import_entries;
  74. for (auto const& import_statement : body->imports())
  75. import_entries.extend(import_statement.entries());
  76. // 5. Let importedBoundNames be ImportedLocalNames(importEntries).
  77. // Note: Since we have to potentially extract the import entry we just use importEntries
  78. // In the future it might be an optimization to have a set/map of string to speed up the search.
  79. // 6. Let indirectExportEntries be a new empty List.
  80. Vector<ExportEntry> indirect_export_entries;
  81. // 7. Let localExportEntries be a new empty List.
  82. Vector<ExportEntry> local_export_entries;
  83. // 8. Let starExportEntries be a new empty List.
  84. Vector<ExportEntry> star_export_entries;
  85. // Note: Not in the spec but makes it easier to find the default.
  86. RefPtr<ExportStatement> default_export;
  87. // 9. Let exportEntries be ExportEntries of body.
  88. // 10. For each ExportEntry Record ee of exportEntries, do
  89. for (auto const& export_statement : body->exports()) {
  90. if (export_statement.is_default_export()) {
  91. VERIFY(!default_export);
  92. VERIFY(export_statement.entries().size() == 1);
  93. VERIFY(export_statement.has_statement());
  94. auto const& entry = export_statement.entries()[0];
  95. VERIFY(entry.kind == ExportStatement::ExportEntry::Kind::NamedExport);
  96. VERIFY(!entry.is_module_request());
  97. VERIFY(import_entries.find_if(
  98. [&](ImportEntry const& import_entry) {
  99. return import_entry.local_name == entry.local_or_import_name;
  100. })
  101. .is_end());
  102. default_export = export_statement;
  103. }
  104. for (auto const& export_entry : export_statement.entries()) {
  105. // a. If ee.[[ModuleRequest]] is null, then
  106. if (!export_entry.is_module_request()) {
  107. auto in_imported_bound_names = import_entries.find_if(
  108. [&](ImportEntry const& import_entry) {
  109. return import_entry.local_name == export_entry.local_or_import_name;
  110. });
  111. // i. If ee.[[LocalName]] is not an element of importedBoundNames, then
  112. if (in_imported_bound_names.is_end()) {
  113. // 1. Append ee to localExportEntries.
  114. local_export_entries.empend(export_entry);
  115. }
  116. // ii. Else,
  117. else {
  118. // 1. Let ie be the element of importEntries whose [[LocalName]] is the same as ee.[[LocalName]].
  119. auto& import_entry = *in_imported_bound_names;
  120. // 2. If ie.[[ImportName]] is namespace-object, then
  121. if (import_entry.is_namespace) {
  122. // a. NOTE: This is a re-export of an imported module namespace object.
  123. VERIFY(export_entry.is_module_request() && export_entry.kind != ExportStatement::ExportEntry::Kind::NamedExport);
  124. // b. Append ee to localExportEntries.
  125. local_export_entries.empend(export_entry);
  126. }
  127. // 3. Else,
  128. else {
  129. // a. NOTE: This is a re-export of a single name.
  130. // b. Append the ExportEntry Record { [[ModuleRequest]]: ie.[[ModuleRequest]], [[ImportName]]: ie.[[ImportName]], [[LocalName]]: null, [[ExportName]]: ee.[[ExportName]] } to indirectExportEntries.
  131. indirect_export_entries.empend(ExportEntry::indirect_export_entry(import_entry.module_request(), import_entry.import_name, export_entry.export_name));
  132. }
  133. }
  134. }
  135. // b. Else if ee.[[ImportName]] is all-but-default, then
  136. else if (export_entry.kind == ExportStatement::ExportEntry::Kind::ModuleRequestAllButDefault) {
  137. // i. Assert: ee.[[ExportName]] is null.
  138. VERIFY(export_entry.export_name.is_null());
  139. // ii. Append ee to starExportEntries.
  140. star_export_entries.empend(export_entry);
  141. }
  142. // c. Else,
  143. else {
  144. // i. Append ee to indirectExportEntries.
  145. indirect_export_entries.empend(export_entry);
  146. }
  147. }
  148. }
  149. // 11. Let async be body Contains await.
  150. bool async = body->has_top_level_await();
  151. // 12. Return Source Text Module Record {
  152. // [[Realm]]: realm, [[Environment]]: empty, [[Namespace]]: empty, [[CycleRoot]]: empty, [[HasTLA]]: async,
  153. // [[AsyncEvaluation]]: false, [[TopLevelCapability]]: empty, [[AsyncParentModules]]: « »,
  154. // [[PendingAsyncDependencies]]: empty, [[Status]]: unlinked, [[EvaluationError]]: empty,
  155. // [[HostDefined]]: hostDefined, [[ECMAScriptCode]]: body, [[Context]]: empty, [[ImportMeta]]: empty,
  156. // [[RequestedModules]]: requestedModules, [[ImportEntries]]: importEntries, [[LocalExportEntries]]: localExportEntries,
  157. // [[IndirectExportEntries]]: indirectExportEntries, [[StarExportEntries]]: starExportEntries, [[DFSIndex]]: empty, [[DFSAncestorIndex]]: empty }.
  158. // FIXME: Add HostDefined
  159. return adopt_ref(*new SourceTextModule(realm, filename, async, move(body), move(requested_modules), move(import_entries), move(local_export_entries), move(indirect_export_entries), move(star_export_entries), move(default_export)));
  160. }
  161. // 16.2.1.6.2 GetExportedNames ( [ exportStarSet ] ), https://tc39.es/ecma262/#sec-getexportednames
  162. ThrowCompletionOr<Vector<FlyString>> SourceTextModule::get_exported_names(VM& vm, Vector<Module*> export_star_set)
  163. {
  164. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] get_export_names of {}", filename());
  165. // 1. If exportStarSet is not present, set exportStarSet to a new empty List.
  166. // Note: This is done by default argument
  167. // 2. If exportStarSet contains module, then
  168. if (export_star_set.contains_slow(this)) {
  169. // a. Assert: We've reached the starting point of an export * circularity.
  170. // FIXME: How do we check that?
  171. // b. Return a new empty List.
  172. return Vector<FlyString> {};
  173. }
  174. // 3. Append module to exportStarSet.
  175. export_star_set.append(this);
  176. // 4. Let exportedNames be a new empty List.
  177. Vector<FlyString> exported_names;
  178. // 5. For each ExportEntry Record e of module.[[LocalExportEntries]], do
  179. for (auto& entry : m_local_export_entries) {
  180. // a. Assert: module provides the direct binding for this export.
  181. // FIXME: How do we check that?
  182. // b. Append e.[[ExportName]] to exportedNames.
  183. exported_names.empend(entry.export_name);
  184. }
  185. // 6. For each ExportEntry Record e of module.[[IndirectExportEntries]], do
  186. for (auto& entry : m_indirect_export_entries) {
  187. // a. Assert: module provides the direct binding for this export.
  188. // FIXME: How do we check that?
  189. // b. Append e.[[ExportName]] to exportedNames.
  190. exported_names.empend(entry.export_name);
  191. }
  192. // 7. For each ExportEntry Record e of module.[[StarExportEntries]], do
  193. for (auto& entry : m_star_export_entries) {
  194. // a. Let requestedModule be ? HostResolveImportedModule(module, e.[[ModuleRequest]]).
  195. auto requested_module = TRY(vm.host_resolve_imported_module(this, entry.module_request()));
  196. // b. Let starNames be ? requestedModule.GetExportedNames(exportStarSet).
  197. auto star_names = TRY(requested_module->get_exported_names(vm, export_star_set));
  198. // c. For each element n of starNames, do
  199. for (auto& name : star_names) {
  200. // i. If SameValue(n, "default") is false, then
  201. if (name != "default"sv) {
  202. // 1. If n is not an element of exportedNames, then
  203. if (!exported_names.contains_slow(name)) {
  204. // a. Append n to exportedNames.
  205. exported_names.empend(name);
  206. }
  207. }
  208. }
  209. }
  210. // 8. Return exportedNames.
  211. return exported_names;
  212. }
  213. // 16.2.1.6.4 InitializeEnvironment ( ), https://tc39.es/ecma262/#sec-source-text-module-record-initialize-environment
  214. Completion SourceTextModule::initialize_environment(VM& vm)
  215. {
  216. // 1. For each ExportEntry Record e of module.[[IndirectExportEntries]], do
  217. for (auto& entry : m_indirect_export_entries) {
  218. // a. Let resolution be ? module.ResolveExport(e.[[ExportName]]).
  219. auto resolution = TRY(resolve_export(vm, entry.export_name));
  220. // b. If resolution is null or ambiguous, throw a SyntaxError exception.
  221. if (!resolution.is_valid())
  222. return vm.throw_completion<SyntaxError>(realm().global_object(), ErrorType::InvalidOrAmbiguousExportEntry, entry.export_name);
  223. // c. Assert: resolution is a ResolvedBinding Record.
  224. VERIFY(resolution.is_valid());
  225. }
  226. // 2. Assert: All named exports from module are resolvable.
  227. // Note: We check all the indirect export entries above in step 1 and all
  228. // the local named exports are resolvable by construction.
  229. // 3. Let realm be module.[[Realm]].
  230. // 4. Assert: realm is not undefined.
  231. // Note: This must be true because we use a reference.
  232. auto& global_object = realm().global_object();
  233. // 5. Let env be NewModuleEnvironment(realm.[[GlobalEnv]]).
  234. auto* environment = vm.heap().allocate<ModuleEnvironment>(global_object, &realm().global_environment());
  235. // 6. Set module.[[Environment]] to env.
  236. set_environment(environment);
  237. // 7. For each ImportEntry Record in of module.[[ImportEntries]], do
  238. for (auto& import_entry : m_import_entries) {
  239. if (!import_entry.module_request().assertions.is_empty())
  240. return vm.throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "import statements with assertions");
  241. // a. Let importedModule be ! HostResolveImportedModule(module, in.[[ModuleRequest]]).
  242. auto imported_module = MUST(vm.host_resolve_imported_module(this, import_entry.module_request()));
  243. // b. NOTE: The above call cannot fail because imported module requests are a subset of module.[[RequestedModules]], and these have been resolved earlier in this algorithm.
  244. // c. If in.[[ImportName]] is namespace-object, then
  245. if (import_entry.is_namespace) {
  246. // i. Let namespace be ? GetModuleNamespace(importedModule).
  247. auto* namespace_ = TRY(imported_module->get_module_namespace(vm));
  248. // ii. Perform ! env.CreateImmutableBinding(in.[[LocalName]], true).
  249. MUST(environment->create_immutable_binding(global_object, import_entry.local_name, true));
  250. // iii. Call env.InitializeBinding(in.[[LocalName]], namespace).
  251. environment->initialize_binding(global_object, import_entry.local_name, namespace_);
  252. }
  253. // d. Else,
  254. else {
  255. // i. Let resolution be ? importedModule.ResolveExport(in.[[ImportName]]).
  256. auto resolution = TRY(imported_module->resolve_export(vm, import_entry.import_name));
  257. // ii. If resolution is null or ambiguous, throw a SyntaxError exception.
  258. if (!resolution.is_valid())
  259. return vm.throw_completion<SyntaxError>(global_object, ErrorType::InvalidOrAmbiguousExportEntry, import_entry.import_name);
  260. // iii. If resolution.[[BindingName]] is namespace, then
  261. if (resolution.is_namespace()) {
  262. // 1. Let namespace be ? GetModuleNamespace(resolution.[[Module]]).
  263. auto* namespace_ = TRY(resolution.module->get_module_namespace(vm));
  264. // 2. Perform ! env.CreateImmutableBinding(in.[[LocalName]], true).
  265. MUST(environment->create_immutable_binding(global_object, import_entry.local_name, true));
  266. // 3. Call env.InitializeBinding(in.[[LocalName]], namespace).
  267. MUST(environment->initialize_binding(global_object, import_entry.local_name, namespace_));
  268. }
  269. // iv. Else,
  270. else {
  271. // 1. Call env.CreateImportBinding(in.[[LocalName]], resolution.[[Module]], resolution.[[BindingName]]).
  272. MUST(environment->create_import_binding(import_entry.local_name, resolution.module, resolution.export_name));
  273. }
  274. }
  275. }
  276. // 8. Let moduleContext be a new ECMAScript code execution context.
  277. // Note: this has already been created during the construction of this object.
  278. // 9. Set the Function of moduleContext to null.
  279. // 10. Assert: module.[[Realm]] is not undefined.
  280. // Note: This must be true because we use a reference.
  281. // 11. Set the Realm of moduleContext to module.[[Realm]].
  282. m_execution_context.realm = &realm();
  283. // 12. Set the ScriptOrModule of moduleContext to module.
  284. m_execution_context.script_or_module = this;
  285. // 13. Set the VariableEnvironment of moduleContext to module.[[Environment]].
  286. m_execution_context.variable_environment = environment;
  287. // 14. Set the LexicalEnvironment of moduleContext to module.[[Environment]].
  288. m_execution_context.lexical_environment = environment;
  289. // 15. Set the PrivateEnvironment of moduleContext to null.
  290. // 16. Set module.[[Context]] to moduleContext.
  291. // Note: We're already working on that one.
  292. // 17. Push moduleContext onto the execution context stack; moduleContext is now the running execution context.
  293. vm.push_execution_context(m_execution_context, realm().global_object());
  294. // 18. Let code be module.[[ECMAScriptCode]].
  295. // 19. Let varDeclarations be the VarScopedDeclarations of code.
  296. // Note: We just loop through them in step 21.
  297. // 20. Let declaredVarNames be a new empty List.
  298. Vector<FlyString> declared_var_names;
  299. // 21. For each element d of varDeclarations, do
  300. // a. For each element dn of the BoundNames of d, do
  301. m_ecmascript_code->for_each_var_declared_name([&](auto const& name) {
  302. // i. If dn is not an element of declaredVarNames, then
  303. if (!declared_var_names.contains_slow(name)) {
  304. // 1. Perform ! env.CreateMutableBinding(dn, false).
  305. MUST(environment->create_mutable_binding(global_object, name, false));
  306. // 2. Call env.InitializeBinding(dn, undefined).
  307. MUST(environment->initialize_binding(global_object, name, js_undefined()));
  308. // 3. Append dn to declaredVarNames.
  309. declared_var_names.empend(name);
  310. }
  311. });
  312. // 22. Let lexDeclarations be the LexicallyScopedDeclarations of code.
  313. // Note: We only loop through them in step 24.
  314. // 23. Let privateEnv be null.
  315. PrivateEnvironment* private_environment = nullptr;
  316. // 24. For each element d of lexDeclarations, do
  317. m_ecmascript_code->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  318. // a. For each element dn of the BoundNames of d, do
  319. declaration.for_each_bound_name([&](FlyString const& name) {
  320. // i. If IsConstantDeclaration of d is true, then
  321. if (declaration.is_constant_declaration()) {
  322. // 1. Perform ! env.CreateImmutableBinding(dn, true).
  323. MUST(environment->create_immutable_binding(global_object, name, true));
  324. }
  325. // ii. Else,
  326. else {
  327. // 1. Perform ! env.CreateMutableBinding(dn, false).
  328. MUST(environment->create_mutable_binding(global_object, name, false));
  329. }
  330. // iii. If d is a FunctionDeclaration, a GeneratorDeclaration, an AsyncFunctionDeclaration, or an AsyncGeneratorDeclaration, then
  331. if (declaration.is_function_declaration()) {
  332. VERIFY(is<FunctionDeclaration>(declaration));
  333. auto const& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  334. // 1. Let fo be InstantiateFunctionObject of d with arguments env and privateEnv.
  335. auto* function = ECMAScriptFunctionObject::create(global_object, function_declaration.name(), function_declaration.source_text(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), environment, private_environment, function_declaration.kind(), function_declaration.is_strict_mode(), function_declaration.might_need_arguments_object(), function_declaration.contains_direct_call_to_eval());
  336. // 2. Call env.InitializeBinding(dn, fo).
  337. environment->initialize_binding(global_object, name, function);
  338. }
  339. });
  340. });
  341. // Note: The default export name is also part of the local lexical declarations but
  342. // instead of making that a special case in the parser we just check it here.
  343. // This is only needed for things which are not declarations.
  344. // For more info check Parser::parse_export_statement.
  345. // Furthermore, that declaration is not constant. so we take 24.a.ii
  346. if (m_default_export) {
  347. VERIFY(m_default_export->has_statement());
  348. auto const& statement = m_default_export->statement();
  349. if (!is<Declaration>(statement)) {
  350. auto const& name = m_default_export->entries()[0].local_or_import_name;
  351. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Adding default export to lexical declarations: local name: {}, Expression: {}", name, statement.class_name());
  352. // 1. Perform ! env.CreateMutableBinding(dn, false).
  353. MUST(environment->create_mutable_binding(global_object, name, false));
  354. // Note: Since this is not a function declaration 24.a.iii never applies
  355. }
  356. }
  357. // 25. Remove moduleContext from the execution context stack.
  358. vm.pop_execution_context();
  359. // 26. Return NormalCompletion(empty).
  360. return normal_completion({});
  361. }
  362. // 16.2.1.6.3 ResolveExport ( exportName [ , resolveSet ] ), https://tc39.es/ecma262/#sec-resolveexport
  363. ThrowCompletionOr<ResolvedBinding> SourceTextModule::resolve_export(VM& vm, FlyString const& export_name, Vector<ResolvedBinding> resolve_set)
  364. {
  365. // 1. If resolveSet is not present, set resolveSet to a new empty List.
  366. // Note: This is done by the default argument.
  367. // 2. For each Record { [[Module]], [[ExportName]] } r of resolveSet, do
  368. for (auto& [type, module, exported_name] : resolve_set) {
  369. // a. If module and r.[[Module]] are the same Module Record and SameValue(exportName, r.[[ExportName]]) is true, then
  370. if (module == this && exported_name == export_name) {
  371. // i. Assert: This is a circular import request.
  372. // ii. Return null.
  373. return ResolvedBinding::null();
  374. }
  375. }
  376. // 3. Append the Record { [[Module]]: module, [[ExportName]]: exportName } to resolveSet.
  377. resolve_set.append({ ResolvedBinding::Type::BindingName, this, export_name });
  378. // 4. For each ExportEntry Record e of module.[[LocalExportEntries]], do
  379. for (auto& entry : m_local_export_entries) {
  380. // a. If SameValue(exportName, e.[[ExportName]]) is true, then
  381. if (export_name != entry.export_name)
  382. continue;
  383. // i. Assert: module provides the direct binding for this export.
  384. // FIXME: What does this mean?
  385. // ii. Return ResolvedBinding Record { [[Module]]: module, [[BindingName]]: e.[[LocalName]] }.
  386. return ResolvedBinding {
  387. ResolvedBinding::Type::BindingName,
  388. this,
  389. entry.local_or_import_name,
  390. };
  391. }
  392. // 5. For each ExportEntry Record e of module.[[IndirectExportEntries]], do
  393. for (auto& entry : m_indirect_export_entries) {
  394. // a. If SameValue(exportName, e.[[ExportName]]) is true, then
  395. if (export_name != entry.export_name)
  396. continue;
  397. // i. Let importedModule be ? HostResolveImportedModule(module, e.[[ModuleRequest]]).
  398. auto imported_module = TRY(vm.host_resolve_imported_module(this, entry.module_request()));
  399. // ii. If e.[[ImportName]] is all, then
  400. if (entry.kind == ExportStatement::ExportEntry::Kind::ModuleRequestAll) {
  401. // 1. Assert: module does not provide the direct binding for this export.
  402. // FIXME: What does this mean? / How do we check this
  403. // 2. Return ResolvedBinding Record { [[Module]]: importedModule, [[BindingName]]: namespace }.
  404. return ResolvedBinding {
  405. ResolvedBinding::Type::Namespace,
  406. imported_module.ptr(),
  407. {}
  408. };
  409. }
  410. // iii. Else,
  411. else {
  412. // 1. Assert: module imports a specific binding for this export.
  413. // FIXME: What does this mean? / How do we check this
  414. // 2. Return importedModule.ResolveExport(e.[[ImportName]], resolveSet).
  415. return imported_module->resolve_export(vm, entry.local_or_import_name, resolve_set);
  416. }
  417. }
  418. // 6. If SameValue(exportName, "default") is true, then
  419. if (export_name == "default"sv) {
  420. // a. Assert: A default export was not explicitly defined by this module.
  421. // FIXME: What does this mean? / How do we check this
  422. // b. Return null.
  423. return ResolvedBinding::null();
  424. // c. NOTE: A default export cannot be provided by an export * from "mod" declaration.
  425. }
  426. // 7. Let starResolution be null.
  427. ResolvedBinding star_resolution = ResolvedBinding::null();
  428. // 8. For each ExportEntry Record e of module.[[StarExportEntries]], do
  429. for (auto& entry : m_star_export_entries) {
  430. // a. Let importedModule be ? HostResolveImportedModule(module, e.[[ModuleRequest]]).
  431. auto imported_module = TRY(vm.host_resolve_imported_module(this, entry.module_request()));
  432. // b. Let resolution be ? importedModule.ResolveExport(exportName, resolveSet).
  433. auto resolution = TRY(imported_module->resolve_export(vm, export_name, resolve_set));
  434. // c. If resolution is ambiguous, return ambiguous.
  435. if (resolution.is_ambiguous())
  436. return ResolvedBinding::ambiguous();
  437. // d. If resolution is not null, then
  438. if (resolution.type == ResolvedBinding::Null)
  439. continue;
  440. // i. Assert: resolution is a ResolvedBinding Record.
  441. VERIFY(resolution.is_valid());
  442. // ii. If starResolution is null, set starResolution to resolution.
  443. if (star_resolution.type == ResolvedBinding::Null) {
  444. star_resolution = resolution;
  445. }
  446. // iii. Else,
  447. else {
  448. // 1. Assert: There is more than one * import that includes the requested name.
  449. // FIXME: Assert this
  450. // 2. If resolution.[[Module]] and starResolution.[[Module]] are not the same Module Record, return ambiguous.
  451. if (resolution.module != star_resolution.module)
  452. return ResolvedBinding::ambiguous();
  453. // 3. If resolution.[[BindingName]] is namespace and starResolution.[[BindingName]] is not namespace, or if resolution.[[BindingName]] is not namespace and starResolution.[[BindingName]] is namespace, return ambiguous.
  454. if (resolution.is_namespace() != star_resolution.is_namespace())
  455. return ResolvedBinding::ambiguous();
  456. // 4. If resolution.[[BindingName]] is a String, starResolution.[[BindingName]] is a String, and SameValue(resolution.[[BindingName]], starResolution.[[BindingName]]) is false, return ambiguous.
  457. if (!resolution.is_namespace() && resolution.export_name != star_resolution.export_name) {
  458. // Note: Because we know from the previous if that either both are namespaces or both are string we can check just one
  459. return ResolvedBinding::ambiguous();
  460. }
  461. }
  462. }
  463. // 9. Return starResolution.
  464. return star_resolution;
  465. }
  466. // 16.2.1.6.5 ExecuteModule ( [ capability ] ), https://tc39.es/ecma262/#sec-source-text-module-record-execute-module
  467. Completion SourceTextModule::execute_module(VM& vm, Optional<PromiseCapability> capability)
  468. {
  469. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] SourceTextModule::execute_module({}, capability has value: {})", filename(), capability.has_value());
  470. // 1. Let moduleContext be a new ECMAScript code execution context.
  471. ExecutionContext module_context { vm.heap() };
  472. // Note: This is not in the spec but we require it.
  473. module_context.is_strict_mode = true;
  474. // 2. Set the Function of moduleContext to null.
  475. // 3. Set the Realm of moduleContext to module.[[Realm]].
  476. module_context.realm = &realm();
  477. // 4. Set the ScriptOrModule of moduleContext to module.
  478. module_context.script_or_module = this;
  479. // 5. Assert: module has been linked and declarations in its module environment have been instantiated.
  480. VERIFY(m_status != ModuleStatus::Unlinked && m_status != ModuleStatus::Linking && environment());
  481. // 6. Set the VariableEnvironment of moduleContext to module.[[Environment]].
  482. module_context.variable_environment = environment();
  483. // 7. Set the LexicalEnvironment of moduleContext to module.[[Environment]].
  484. module_context.lexical_environment = environment();
  485. // 8. Suspend the currently running execution context.
  486. // FIXME: We don't have suspend yet
  487. // 9. If module.[[HasTLA]] is false, then
  488. if (!m_has_top_level_await) {
  489. // a. Assert: capability is not present.
  490. VERIFY(!capability.has_value());
  491. // b. Push moduleContext onto the execution context stack; moduleContext is now the running execution context.
  492. vm.push_execution_context(module_context, realm().global_object());
  493. // c. Let result be the result of evaluating module.[[ECMAScriptCode]].
  494. auto result = m_ecmascript_code->execute(vm.interpreter(), realm().global_object());
  495. // d. Suspend moduleContext and remove it from the execution context stack.
  496. vm.pop_execution_context();
  497. vm.clear_exception();
  498. // e. Resume the context that is now on the top of the execution context stack as the running execution context.
  499. // FIXME: We don't have resume yet.
  500. // f. Return Completion(result).
  501. if (result.is_error())
  502. return result;
  503. // 16.2.1.11 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-module-semantics-runtime-semantics-evaluation
  504. // -> Replace any empty value with undefined.
  505. result = result.update_empty(js_undefined());
  506. return *result.value();
  507. }
  508. // 10. Else,
  509. // a. Assert: capability is a PromiseCapability Record.
  510. VERIFY(capability.has_value());
  511. // b. Perform ! AsyncBlockStart(capability, module.[[ECMAScriptCode]], moduleContext).
  512. async_block_start(vm, m_ecmascript_code, capability.value(), module_context);
  513. // c. Return NormalCompletion(empty).
  514. return normal_completion({});
  515. }
  516. }