VM.cpp 49 KB

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