VM.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #pragma once
  27. #include <AK/FlyString.h>
  28. #include <AK/HashMap.h>
  29. #include <AK/RefCounted.h>
  30. #include <LibJS/Heap/Heap.h>
  31. #include <LibJS/Runtime/CommonPropertyNames.h>
  32. #include <LibJS/Runtime/ErrorTypes.h>
  33. #include <LibJS/Runtime/Exception.h>
  34. #include <LibJS/Runtime/MarkedValueList.h>
  35. #include <LibJS/Runtime/Value.h>
  36. namespace JS {
  37. enum class ScopeType {
  38. None,
  39. Function,
  40. Block,
  41. Try,
  42. Breakable,
  43. Continuable,
  44. };
  45. struct ScopeFrame {
  46. ScopeType type;
  47. NonnullRefPtr<ScopeNode> scope_node;
  48. bool pushed_environment { false };
  49. };
  50. struct CallFrame {
  51. FlyString function_name;
  52. Value this_value;
  53. Vector<Value> arguments;
  54. LexicalEnvironment* environment { nullptr };
  55. bool is_strict_mode { false };
  56. };
  57. struct Argument {
  58. FlyString name;
  59. Value value;
  60. };
  61. typedef Vector<Argument, 8> ArgumentVector;
  62. class VM : public RefCounted<VM> {
  63. public:
  64. static NonnullRefPtr<VM> create();
  65. ~VM();
  66. Heap& heap() { return m_heap; }
  67. const Heap& heap() const { return m_heap; }
  68. Interpreter& interpreter();
  69. Interpreter* interpreter_if_exists();
  70. void push_interpreter(Interpreter&);
  71. void pop_interpreter(Interpreter&);
  72. Exception* exception()
  73. {
  74. return m_exception;
  75. }
  76. void clear_exception() { m_exception = nullptr; }
  77. class InterpreterExecutionScope {
  78. public:
  79. InterpreterExecutionScope(Interpreter&);
  80. ~InterpreterExecutionScope();
  81. private:
  82. Interpreter& m_interpreter;
  83. };
  84. void gather_roots(HashTable<Cell*>&);
  85. #define __JS_ENUMERATE(SymbolName, snake_name) \
  86. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  87. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  88. #undef __JS_ENUMERATE
  89. Symbol* get_global_symbol(const String& description);
  90. PrimitiveString& empty_string() { return *m_empty_string; }
  91. PrimitiveString& single_ascii_character_string(u8 character)
  92. {
  93. ASSERT(character < 0x80);
  94. return *m_single_ascii_character_strings[character];
  95. }
  96. CallFrame& push_call_frame(bool strict_mode = false)
  97. {
  98. m_call_stack.append({ {}, js_undefined(), {}, nullptr, strict_mode });
  99. return m_call_stack.last();
  100. }
  101. void pop_call_frame() { m_call_stack.take_last(); }
  102. CallFrame& call_frame() { return m_call_stack.last(); }
  103. const CallFrame& call_frame() const { return m_call_stack.last(); }
  104. const Vector<CallFrame>& call_stack() const { return m_call_stack; }
  105. Vector<CallFrame>& call_stack() { return m_call_stack; }
  106. const LexicalEnvironment* current_environment() const { return m_call_stack.last().environment; }
  107. LexicalEnvironment* current_environment() { return m_call_stack.last().environment; }
  108. bool in_strict_mode() const;
  109. template<typename Callback>
  110. void for_each_argument(Callback callback)
  111. {
  112. if (m_call_stack.is_empty())
  113. return;
  114. for (auto& value : m_call_stack.last().arguments)
  115. callback(value);
  116. }
  117. size_t argument_count() const
  118. {
  119. if (m_call_stack.is_empty())
  120. return 0;
  121. return m_call_stack.last().arguments.size();
  122. }
  123. Value argument(size_t index) const
  124. {
  125. if (m_call_stack.is_empty())
  126. return {};
  127. auto& arguments = m_call_stack.last().arguments;
  128. return index < arguments.size() ? arguments[index] : js_undefined();
  129. }
  130. Value this_value(Object& global_object) const
  131. {
  132. if (m_call_stack.is_empty())
  133. return &global_object;
  134. return m_call_stack.last().this_value;
  135. }
  136. Value last_value() const { return m_last_value; }
  137. void set_last_value(Badge<Interpreter>, Value value) { m_last_value = value; }
  138. bool underscore_is_last_value() const { return m_underscore_is_last_value; }
  139. void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
  140. void unwind(ScopeType type, FlyString label = {})
  141. {
  142. m_unwind_until = type;
  143. m_unwind_until_label = label;
  144. }
  145. void stop_unwind() { m_unwind_until = ScopeType::None; }
  146. bool should_unwind_until(ScopeType type, FlyString label = {}) const
  147. {
  148. if (m_unwind_until_label.is_null())
  149. return m_unwind_until == type;
  150. return m_unwind_until == type && m_unwind_until_label == label;
  151. }
  152. bool should_unwind() const { return m_unwind_until != ScopeType::None; }
  153. ScopeType unwind_until() const { return m_unwind_until; }
  154. Value get_variable(const FlyString& name, GlobalObject&);
  155. void set_variable(const FlyString& name, Value, GlobalObject&, bool first_assignment = false);
  156. Reference get_reference(const FlyString& name);
  157. template<typename T, typename... Args>
  158. void throw_exception(GlobalObject& global_object, Args&&... args)
  159. {
  160. return throw_exception(global_object, T::create(global_object, forward<Args>(args)...));
  161. }
  162. void throw_exception(Exception*);
  163. void throw_exception(GlobalObject& global_object, Value value)
  164. {
  165. return throw_exception(heap().allocate<Exception>(global_object, value));
  166. }
  167. template<typename T, typename... Args>
  168. void throw_exception(GlobalObject& global_object, ErrorType type, Args&&... args)
  169. {
  170. return throw_exception(global_object, T::create(global_object, String::formatted(type.message(), forward<Args>(args)...)));
  171. }
  172. Value construct(Function&, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject&);
  173. String join_arguments() const;
  174. Value resolve_this_binding(GlobalObject&) const;
  175. const LexicalEnvironment* get_this_environment() const;
  176. Value get_new_target() const;
  177. template<typename... Args>
  178. [[nodiscard]] ALWAYS_INLINE Value call(Function& function, Value this_value, Args... args)
  179. {
  180. // Are there any values in this argpack?
  181. // args = [] -> if constexpr (false)
  182. // args = [x, y, z] -> if constexpr ((void)x, true || ...)
  183. if constexpr ((((void)args, true) || ...)) {
  184. MarkedValueList arglist { heap() };
  185. (..., arglist.append(move(args)));
  186. return call(function, this_value, move(arglist));
  187. }
  188. return call(function, this_value);
  189. }
  190. CommonPropertyNames names;
  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. bool m_underscore_is_last_value { false };
  202. HashMap<String, Symbol*> m_global_symbol_map;
  203. PrimitiveString* m_empty_string { nullptr };
  204. PrimitiveString* m_single_ascii_character_strings[128] {};
  205. #define __JS_ENUMERATE(SymbolName, snake_name) \
  206. Symbol* m_well_known_symbol_##snake_name { nullptr };
  207. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  208. #undef __JS_ENUMERATE
  209. };
  210. template<>
  211. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value, MarkedValueList arguments) { return call_internal(function, this_value, move(arguments)); }
  212. template<>
  213. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value, Optional<MarkedValueList> arguments) { return call_internal(function, this_value, move(arguments)); }
  214. template<>
  215. [[nodiscard]] ALWAYS_INLINE Value VM::call(Function& function, Value this_value) { return call(function, this_value, Optional<MarkedValueList> {}); }
  216. }