VM.cpp 51 KB

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