Interpreter.h 8.5 KB

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