VM.cpp 29 KB

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