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