VM.cpp 52 KB

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