VM.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, 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/Completion.h>
  16. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  17. #include <LibJS/Runtime/Error.h>
  18. #include <LibJS/Runtime/FinalizationRegistry.h>
  19. #include <LibJS/Runtime/FunctionEnvironment.h>
  20. #include <LibJS/Runtime/GlobalObject.h>
  21. #include <LibJS/Runtime/IteratorOperations.h>
  22. #include <LibJS/Runtime/NativeFunction.h>
  23. #include <LibJS/Runtime/PromiseReaction.h>
  24. #include <LibJS/Runtime/Reference.h>
  25. #include <LibJS/Runtime/Symbol.h>
  26. #include <LibJS/Runtime/TemporaryClearException.h>
  27. #include <LibJS/Runtime/VM.h>
  28. namespace JS {
  29. NonnullRefPtr<VM> VM::create(OwnPtr<CustomData> custom_data)
  30. {
  31. return adopt_ref(*new VM(move(custom_data)));
  32. }
  33. VM::VM(OwnPtr<CustomData> custom_data)
  34. : m_heap(*this)
  35. , m_custom_data(move(custom_data))
  36. {
  37. m_empty_string = m_heap.allocate_without_global_object<PrimitiveString>(String::empty());
  38. for (size_t i = 0; i < 128; ++i) {
  39. m_single_ascii_character_strings[i] = m_heap.allocate_without_global_object<PrimitiveString>(String::formatted("{:c}", i));
  40. }
  41. #define __JS_ENUMERATE(SymbolName, snake_name) \
  42. m_well_known_symbol_##snake_name = js_symbol(*this, "Symbol." #SymbolName, false);
  43. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  44. #undef __JS_ENUMERATE
  45. }
  46. VM::~VM()
  47. {
  48. }
  49. Interpreter& VM::interpreter()
  50. {
  51. VERIFY(!m_interpreters.is_empty());
  52. return *m_interpreters.last();
  53. }
  54. Interpreter* VM::interpreter_if_exists()
  55. {
  56. if (m_interpreters.is_empty())
  57. return nullptr;
  58. return m_interpreters.last();
  59. }
  60. void VM::push_interpreter(Interpreter& interpreter)
  61. {
  62. m_interpreters.append(&interpreter);
  63. }
  64. void VM::pop_interpreter(Interpreter& interpreter)
  65. {
  66. VERIFY(!m_interpreters.is_empty());
  67. auto* popped_interpreter = m_interpreters.take_last();
  68. VERIFY(popped_interpreter == &interpreter);
  69. }
  70. VM::InterpreterExecutionScope::InterpreterExecutionScope(Interpreter& interpreter)
  71. : m_interpreter(interpreter)
  72. {
  73. m_interpreter.vm().push_interpreter(m_interpreter);
  74. }
  75. VM::InterpreterExecutionScope::~InterpreterExecutionScope()
  76. {
  77. m_interpreter.vm().pop_interpreter(m_interpreter);
  78. }
  79. void VM::gather_roots(HashTable<Cell*>& roots)
  80. {
  81. roots.set(m_empty_string);
  82. for (auto* string : m_single_ascii_character_strings)
  83. roots.set(string);
  84. roots.set(m_exception);
  85. auto gather_roots_from_execution_context_stack = [&roots](Vector<ExecutionContext*> const& stack) {
  86. for (auto& execution_context : stack) {
  87. if (execution_context->this_value.is_cell())
  88. roots.set(&execution_context->this_value.as_cell());
  89. for (auto& argument : execution_context->arguments) {
  90. if (argument.is_cell())
  91. roots.set(&argument.as_cell());
  92. }
  93. roots.set(execution_context->lexical_environment);
  94. roots.set(execution_context->variable_environment);
  95. roots.set(execution_context->private_environment);
  96. }
  97. };
  98. gather_roots_from_execution_context_stack(m_execution_context_stack);
  99. for (auto& saved_stack : m_saved_execution_context_stacks)
  100. gather_roots_from_execution_context_stack(saved_stack);
  101. #define __JS_ENUMERATE(SymbolName, snake_name) \
  102. roots.set(well_known_symbol_##snake_name());
  103. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  104. #undef __JS_ENUMERATE
  105. for (auto& symbol : m_global_symbol_map)
  106. roots.set(symbol.value);
  107. for (auto* job : m_promise_jobs)
  108. roots.set(job);
  109. for (auto* finalization_registry : m_finalization_registry_cleanup_jobs)
  110. roots.set(finalization_registry);
  111. }
  112. Symbol* VM::get_global_symbol(const String& description)
  113. {
  114. auto result = m_global_symbol_map.get(description);
  115. if (result.has_value())
  116. return result.value();
  117. auto new_global_symbol = js_symbol(*this, description, true);
  118. m_global_symbol_map.set(description, new_global_symbol);
  119. return new_global_symbol;
  120. }
  121. ThrowCompletionOr<Value> VM::named_evaluation_if_anonymous_function(GlobalObject& global_object, ASTNode const& expression, FlyString const& name)
  122. {
  123. // 8.3.3 Static Semantics: IsAnonymousFunctionDefinition ( expr ), https://tc39.es/ecma262/#sec-isanonymousfunctiondefinition
  124. // And 8.3.5 Runtime Semantics: NamedEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-namedevaluation
  125. if (is<FunctionExpression>(expression)) {
  126. auto& function = static_cast<FunctionExpression const&>(expression);
  127. if (!function.has_name()) {
  128. return function.instantiate_ordinary_function_expression(interpreter(), global_object, name);
  129. }
  130. } else if (is<ClassExpression>(expression)) {
  131. auto& class_expression = static_cast<ClassExpression const&>(expression);
  132. if (!class_expression.has_name()) {
  133. return TRY(class_expression.class_definition_evaluation(interpreter(), global_object, {}, name));
  134. }
  135. }
  136. return TRY(expression.execute(interpreter(), global_object)).release_value();
  137. }
  138. // 13.15.5.2 Runtime Semantics: DestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-destructuringassignmentevaluation
  139. ThrowCompletionOr<void> VM::destructuring_assignment_evaluation(NonnullRefPtr<BindingPattern> const& target, Value value, GlobalObject& global_object)
  140. {
  141. // Note: DestructuringAssignmentEvaluation is just like BindingInitialization without an environment
  142. // And it allows member expressions. We thus trust the parser to disallow member expressions
  143. // in any non assignment binding and just call BindingInitialization with a nullptr environment
  144. return binding_initialization(target, value, nullptr, global_object);
  145. }
  146. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  147. ThrowCompletionOr<void> VM::binding_initialization(FlyString const& target, Value value, Environment* environment, GlobalObject& global_object)
  148. {
  149. // 1. Let name be StringValue of Identifier.
  150. // 2. Return ? InitializeBoundName(name, value, environment).
  151. return initialize_bound_name(global_object, target, value, environment);
  152. }
  153. // 8.5.2 Runtime Semantics: BindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-bindinginitialization
  154. ThrowCompletionOr<void> VM::binding_initialization(NonnullRefPtr<BindingPattern> const& target, Value value, Environment* environment, GlobalObject& global_object)
  155. {
  156. // BindingPattern : ObjectBindingPattern
  157. if (target->kind == BindingPattern::Kind::Object) {
  158. // 1. Perform ? RequireObjectCoercible(value).
  159. TRY(require_object_coercible(global_object, value));
  160. // 2. Return the result of performing BindingInitialization of ObjectBindingPattern using value and environment as arguments.
  161. // BindingInitialization of ObjectBindingPattern
  162. // 1. Perform ? PropertyBindingInitialization of BindingPropertyList using value and environment as the arguments.
  163. TRY(property_binding_initialization(*target, value, environment, global_object));
  164. // 2. Return NormalCompletion(empty).
  165. return {};
  166. }
  167. // BindingPattern : ArrayBindingPattern
  168. else {
  169. // 1. Let iteratorRecord be ? GetIterator(value).
  170. auto iterator_record = TRY(get_iterator(global_object, value));
  171. // 2. Let result be IteratorBindingInitialization of ArrayBindingPattern with arguments iteratorRecord and environment.
  172. auto result = iterator_binding_initialization(*target, iterator_record, environment, global_object);
  173. // 3. If iteratorRecord.[[Done]] is false, return ? IteratorClose(iteratorRecord, result).
  174. if (!iterator_record.done) {
  175. // iterator_close() always returns a Completion, which ThrowCompletionOr will interpret as a throw
  176. // completion. So only return the result of iterator_close() if it is indeed a throw completion.
  177. auto completion = result.is_throw_completion() ? result.release_error() : normal_completion({});
  178. if (completion = iterator_close(global_object, iterator_record, move(completion)); completion.is_error())
  179. return completion.release_error();
  180. }
  181. // 4. Return result.
  182. return result;
  183. }
  184. }
  185. // 13.15.5.3 Runtime Semantics: PropertyDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-propertydestructuringassignmentevaluation
  186. // 14.3.3.1 Runtime Semantics: PropertyBindingInitialization, https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-propertybindinginitialization
  187. ThrowCompletionOr<void> VM::property_binding_initialization(BindingPattern const& binding, Value value, Environment* environment, GlobalObject& global_object)
  188. {
  189. auto* object = TRY(value.to_object(global_object));
  190. HashTable<PropertyKey> seen_names;
  191. for (auto& property : binding.entries) {
  192. VERIFY(!property.is_elision());
  193. if (property.is_rest) {
  194. Reference assignment_target;
  195. if (auto identifier_ptr = property.name.get_pointer<NonnullRefPtr<Identifier>>()) {
  196. assignment_target = TRY(resolve_binding((*identifier_ptr)->string(), environment));
  197. } else if (auto member_ptr = property.alias.get_pointer<NonnullRefPtr<MemberExpression>>()) {
  198. assignment_target = TRY((*member_ptr)->to_reference(interpreter(), global_object));
  199. } else {
  200. VERIFY_NOT_REACHED();
  201. }
  202. auto* rest_object = Object::create(global_object, global_object.object_prototype());
  203. VERIFY(rest_object);
  204. TRY(rest_object->copy_data_properties(object, seen_names, global_object));
  205. if (!environment)
  206. return assignment_target.put_value(global_object, rest_object);
  207. else
  208. return assignment_target.initialize_referenced_binding(global_object, rest_object);
  209. }
  210. auto name = TRY(property.name.visit(
  211. [&](Empty) -> ThrowCompletionOr<PropertyKey> { VERIFY_NOT_REACHED(); },
  212. [&](NonnullRefPtr<Identifier> const& identifier) -> ThrowCompletionOr<PropertyKey> {
  213. return identifier->string();
  214. },
  215. [&](NonnullRefPtr<Expression> const& expression) -> ThrowCompletionOr<PropertyKey> {
  216. auto result = TRY(expression->execute(interpreter(), global_object)).release_value();
  217. return result.to_property_key(global_object);
  218. }));
  219. seen_names.set(name);
  220. if (property.name.has<NonnullRefPtr<Identifier>>() && property.alias.has<Empty>()) {
  221. // FIXME: this branch and not taking this have a lot in common we might want to unify it more (like it was before).
  222. auto& identifier = *property.name.get<NonnullRefPtr<Identifier>>();
  223. auto reference = TRY(resolve_binding(identifier.string(), environment));
  224. auto value_to_assign = TRY(object->get(name));
  225. if (property.initializer && value_to_assign.is_undefined()) {
  226. value_to_assign = TRY(named_evaluation_if_anonymous_function(global_object, *property.initializer, identifier.string()));
  227. }
  228. if (!environment)
  229. TRY(reference.put_value(global_object, value_to_assign));
  230. else
  231. TRY(reference.initialize_referenced_binding(global_object, value_to_assign));
  232. continue;
  233. }
  234. auto reference_to_assign_to = TRY(property.alias.visit(
  235. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  236. [&](NonnullRefPtr<Identifier> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  237. return TRY(resolve_binding(identifier->string(), environment));
  238. },
  239. [&](NonnullRefPtr<BindingPattern> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  240. [&](NonnullRefPtr<MemberExpression> const& member_expression) -> ThrowCompletionOr<Optional<Reference>> {
  241. return TRY(member_expression->to_reference(interpreter(), global_object));
  242. }));
  243. auto value_to_assign = TRY(object->get(name));
  244. if (property.initializer && value_to_assign.is_undefined()) {
  245. if (auto* identifier_ptr = property.alias.get_pointer<NonnullRefPtr<Identifier>>())
  246. value_to_assign = TRY(named_evaluation_if_anonymous_function(global_object, *property.initializer, (*identifier_ptr)->string()));
  247. else
  248. value_to_assign = TRY(property.initializer->execute(interpreter(), global_object)).release_value();
  249. }
  250. if (auto* binding_ptr = property.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  251. TRY(binding_initialization(*binding_ptr, value_to_assign, environment, global_object));
  252. } else {
  253. VERIFY(reference_to_assign_to.has_value());
  254. if (!environment)
  255. TRY(reference_to_assign_to->put_value(global_object, value_to_assign));
  256. else
  257. TRY(reference_to_assign_to->initialize_referenced_binding(global_object, value_to_assign));
  258. }
  259. }
  260. return {};
  261. }
  262. // 13.15.5.5 Runtime Semantics: IteratorDestructuringAssignmentEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-iteratordestructuringassignmentevaluation
  263. // 8.5.3 Runtime Semantics: IteratorBindingInitialization, https://tc39.es/ecma262/#sec-runtime-semantics-iteratorbindinginitialization
  264. ThrowCompletionOr<void> VM::iterator_binding_initialization(BindingPattern const& binding, Iterator& iterator_record, Environment* environment, GlobalObject& global_object)
  265. {
  266. // FIXME: this method is nearly identical to destructuring assignment!
  267. for (size_t i = 0; i < binding.entries.size(); i++) {
  268. auto& entry = binding.entries[i];
  269. Value value;
  270. auto assignment_target = TRY(entry.alias.visit(
  271. [&](Empty) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  272. [&](NonnullRefPtr<Identifier> const& identifier) -> ThrowCompletionOr<Optional<Reference>> {
  273. return TRY(resolve_binding(identifier->string(), environment));
  274. },
  275. [&](NonnullRefPtr<BindingPattern> const&) -> ThrowCompletionOr<Optional<Reference>> { return Optional<Reference> {}; },
  276. [&](NonnullRefPtr<MemberExpression> const& member_expression) -> ThrowCompletionOr<Optional<Reference>> {
  277. return TRY(member_expression->to_reference(interpreter(), global_object));
  278. }));
  279. // BindingRestElement : ... BindingIdentifier
  280. // BindingRestElement : ... BindingPattern
  281. if (entry.is_rest) {
  282. VERIFY(i == binding.entries.size() - 1);
  283. // 2. Let A be ! ArrayCreate(0).
  284. auto* array = MUST(Array::create(global_object, 0));
  285. // 3. Let n be 0.
  286. // 4. Repeat,
  287. while (true) {
  288. ThrowCompletionOr<Object*> next { nullptr };
  289. // a. If iteratorRecord.[[Done]] is false, then
  290. if (!iterator_record.done) {
  291. // i. Let next be IteratorStep(iteratorRecord).
  292. next = iterator_step(global_object, iterator_record);
  293. // ii. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  294. // iii. ReturnIfAbrupt(next).
  295. if (next.is_error()) {
  296. iterator_record.done = true;
  297. return next.release_error();
  298. }
  299. // iv. If next is false, set iteratorRecord.[[Done]] to true.
  300. if (!next.value())
  301. iterator_record.done = true;
  302. }
  303. // b. If iteratorRecord.[[Done]] is true, then
  304. if (iterator_record.done) {
  305. // NOTE: Step i. and ii. are handled below.
  306. break;
  307. }
  308. // c. Let nextValue be IteratorValue(next).
  309. auto next_value = iterator_value(global_object, *next.value());
  310. // d. If nextValue is an abrupt completion, set iteratorRecord.[[Done]] to true.
  311. // e. ReturnIfAbrupt(nextValue).
  312. if (next_value.is_error()) {
  313. iterator_record.done = true;
  314. return next_value.release_error();
  315. }
  316. // f. Perform ! CreateDataPropertyOrThrow(A, ! ToString(𝔽(n)), nextValue).
  317. array->indexed_properties().append(next_value.value());
  318. // g. Set n to n + 1.
  319. }
  320. value = array;
  321. }
  322. // SingleNameBinding : BindingIdentifier Initializer[opt]
  323. // BindingElement : BindingPattern Initializer[opt]
  324. else {
  325. // 1. Let v be undefined.
  326. value = js_undefined();
  327. // 2. If iteratorRecord.[[Done]] is false, then
  328. if (!iterator_record.done) {
  329. // a. Let next be IteratorStep(iteratorRecord).
  330. auto next = iterator_step(global_object, iterator_record);
  331. // b. If next is an abrupt completion, set iteratorRecord.[[Done]] to true.
  332. // c. ReturnIfAbrupt(next).
  333. if (next.is_error()) {
  334. iterator_record.done = true;
  335. return next.release_error();
  336. }
  337. // d. If next is false, set iteratorRecord.[[Done]] to true.
  338. if (!next.value()) {
  339. iterator_record.done = true;
  340. }
  341. // e. Else,
  342. else {
  343. // i. Set v to IteratorValue(next).
  344. auto value_or_error = iterator_value(global_object, *next.value());
  345. // ii. If v is an abrupt completion, set iteratorRecord.[[Done]] to true.
  346. // iii. ReturnIfAbrupt(v).
  347. if (value_or_error.is_throw_completion()) {
  348. iterator_record.done = true;
  349. return value_or_error.release_error();
  350. }
  351. value = value_or_error.release_value();
  352. }
  353. }
  354. // NOTE: Step 3. and 4. are handled below.
  355. }
  356. if (value.is_undefined() && entry.initializer) {
  357. VERIFY(!entry.is_rest);
  358. if (auto* identifier_ptr = entry.alias.get_pointer<NonnullRefPtr<Identifier>>())
  359. value = TRY(named_evaluation_if_anonymous_function(global_object, *entry.initializer, (*identifier_ptr)->string()));
  360. else
  361. value = TRY(entry.initializer->execute(interpreter(), global_object)).release_value();
  362. }
  363. if (auto* binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>()) {
  364. TRY(binding_initialization(*binding_ptr, value, environment, global_object));
  365. } else if (!entry.alias.has<Empty>()) {
  366. VERIFY(assignment_target.has_value());
  367. if (!environment)
  368. TRY(assignment_target->put_value(global_object, value));
  369. else
  370. TRY(assignment_target->initialize_referenced_binding(global_object, value));
  371. }
  372. }
  373. return {};
  374. }
  375. // 9.1.2.1 GetIdentifierReference ( env, name, strict ), https://tc39.es/ecma262/#sec-getidentifierreference
  376. ThrowCompletionOr<Reference> VM::get_identifier_reference(Environment* environment, FlyString name, bool strict, size_t hops)
  377. {
  378. // 1. If env is the value null, then
  379. if (!environment) {
  380. // a. Return the Reference Record { [[Base]]: unresolvable, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  381. return Reference { Reference::BaseType::Unresolvable, move(name), strict };
  382. }
  383. // 2. Let exists be ? env.HasBinding(name).
  384. Optional<size_t> index;
  385. auto exists = TRY(environment->has_binding(name, &index));
  386. // Note: This is an optimization for looking up the same reference.
  387. Optional<EnvironmentCoordinate> environment_coordinate;
  388. if (index.has_value())
  389. environment_coordinate = EnvironmentCoordinate { .hops = hops, .index = index.value() };
  390. // 3. If exists is true, then
  391. if (exists) {
  392. // a. Return the Reference Record { [[Base]]: env, [[ReferencedName]]: name, [[Strict]]: strict, [[ThisValue]]: empty }.
  393. return Reference { *environment, move(name), strict, environment_coordinate };
  394. }
  395. // 4. Else,
  396. else {
  397. // a. Let outer be env.[[OuterEnv]].
  398. // b. Return ? GetIdentifierReference(outer, name, strict).
  399. return get_identifier_reference(environment->outer_environment(), move(name), strict, hops + 1);
  400. }
  401. }
  402. // 9.4.2 ResolveBinding ( name [ , env ] ), https://tc39.es/ecma262/#sec-resolvebinding
  403. ThrowCompletionOr<Reference> VM::resolve_binding(FlyString const& name, Environment* environment)
  404. {
  405. // 1. If env is not present or if env is undefined, then
  406. if (!environment) {
  407. // a. Set env to the running execution context's LexicalEnvironment.
  408. environment = running_execution_context().lexical_environment;
  409. }
  410. // 2. Assert: env is an Environment Record.
  411. VERIFY(environment);
  412. // 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.
  413. bool strict = in_strict_mode();
  414. // 4. Return ? GetIdentifierReference(env, name, strict).
  415. return get_identifier_reference(environment, name, strict);
  416. // NOTE: The spec says:
  417. // Note: The result of ResolveBinding is always a Reference Record whose [[ReferencedName]] field is name.
  418. // But this is not actually correct as GetIdentifierReference (or really the methods it calls) can throw.
  419. }
  420. // 7.3.33 InitializeInstanceElements ( O, constructor ), https://tc39.es/ecma262/#sec-initializeinstanceelements
  421. ThrowCompletionOr<void> VM::initialize_instance_elements(Object& object, ECMAScriptFunctionObject& constructor)
  422. {
  423. for (auto& method : constructor.private_methods())
  424. TRY(object.private_method_or_accessor_add(method));
  425. for (auto& field : constructor.fields())
  426. TRY(object.define_field(field.name, field.initializer));
  427. return {};
  428. }
  429. void VM::throw_exception(Exception& exception)
  430. {
  431. set_exception(exception);
  432. }
  433. // 9.4.4 ResolveThisBinding ( ), https://tc39.es/ecma262/#sec-resolvethisbinding
  434. ThrowCompletionOr<Value> VM::resolve_this_binding(GlobalObject& global_object)
  435. {
  436. // 1. Let envRec be GetThisEnvironment().
  437. auto& environment = get_this_environment(*this);
  438. // 2. Return ? envRec.GetThisBinding().
  439. return TRY(environment.get_this_binding(global_object));
  440. }
  441. String VM::join_arguments(size_t start_index) const
  442. {
  443. StringBuilder joined_arguments;
  444. for (size_t i = start_index; i < argument_count(); ++i) {
  445. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  446. if (i != argument_count() - 1)
  447. joined_arguments.append(' ');
  448. }
  449. return joined_arguments.build();
  450. }
  451. // 9.4.5 GetNewTarget ( ), https://tc39.es/ecma262/#sec-getnewtarget
  452. Value VM::get_new_target()
  453. {
  454. // 1. Let envRec be GetThisEnvironment().
  455. auto& env = get_this_environment(*this);
  456. // 2. Assert: envRec has a [[NewTarget]] field.
  457. // 3. Return envRec.[[NewTarget]].
  458. return verify_cast<FunctionEnvironment>(env).new_target();
  459. }
  460. // NOTE: This is only here because there's a million invocations of vm.call() - it used to be tied to the VM in weird ways.
  461. // We should update all of those and then remove this, along with the call() template functions in VM.h, and use the standalone call() AO.
  462. ThrowCompletionOr<Value> VM::call_internal(FunctionObject& function, Value this_value, Optional<MarkedValueList> arguments)
  463. {
  464. VERIFY(!exception());
  465. VERIFY(!this_value.is_empty());
  466. return JS::call_impl(function.global_object(), &function, this_value, move(arguments));
  467. }
  468. bool VM::in_strict_mode() const
  469. {
  470. if (execution_context_stack().is_empty())
  471. return false;
  472. return running_execution_context().is_strict_mode;
  473. }
  474. void VM::run_queued_promise_jobs()
  475. {
  476. dbgln_if(PROMISE_DEBUG, "Running queued promise jobs");
  477. // Temporarily get rid of the exception, if any - job functions must be called
  478. // either way, and that can't happen if we already have an exception stored.
  479. TemporaryClearException temporary_clear_exception(*this);
  480. while (!m_promise_jobs.is_empty()) {
  481. auto* job = m_promise_jobs.take_first();
  482. dbgln_if(PROMISE_DEBUG, "Calling promise job function @ {}", job);
  483. // NOTE: If the execution context stack is empty, we make and push a temporary context.
  484. ExecutionContext execution_context(heap());
  485. bool pushed_execution_context = false;
  486. if (m_execution_context_stack.is_empty()) {
  487. static FlyString promise_execution_context_name = "(promise execution context)";
  488. execution_context.function_name = promise_execution_context_name;
  489. // FIXME: Propagate potential failure
  490. MUST(push_execution_context(execution_context, job->global_object()));
  491. pushed_execution_context = true;
  492. }
  493. [[maybe_unused]] auto result = call(*job, js_undefined());
  494. // This doesn't match the spec, it actually defines that Job Abstract Closures must return
  495. // a normal completion. In reality that's not the case however, and all major engines clear
  496. // exceptions when running Promise jobs. See the commit where these two lines were initially
  497. // added for a much more detailed explanation.
  498. clear_exception();
  499. if (pushed_execution_context)
  500. pop_execution_context();
  501. }
  502. // Ensure no job has created a new exception, they must clean up after themselves.
  503. // If they don't, we help a little (see above) so that this assumption remains valid.
  504. VERIFY(!m_exception);
  505. }
  506. // 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejob
  507. void VM::enqueue_promise_job(NativeFunction& job)
  508. {
  509. m_promise_jobs.append(&job);
  510. }
  511. void VM::run_queued_finalization_registry_cleanup_jobs()
  512. {
  513. while (!m_finalization_registry_cleanup_jobs.is_empty()) {
  514. auto* registry = m_finalization_registry_cleanup_jobs.take_first();
  515. registry->cleanup();
  516. }
  517. }
  518. // 9.10.4.1 HostEnqueueFinalizationRegistryCleanupJob ( finalizationRegistry ), https://tc39.es/ecma262/#sec-host-cleanup-finalization-registry
  519. void VM::enqueue_finalization_registry_cleanup_job(FinalizationRegistry& registry)
  520. {
  521. m_finalization_registry_cleanup_jobs.append(&registry);
  522. }
  523. // 27.2.1.9 HostPromiseRejectionTracker ( promise, operation ), https://tc39.es/ecma262/#sec-host-promise-rejection-tracker
  524. void VM::promise_rejection_tracker(const Promise& promise, Promise::RejectionOperation operation) const
  525. {
  526. switch (operation) {
  527. case Promise::RejectionOperation::Reject:
  528. // A promise was rejected without any handlers
  529. if (on_promise_unhandled_rejection)
  530. on_promise_unhandled_rejection(promise);
  531. break;
  532. case Promise::RejectionOperation::Handle:
  533. // A handler was added to an already rejected promise
  534. if (on_promise_rejection_handled)
  535. on_promise_rejection_handled(promise);
  536. break;
  537. default:
  538. VERIFY_NOT_REACHED();
  539. }
  540. }
  541. void VM::dump_backtrace() const
  542. {
  543. for (ssize_t i = m_execution_context_stack.size() - 1; i >= 0; --i) {
  544. auto& frame = m_execution_context_stack[i];
  545. if (frame->current_node) {
  546. auto& source_range = frame->current_node->source_range();
  547. dbgln("-> {} @ {}:{},{}", frame->function_name, source_range.filename, source_range.start.line, source_range.start.column);
  548. } else {
  549. dbgln("-> {}", frame->function_name);
  550. }
  551. }
  552. }
  553. VM::CustomData::~CustomData()
  554. {
  555. }
  556. void VM::save_execution_context_stack()
  557. {
  558. m_saved_execution_context_stacks.append(move(m_execution_context_stack));
  559. }
  560. void VM::restore_execution_context_stack()
  561. {
  562. m_execution_context_stack = m_saved_execution_context_stacks.take_last();
  563. }
  564. }