SourceTextModule.cpp 36 KB

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