Interpreter.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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/String.h>
  30. #include <AK/Vector.h>
  31. #include <AK/Weakable.h>
  32. #include <LibJS/AST.h>
  33. #include <LibJS/Console.h>
  34. #include <LibJS/Forward.h>
  35. #include <LibJS/Heap/Heap.h>
  36. #include <LibJS/Runtime/ErrorTypes.h>
  37. #include <LibJS/Runtime/Exception.h>
  38. #include <LibJS/Runtime/LexicalEnvironment.h>
  39. #include <LibJS/Runtime/MarkedValueList.h>
  40. #include <LibJS/Runtime/Value.h>
  41. namespace JS {
  42. enum class ScopeType {
  43. None,
  44. Function,
  45. Block,
  46. Try,
  47. Breakable,
  48. Continuable,
  49. };
  50. struct ScopeFrame {
  51. ScopeType type;
  52. NonnullRefPtr<ScopeNode> scope_node;
  53. bool pushed_environment { false };
  54. };
  55. struct CallFrame {
  56. FlyString function_name;
  57. Value this_value;
  58. Vector<Value> arguments;
  59. LexicalEnvironment* environment { nullptr };
  60. };
  61. struct Argument {
  62. FlyString name;
  63. Value value;
  64. };
  65. typedef Vector<Argument, 8> ArgumentVector;
  66. class Interpreter : public Weakable<Interpreter> {
  67. public:
  68. template<typename GlobalObjectType, typename... Args>
  69. static NonnullOwnPtr<Interpreter> create(Args&&... args)
  70. {
  71. auto interpreter = adopt_own(*new Interpreter);
  72. interpreter->m_global_object = interpreter->heap().allocate_without_global_object<GlobalObjectType>(forward<Args>(args)...);
  73. static_cast<GlobalObjectType*>(interpreter->m_global_object)->initialize();
  74. return interpreter;
  75. }
  76. template<typename... Args>
  77. [[nodiscard]] ALWAYS_INLINE Value call(Function& function, Value this_value, Args... args)
  78. {
  79. // Are there any values in this argpack?
  80. // args = [] -> if constexpr (false)
  81. // args = [x, y, z] -> if constexpr ((void)x, true || ...)
  82. if constexpr ((((void)args, true) || ...)) {
  83. MarkedValueList arglist { heap() };
  84. (..., arglist.append(move(args)));
  85. return call(function, this_value, move(arglist));
  86. }
  87. return call(function, this_value);
  88. }
  89. ~Interpreter();
  90. Value run(GlobalObject&, const Program&);
  91. Value execute_statement(GlobalObject&, const Statement&, ArgumentVector = {}, ScopeType = ScopeType::Block);
  92. GlobalObject& global_object();
  93. const GlobalObject& global_object() const;
  94. Heap& heap() { return m_heap; }
  95. void unwind(ScopeType type, FlyString label = {})
  96. {
  97. m_unwind_until = type;
  98. m_unwind_until_label = label;
  99. }
  100. void stop_unwind() { m_unwind_until = ScopeType::None; }
  101. bool should_unwind_until(ScopeType type, FlyString label) const
  102. {
  103. if (m_unwind_until_label.is_null())
  104. return m_unwind_until == type;
  105. return m_unwind_until == type && m_unwind_until_label == label;
  106. }
  107. bool should_unwind() const { return m_unwind_until != ScopeType::None; }
  108. Value get_variable(const FlyString& name, GlobalObject&);
  109. void set_variable(const FlyString& name, Value, GlobalObject&, bool first_assignment = false);
  110. Reference get_reference(const FlyString& name);
  111. Symbol* get_global_symbol(const String& description);
  112. void gather_roots(Badge<Heap>, HashTable<Cell*>&);
  113. void enter_scope(const ScopeNode&, ArgumentVector, ScopeType, GlobalObject&);
  114. void exit_scope(const ScopeNode&);
  115. Value construct(Function&, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject&);
  116. CallFrame& push_call_frame()
  117. {
  118. m_call_stack.append({ {}, js_undefined(), {}, nullptr });
  119. return m_call_stack.last();
  120. }
  121. void pop_call_frame() { m_call_stack.take_last(); }
  122. const CallFrame& call_frame() { return m_call_stack.last(); }
  123. const Vector<CallFrame>& call_stack() { return m_call_stack; }
  124. void push_environment(LexicalEnvironment*);
  125. void pop_environment();
  126. const LexicalEnvironment* current_environment() const { return m_call_stack.last().environment; }
  127. LexicalEnvironment* current_environment() { return m_call_stack.last().environment; }
  128. bool in_strict_mode() const { return m_scope_stack.last().scope_node->in_strict_mode(); }
  129. template<typename Callback>
  130. void for_each_argument(Callback callback)
  131. {
  132. if (m_call_stack.is_empty())
  133. return;
  134. for (auto& value : m_call_stack.last().arguments)
  135. callback(value);
  136. }
  137. size_t argument_count() const
  138. {
  139. if (m_call_stack.is_empty())
  140. return 0;
  141. return m_call_stack.last().arguments.size();
  142. }
  143. Value argument(size_t index) const
  144. {
  145. if (m_call_stack.is_empty())
  146. return {};
  147. auto& arguments = m_call_stack.last().arguments;
  148. return index < arguments.size() ? arguments[index] : js_undefined();
  149. }
  150. Value this_value(Object& global_object) const
  151. {
  152. if (m_call_stack.is_empty())
  153. return &global_object;
  154. return m_call_stack.last().this_value;
  155. }
  156. Exception* exception()
  157. {
  158. return m_exception;
  159. }
  160. void clear_exception() { m_exception = nullptr; }
  161. template<typename T, typename... Args>
  162. void throw_exception(Args&&... args)
  163. {
  164. return throw_exception(T::create(global_object(), forward<Args>(args)...));
  165. }
  166. void throw_exception(Exception*);
  167. void throw_exception(Value value)
  168. {
  169. return throw_exception(heap().allocate<Exception>(global_object(), value));
  170. }
  171. template<typename T, typename... Args>
  172. void throw_exception(ErrorType type, Args&&... args)
  173. {
  174. return throw_exception(T::create(global_object(), String::format(type.message(), forward<Args>(args)...)));
  175. }
  176. Value last_value() const { return m_last_value; }
  177. bool underscore_is_last_value() const { return m_underscore_is_last_value; }
  178. void set_underscore_is_last_value(bool b) { m_underscore_is_last_value = b; }
  179. Console& console() { return m_console; }
  180. const Console& console() const { return m_console; }
  181. String join_arguments() const;
  182. Value resolve_this_binding() const;
  183. const LexicalEnvironment* get_this_environment() const;
  184. Value get_new_target() const;
  185. #define __JS_ENUMERATE(SymbolName, snake_name) \
  186. Symbol* well_known_symbol_##snake_name() const { return m_well_known_symbol_##snake_name; }
  187. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  188. #undef __JS_ENUMERATE
  189. private:
  190. Interpreter();
  191. [[nodiscard]] Value call_internal(Function&, Value this_value, Optional<MarkedValueList>);
  192. Heap m_heap;
  193. Value m_last_value;
  194. Vector<ScopeFrame> m_scope_stack;
  195. Vector<CallFrame> m_call_stack;
  196. Object* m_global_object { nullptr };
  197. Exception* m_exception { nullptr };
  198. ScopeType m_unwind_until { ScopeType::None };
  199. FlyString m_unwind_until_label;
  200. bool m_underscore_is_last_value { false };
  201. Console m_console;
  202. HashMap<String, Symbol*> m_global_symbol_map;
  203. #define __JS_ENUMERATE(SymbolName, snake_name) \
  204. Symbol* m_well_known_symbol_##snake_name { nullptr };
  205. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  206. #undef __JS_ENUMERATE
  207. };
  208. template<>
  209. [[nodiscard]] ALWAYS_INLINE Value Interpreter::call(Function& function, Value this_value, MarkedValueList arguments) { return call_internal(function, this_value, move(arguments)); }
  210. template<>
  211. [[nodiscard]] ALWAYS_INLINE Value Interpreter::call(Function& function, Value this_value, Optional<MarkedValueList> arguments) { return call_internal(function, this_value, move(arguments)); }
  212. template<>
  213. [[nodiscard]] ALWAYS_INLINE Value Interpreter::call(Function& function, Value this_value) { return call(function, this_value, Optional<MarkedValueList> {}); }
  214. }