SourceTextModule.cpp 35 KB

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