SourceTextModule.cpp 33 KB

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