VM.cpp 50 KB

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