VM.cpp 50 KB

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