VM.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Debug.h>
  9. #include <AK/ScopeGuard.h>
  10. #include <AK/StringBuilder.h>
  11. #include <LibJS/Interpreter.h>
  12. #include <LibJS/Runtime/AbstractOperations.h>
  13. #include <LibJS/Runtime/Array.h>
  14. #include <LibJS/Runtime/BoundFunction.h>
  15. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  16. #include <LibJS/Runtime/Error.h>
  17. #include <LibJS/Runtime/FinalizationRegistry.h>
  18. #include <LibJS/Runtime/FunctionEnvironment.h>
  19. #include <LibJS/Runtime/GlobalObject.h>
  20. #include <LibJS/Runtime/IteratorOperations.h>
  21. #include <LibJS/Runtime/NativeFunction.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. auto gather_roots_from_execution_context_stack = [&roots](Vector<ExecutionContext*> const& stack) {
  87. for (auto& execution_context : stack) {
  88. if (execution_context->this_value.is_cell())
  89. roots.set(&execution_context->this_value.as_cell());
  90. roots.set(execution_context->arguments_object);
  91. for (auto& argument : execution_context->arguments) {
  92. if (argument.is_cell())
  93. roots.set(&argument.as_cell());
  94. }
  95. roots.set(execution_context->lexical_environment);
  96. roots.set(execution_context->variable_environment);
  97. }
  98. };
  99. gather_roots_from_execution_context_stack(m_execution_context_stack);
  100. for (auto& saved_stack : m_saved_execution_context_stacks)
  101. gather_roots_from_execution_context_stack(saved_stack);
  102. #define __JS_ENUMERATE(SymbolName, snake_name) \
  103. roots.set(well_known_symbol_##snake_name());
  104. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  105. #undef __JS_ENUMERATE
  106. for (auto& symbol : m_global_symbol_map)
  107. roots.set(symbol.value);
  108. for (auto* job : m_promise_jobs)
  109. roots.set(job);
  110. for (auto* finalization_registry : m_finalization_registry_cleanup_jobs)
  111. roots.set(finalization_registry);
  112. }
  113. Symbol* VM::get_global_symbol(const String& description)
  114. {
  115. auto result = m_global_symbol_map.get(description);
  116. if (result.has_value())
  117. return result.value();
  118. auto new_global_symbol = js_symbol(*this, description, true);
  119. m_global_symbol_map.set(description, new_global_symbol);
  120. return new_global_symbol;
  121. }
  122. ThrowCompletionOr<Value> VM::named_evaluation_if_anonymous_function(GlobalObject& global_object, ASTNode const& expression, FlyString const& name)
  123. {
  124. // 8.3.3 Static Semantics: IsAnonymousFunctionDefinition ( expr ), https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition
  125. // And 8.3.5 Runtime Semantics: NamedEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-namedevaluation
  126. if (is<FunctionExpression>(expression)) {
  127. auto& function = static_cast<FunctionExpression const&>(expression);
  128. if (!function.has_name()) {
  129. return function.instantiate_ordinary_function_expression(interpreter(), global_object, name);
  130. }
  131. } else if (is<ClassExpression>(expression)) {
  132. auto& class_expression = static_cast<ClassExpression const&>(expression);
  133. if (!class_expression.has_name()) {
  134. return TRY(class_expression.class_definition_evaluation(interpreter(), global_object, {}, name));
  135. }
  136. }
  137. auto value = expression.execute(interpreter(), global_object);
  138. if (auto* thrown_exception = exception())
  139. return JS::throw_completion(thrown_exception->value());
  140. return value;
  141. }
  142. // 13.15.5.2 Runtime Semantics: DestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-destructuringassignmentevaluation
  143. ThrowCompletionOr<void> VM::destructuring_assignment_evaluation(NonnullRefPtr<BindingPattern> const& target, Value value, GlobalObject& global_object)
  144. {
  145. // Note: DestructuringAssignmentEvaluation is just like BindingInitialization without an environment
  146. // And it allows member expressions. We thus trust the parser to disallow member expressions
  147. // in any non assignment binding and just call BindingInitialization with a nullptr environment
  148. return binding_initialization(target, value, nullptr, global_object);
  149. }
  150. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  151. ThrowCompletionOr<void> VM::binding_initialization(FlyString const& target, Value value, Environment* environment, GlobalObject& global_object)
  152. {
  153. if (environment) {
  154. environment->initialize_binding(global_object, target, value);
  155. return {};
  156. }
  157. auto reference = resolve_binding(target);
  158. reference.put_value(global_object, value);
  159. if (auto* thrown_exception = exception())
  160. return JS::throw_completion(thrown_exception->value());
  161. return {};
  162. }
  163. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  164. ThrowCompletionOr<void> VM::binding_initialization(NonnullRefPtr<BindingPattern> const& target, Value value, Environment* environment, GlobalObject& global_object)
  165. {
  166. if (target->kind == BindingPattern::Kind::Object) {
  167. TRY(require_object_coercible(global_object, value));
  168. TRY(property_binding_initialization(*target, value, environment, global_object));
  169. return {};
  170. } else {
  171. auto* iterator = get_iterator(global_object, value);
  172. if (!iterator) {
  173. VERIFY(exception());
  174. return JS::throw_completion(exception()->value());
  175. }
  176. auto iterator_done = false;
  177. auto result = iterator_binding_initialization(*target, iterator, iterator_done, environment, global_object);
  178. if (!iterator_done) {
  179. // FIXME: Iterator close should take result and potentially return that. This logic should achieve the same until that is possible.
  180. iterator_close(*iterator);
  181. if (auto* thrown_exception = exception())
  182. return JS::throw_completion(thrown_exception->value());
  183. }
  184. return result;
  185. }
  186. }
  187. // 13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-propertydestructuringassignmentevaluation
  188. // 14.3.3.1 Runtime Semantics: PropertyBindingInitialization, https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-propertybindinginitialization
  189. ThrowCompletionOr<void> VM::property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment, GlobalObject& global_object)
  190. {
  191. auto* object = value.to_object(global_object);
  192. if (!object) {
  193. VERIFY(exception());
  194. return JS::throw_completion(exception()->value());
  195. }
  196. HashTable<PropertyName, PropertyNameTraits> seen_names;
  197. for (auto& property : binding.entries) {
  198. VERIFY(!property.is_elision());
  199. if (property.is_rest) {
  200. Reference assignment_target;
  201. if (auto identifier_ptr = property.name.get_pointer<NonnullRefPtr<Identifier>>()) {
  202. assignment_target = resolve_binding((*identifier_ptr)->string(), environment);
  203. } else if (auto member_ptr = property.alias.get_pointer<NonnullRefPtr<MemberExpression>>()) {
  204. assignment_target = (*member_ptr)->to_reference(interpreter(), global_object);
  205. } else {
  206. VERIFY_NOT_REACHED();
  207. }
  208. if (auto* thrown_exception = exception())
  209. return JS::throw_completion(thrown_exception->value());
  210. auto* rest_object = Object::create(global_object, global_object.object_prototype());
  211. VERIFY(rest_object);
  212. TRY(rest_object->copy_data_properties(object, seen_names, global_object));
  213. if (!environment)
  214. assignment_target.put_value(global_object, rest_object);
  215. else
  216. assignment_target.initialize_referenced_binding(global_object, rest_object);
  217. break;
  218. }
  219. PropertyName name;
  220. property.name.visit(
  221. [&](Empty) { VERIFY_NOT_REACHED(); },
  222. [&](NonnullRefPtr<Identifier> const& identifier) {
  223. name = identifier->string();
  224. },
  225. [&](NonnullRefPtr<Expression> const& expression) {
  226. auto result = expression->execute(interpreter(), global_object);
  227. if (exception())
  228. return;
  229. name = result.to_property_key(global_object);
  230. });
  231. if (auto* thrown_exception = exception())
  232. return JS::throw_completion(thrown_exception->value());
  233. seen_names.set(name);
  234. if (property.name.has<NonnullRefPtr<Identifier>>() && property.alias.has<Empty>()) {
  235. // FIXME: this branch and not taking this have a lot in common we might want to unify it more (like it was before).
  236. auto& identifier = *property.name.get<NonnullRefPtr<Identifier>>();
  237. auto reference = resolve_binding(identifier.string(), environment);
  238. if (auto* thrown_exception = exception())
  239. return JS::throw_completion(thrown_exception->value());
  240. auto value_to_assign = object->get(name);
  241. if (auto* thrown_exception = exception())
  242. return JS::throw_completion(thrown_exception->value());
  243. if (property.initializer && value_to_assign.is_undefined()) {
  244. value_to_assign = TRY(named_evaluation_if_anonymous_function(global_object, *property.initializer, identifier.string()));
  245. }
  246. if (!environment)
  247. reference.put_value(global_object, value_to_assign);
  248. else
  249. reference.initialize_referenced_binding(global_object, value_to_assign);
  250. continue;
  251. }
  252. Optional<Reference> reference_to_assign_to;
  253. property.alias.visit(
  254. [&](Empty) {},
  255. [&](NonnullRefPtr<Identifier> const& identifier) {
  256. reference_to_assign_to = resolve_binding(identifier->string(), environment);
  257. },
  258. [&](NonnullRefPtr<BindingPattern> const&) {},
  259. [&](NonnullRefPtr<MemberExpression> const& member_expression) {
  260. reference_to_assign_to = member_expression->to_reference(interpreter(), global_object);
  261. });
  262. if (auto* thrown_exception = exception())
  263. return JS::throw_completion(thrown_exception->value());
  264. auto value_to_assign = object->get(name);
  265. if (auto* thrown_exception = exception())
  266. return JS::throw_completion(thrown_exception->value());
  267. if (property.initializer && value_to_assign.is_undefined()) {
  268. if (auto* identifier_ptr = property.alias.get_pointer<NonnullRefPtr<Identifier>>())
  269. value_to_assign = TRY(named_evaluation_if_anonymous_function(global_object, *property.initializer, (*identifier_ptr)->string()));
  270. else
  271. value_to_assign = property.initializer->execute(interpreter(), global_object);
  272. if (auto* thrown_exception = exception())
  273. return JS::throw_completion(thrown_exception->value());
  274. }
  275. if (auto* binding_ptr = property.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  276. TRY(binding_initialization(*binding_ptr, value_to_assign, environment, global_object));
  277. } else {
  278. VERIFY(reference_to_assign_to.has_value());
  279. if (!environment)
  280. reference_to_assign_to->put_value(global_object, value_to_assign);
  281. else
  282. reference_to_assign_to->initialize_referenced_binding(global_object, value_to_assign);
  283. if (auto* thrown_exception = exception())
  284. return JS::throw_completion(thrown_exception->value());
  285. }
  286. }
  287. return {};
  288. }
  289. // 13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-iteratordestructuringassignmentevaluation
  290. // 8.5.3 Runtime Semantics: IteratorBindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization
  291. ThrowCompletionOr<void> VM::iterator_binding_initialization(BindingPattern const& binding, Object* iterator, bool& iterator_done, Environment* environment, GlobalObject& global_object)
  292. {
  293. // FIXME: this method is nearly identical to destructuring assignment!
  294. for (size_t i = 0; i < binding.entries.size(); i++) {
  295. auto& entry = binding.entries[i];
  296. Value value;
  297. Optional<Reference> assignment_target;
  298. entry.alias.visit(
  299. [&](Empty) {},
  300. [&](NonnullRefPtr<Identifier> const& identifier) {
  301. assignment_target = resolve_binding(identifier->string(), environment);
  302. },
  303. [&](NonnullRefPtr<BindingPattern> const&) {},
  304. [&](NonnullRefPtr<MemberExpression> const& member_expression) {
  305. assignment_target = member_expression->to_reference(interpreter(), global_object);
  306. });
  307. if (auto* thrown_exception = exception())
  308. return JS::throw_completion(thrown_exception->value());
  309. if (entry.is_rest) {
  310. VERIFY(i == binding.entries.size() - 1);
  311. auto* array = Array::create(global_object, 0);
  312. while (!iterator_done) {
  313. auto next_object = iterator_next(*iterator);
  314. if (!next_object) {
  315. iterator_done = true;
  316. VERIFY(exception());
  317. return JS::throw_completion(exception()->value());
  318. }
  319. auto done_property = next_object->get(names.done);
  320. if (auto* thrown_exception = exception())
  321. return JS::throw_completion(thrown_exception->value());
  322. if (done_property.to_boolean()) {
  323. iterator_done = true;
  324. break;
  325. }
  326. auto next_value = next_object->get(names.value);
  327. if (auto* thrown_exception = exception())
  328. return JS::throw_completion(thrown_exception->value());
  329. array->indexed_properties().append(next_value);
  330. }
  331. value = array;
  332. } else if (!iterator_done) {
  333. auto next_object = iterator_next(*iterator);
  334. if (!next_object) {
  335. iterator_done = true;
  336. VERIFY(exception());
  337. return JS::throw_completion(exception()->value());
  338. }
  339. auto done_property = next_object->get(names.done);
  340. if (auto* thrown_exception = exception())
  341. return JS::throw_completion(thrown_exception->value());
  342. if (done_property.to_boolean()) {
  343. iterator_done = true;
  344. value = js_undefined();
  345. } else {
  346. value = next_object->get(names.value);
  347. if (auto* thrown_exception = exception()) {
  348. iterator_done = true;
  349. return JS::throw_completion(thrown_exception->value());
  350. }
  351. }
  352. } else {
  353. value = js_undefined();
  354. }
  355. if (value.is_undefined() && entry.initializer) {
  356. VERIFY(!entry.is_rest);
  357. if (auto* identifier_ptr = entry.alias.get_pointer<NonnullRefPtr<Identifier>>())
  358. value = TRY(named_evaluation_if_anonymous_function(global_object, *entry.initializer, (*identifier_ptr)->string()));
  359. else
  360. value = entry.initializer->execute(interpreter(), global_object);
  361. if (auto* thrown_exception = exception())
  362. return JS::throw_completion(thrown_exception->value());
  363. }
  364. if (auto* binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  365. TRY(binding_initialization(*binding_ptr, value, environment, global_object));
  366. } else if (!entry.alias.has<Empty>()) {
  367. VERIFY(assignment_target.has_value());
  368. if (!environment)
  369. assignment_target->put_value(global_object, value);
  370. else
  371. assignment_target->initialize_referenced_binding(global_object, value);
  372. if (auto* thrown_exception = exception())
  373. return JS::throw_completion(thrown_exception->value());
  374. }
  375. }
  376. return {};
  377. }
  378. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  379. Reference VM::get_identifier_reference(Environment* environment, FlyString name, bool strict)
  380. {
  381. // 1. If env is the value null, then
  382. if (!environment) {
  383. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  384. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  385. }
  386. auto exists = environment->has_binding(name);
  387. if (exception())
  388. return {};
  389. if (exists)
  390. return Reference { *environment, move(name), strict };
  391. else
  392. return get_identifier_reference(environment->outer_environment(), move(name), strict);
  393. }
  394. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  395. Reference VM::resolve_binding(FlyString const& name, Environment* environment)
  396. {
  397. // 1. If env is not present or if env is undefined, then
  398. if (!environment) {
  399. // a. Set env to the running execution context's LexicalEnvironment.
  400. environment = running_execution_context().lexical_environment;
  401. }
  402. // 2. Assert: env is an Environment Record.
  403. VERIFY(environment);
  404. // 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.
  405. bool strict = in_strict_mode();
  406. // 4. Return ? GetIdentifierReference(env, name, strict).
  407. return get_identifier_reference(environment, name, strict);
  408. }
  409. static void append_bound_and_passed_arguments(MarkedValueList& arguments, Vector<Value> bound_arguments, Optional<MarkedValueList> passed_arguments)
  410. {
  411. arguments.ensure_capacity(bound_arguments.size());
  412. arguments.extend(move(bound_arguments));
  413. if (passed_arguments.has_value()) {
  414. auto arguments_list = move(passed_arguments.release_value().values());
  415. arguments.grow_capacity(arguments_list.size());
  416. arguments.extend(move(arguments_list));
  417. }
  418. }
  419. // 7.3.32 InitializeInstanceElements ( O, constructor ), https://tc39.es/ecma262/#sec-initializeinstanceelements
  420. void VM::initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor)
  421. {
  422. for (auto& field : constructor.fields()) {
  423. field.define_field(*this, object);
  424. if (exception())
  425. return;
  426. }
  427. }
  428. // FIXME: This function should not exist as-is, most of it should be moved to the individual
  429. // [[Construct]] implementations so that this becomes the Construct() AO (3 steps).
  430. Value VM::construct(FunctionObject& function, FunctionObject& new_target, Optional<MarkedValueList> arguments)
  431. {
  432. auto& global_object = function.global_object();
  433. Value this_argument;
  434. if (!is<ECMAScriptFunctionObject>(function) || static_cast<ECMAScriptFunctionObject&>(function).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Base)
  435. this_argument = TRY_OR_DISCARD(ordinary_create_from_constructor<Object>(global_object, new_target, &GlobalObject::object_prototype));
  436. // FIXME: prepare_for_ordinary_call() is not supposed to receive a BoundFunction, ProxyObject, etc. - ever.
  437. // This needs to be moved to NativeFunction/ECMAScriptFunctionObject's construct() (10.2.2 [[Construct]])
  438. ExecutionContext callee_context(heap());
  439. prepare_for_ordinary_call(function, callee_context, &new_target);
  440. if (exception())
  441. return {};
  442. ArmedScopeGuard pop_guard = [&] {
  443. pop_execution_context();
  444. };
  445. if (auto* interpreter = interpreter_if_exists())
  446. callee_context.current_node = interpreter->current_node();
  447. if (is<BoundFunction>(function)) {
  448. auto& bound_function = static_cast<BoundFunction&>(function);
  449. append_bound_and_passed_arguments(callee_context.arguments, bound_function.bound_arguments(), move(arguments));
  450. } else {
  451. append_bound_and_passed_arguments(callee_context.arguments, {}, move(arguments));
  452. }
  453. if (auto* environment = callee_context.lexical_environment) {
  454. auto& function_environment = verify_cast<FunctionEnvironment>(*environment);
  455. function_environment.set_new_target(&new_target);
  456. if (!this_argument.is_empty() && function_environment.this_binding_status() != FunctionEnvironment::ThisBindingStatus::Lexical) {
  457. function_environment.bind_this_value(global_object, this_argument);
  458. if (exception())
  459. return {};
  460. }
  461. }
  462. // If we are a Derived constructor, |this| has not been constructed before super is called.
  463. callee_context.this_value = this_argument;
  464. if (is<ECMAScriptFunctionObject>(function) && static_cast<ECMAScriptFunctionObject&>(function).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Base) {
  465. VERIFY(this_argument.is_object());
  466. initialize_instance_elements(this_argument.as_object(), static_cast<ECMAScriptFunctionObject&>(function));
  467. if (exception())
  468. return {};
  469. }
  470. auto* constructor_environment = callee_context.lexical_environment;
  471. auto result = function.construct(new_target);
  472. VERIFY(constructor_environment);
  473. pop_execution_context();
  474. pop_guard.disarm();
  475. // If we are constructing an instance of a derived class,
  476. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  477. if ((!is<ECMAScriptFunctionObject>(function) || static_cast<ECMAScriptFunctionObject&>(function).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Base)
  478. && is<ECMAScriptFunctionObject>(new_target) && static_cast<ECMAScriptFunctionObject&>(new_target).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Derived
  479. && result.is_object()) {
  480. verify_cast<FunctionEnvironment>(constructor_environment)->replace_this_binding(result);
  481. auto prototype = new_target.get(names.prototype);
  482. if (exception())
  483. return {};
  484. if (prototype.is_object())
  485. TRY_OR_DISCARD(result.as_object().internal_set_prototype_of(&prototype.as_object()));
  486. return result;
  487. }
  488. if (exception())
  489. return {};
  490. if (result.is_object())
  491. return result;
  492. if (is<ECMAScriptFunctionObject>(function) && static_cast<ECMAScriptFunctionObject&>(function).constructor_kind() == ECMAScriptFunctionObject::ConstructorKind::Base)
  493. return this_argument;
  494. if (!result.is_empty() && !result.is_undefined()) {
  495. throw_exception<TypeError>(global_object, ErrorType::DerivedConstructorReturningInvalidValue);
  496. return {};
  497. }
  498. VERIFY(constructor_environment);
  499. return constructor_environment->get_this_binding(global_object);
  500. }
  501. void VM::throw_exception(Exception& exception)
  502. {
  503. set_exception(exception);
  504. unwind(ScopeType::Try);
  505. }
  506. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  507. Value VM::resolve_this_binding(GlobalObject& global_object)
  508. {
  509. auto& environment = get_this_environment(*this);
  510. return environment.get_this_binding(global_object);
  511. }
  512. String VM::join_arguments(size_t start_index) const
  513. {
  514. StringBuilder joined_arguments;
  515. for (size_t i = start_index; i < argument_count(); ++i) {
  516. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  517. if (i != argument_count() - 1)
  518. joined_arguments.append(' ');
  519. }
  520. return joined_arguments.build();
  521. }
  522. Value VM::get_new_target()
  523. {
  524. auto& env = get_this_environment(*this);
  525. return verify_cast<FunctionEnvironment>(env).new_target();
  526. }
  527. // 10.2.1.1 PrepareForOrdinaryCall ( F, newTarget ), https://tc39.es/ecma262/#sec-prepareforordinarycall
  528. void VM::prepare_for_ordinary_call(FunctionObject& function, ExecutionContext& callee_context, Object* new_target)
  529. {
  530. // NOTE: This is a LibJS specific hack for NativeFunction to inherit the strictness of its caller.
  531. // FIXME: I feel like we should be able to get rid of this.
  532. if (is<NativeFunction>(function))
  533. callee_context.is_strict_mode = in_strict_mode();
  534. else
  535. callee_context.is_strict_mode = function.is_strict_mode();
  536. // 1. Let callerContext be the running execution context.
  537. // 2. Let calleeContext be a new ECMAScript code execution context.
  538. // NOTE: In the specification, PrepareForOrdinaryCall "returns" a new callee execution context.
  539. // To avoid heap allocations, we put our ExecutionContext objects on the C++ stack instead.
  540. // Whoever calls us should put an ExecutionContext on their stack and pass that as the `callee_context`.
  541. // 3. Set the Function of calleeContext to F.
  542. callee_context.function = &function;
  543. callee_context.function_name = function.name();
  544. // 4. Let calleeRealm be F.[[Realm]].
  545. auto* callee_realm = function.realm();
  546. // FIXME: See FIXME in VM::call_internal() / VM::construct().
  547. if (!callee_realm)
  548. callee_realm = current_realm();
  549. VERIFY(callee_realm);
  550. // 5. Set the Realm of calleeContext to calleeRealm.
  551. callee_context.realm = callee_realm;
  552. // 6. Set the ScriptOrModule of calleeContext to F.[[ScriptOrModule]].
  553. // FIXME: Our execution context struct currently does not track this item.
  554. // 7. Let localEnv be NewFunctionEnvironment(F, newTarget).
  555. auto* local_environment = function.new_function_environment(new_target);
  556. // 8. Set the LexicalEnvironment of calleeContext to localEnv.
  557. callee_context.lexical_environment = local_environment;
  558. // 9. Set the VariableEnvironment of calleeContext to localEnv.
  559. callee_context.variable_environment = local_environment;
  560. // 10. Set the PrivateEnvironment of calleeContext to F.[[PrivateEnvironment]].
  561. // FIXME: We currently don't support private environments.
  562. // 11. If callerContext is not already suspended, suspend callerContext.
  563. // FIXME: We don't have this concept yet.
  564. // 12. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
  565. push_execution_context(callee_context, function.global_object());
  566. // 13. NOTE: Any exception objects produced after this point are associated with calleeRealm.
  567. // 14. Return calleeContext. (See NOTE above about how contexts are allocated on the C++ stack.)
  568. }
  569. // 10.2.1.2 OrdinaryCallBindThis ( F, calleeContext, thisArgument ), https://tc39.es/ecma262/#sec-ordinarycallbindthis
  570. void VM::ordinary_call_bind_this(FunctionObject& function, ExecutionContext& callee_context, Value this_argument)
  571. {
  572. auto* callee_realm = function.realm();
  573. auto* local_environment = callee_context.lexical_environment;
  574. auto& function_environment = verify_cast<FunctionEnvironment>(*local_environment);
  575. // This almost as the spec describes it however we sometimes don't have callee_realm when dealing
  576. // with proxies and arrow functions however this does seemingly achieve spec like behavior.
  577. if (!callee_realm || (is<ECMAScriptFunctionObject>(function) && static_cast<ECMAScriptFunctionObject&>(function).this_mode() == ECMAScriptFunctionObject::ThisMode::Lexical)) {
  578. return;
  579. }
  580. Value this_value;
  581. if (function.is_strict_mode()) {
  582. this_value = this_argument;
  583. } else if (this_argument.is_nullish()) {
  584. auto& global_environment = callee_realm->global_environment();
  585. this_value = &global_environment.global_this_value();
  586. } else {
  587. this_value = this_argument.to_object(function.global_object());
  588. }
  589. function_environment.bind_this_value(function.global_object(), this_value);
  590. callee_context.this_value = this_value;
  591. }
  592. ThrowCompletionOr<Value> VM::call_internal(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments)
  593. {
  594. VERIFY(!exception());
  595. VERIFY(!this_value.is_empty());
  596. if (is<BoundFunction>(function)) {
  597. auto& bound_function = static_cast<BoundFunction&>(function);
  598. MarkedValueList with_bound_arguments { heap() };
  599. append_bound_and_passed_arguments(with_bound_arguments, bound_function.bound_arguments(), move(arguments));
  600. return call_internal(bound_function.bound_target_function(), bound_function.bound_this(), move(with_bound_arguments));
  601. }
  602. // FIXME: prepare_for_ordinary_call() is not supposed to receive a BoundFunction, ProxyObject, etc. - ever.
  603. // This needs to be moved to NativeFunction/ECMAScriptFunctionObject's construct() (10.2.2 [[Construct]])
  604. ExecutionContext callee_context(heap());
  605. prepare_for_ordinary_call(function, callee_context, nullptr);
  606. if (auto* exception = this->exception())
  607. return JS::throw_completion(exception->value());
  608. ScopeGuard pop_guard = [&] {
  609. pop_execution_context();
  610. };
  611. if (auto* interpreter = interpreter_if_exists())
  612. callee_context.current_node = interpreter->current_node();
  613. callee_context.this_value = this_value;
  614. append_bound_and_passed_arguments(callee_context.arguments, {}, move(arguments));
  615. ordinary_call_bind_this(function, callee_context, this_value);
  616. if (auto* exception = this->exception())
  617. return JS::throw_completion(exception->value());
  618. auto result = function.call();
  619. if (auto* exception = this->exception())
  620. return JS::throw_completion(exception->value());
  621. return result;
  622. }
  623. bool VM::in_strict_mode() const
  624. {
  625. if (execution_context_stack().is_empty())
  626. return false;
  627. return running_execution_context().is_strict_mode;
  628. }
  629. void VM::run_queued_promise_jobs()
  630. {
  631. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  632. // Temporarily get rid of the exception, if any - job functions must be called
  633. // either way, and that can't happen if we already have an exception stored.
  634. TemporaryClearException clear_exception(*this);
  635. while (!m_promise_jobs.is_empty()) {
  636. auto* job = m_promise_jobs.take_first();
  637. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  638. [[maybe_unused]] auto result = call(*job, js_undefined());
  639. }
  640. // Ensure no job has created a new exception, they must clean up after themselves.
  641. VERIFY(!m_exception);
  642. }
  643. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  644. void VM::enqueue_promise_job(NativeFunction& job)
  645. {
  646. m_promise_jobs.append(&job);
  647. }
  648. void VM::run_queued_finalization_registry_cleanup_jobs()
  649. {
  650. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  651. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  652. registry->cleanup();
  653. }
  654. }
  655. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  656. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  657. {
  658. m_finalization_registry_cleanup_jobs.append(&registry);
  659. }
  660. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  661. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  662. {
  663. switch (operation) {
  664. case Promise::RejectionOperation::Reject:
  665. // A promise was rejected without any handlers
  666. if (on_promise_unhandled_rejection)
  667. on_promise_unhandled_rejection(promise);
  668. break;
  669. case Promise::RejectionOperation::Handle:
  670. // A handler was added to an already rejected promise
  671. if (on_promise_rejection_handled)
  672. on_promise_rejection_handled(promise);
  673. break;
  674. default:
  675. VERIFY_NOT_REACHED();
  676. }
  677. }
  678. void VM::dump_backtrace() const
  679. {
  680. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  681. auto& frame = m_execution_context_stack[i];
  682. if (frame->current_node) {
  683. auto& source_range = frame->current_node->source_range();
  684. dbgln("-> {} @ {}:{},{}", frame->function_name, source_range.filename, source_range.start.line, source_range.start.column);
  685. } else {
  686. dbgln("-> {}", frame->function_name);
  687. }
  688. }
  689. }
  690. VM::CustomData::~CustomData()
  691. {
  692. }
  693. void VM::save_execution_context_stack()
  694. {
  695. m_saved_execution_context_stacks.append(move(m_execution_context_stack));
  696. }
  697. void VM::restore_execution_context_stack()
  698. {
  699. m_execution_context_stack = m_saved_execution_context_stacks.take_last();
  700. }
  701. }