VM.cpp 49 KB

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