VM.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibJS/Interpreter.h>
  11. #include <LibJS/Runtime/AbstractOperations.h>
  12. #include <LibJS/Runtime/Array.h>
  13. #include <LibJS/Runtime/Error.h>
  14. #include <LibJS/Runtime/FinalizationRegistry.h>
  15. #include <LibJS/Runtime/FunctionEnvironment.h>
  16. #include <LibJS/Runtime/GlobalEnvironment.h>
  17. #include <LibJS/Runtime/GlobalObject.h>
  18. #include <LibJS/Runtime/IteratorOperations.h>
  19. #include <LibJS/Runtime/NativeFunction.h>
  20. #include <LibJS/Runtime/OrdinaryFunctionObject.h>
  21. #include <LibJS/Runtime/PromiseReaction.h>
  22. #include <LibJS/Runtime/Reference.h>
  23. #include <LibJS/Runtime/Symbol.h>
  24. #include <LibJS/Runtime/TemporaryClearException.h>
  25. #include <LibJS/Runtime/VM.h>
  26. namespace JS {
  27. NonnullRefPtr<VM> VM::create()
  28. {
  29. return adopt_ref(*new VM);
  30. }
  31. VM::VM()
  32. : m_heap(*this)
  33. {
  34. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  35. for (size_t i = 0; i < 128; ++i) {
  36. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::formatted("{:c}", i));
  37. }
  38. #define __JS_ENUMERATE(SymbolName, snake_name) \
  39. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  40. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  41. #undef __JS_ENUMERATE
  42. }
  43. VM::~VM()
  44. {
  45. }
  46. Interpreter& VM::interpreter()
  47. {
  48. VERIFY(!m_interpreters.is_empty());
  49. return *m_interpreters.last();
  50. }
  51. Interpreter* VM::interpreter_if_exists()
  52. {
  53. if (m_interpreters.is_empty())
  54. return nullptr;
  55. return m_interpreters.last();
  56. }
  57. void VM::push_interpreter(Interpreter& interpreter)
  58. {
  59. m_interpreters.append(&interpreter);
  60. }
  61. void VM::pop_interpreter(Interpreter& interpreter)
  62. {
  63. VERIFY(!m_interpreters.is_empty());
  64. auto* popped_interpreter = m_interpreters.take_last();
  65. VERIFY(popped_interpreter == &interpreter);
  66. }
  67. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  68. : m_interpreter(interpreter)
  69. {
  70. m_interpreter.vm().push_interpreter(m_interpreter);
  71. }
  72. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  73. {
  74. m_interpreter.vm().pop_interpreter(m_interpreter);
  75. }
  76. void VM::gather_roots(HashTable<Cell*>& roots)
  77. {
  78. roots.set(m_empty_string);
  79. for (auto* string : m_single_ascii_character_strings)
  80. roots.set(string);
  81. roots.set(m_exception);
  82. if (m_last_value.is_cell())
  83. roots.set(&m_last_value.as_cell());
  84. for (auto& execution_context : m_execution_context_stack) {
  85. if (execution_context->this_value.is_cell())
  86. roots.set(&execution_context->this_value.as_cell());
  87. roots.set(execution_context->arguments_object);
  88. for (auto& argument : execution_context->arguments) {
  89. if (argument.is_cell())
  90. roots.set(&argument.as_cell());
  91. }
  92. roots.set(execution_context->lexical_environment);
  93. roots.set(execution_context->variable_environment);
  94. }
  95. #define __JS_ENUMERATE(SymbolName, snake_name) \
  96. roots.set(well_known_symbol_##snake_name());
  97. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  98. #undef __JS_ENUMERATE
  99. for (auto& symbol : m_global_symbol_map)
  100. roots.set(symbol.value);
  101. for (auto* job : m_promise_jobs)
  102. roots.set(job);
  103. }
  104. Symbol* VM::get_global_symbol(const String& description)
  105. {
  106. auto result = m_global_symbol_map.get(description);
  107. if (result.has_value())
  108. return result.value();
  109. auto new_global_symbol = js_symbol(*this, description, true);
  110. m_global_symbol_map.set(description, new_global_symbol);
  111. return new_global_symbol;
  112. }
  113. void VM::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  114. {
  115. Optional<Variable> possible_match;
  116. if (!specific_scope && m_execution_context_stack.size()) {
  117. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  118. possible_match = environment->get_from_environment(name);
  119. if (possible_match.has_value()) {
  120. specific_scope = environment;
  121. break;
  122. }
  123. }
  124. }
  125. if (specific_scope && possible_match.has_value()) {
  126. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  127. throw_exception<TypeError>(global_object, ErrorType::InvalidAssignToConst);
  128. return;
  129. }
  130. specific_scope->put_into_environment(name, { value, possible_match.value().declaration_kind });
  131. return;
  132. }
  133. if (specific_scope) {
  134. specific_scope->put_into_environment(name, { value, DeclarationKind::Var });
  135. return;
  136. }
  137. global_object.put(name, value);
  138. }
  139. bool VM::delete_variable(FlyString const& name)
  140. {
  141. Environment* specific_scope = nullptr;
  142. Optional<Variable> possible_match;
  143. if (!m_execution_context_stack.is_empty()) {
  144. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  145. possible_match = environment->get_from_environment(name);
  146. if (possible_match.has_value()) {
  147. specific_scope = environment;
  148. break;
  149. }
  150. }
  151. }
  152. if (!possible_match.has_value())
  153. return false;
  154. if (possible_match.value().declaration_kind == DeclarationKind::Const)
  155. return false;
  156. VERIFY(specific_scope);
  157. return specific_scope->delete_from_environment(name);
  158. }
  159. void VM::assign(const FlyString& target, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  160. {
  161. set_variable(target, move(value), global_object, first_assignment, specific_scope);
  162. }
  163. void VM::assign(const Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>& target, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  164. {
  165. if (auto id_ptr = target.get_pointer<NonnullRefPtr<Identifier>>())
  166. return assign((*id_ptr)->string(), move(value), global_object, first_assignment, specific_scope);
  167. assign(target.get<NonnullRefPtr<BindingPattern>>(), move(value), global_object, first_assignment, specific_scope);
  168. }
  169. void VM::assign(const NonnullRefPtr<BindingPattern>& target, Value value, GlobalObject& global_object, bool first_assignment, Environment* specific_scope)
  170. {
  171. auto& binding = *target;
  172. switch (binding.kind) {
  173. case BindingPattern::Kind::Array: {
  174. auto iterator = get_iterator(global_object, value);
  175. if (!iterator)
  176. return;
  177. for (size_t i = 0; i < binding.entries.size(); i++) {
  178. if (exception())
  179. return;
  180. auto& entry = binding.entries[i];
  181. if (entry.is_rest) {
  182. VERIFY(i == binding.entries.size() - 1);
  183. auto* array = Array::create(global_object);
  184. for (;;) {
  185. auto next_object = iterator_next(*iterator);
  186. if (!next_object)
  187. return;
  188. auto done_property = next_object->get(names.done);
  189. if (exception())
  190. return;
  191. if (!done_property.is_empty() && done_property.to_boolean())
  192. break;
  193. auto next_value = next_object->get(names.value);
  194. if (exception())
  195. return;
  196. array->indexed_properties().append(next_value);
  197. }
  198. value = array;
  199. } else if (iterator) {
  200. auto next_object = iterator_next(*iterator);
  201. if (!next_object)
  202. return;
  203. auto done_property = next_object->get(names.done);
  204. if (exception())
  205. return;
  206. if (!done_property.is_empty() && done_property.to_boolean()) {
  207. iterator = nullptr;
  208. value = js_undefined();
  209. } else {
  210. value = next_object->get(names.value);
  211. if (exception())
  212. return;
  213. }
  214. } else {
  215. value = js_undefined();
  216. }
  217. if (value.is_undefined() && entry.initializer) {
  218. value = entry.initializer->execute(interpreter(), global_object);
  219. if (exception())
  220. return;
  221. }
  222. entry.alias.visit(
  223. [&](Empty) {},
  224. [&](NonnullRefPtr<Identifier> const& identifier) {
  225. set_variable(identifier->string(), value, global_object, first_assignment, specific_scope);
  226. },
  227. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  228. assign(pattern, value, global_object, first_assignment, specific_scope);
  229. });
  230. if (entry.is_rest)
  231. break;
  232. }
  233. break;
  234. }
  235. case BindingPattern::Kind::Object: {
  236. auto object = value.to_object(global_object);
  237. HashTable<PropertyName, PropertyNameTraits> seen_names;
  238. for (auto& property : binding.entries) {
  239. VERIFY(!property.is_elision());
  240. PropertyName assignment_name;
  241. JS::Value value_to_assign;
  242. if (property.is_rest) {
  243. VERIFY(property.name.has<NonnullRefPtr<Identifier>>());
  244. assignment_name = property.name.get<NonnullRefPtr<Identifier>>()->string();
  245. auto* rest_object = Object::create(global_object, global_object.object_prototype());
  246. for (auto& object_property : object->shape().property_table()) {
  247. if (!object_property.value.attributes.has_enumerable())
  248. continue;
  249. if (seen_names.contains(object_property.key.to_display_string()))
  250. continue;
  251. rest_object->put(object_property.key, object->get(object_property.key));
  252. if (exception())
  253. return;
  254. }
  255. value_to_assign = rest_object;
  256. } else {
  257. property.name.visit(
  258. [&](Empty) { VERIFY_NOT_REACHED(); },
  259. [&](NonnullRefPtr<Identifier> const& identifier) {
  260. assignment_name = identifier->string();
  261. },
  262. [&](NonnullRefPtr<Expression> const& expression) {
  263. auto result = expression->execute(interpreter(), global_object);
  264. if (exception())
  265. return;
  266. assignment_name = result.to_property_key(global_object);
  267. });
  268. if (exception())
  269. break;
  270. value_to_assign = object->get(assignment_name);
  271. }
  272. seen_names.set(assignment_name);
  273. if (value_to_assign.is_empty())
  274. value_to_assign = js_undefined();
  275. if (value_to_assign.is_undefined() && property.initializer)
  276. value_to_assign = property.initializer->execute(interpreter(), global_object);
  277. if (exception())
  278. break;
  279. property.alias.visit(
  280. [&](Empty) {
  281. set_variable(assignment_name.to_string(), value_to_assign, global_object, first_assignment, specific_scope);
  282. },
  283. [&](NonnullRefPtr<Identifier> const& identifier) {
  284. VERIFY(!property.is_rest);
  285. set_variable(identifier->string(), value_to_assign, global_object, first_assignment, specific_scope);
  286. },
  287. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  288. VERIFY(!property.is_rest);
  289. assign(pattern, value_to_assign, global_object, first_assignment, specific_scope);
  290. });
  291. if (property.is_rest)
  292. break;
  293. }
  294. break;
  295. }
  296. }
  297. }
  298. Value VM::get_variable(const FlyString& name, GlobalObject& global_object)
  299. {
  300. if (!m_execution_context_stack.is_empty()) {
  301. auto& context = running_execution_context();
  302. if (name == names.arguments.as_string() && context.function) {
  303. // HACK: Special handling for the name "arguments":
  304. // If the name "arguments" is defined in the current scope, for example via
  305. // a function parameter, or by a local var declaration, we use that.
  306. // Otherwise, we return a lazily constructed Array with all the argument values.
  307. // FIXME: Do something much more spec-compliant.
  308. auto possible_match = lexical_environment()->get_from_environment(name);
  309. if (possible_match.has_value())
  310. return possible_match.value().value;
  311. if (!context.arguments_object) {
  312. if (context.function->is_strict_mode() || !context.function->has_simple_parameter_list()) {
  313. context.arguments_object = create_unmapped_arguments_object(global_object, context.arguments);
  314. } else {
  315. context.arguments_object = create_mapped_arguments_object(global_object, *context.function, verify_cast<OrdinaryFunctionObject>(context.function)->parameters(), context.arguments, *lexical_environment());
  316. }
  317. }
  318. return context.arguments_object;
  319. }
  320. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  321. auto possible_match = environment->get_from_environment(name);
  322. if (exception())
  323. return {};
  324. if (possible_match.has_value())
  325. return possible_match.value().value;
  326. }
  327. }
  328. auto value = global_object.get(name);
  329. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  330. return m_last_value;
  331. return value;
  332. }
  333. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  334. Reference VM::get_identifier_reference(Environment* environment, FlyString const& name, bool strict)
  335. {
  336. // 1. If env is the value null, then
  337. if (!environment) {
  338. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  339. return Reference { Reference::BaseType::Unresolvable, name, strict };
  340. }
  341. // FIXME: The remainder of this function is non-conforming.
  342. auto& global_object = environment->global_object();
  343. for (; environment && environment->outer_environment(); environment = environment->outer_environment()) {
  344. auto possible_match = environment->get_from_environment(name);
  345. if (possible_match.has_value())
  346. return Reference { *environment, name, strict };
  347. }
  348. return Reference { global_object.environment(), name, strict };
  349. }
  350. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  351. Reference VM::resolve_binding(FlyString const& name, Environment* environment)
  352. {
  353. // 1. If env is not present or if env is undefined, then
  354. if (!environment) {
  355. // a. Set env to the running execution context's LexicalEnvironment.
  356. environment = running_execution_context().lexical_environment;
  357. }
  358. // 2. Assert: env is an Environment Record.
  359. VERIFY(environment);
  360. // 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.
  361. bool strict = in_strict_mode();
  362. // 4. Return ? GetIdentifierReference(env, name, strict).
  363. return get_identifier_reference(environment, name, strict);
  364. }
  365. Value VM::construct(FunctionObject& function, FunctionObject& new_target, Optional<MarkedValueList> arguments)
  366. {
  367. auto& global_object = function.global_object();
  368. Value this_argument;
  369. if (function.constructor_kind() == FunctionObject::ConstructorKind::Base) {
  370. this_argument = ordinary_create_from_constructor<Object>(global_object, new_target, &GlobalObject::object_prototype);
  371. if (exception())
  372. return {};
  373. }
  374. ExecutionContext callee_context;
  375. prepare_for_ordinary_call(function, callee_context, &new_target);
  376. if (exception())
  377. return {};
  378. ArmedScopeGuard pop_guard = [&] {
  379. pop_execution_context();
  380. };
  381. if (auto* interpreter = interpreter_if_exists())
  382. callee_context.current_node = interpreter->current_node();
  383. callee_context.arguments = function.bound_arguments();
  384. if (arguments.has_value())
  385. callee_context.arguments.extend(arguments.value().values());
  386. if (auto* environment = callee_context.lexical_environment) {
  387. auto& function_environment = verify_cast<FunctionEnvironment>(*environment);
  388. function_environment.set_new_target(&new_target);
  389. if (!this_argument.is_empty()) {
  390. function_environment.bind_this_value(global_object, this_argument);
  391. if (exception())
  392. return {};
  393. }
  394. }
  395. // If we are a Derived constructor, |this| has not been constructed before super is called.
  396. callee_context.this_value = this_argument;
  397. auto result = function.construct(new_target);
  398. Value this_value = this_argument;
  399. if (auto* environment = callee_context.lexical_environment)
  400. this_value = environment->get_this_binding(global_object);
  401. pop_execution_context();
  402. pop_guard.disarm();
  403. // If we are constructing an instance of a derived class,
  404. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  405. if (function.constructor_kind() == FunctionObject::ConstructorKind::Base && new_target.constructor_kind() == FunctionObject::ConstructorKind::Derived && result.is_object()) {
  406. if (auto* environment = callee_context.lexical_environment)
  407. verify_cast<FunctionEnvironment>(environment)->replace_this_binding(result);
  408. auto prototype = new_target.get(names.prototype);
  409. if (exception())
  410. return {};
  411. if (prototype.is_object()) {
  412. result.as_object().set_prototype(&prototype.as_object());
  413. if (exception())
  414. return {};
  415. }
  416. return result;
  417. }
  418. if (exception())
  419. return {};
  420. if (result.is_object())
  421. return result;
  422. return this_value;
  423. }
  424. void VM::throw_exception(Exception& exception)
  425. {
  426. set_exception(exception);
  427. unwind(ScopeType::Try);
  428. }
  429. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  430. Value VM::resolve_this_binding(GlobalObject& global_object)
  431. {
  432. auto& environment = get_this_environment(*this);
  433. return environment.get_this_binding(global_object);
  434. }
  435. String VM::join_arguments(size_t start_index) const
  436. {
  437. StringBuilder joined_arguments;
  438. for (size_t i = start_index; i < argument_count(); ++i) {
  439. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  440. if (i != argument_count() - 1)
  441. joined_arguments.append(' ');
  442. }
  443. return joined_arguments.build();
  444. }
  445. Value VM::get_new_target()
  446. {
  447. auto& env = get_this_environment(*this);
  448. return verify_cast<FunctionEnvironment>(env).new_target();
  449. }
  450. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  451. void VM::prepare_for_ordinary_call(FunctionObject& function, ExecutionContext& callee_context, Value new_target)
  452. {
  453. // NOTE: This is a LibJS specific hack for NativeFunction to inherit the strictness of its caller.
  454. // FIXME: I feel like we should be able to get rid of this.
  455. if (is<NativeFunction>(function))
  456. callee_context.is_strict_mode = in_strict_mode();
  457. else
  458. callee_context.is_strict_mode = function.is_strict_mode();
  459. // 1. Assert: Type(newTarget) is Undefined or Object.
  460. VERIFY(new_target.is_undefined() || new_target.is_object());
  461. // 2. Let callerContext be the running execution context.
  462. // 3. Let calleeContext be a new ECMAScript code execution context.
  463. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  464. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  465. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  466. // 4. Set the Function of calleeContext to F.
  467. callee_context.function = &function;
  468. callee_context.function_name = function.name();
  469. // 5. Let calleeRealm be F.[[Realm]].
  470. // 6. Set the Realm of calleeContext to calleeRealm.
  471. // 7. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  472. // FIXME: Our execution context struct currently does not track these items.
  473. // 8. Let localEnv be NewFunctionEnvironment(F, newTarget).
  474. // FIXME: This should call NewFunctionEnvironment instead of the ad-hoc FunctionObject::create_environment()
  475. auto* local_environment = function.create_environment(function);
  476. // 9. Set the LexicalEnvironment of calleeContext to localEnv.
  477. callee_context.lexical_environment = local_environment;
  478. // 10. Set the VariableEnvironment of calleeContext to localEnv.
  479. callee_context.variable_environment = local_environment;
  480. // 11. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  481. // FIXME: We currently don't support private environments.
  482. // 12. If callerContext is not already suspended, suspend callerContext.
  483. // FIXME: We don't have this concept yet.
  484. // 13. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  485. push_execution_context(callee_context, function.global_object());
  486. // 14. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  487. // 15. Return calleeContext. (See NOTE above about how contexts are allocated on the C++ stack.)
  488. }
  489. Value VM::call_internal(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments)
  490. {
  491. VERIFY(!exception());
  492. VERIFY(!this_value.is_empty());
  493. ExecutionContext callee_context;
  494. prepare_for_ordinary_call(function, callee_context, js_undefined());
  495. if (exception())
  496. return {};
  497. ScopeGuard pop_guard = [&] {
  498. pop_execution_context();
  499. };
  500. if (auto* interpreter = interpreter_if_exists())
  501. callee_context.current_node = interpreter->current_node();
  502. callee_context.this_value = function.bound_this().value_or(this_value);
  503. callee_context.arguments = function.bound_arguments();
  504. if (arguments.has_value())
  505. callee_context.arguments.extend(arguments.value().values());
  506. if (auto* environment = callee_context.lexical_environment) {
  507. auto& function_environment = verify_cast<FunctionEnvironment>(*environment);
  508. VERIFY(function_environment.this_binding_status() == FunctionEnvironment::ThisBindingStatus::Uninitialized);
  509. function_environment.bind_this_value(function.global_object(), callee_context.this_value);
  510. }
  511. if (exception())
  512. return {};
  513. return function.call();
  514. }
  515. bool VM::in_strict_mode() const
  516. {
  517. if (execution_context_stack().is_empty())
  518. return false;
  519. return running_execution_context().is_strict_mode;
  520. }
  521. void VM::run_queued_promise_jobs()
  522. {
  523. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  524. // Temporarily get rid of the exception, if any - job functions must be called
  525. // either way, and that can't happen if we already have an exception stored.
  526. TemporaryClearException clear_exception(*this);
  527. while (!m_promise_jobs.is_empty()) {
  528. auto* job = m_promise_jobs.take_first();
  529. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  530. [[maybe_unused]] auto result = call(*job, js_undefined());
  531. }
  532. // Ensure no job has created a new exception, they must clean up after themselves.
  533. VERIFY(!m_exception);
  534. }
  535. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  536. void VM::enqueue_promise_job(NativeFunction& job)
  537. {
  538. m_promise_jobs.append(&job);
  539. }
  540. void VM::run_queued_finalization_registry_cleanup_jobs()
  541. {
  542. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  543. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  544. registry->cleanup();
  545. }
  546. }
  547. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  548. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  549. {
  550. m_finalization_registry_cleanup_jobs.append(&registry);
  551. }
  552. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  553. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  554. {
  555. switch (operation) {
  556. case Promise::RejectionOperation::Reject:
  557. // A promise was rejected without any handlers
  558. if (on_promise_unhandled_rejection)
  559. on_promise_unhandled_rejection(promise);
  560. break;
  561. case Promise::RejectionOperation::Handle:
  562. // A handler was added to an already rejected promise
  563. if (on_promise_rejection_handled)
  564. on_promise_rejection_handled(promise);
  565. break;
  566. default:
  567. VERIFY_NOT_REACHED();
  568. }
  569. }
  570. void VM::dump_backtrace() const
  571. {
  572. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i)
  573. dbgln("-> {}", m_execution_context_stack[i]->function_name);
  574. }
  575. void VM::dump_environment_chain() const
  576. {
  577. for (auto* environment = lexical_environment(); environment; environment = environment->outer_environment()) {
  578. dbgln("+> {} ({:p})", environment->class_name(), environment);
  579. if (is<DeclarativeEnvironment>(*environment)) {
  580. auto& declarative_environment = static_cast<DeclarativeEnvironment const&>(*environment);
  581. for (auto& variable : declarative_environment.variables()) {
  582. dbgln(" {}", variable.key);
  583. }
  584. }
  585. }
  586. }
  587. }