VM.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Debug.h>
  9. #include <AK/LexicalPath.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/StringBuilder.h>
  12. #include <LibCore/File.h>
  13. #include <LibJS/Interpreter.h>
  14. #include <LibJS/Runtime/AbstractOperations.h>
  15. #include <LibJS/Runtime/Array.h>
  16. #include <LibJS/Runtime/BoundFunction.h>
  17. #include <LibJS/Runtime/Completion.h>
  18. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  19. #include <LibJS/Runtime/Error.h>
  20. #include <LibJS/Runtime/FinalizationRegistry.h>
  21. #include <LibJS/Runtime/FunctionEnvironment.h>
  22. #include <LibJS/Runtime/IteratorOperations.h>
  23. #include <LibJS/Runtime/NativeFunction.h>
  24. #include <LibJS/Runtime/PromiseCapability.h>
  25. #include <LibJS/Runtime/Reference.h>
  26. #include <LibJS/Runtime/Symbol.h>
  27. #include <LibJS/Runtime/VM.h>
  28. #include <LibJS/SourceTextModule.h>
  29. #include <LibJS/SyntheticModule.h>
  30. namespace JS {
  31. NonnullRefPtr<VM> VM::create(OwnPtr<CustomData> custom_data)
  32. {
  33. return adopt_ref(*new VM(move(custom_data)));
  34. }
  35. VM::VM(OwnPtr<CustomData> custom_data)
  36. : m_heap(*this)
  37. , m_custom_data(move(custom_data))
  38. {
  39. m_empty_string = m_heap.allocate_without_realm<PrimitiveString>(String::empty());
  40. for (size_t i = 0; i < 128; ++i) {
  41. m_single_ascii_character_strings[i] = m_heap.allocate_without_realm<PrimitiveString>(String::formatted("{:c}", i));
  42. }
  43. // Default hook implementations. These can be overridden by the host, for example, LibWeb overrides the default hooks to place promise jobs on the microtask queue.
  44. host_promise_rejection_tracker = [this](Promise& promise, Promise::RejectionOperation operation) {
  45. promise_rejection_tracker(promise, operation);
  46. };
  47. host_call_job_callback = [this](JobCallback& job_callback, Value this_value, MarkedVector<Value> arguments) {
  48. return call_job_callback(*this, job_callback, this_value, move(arguments));
  49. };
  50. host_enqueue_finalization_registry_cleanup_job = [this](FinalizationRegistry& finalization_registry) {
  51. enqueue_finalization_registry_cleanup_job(finalization_registry);
  52. };
  53. host_enqueue_promise_job = [this](Function<ThrowCompletionOr<Value>()> job, Realm* realm) {
  54. enqueue_promise_job(move(job), realm);
  55. };
  56. host_make_job_callback = [](FunctionObject& function_object) {
  57. return make_job_callback(function_object);
  58. };
  59. host_resolve_imported_module = [&](ScriptOrModule referencing_script_or_module, ModuleRequest const& specifier) {
  60. return resolve_imported_module(move(referencing_script_or_module), specifier);
  61. };
  62. host_import_module_dynamically = [&](ScriptOrModule, ModuleRequest const&, PromiseCapability const& promise_capability) {
  63. // By default, we throw on dynamic imports this is to prevent arbitrary file access by scripts.
  64. VERIFY(current_realm());
  65. auto& realm = *current_realm();
  66. auto* promise = Promise::create(realm);
  67. // If you are here because you want to enable dynamic module importing make sure it won't be a security problem
  68. // by checking the default implementation of HostImportModuleDynamically and creating your own hook or calling
  69. // vm.enable_default_host_import_module_dynamically_hook().
  70. promise->reject(Error::create(realm, ErrorType::DynamicImportNotAllowed.message()));
  71. promise->perform_then(
  72. NativeFunction::create(realm, "", [](auto&) -> ThrowCompletionOr<Value> {
  73. VERIFY_NOT_REACHED();
  74. }),
  75. NativeFunction::create(realm, "", [&promise_capability](auto& vm) -> ThrowCompletionOr<Value> {
  76. auto error = vm.argument(0);
  77. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « error »).
  78. MUST(call(vm, *promise_capability.reject(), js_undefined(), error));
  79. // b. Return undefined.
  80. return js_undefined();
  81. }),
  82. {});
  83. };
  84. host_finish_dynamic_import = [&](ScriptOrModule referencing_script_or_module, ModuleRequest const& specifier, PromiseCapability const& promise_capability, Promise* promise) {
  85. return finish_dynamic_import(move(referencing_script_or_module), specifier, promise_capability, promise);
  86. };
  87. host_get_import_meta_properties = [&](SourceTextModule const&) -> HashMap<PropertyKey, Value> {
  88. return {};
  89. };
  90. host_finalize_import_meta = [&](Object*, SourceTextModule const&) {
  91. };
  92. host_get_supported_import_assertions = [&] {
  93. return Vector<String> { "type" };
  94. };
  95. // 19.2.1.2 HostEnsureCanCompileStrings ( callerRealm, calleeRealm ), https://tc39.es/ecma262/#sec-hostensurecancompilestrings
  96. host_ensure_can_compile_strings = [](Realm&) -> ThrowCompletionOr<void> {
  97. // The host-defined abstract operation HostEnsureCanCompileStrings takes argument calleeRealm (a Realm Record)
  98. // and returns either a normal completion containing unused or a throw completion.
  99. // It allows host environments to block certain ECMAScript functions which allow developers to compile strings into ECMAScript code.
  100. // An implementation of HostEnsureCanCompileStrings must conform to the following requirements:
  101. // - If the returned Completion Record is a normal completion, it must be a normal completion containing unused.
  102. // The default implementation of HostEnsureCanCompileStrings is to return NormalCompletion(unused).
  103. return {};
  104. };
  105. host_ensure_can_add_private_element = [](Object&) -> ThrowCompletionOr<void> {
  106. // The host-defined abstract operation HostEnsureCanAddPrivateElement takes argument O (an Object)
  107. // and returns either a normal completion containing unused or a throw completion.
  108. // It allows host environments to prevent the addition of private elements to particular host-defined exotic objects.
  109. // An implementation of HostEnsureCanAddPrivateElement must conform to the following requirements:
  110. // - If O is not a host-defined exotic object, this abstract operation must return NormalCompletion(unused) and perform no other steps.
  111. // - Any two calls of this abstract operation with the same argument must return the same kind of Completion Record.
  112. // The default implementation of HostEnsureCanAddPrivateElement is to return NormalCompletion(unused).
  113. return {};
  114. // This abstract operation is only invoked by ECMAScript hosts that are web browsers.
  115. // NOTE: Since LibJS has no way of knowing whether the current environment is a browser we always
  116. // call HostEnsureCanAddPrivateElement when needed.
  117. };
  118. #define __JS_ENUMERATE(SymbolName, snake_name) \
  119. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  120. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  121. #undef __JS_ENUMERATE
  122. }
  123. void VM::enable_default_host_import_module_dynamically_hook()
  124. {
  125. host_import_module_dynamically = [&](ScriptOrModule referencing_script_or_module, ModuleRequest const& specifier, PromiseCapability const& promise_capability) {
  126. return import_module_dynamically(move(referencing_script_or_module), specifier, promise_capability);
  127. };
  128. }
  129. Interpreter& VM::interpreter()
  130. {
  131. VERIFY(!m_interpreters.is_empty());
  132. return *m_interpreters.last();
  133. }
  134. Interpreter* VM::interpreter_if_exists()
  135. {
  136. if (m_interpreters.is_empty())
  137. return nullptr;
  138. return m_interpreters.last();
  139. }
  140. void VM::push_interpreter(Interpreter& interpreter)
  141. {
  142. m_interpreters.append(&interpreter);
  143. }
  144. void VM::pop_interpreter(Interpreter& interpreter)
  145. {
  146. VERIFY(!m_interpreters.is_empty());
  147. auto* popped_interpreter = m_interpreters.take_last();
  148. VERIFY(popped_interpreter == &interpreter);
  149. }
  150. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  151. : m_interpreter(interpreter)
  152. {
  153. m_interpreter.vm().push_interpreter(m_interpreter);
  154. }
  155. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  156. {
  157. m_interpreter.vm().pop_interpreter(m_interpreter);
  158. }
  159. void VM::gather_roots(HashTable<Cell*>& roots)
  160. {
  161. roots.set(m_empty_string);
  162. for (auto* string : m_single_ascii_character_strings)
  163. roots.set(string);
  164. auto gather_roots_from_execution_context_stack = [&roots](Vector<ExecutionContext*> const& stack) {
  165. for (auto& execution_context : stack) {
  166. if (execution_context->this_value.is_cell())
  167. roots.set(&execution_context->this_value.as_cell());
  168. for (auto& argument : execution_context->arguments) {
  169. if (argument.is_cell())
  170. roots.set(&argument.as_cell());
  171. }
  172. roots.set(execution_context->lexical_environment);
  173. roots.set(execution_context->variable_environment);
  174. roots.set(execution_context->private_environment);
  175. execution_context->script_or_module.visit(
  176. [](Empty) {},
  177. [&](auto& script_or_module) {
  178. roots.set(script_or_module.ptr());
  179. });
  180. }
  181. };
  182. gather_roots_from_execution_context_stack(m_execution_context_stack);
  183. for (auto& saved_stack : m_saved_execution_context_stacks)
  184. gather_roots_from_execution_context_stack(saved_stack);
  185. #define __JS_ENUMERATE(SymbolName, snake_name) \
  186. roots.set(well_known_symbol_##snake_name());
  187. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  188. #undef __JS_ENUMERATE
  189. for (auto& symbol : m_global_symbol_map)
  190. roots.set(symbol.value);
  191. for (auto* finalization_registry : m_finalization_registry_cleanup_jobs)
  192. roots.set(finalization_registry);
  193. }
  194. Symbol* VM::get_global_symbol(String const& description)
  195. {
  196. auto result = m_global_symbol_map.get(description);
  197. if (result.has_value())
  198. return result.value();
  199. auto new_global_symbol = js_symbol(*this, description, true);
  200. m_global_symbol_map.set(description, new_global_symbol);
  201. return new_global_symbol;
  202. }
  203. ThrowCompletionOr<Value> VM::named_evaluation_if_anonymous_function(ASTNode const& expression, FlyString const& name)
  204. {
  205. // 8.3.3 Static Semantics: IsAnonymousFunctionDefinition ( expr ), https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition
  206. // And 8.3.5 Runtime Semantics: NamedEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-namedevaluation
  207. if (is<FunctionExpression>(expression)) {
  208. auto& function = static_cast<FunctionExpression const&>(expression);
  209. if (!function.has_name()) {
  210. return function.instantiate_ordinary_function_expression(interpreter(), name);
  211. }
  212. } else if (is<ClassExpression>(expression)) {
  213. auto& class_expression = static_cast<ClassExpression const&>(expression);
  214. if (!class_expression.has_name()) {
  215. return TRY(class_expression.class_definition_evaluation(interpreter(), {}, name));
  216. }
  217. }
  218. return TRY(expression.execute(interpreter())).release_value();
  219. }
  220. // 13.15.5.2 Runtime Semantics: DestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-destructuringassignmentevaluation
  221. ThrowCompletionOr<void> VM::destructuring_assignment_evaluation(NonnullRefPtr<BindingPattern> const& target, Value value)
  222. {
  223. // Note: DestructuringAssignmentEvaluation is just like BindingInitialization without an environment
  224. // And it allows member expressions. We thus trust the parser to disallow member expressions
  225. // in any non assignment binding and just call BindingInitialization with a nullptr environment
  226. return binding_initialization(target, value, nullptr);
  227. }
  228. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  229. ThrowCompletionOr<void> VM::binding_initialization(FlyString const& target, Value value, Environment* environment)
  230. {
  231. // 1. Let name be StringValue of Identifier.
  232. // 2. Return ? InitializeBoundName(name, value, environment).
  233. return initialize_bound_name(*this, target, value, environment);
  234. }
  235. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  236. ThrowCompletionOr<void> VM::binding_initialization(NonnullRefPtr<BindingPattern> const& target, Value value, Environment* environment)
  237. {
  238. auto& vm = *this;
  239. // BindingPattern : ObjectBindingPattern
  240. if (target->kind == BindingPattern::Kind::Object) {
  241. // 1. Perform ? RequireObjectCoercible(value).
  242. TRY(require_object_coercible(vm, value));
  243. // 2. Return ? BindingInitialization of ObjectBindingPattern with arguments value and environment.
  244. // BindingInitialization of ObjectBindingPattern
  245. // 1. Perform ? PropertyBindingInitialization of BindingPropertyList with arguments value and environment.
  246. TRY(property_binding_initialization(*target, value, environment));
  247. // 2. Return unused.
  248. return {};
  249. }
  250. // BindingPattern : ArrayBindingPattern
  251. else {
  252. // 1. Let iteratorRecord be ? GetIterator(value).
  253. auto iterator_record = TRY(get_iterator(vm, value));
  254. // 2. Let result be Completion(IteratorBindingInitialization of ArrayBindingPattern with arguments iteratorRecord and environment).
  255. auto result = iterator_binding_initialization(*target, iterator_record, environment);
  256. // 3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  257. if (!iterator_record.done) {
  258. // iterator_close() always returns a Completion, which ThrowCompletionOr will interpret as a throw
  259. // completion. So only return the result of iterator_close() if it is indeed a throw completion.
  260. auto completion = result.is_throw_completion() ? result.release_error() : normal_completion({});
  261. if (completion = iterator_close(vm, iterator_record, move(completion)); completion.is_error())
  262. return completion.release_error();
  263. }
  264. // 4. Return ? result.
  265. return result;
  266. }
  267. }
  268. // 13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-propertydestructuringassignmentevaluation
  269. // 14.3.3.1 Runtime Semantics: PropertyBindingInitialization, https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-propertybindinginitialization
  270. ThrowCompletionOr<void> VM::property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment)
  271. {
  272. auto& vm = *this;
  273. auto& realm = *vm.current_realm();
  274. auto* object = TRY(value.to_object(vm));
  275. HashTable<PropertyKey> seen_names;
  276. for (auto& property : binding.entries) {
  277. VERIFY(!property.is_elision());
  278. if (property.is_rest) {
  279. Reference assignment_target;
  280. if (auto identifier_ptr = property.name.get_pointer<NonnullRefPtr<Identifier>>()) {
  281. assignment_target = TRY(resolve_binding((*identifier_ptr)->string(), environment));
  282. } else if (auto member_ptr = property.alias.get_pointer<NonnullRefPtr<MemberExpression>>()) {
  283. assignment_target = TRY((*member_ptr)->to_reference(interpreter()));
  284. } else {
  285. VERIFY_NOT_REACHED();
  286. }
  287. auto* rest_object = Object::create(realm, realm.intrinsics().object_prototype());
  288. VERIFY(rest_object);
  289. TRY(rest_object->copy_data_properties(vm, object, seen_names));
  290. if (!environment)
  291. return assignment_target.put_value(vm, rest_object);
  292. else
  293. return assignment_target.initialize_referenced_binding(vm, rest_object);
  294. }
  295. auto name = TRY(property.name.visit(
  296. [&](Empty) -> ThrowCompletionOr<PropertyKey> { VERIFY_NOT_REACHED(); },
  297. [&](NonnullRefPtr<Identifier> const& identifier) -> ThrowCompletionOr<PropertyKey> {
  298. return identifier->string();
  299. },
  300. [&](NonnullRefPtr<Expression> const& expression) -> ThrowCompletionOr<PropertyKey> {
  301. auto result = TRY(expression->execute(interpreter())).release_value();
  302. return result.to_property_key(vm);
  303. }));
  304. seen_names.set(name);
  305. if (property.name.has<NonnullRefPtr<Identifier>>() && property.alias.has<Empty>()) {
  306. // FIXME: this branch and not taking this have a lot in common we might want to unify it more (like it was before).
  307. auto& identifier = *property.name.get<NonnullRefPtr<Identifier>>();
  308. auto reference = TRY(resolve_binding(identifier.string(), environment));
  309. auto value_to_assign = TRY(object->get(name));
  310. if (property.initializer && value_to_assign.is_undefined()) {
  311. value_to_assign = TRY(named_evaluation_if_anonymous_function(*property.initializer, identifier.string()));
  312. }
  313. if (!environment)
  314. TRY(reference.put_value(vm, value_to_assign));
  315. else
  316. TRY(reference.initialize_referenced_binding(vm, value_to_assign));
  317. continue;
  318. }
  319. auto reference_to_assign_to = TRY(property.alias.visit(
  320. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  321. [&](NonnullRefPtr<Identifier> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  322. return TRY(resolve_binding(identifier->string(), environment));
  323. },
  324. [&](NonnullRefPtr<BindingPattern> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  325. [&](NonnullRefPtr<MemberExpression> const& member_expression) -> ThrowCompletionOr<Optional<Reference>> {
  326. return TRY(member_expression->to_reference(interpreter()));
  327. }));
  328. auto value_to_assign = TRY(object->get(name));
  329. if (property.initializer && value_to_assign.is_undefined()) {
  330. if (auto* identifier_ptr = property.alias.get_pointer<NonnullRefPtr<Identifier>>())
  331. value_to_assign = TRY(named_evaluation_if_anonymous_function(*property.initializer, (*identifier_ptr)->string()));
  332. else
  333. value_to_assign = TRY(property.initializer->execute(interpreter())).release_value();
  334. }
  335. if (auto* binding_ptr = property.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  336. TRY(binding_initialization(*binding_ptr, value_to_assign, environment));
  337. } else {
  338. VERIFY(reference_to_assign_to.has_value());
  339. if (!environment)
  340. TRY(reference_to_assign_to->put_value(vm, value_to_assign));
  341. else
  342. TRY(reference_to_assign_to->initialize_referenced_binding(vm, value_to_assign));
  343. }
  344. }
  345. return {};
  346. }
  347. // 13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-iteratordestructuringassignmentevaluation
  348. // 8.5.3 Runtime Semantics: IteratorBindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization
  349. ThrowCompletionOr<void> VM::iterator_binding_initialization(BindingPattern const& binding, Iterator& iterator_record, Environment* environment)
  350. {
  351. auto& vm = *this;
  352. auto& realm = *vm.current_realm();
  353. // FIXME: this method is nearly identical to destructuring assignment!
  354. for (size_t i = 0; i < binding.entries.size(); i++) {
  355. auto& entry = binding.entries[i];
  356. Value value;
  357. auto assignment_target = TRY(entry.alias.visit(
  358. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  359. [&](NonnullRefPtr<Identifier> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  360. return TRY(resolve_binding(identifier->string(), environment));
  361. },
  362. [&](NonnullRefPtr<BindingPattern> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  363. [&](NonnullRefPtr<MemberExpression> const& member_expression) -> ThrowCompletionOr<Optional<Reference>> {
  364. return TRY(member_expression->to_reference(interpreter()));
  365. }));
  366. // BindingRestElement : ... BindingIdentifier
  367. // BindingRestElement : ... BindingPattern
  368. if (entry.is_rest) {
  369. VERIFY(i == binding.entries.size() - 1);
  370. // 2. Let A be ! ArrayCreate(0).
  371. auto* array = MUST(Array::create(realm, 0));
  372. // 3. Let n be 0.
  373. // 4. Repeat,
  374. while (true) {
  375. ThrowCompletionOr<Object*> next { nullptr };
  376. // a. If iteratorRecord.[[Done]] is false, then
  377. if (!iterator_record.done) {
  378. // i. Let next be Completion(IteratorStep(iteratorRecord)).
  379. next = iterator_step(vm, iterator_record);
  380. // ii. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  381. // iii. ReturnIfAbrupt(next).
  382. if (next.is_error()) {
  383. iterator_record.done = true;
  384. return next.release_error();
  385. }
  386. // iv. If next is false, set iteratorRecord.[[Done]] to true.
  387. if (!next.value())
  388. iterator_record.done = true;
  389. }
  390. // b. If iteratorRecord.[[Done]] is true, then
  391. if (iterator_record.done) {
  392. // NOTE: Step i. and ii. are handled below.
  393. break;
  394. }
  395. // c. Let nextValue be Completion(IteratorValue(next)).
  396. auto next_value = iterator_value(vm, *next.value());
  397. // d. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
  398. // e. ReturnIfAbrupt(nextValue).
  399. if (next_value.is_error()) {
  400. iterator_record.done = true;
  401. return next_value.release_error();
  402. }
  403. // f. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), nextValue).
  404. array->indexed_properties().append(next_value.value());
  405. // g. Set n to n + 1.
  406. }
  407. value = array;
  408. }
  409. // SingleNameBinding : BindingIdentifier Initializer[opt]
  410. // BindingElement : BindingPattern Initializer[opt]
  411. else {
  412. // 1. Let v be undefined.
  413. value = js_undefined();
  414. // 2. If iteratorRecord.[[Done]] is false, then
  415. if (!iterator_record.done) {
  416. // a. Let next be Completion(IteratorStep(iteratorRecord)).
  417. auto next = iterator_step(vm, iterator_record);
  418. // b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  419. // c. ReturnIfAbrupt(next).
  420. if (next.is_error()) {
  421. iterator_record.done = true;
  422. return next.release_error();
  423. }
  424. // d. If next is false, set iteratorRecord.[[Done]] to true.
  425. if (!next.value()) {
  426. iterator_record.done = true;
  427. }
  428. // e. Else,
  429. else {
  430. // i. Set v to Completion(IteratorValue(next)).
  431. auto value_or_error = iterator_value(vm, *next.value());
  432. // ii. If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
  433. // iii. ReturnIfAbrupt(v).
  434. if (value_or_error.is_throw_completion()) {
  435. iterator_record.done = true;
  436. return value_or_error.release_error();
  437. }
  438. value = value_or_error.release_value();
  439. }
  440. }
  441. // NOTE: Step 3. and 4. are handled below.
  442. }
  443. if (value.is_undefined() && entry.initializer) {
  444. VERIFY(!entry.is_rest);
  445. if (auto* identifier_ptr = entry.alias.get_pointer<NonnullRefPtr<Identifier>>())
  446. value = TRY(named_evaluation_if_anonymous_function(*entry.initializer, (*identifier_ptr)->string()));
  447. else
  448. value = TRY(entry.initializer->execute(interpreter())).release_value();
  449. }
  450. if (auto* binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  451. TRY(binding_initialization(*binding_ptr, value, environment));
  452. } else if (!entry.alias.has<Empty>()) {
  453. VERIFY(assignment_target.has_value());
  454. if (!environment)
  455. TRY(assignment_target->put_value(vm, value));
  456. else
  457. TRY(assignment_target->initialize_referenced_binding(vm, value));
  458. }
  459. }
  460. return {};
  461. }
  462. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  463. ThrowCompletionOr<Reference> VM::get_identifier_reference(Environment* environment, FlyString name, bool strict, size_t hops)
  464. {
  465. // 1. If env is the value null, then
  466. if (!environment) {
  467. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  468. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  469. }
  470. // 2. Let exists be ? env.HasBinding(name).
  471. Optional<size_t> index;
  472. auto exists = TRY(environment->has_binding(name, &index));
  473. // Note: This is an optimization for looking up the same reference.
  474. Optional<EnvironmentCoordinate> environment_coordinate;
  475. if (index.has_value())
  476. environment_coordinate = EnvironmentCoordinate { .hops = hops, .index = index.value() };
  477. // 3. If exists is true, then
  478. if (exists) {
  479. // a. Return the Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  480. return Reference { *environment, move(name), strict, environment_coordinate };
  481. }
  482. // 4. Else,
  483. else {
  484. // a. Let outer be env.[[OuterEnv]].
  485. // b. Return ? GetIdentifierReference(outer, name, strict).
  486. return get_identifier_reference(environment->outer_environment(), move(name), strict, hops + 1);
  487. }
  488. }
  489. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  490. ThrowCompletionOr<Reference> VM::resolve_binding(FlyString const& name, Environment* environment)
  491. {
  492. // 1. If env is not present or if env is undefined, then
  493. if (!environment) {
  494. // a. Set env to the running execution context's LexicalEnvironment.
  495. environment = running_execution_context().lexical_environment;
  496. }
  497. // 2. Assert: env is an Environment Record.
  498. VERIFY(environment);
  499. // 3. If the source text matched by the syntactic production that is being evaluated is contained in strict mode code, let strict be true; else let strict be false.
  500. bool strict = in_strict_mode();
  501. // 4. Return ? GetIdentifierReference(env, name, strict).
  502. return get_identifier_reference(environment, name, strict);
  503. // NOTE: The spec says:
  504. // Note: The result of ResolveBinding is always a Reference Record whose [[ReferencedName]] field is name.
  505. // But this is not actually correct as GetIdentifierReference (or really the methods it calls) can throw.
  506. }
  507. // 7.3.33 InitializeInstanceElements ( O, constructor ), https://tc39.es/ecma262/#sec-initializeinstanceelements
  508. ThrowCompletionOr<void> VM::initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor)
  509. {
  510. for (auto& method : constructor.private_methods())
  511. TRY(object.private_method_or_accessor_add(method));
  512. for (auto& field : constructor.fields())
  513. TRY(object.define_field(field));
  514. return {};
  515. }
  516. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  517. ThrowCompletionOr<Value> VM::resolve_this_binding()
  518. {
  519. auto& vm = *this;
  520. // 1. Let envRec be GetThisEnvironment().
  521. auto& environment = get_this_environment(vm);
  522. // 2. Return ? envRec.GetThisBinding().
  523. return TRY(environment.get_this_binding(vm));
  524. }
  525. String VM::join_arguments(size_t start_index) const
  526. {
  527. StringBuilder joined_arguments;
  528. for (size_t i = start_index; i < argument_count(); ++i) {
  529. joined_arguments.append(argument(i).to_string_without_side_effects().view());
  530. if (i != argument_count() - 1)
  531. joined_arguments.append(' ');
  532. }
  533. return joined_arguments.build();
  534. }
  535. // 9.4.5 GetNewTarget ( ), https://tc39.es/ecma262/#sec-getnewtarget
  536. Value VM::get_new_target()
  537. {
  538. // 1. Let envRec be GetThisEnvironment().
  539. auto& env = get_this_environment(*this);
  540. // 2. Assert: envRec has a [[NewTarget]] field.
  541. // 3. Return envRec.[[NewTarget]].
  542. return verify_cast<FunctionEnvironment>(env).new_target();
  543. }
  544. // 9.4.5 GetGlobalObject ( ), https://tc39.es/ecma262/#sec-getglobalobject
  545. Object& VM::get_global_object()
  546. {
  547. // 1. Let currentRealm be the current Realm Record.
  548. auto& current_realm = *this->current_realm();
  549. // 2. Return currentRealm.[[GlobalObject]].
  550. return current_realm.global_object();
  551. }
  552. bool VM::in_strict_mode() const
  553. {
  554. if (execution_context_stack().is_empty())
  555. return false;
  556. return running_execution_context().is_strict_mode;
  557. }
  558. void VM::run_queued_promise_jobs()
  559. {
  560. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  561. while (!m_promise_jobs.is_empty()) {
  562. auto job = m_promise_jobs.take_first();
  563. dbgln_if(PROMISE_DEBUG, "Calling promise job function");
  564. [[maybe_unused]] auto result = job();
  565. }
  566. }
  567. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  568. void VM::enqueue_promise_job(Function<ThrowCompletionOr<Value>()> job, Realm*)
  569. {
  570. // An implementation of HostEnqueuePromiseJob must conform to the requirements in 9.5 as well as the following:
  571. // - FIXME: If realm is not null, each time job is invoked the implementation must perform implementation-defined steps such that execution is prepared to evaluate ECMAScript code at the time of job's invocation.
  572. // - FIXME: Let scriptOrModule be GetActiveScriptOrModule() at the time HostEnqueuePromiseJob is invoked. If realm is not null, each time job is invoked the implementation must perform implementation-defined steps
  573. // such that scriptOrModule is the active script or module at the time of job's invocation.
  574. // - Jobs must run in the same order as the HostEnqueuePromiseJob invocations that scheduled them.
  575. m_promise_jobs.append(move(job));
  576. }
  577. void VM::run_queued_finalization_registry_cleanup_jobs()
  578. {
  579. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  580. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  581. // FIXME: Handle any uncatched exceptions here.
  582. (void)registry->cleanup();
  583. }
  584. }
  585. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  586. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  587. {
  588. m_finalization_registry_cleanup_jobs.append(&registry);
  589. }
  590. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  591. void VM::promise_rejection_tracker(Promise& promise, Promise::RejectionOperation operation) const
  592. {
  593. switch (operation) {
  594. case Promise::RejectionOperation::Reject:
  595. // A promise was rejected without any handlers
  596. if (on_promise_unhandled_rejection)
  597. on_promise_unhandled_rejection(promise);
  598. break;
  599. case Promise::RejectionOperation::Handle:
  600. // A handler was added to an already rejected promise
  601. if (on_promise_rejection_handled)
  602. on_promise_rejection_handled(promise);
  603. break;
  604. default:
  605. VERIFY_NOT_REACHED();
  606. }
  607. }
  608. void VM::dump_backtrace() const
  609. {
  610. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  611. auto& frame = m_execution_context_stack[i];
  612. if (frame->current_node) {
  613. auto& source_range = frame->current_node->source_range();
  614. dbgln("-> {} @ {}:{},{}", frame->function_name, source_range.filename, source_range.start.line, source_range.start.column);
  615. } else {
  616. dbgln("-> {}", frame->function_name);
  617. }
  618. }
  619. }
  620. void VM::save_execution_context_stack()
  621. {
  622. m_saved_execution_context_stacks.append(move(m_execution_context_stack));
  623. }
  624. void VM::restore_execution_context_stack()
  625. {
  626. m_execution_context_stack = m_saved_execution_context_stacks.take_last();
  627. }
  628. // 9.4.1 GetActiveScriptOrModule ( ), https://tc39.es/ecma262/#sec-getactivescriptormodule
  629. ScriptOrModule VM::get_active_script_or_module() const
  630. {
  631. // 1. If the execution context stack is empty, return null.
  632. if (m_execution_context_stack.is_empty())
  633. return Empty {};
  634. // 2. Let ec be the topmost execution context on the execution context stack whose ScriptOrModule component is not null.
  635. for (auto i = m_execution_context_stack.size() - 1; i > 0; i--) {
  636. if (!m_execution_context_stack[i]->script_or_module.has<Empty>())
  637. return m_execution_context_stack[i]->script_or_module;
  638. }
  639. // 3. If no such execution context exists, return null. Otherwise, return ec's ScriptOrModule.
  640. // Note: Since it is not empty we have 0 and since we got here all the
  641. // above contexts don't have a non-null ScriptOrModule
  642. return m_execution_context_stack[0]->script_or_module;
  643. }
  644. VM::StoredModule* VM::get_stored_module(ScriptOrModule const&, String const& filename, String const&)
  645. {
  646. // Note the spec says:
  647. // Each time this operation is called with a specific referencingScriptOrModule, specifier pair as arguments
  648. // it must return the same Module Record instance if it completes normally.
  649. // Currently, we ignore the referencing script or module but this might not be correct in all cases.
  650. // Editor's Note from https://tc39.es/proposal-json-modules/#sec-hostresolveimportedmodule
  651. // The above text implies that is recommended but not required that hosts do not use moduleRequest.[[Assertions]]
  652. // as part of the module cache key. In either case, an exception thrown from an import with a given assertion list
  653. // does not rule out success of another import with the same specifier but a different assertion list.
  654. auto end_or_module = m_loaded_modules.find_if([&](StoredModule const& stored_module) {
  655. return stored_module.filename == filename;
  656. });
  657. if (end_or_module.is_end())
  658. return nullptr;
  659. return &(*end_or_module);
  660. }
  661. ThrowCompletionOr<void> VM::link_and_eval_module(Badge<Interpreter>, SourceTextModule& module)
  662. {
  663. return link_and_eval_module(module);
  664. }
  665. ThrowCompletionOr<void> VM::link_and_eval_module(Module& module)
  666. {
  667. auto filename = module.filename();
  668. auto module_or_end = m_loaded_modules.find_if([&](StoredModule const& stored_module) {
  669. return stored_module.module.ptr() == &module;
  670. });
  671. StoredModule* stored_module;
  672. if (module_or_end.is_end()) {
  673. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Warning introducing module via link_and_eval_module {}", module.filename());
  674. if (m_loaded_modules.size() > 0)
  675. dbgln("Warning: Using multiple modules as entry point can lead to unexpected results");
  676. m_loaded_modules.empend(
  677. NonnullGCPtr(module),
  678. module.filename(),
  679. String {}, // Null type
  680. module,
  681. true);
  682. stored_module = &m_loaded_modules.last();
  683. } else {
  684. stored_module = module_or_end.operator->();
  685. if (stored_module->has_once_started_linking) {
  686. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Module already has started linking once {}", module.filename());
  687. return {};
  688. }
  689. stored_module->has_once_started_linking = true;
  690. }
  691. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking module {}", filename);
  692. auto linked_or_error = module.link(*this);
  693. if (linked_or_error.is_error())
  694. return linked_or_error.throw_completion();
  695. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Linking passed, now evaluating module {}", filename);
  696. auto evaluated_or_error = module.evaluate(*this);
  697. if (evaluated_or_error.is_error())
  698. return evaluated_or_error.throw_completion();
  699. auto* evaluated_value = evaluated_or_error.value();
  700. run_queued_promise_jobs();
  701. VERIFY(m_promise_jobs.is_empty());
  702. // FIXME: This will break if we start doing promises actually asynchronously.
  703. VERIFY(evaluated_value->state() != Promise::State::Pending);
  704. if (evaluated_value->state() == Promise::State::Rejected)
  705. return JS::throw_completion(evaluated_value->result());
  706. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] Evaluating passed for module {}", module.filename());
  707. return {};
  708. }
  709. static String resolve_module_filename(StringView filename, StringView module_type)
  710. {
  711. auto extensions = Vector<StringView, 2> { "js"sv, "mjs"sv };
  712. if (module_type == "json"sv)
  713. extensions = { "json"sv };
  714. if (!Core::File::exists(filename)) {
  715. for (auto extension : extensions) {
  716. // import "./foo" -> import "./foo.ext"
  717. auto resolved_filepath = String::formatted("{}.{}", filename, extension);
  718. if (Core::File::exists(resolved_filepath))
  719. return resolved_filepath;
  720. }
  721. } else if (Core::File::is_directory(filename)) {
  722. for (auto extension : extensions) {
  723. // import "./foo" -> import "./foo/index.ext"
  724. auto resolved_filepath = LexicalPath::join(filename, String::formatted("index.{}", extension)).string();
  725. if (Core::File::exists(resolved_filepath))
  726. return resolved_filepath;
  727. }
  728. }
  729. return filename;
  730. }
  731. // 16.2.1.7 HostResolveImportedModule ( referencingScriptOrModule, specifier ), https://tc39.es/ecma262/#sec-hostresolveimportedmodule
  732. ThrowCompletionOr<NonnullGCPtr<Module>> VM::resolve_imported_module(ScriptOrModule referencing_script_or_module, ModuleRequest const& module_request)
  733. {
  734. // An implementation of HostResolveImportedModule must conform to the following requirements:
  735. // - If it completes normally, the [[Value]] slot of the completion must contain an instance of a concrete subclass of Module Record.
  736. // - If a Module Record corresponding to the pair referencingScriptOrModule, moduleRequest does not exist or cannot be created, an exception must be thrown.
  737. // - Each time this operation is called with a specific referencingScriptOrModule, moduleRequest.[[Specifier]], moduleRequest.[[Assertions]] triple
  738. // as arguments it must return the same Module Record instance if it completes normally.
  739. // * It is recommended but not required that implementations additionally conform to the following stronger constraint:
  740. // each time this operation is called with a specific referencingScriptOrModule, moduleRequest.[[Specifier]] pair as arguments it must return the same Module Record instance if it completes normally.
  741. // - moduleRequest.[[Assertions]] must not influence the interpretation of the module or the module specifier;
  742. // instead, it may be used to determine whether the algorithm completes normally or with an abrupt completion.
  743. // Multiple different referencingScriptOrModule, moduleRequest.[[Specifier]] pairs may map to the same Module Record instance.
  744. // The actual mapping semantic is host-defined but typically a normalization process is applied to specifier as part of the mapping process.
  745. // A typical normalization process would include actions such as alphabetic case folding and expansion of relative and abbreviated path specifiers.
  746. // We only allow "type" as a supported assertion so it is the only valid key that should ever arrive here.
  747. VERIFY(module_request.assertions.is_empty() || (module_request.assertions.size() == 1 && module_request.assertions.first().key == "type"));
  748. auto module_type = module_request.assertions.is_empty() ? String {} : module_request.assertions.first().value;
  749. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] module at {} has type {} [is_null={}]", module_request.module_specifier, module_type, module_type.is_null());
  750. StringView base_filename = referencing_script_or_module.visit(
  751. [&](Empty) {
  752. return "."sv;
  753. },
  754. [&](auto& script_or_module) {
  755. return script_or_module->filename();
  756. });
  757. LexicalPath base_path { base_filename };
  758. auto filename = LexicalPath::absolute_path(base_path.dirname(), module_request.module_specifier);
  759. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] base path: '{}'", base_path);
  760. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] initial filename: '{}'", filename);
  761. filename = resolve_module_filename(filename, module_type);
  762. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved filename: '{}'", filename);
  763. #if JS_MODULE_DEBUG
  764. String referencing_module_string = referencing_script_or_module.visit(
  765. [&](Empty) -> String {
  766. return ".";
  767. },
  768. [&](auto& script_or_module) {
  769. if constexpr (IsSame<Script*, decltype(script_or_module)>) {
  770. return String::formatted("Script @ {}", script_or_module.ptr());
  771. }
  772. return String::formatted("Module @ {}", script_or_module.ptr());
  773. });
  774. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolve_imported_module({}, {})", referencing_module_string, filename);
  775. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolved {} + {} -> {}", base_path, module_request.module_specifier, filename);
  776. #endif
  777. auto* loaded_module_or_end = get_stored_module(referencing_script_or_module, filename, module_type);
  778. if (loaded_module_or_end != nullptr) {
  779. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolve_imported_module({}) already loaded at {}", filename, loaded_module_or_end->module.ptr());
  780. return NonnullGCPtr(*loaded_module_or_end->module);
  781. }
  782. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing module {}", filename);
  783. auto file_or_error = Core::File::open(filename, Core::OpenMode::ReadOnly);
  784. if (file_or_error.is_error()) {
  785. return throw_completion<SyntaxError>(ErrorType::ModuleNotFound, module_request.module_specifier);
  786. }
  787. // FIXME: Don't read the file in one go.
  788. auto file_content = file_or_error.value()->read_all();
  789. StringView content_view { file_content.data(), file_content.size() };
  790. auto module = TRY([&]() -> ThrowCompletionOr<NonnullGCPtr<Module>> {
  791. // If assertions has an entry entry such that entry.[[Key]] is "type", let type be entry.[[Value]]. The following requirements apply:
  792. // If type is "json", then this algorithm must either invoke ParseJSONModule and return the resulting Completion Record, or throw an exception.
  793. if (module_type == "json"sv) {
  794. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing JSON module {}", filename);
  795. return parse_json_module(content_view, *current_realm(), filename);
  796. }
  797. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] reading and parsing as SourceTextModule module {}", filename);
  798. // Note: We treat all files as module, so if a script does not have exports it just runs it.
  799. auto module_or_errors = SourceTextModule::parse(content_view, *current_realm(), filename);
  800. if (module_or_errors.is_error()) {
  801. VERIFY(module_or_errors.error().size() > 0);
  802. return throw_completion<SyntaxError>(module_or_errors.error().first().to_string());
  803. }
  804. return module_or_errors.release_value();
  805. }());
  806. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] resolve_imported_module(...) parsed {} to {}", filename, module.ptr());
  807. // We have to set it here already in case it references itself.
  808. m_loaded_modules.empend(
  809. referencing_script_or_module,
  810. filename,
  811. module_type,
  812. *module,
  813. false);
  814. return module;
  815. }
  816. // 16.2.1.8 HostImportModuleDynamically ( referencingScriptOrModule, specifier, promiseCapability ), https://tc39.es/ecma262/#sec-hostimportmoduledynamically
  817. void VM::import_module_dynamically(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability const& promise_capability)
  818. {
  819. auto& realm = *current_realm();
  820. // Success path:
  821. // - At some future time, the host environment must perform FinishDynamicImport(referencingScriptOrModule, moduleRequest, promiseCapability, promise),
  822. // where promise is a Promise resolved with undefined.
  823. // - Any subsequent call to HostResolveImportedModule after FinishDynamicImport has completed,
  824. // given the arguments referencingScriptOrModule and specifier, must return a normal completion
  825. // containing a module which has already been evaluated, i.e. whose Evaluate concrete method has
  826. // already been called and returned a normal completion.
  827. // Failure path:
  828. // - At some future time, the host environment must perform
  829. // FinishDynamicImport(referencingScriptOrModule, moduleRequest, promiseCapability, promise),
  830. // where promise is a Promise rejected with an error representing the cause of failure.
  831. auto* promise = Promise::create(realm);
  832. ScopeGuard finish_dynamic_import = [&] {
  833. host_finish_dynamic_import(referencing_script_or_module, module_request, promise_capability, promise);
  834. };
  835. // Generally within ECMA262 we always get a referencing_script_or_moulde. However, ShadowRealm gives an explicit null.
  836. // To get around this is we attempt to get the active script_or_module otherwise we might start loading "random" files from the working directory.
  837. if (referencing_script_or_module.has<Empty>()) {
  838. referencing_script_or_module = get_active_script_or_module();
  839. // If there is no ScriptOrModule in any of the execution contexts
  840. if (referencing_script_or_module.has<Empty>()) {
  841. // Throw an error for now
  842. promise->reject(InternalError::create(realm, String::formatted(ErrorType::ModuleNotFoundNoReferencingScript.message(), module_request.module_specifier)));
  843. return;
  844. }
  845. }
  846. // Note: If host_resolve_imported_module returns a module it has been loaded successfully and the next call in finish_dynamic_import will retrieve it again.
  847. auto module_or_error = host_resolve_imported_module(referencing_script_or_module, module_request);
  848. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] HostImportModuleDynamically(..., {}) -> {}", module_request.module_specifier, module_or_error.is_error() ? "failed" : "passed");
  849. if (module_or_error.is_throw_completion()) {
  850. promise->reject(*module_or_error.throw_completion().value());
  851. } else {
  852. auto module = module_or_error.release_value();
  853. auto& source_text_module = static_cast<Module&>(*module);
  854. auto evaluated_or_error = link_and_eval_module(source_text_module);
  855. if (evaluated_or_error.is_throw_completion()) {
  856. promise->reject(*evaluated_or_error.throw_completion().value());
  857. } else {
  858. promise->fulfill(js_undefined());
  859. }
  860. }
  861. // It must return unused.
  862. // Note: Just return void always since the resulting value cannot be accessed by user code.
  863. }
  864. // 16.2.1.9 FinishDynamicImport ( referencingScriptOrModule, specifier, promiseCapability, innerPromise ), https://tc39.es/ecma262/#sec-finishdynamicimport
  865. void VM::finish_dynamic_import(ScriptOrModule referencing_script_or_module, ModuleRequest module_request, PromiseCapability const& promise_capability, Promise* inner_promise)
  866. {
  867. dbgln_if(JS_MODULE_DEBUG, "[JS MODULE] finish_dynamic_import on {}", module_request.module_specifier);
  868. auto& realm = *current_realm();
  869. // 1. Let fulfilledClosure be a new Abstract Closure with parameters (result) that captures referencingScriptOrModule, specifier, and promiseCapability and performs the following steps when called:
  870. auto fulfilled_closure = [referencing_script_or_module = move(referencing_script_or_module), module_request = move(module_request), &promise_capability](VM& vm) -> ThrowCompletionOr<Value> {
  871. auto result = vm.argument(0);
  872. // a. Assert: result is undefined.
  873. VERIFY(result.is_undefined());
  874. // b. Let moduleRecord be ! HostResolveImportedModule(referencingScriptOrModule, specifier).
  875. auto module_record = MUST(vm.host_resolve_imported_module(referencing_script_or_module, module_request));
  876. // c. Assert: Evaluate has already been invoked on moduleRecord and successfully completed.
  877. // Note: If HostResolveImportedModule returns a module evaluate will have been called on it.
  878. // d. Let namespace be Completion(GetModuleNamespace(moduleRecord)).
  879. auto namespace_ = module_record->get_module_namespace(vm);
  880. // e. If namespace is an abrupt completion, then
  881. if (namespace_.is_throw_completion()) {
  882. // i. Perform ! Call(promiseCapability.[[Reject]], undefined, « namespace.[[Value]] »).
  883. MUST(call(vm, *promise_capability.reject(), js_undefined(), *namespace_.throw_completion().value()));
  884. }
  885. // f. Else,
  886. else {
  887. // i. Perform ! Call(promiseCapability.[[Resolve]], undefined, « namespace.[[Value]] »).
  888. MUST(call(vm, *promise_capability.resolve(), js_undefined(), namespace_.release_value()));
  889. }
  890. // g. Return unused.
  891. // NOTE: We don't support returning an empty/optional/unused value here.
  892. return js_undefined();
  893. };
  894. // 2. Let onFulfilled be CreateBuiltinFunction(fulfilledClosure, 0, "", « »).
  895. auto* on_fulfilled = NativeFunction::create(realm, move(fulfilled_closure), 0, "");
  896. // 3. Let rejectedClosure be a new Abstract Closure with parameters (error) that captures promiseCapability and performs the following steps when called:
  897. auto rejected_closure = [&promise_capability](VM& vm) -> ThrowCompletionOr<Value> {
  898. auto error = vm.argument(0);
  899. // a. Perform ! Call(promiseCapability.[[Reject]], undefined, « error »).
  900. MUST(call(vm, *promise_capability.reject(), js_undefined(), error));
  901. // b. Return unused.
  902. // NOTE: We don't support returning an empty/optional/unused value here.
  903. return js_undefined();
  904. };
  905. // 4. Let onRejected be CreateBuiltinFunction(rejectedClosure, 0, "", « »).
  906. auto* on_rejected = NativeFunction::create(realm, move(rejected_closure), 0, "");
  907. // 5. Perform PerformPromiseThen(innerPromise, onFulfilled, onRejected).
  908. inner_promise->perform_then(on_fulfilled, on_rejected, {});
  909. // 6. Return unused.
  910. }
  911. }