VM.cpp 50 KB

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