VM.cpp 48 KB

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