SourceTextModule.cpp 36 KB

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