VM.cpp 52 KB

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