VM.h 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (c) 2020, 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. #pragma once
  8. #include <AK/FlyString.h>
  9. #include <AK/Function.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/RefCounted.h>
  12. #include <AK/StackInfo.h>
  13. #include <LibJS/Heap/Heap.h>
  14. #include <LibJS/Runtime/CommonPropertyNames.h>
  15. #include <LibJS/Runtime/Error.h>
  16. #include <LibJS/Runtime/ErrorTypes.h>
  17. #include <LibJS/Runtime/Exception.h>
  18. #include <LibJS/Runtime/MarkedValueList.h>
  19. #include <LibJS/Runtime/Promise.h>
  20. #include <LibJS/Runtime/Value.h>
  21. namespace JS {
  22. enum class ScopeType {
  23. None,
  24. Function,
  25. Block,
  26. Try,
  27. Breakable,
  28. Continuable,
  29. };
  30. struct ScopeFrame {
  31. ScopeType type;
  32. NonnullRefPtr<ScopeNode> scope_node;
  33. bool pushed_environment { false };
  34. };
  35. struct CallFrame {
  36. const ASTNode* current_node { nullptr };
  37. FlyString function_name;
  38. Value callee;
  39. Value this_value;
  40. Vector<Value> arguments;
  41. Array* arguments_object { nullptr };
  42. ScopeObject* scope { nullptr };
  43. bool is_strict_mode { false };
  44. };
  45. class VM : public RefCounted<VM> {
  46. public:
  47. static NonnullRefPtr<VM> create();
  48. ~VM();
  49. Heap& heap() { return m_heap; }
  50. const Heap& heap() const { return m_heap; }
  51. Interpreter& interpreter();
  52. Interpreter* interpreter_if_exists();
  53. void push_interpreter(Interpreter&);
  54. void pop_interpreter(Interpreter&);
  55. Exception* exception() { return m_exception; }
  56. void set_exception(Exception& exception) { m_exception = &exception; }
  57. void clear_exception() { m_exception = nullptr; }
  58. class InterpreterExecutionScope {
  59. public:
  60. InterpreterExecutionScope(Interpreter&);
  61. ~InterpreterExecutionScope();
  62. private:
  63. Interpreter& m_interpreter;
  64. };
  65. void gather_roots(HashTable<Cell*>&);
  66. #define __JS_ENUMERATE(SymbolName, snake_name) \
  67. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  68. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  69. #undef __JS_ENUMERATE
  70. Symbol* get_global_symbol(const String& description);
  71. PrimitiveString& empty_string() { return *m_empty_string; }
  72. PrimitiveString& single_ascii_character_string(u8 character)
  73. {
  74. VERIFY(character < 0x80);
  75. return *m_single_ascii_character_strings[character];
  76. }
  77. void push_call_frame(CallFrame& call_frame, GlobalObject& global_object)
  78. {
  79. VERIFY(!exception());
  80. // Ensure we got some stack space left, so the next function call doesn't kill us.
  81. // This value is merely a guess and might need tweaking at a later point.
  82. if (m_stack_info.size_free() < 16 * KiB)
  83. throw_exception<Error>(global_object, "Call stack size limit exceeded");
  84. else
  85. m_call_stack.append(&call_frame);
  86. }
  87. void pop_call_frame()
  88. {
  89. m_call_stack.take_last();
  90. if (m_call_stack.is_empty() && on_call_stack_emptied)
  91. on_call_stack_emptied();
  92. }
  93. CallFrame& call_frame() { return *m_call_stack.last(); }
  94. const CallFrame& call_frame() const { return *m_call_stack.last(); }
  95. const Vector<CallFrame*>& call_stack() const { return m_call_stack; }
  96. Vector<CallFrame*>& call_stack() { return m_call_stack; }
  97. const ScopeObject* current_scope() const { return call_frame().scope; }
  98. ScopeObject* current_scope() { return call_frame().scope; }
  99. bool in_strict_mode() const;
  100. template<typename Callback>
  101. void for_each_argument(Callback callback)
  102. {
  103. if (m_call_stack.is_empty())
  104. return;
  105. for (auto& value : call_frame().arguments)
  106. callback(value);
  107. }
  108. size_t argument_count() const
  109. {
  110. if (m_call_stack.is_empty())
  111. return 0;
  112. return call_frame().arguments.size();
  113. }
  114. Value argument(size_t index) const
  115. {
  116. if (m_call_stack.is_empty())
  117. return {};
  118. auto& arguments = call_frame().arguments;
  119. return index < arguments.size() ? arguments[index] : js_undefined();
  120. }
  121. Value this_value(Object& global_object) const
  122. {
  123. if (m_call_stack.is_empty())
  124. return &global_object;
  125. return call_frame().this_value;
  126. }
  127. Value last_value() const { return m_last_value; }
  128. void set_last_value(Badge<Interpreter>, Value value) { m_last_value = value; }
  129. const StackInfo& stack_info() const { return m_stack_info; };
  130. bool underscore_is_last_value() const { return m_underscore_is_last_value; }
  131. void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
  132. void unwind(ScopeType type, FlyString label = {})
  133. {
  134. m_unwind_until = type;
  135. m_unwind_until_label = label;
  136. }
  137. void stop_unwind()
  138. {
  139. m_unwind_until = ScopeType::None;
  140. m_unwind_until_label = {};
  141. }
  142. bool should_unwind_until(ScopeType type, FlyString label = {}) const
  143. {
  144. if (m_unwind_until_label.is_null())
  145. return m_unwind_until == type;
  146. return m_unwind_until == type && m_unwind_until_label == label;
  147. }
  148. bool should_unwind() const { return m_unwind_until != ScopeType::None; }
  149. ScopeType unwind_until() const { return m_unwind_until; }
  150. Value get_variable(const FlyString& name, GlobalObject&);
  151. void set_variable(const FlyString& name, Value, GlobalObject&, bool first_assignment = false);
  152. Reference get_reference(const FlyString& name);
  153. template<typename T, typename... Args>
  154. void throw_exception(GlobalObject& global_object, Args&&... args)
  155. {
  156. return throw_exception(global_object, T::create(global_object, forward<Args>(args)...));
  157. }
  158. void throw_exception(Exception&);
  159. void throw_exception(GlobalObject& global_object, Value value)
  160. {
  161. return throw_exception(*heap().allocate<Exception>(global_object, value));
  162. }
  163. template<typename T, typename... Args>
  164. void throw_exception(GlobalObject& global_object, ErrorType type, Args&&... args)
  165. {
  166. return throw_exception(global_object, T::create(global_object, String::formatted(type.message(), forward<Args>(args)...)));
  167. }
  168. Value construct(Function&, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject&);
  169. String join_arguments(size_t start_index = 0) const;
  170. Value resolve_this_binding(GlobalObject&) const;
  171. const ScopeObject* find_this_scope() const;
  172. Value get_new_target() const;
  173. template<typename... Args>
  174. [[nodiscard]] ALWAYS_INLINE Value call(Function& function, Value this_value, Args... args)
  175. {
  176. if constexpr (sizeof...(Args) > 0) {
  177. MarkedValueList arglist { heap() };
  178. (..., arglist.append(move(args)));
  179. return call(function, this_value, move(arglist));
  180. }
  181. return call(function, this_value);
  182. }
  183. CommonPropertyNames names;
  184. Shape& scope_object_shape() { return *m_scope_object_shape; }
  185. void run_queued_promise_jobs();
  186. void enqueue_promise_job(NativeFunction&);
  187. void promise_rejection_tracker(const Promise&, Promise::RejectionOperation) const;
  188. AK::Function<void()> on_call_stack_emptied;
  189. AK::Function<void(const Promise&)> on_promise_unhandled_rejection;
  190. AK::Function<void(const Promise&)> on_promise_rejection_handled;
  191. private:
  192. VM();
  193. [[nodiscard]] Value call_internal(Function&, Value this_value, Optional<MarkedValueList> arguments);
  194. Exception* m_exception { nullptr };
  195. Heap m_heap;
  196. Vector<Interpreter*> m_interpreters;
  197. Vector<CallFrame*> m_call_stack;
  198. Value m_last_value;
  199. ScopeType m_unwind_until { ScopeType::None };
  200. FlyString m_unwind_until_label;
  201. StackInfo m_stack_info;
  202. HashMap<String, Symbol*> m_global_symbol_map;
  203. Vector<NativeFunction*> m_promise_jobs;
  204. PrimitiveString* m_empty_string { nullptr };
  205. PrimitiveString* m_single_ascii_character_strings[128] {};
  206. #define __JS_ENUMERATE(SymbolName, snake_name) \
  207. Symbol* m_well_known_symbol_##snake_name { nullptr };
  208. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  209. #undef __JS_ENUMERATE
  210. Shape* m_scope_object_shape { nullptr };
  211. bool m_underscore_is_last_value { false };
  212. };
  213. template<>
  214. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value, MarkedValueList arguments) { return call_internal(function, this_value, move(arguments)); }
  215. template<>
  216. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value, Optional<MarkedValueList> arguments) { return call_internal(function, this_value, move(arguments)); }
  217. template<>
  218. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value) { return call(function, this_value, Optional<MarkedValueList> {}); }
  219. ALWAYS_INLINE Heap& Cell::heap() const
  220. {
  221. return HeapBlock::from_cell(this)->heap();
  222. }
  223. ALWAYS_INLINE VM& Cell::vm() const
  224. {
  225. return heap().vm();
  226. }
  227. }