SourceTextModule.cpp 37 KB

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