VM.cpp 50 KB

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