VM.cpp 46 KB

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