SourceTextModule.cpp 33 KB

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