Interpreter.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. #include <AK/Badge.h>
  27. #include <LibJS/AST.h>
  28. #include <LibJS/Interpreter.h>
  29. #include <LibJS/Runtime/ArrayPrototype.h>
  30. #include <LibJS/Runtime/BooleanPrototype.h>
  31. #include <LibJS/Runtime/DatePrototype.h>
  32. #include <LibJS/Runtime/Error.h>
  33. #include <LibJS/Runtime/ErrorPrototype.h>
  34. #include <LibJS/Runtime/FunctionPrototype.h>
  35. #include <LibJS/Runtime/GlobalObject.h>
  36. #include <LibJS/Runtime/LexicalEnvironment.h>
  37. #include <LibJS/Runtime/NativeFunction.h>
  38. #include <LibJS/Runtime/NumberPrototype.h>
  39. #include <LibJS/Runtime/Object.h>
  40. #include <LibJS/Runtime/ObjectPrototype.h>
  41. #include <LibJS/Runtime/Shape.h>
  42. #include <LibJS/Runtime/StringPrototype.h>
  43. #include <LibJS/Runtime/Value.h>
  44. namespace JS {
  45. Interpreter::Interpreter()
  46. : m_heap(*this)
  47. {
  48. m_empty_object_shape = heap().allocate<Shape>();
  49. // These are done first since other prototypes depend on their presence.
  50. m_object_prototype = heap().allocate<ObjectPrototype>();
  51. m_function_prototype = heap().allocate<FunctionPrototype>();
  52. static_cast<FunctionPrototype*>(m_function_prototype)->initialize();
  53. static_cast<ObjectPrototype*>(m_object_prototype)->initialize();
  54. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  55. if (!m_##snake_name##_prototype) \
  56. m_##snake_name##_prototype = heap().allocate<PrototypeName>();
  57. JS_ENUMERATE_BUILTIN_TYPES
  58. #undef __JS_ENUMERATE
  59. }
  60. Interpreter::~Interpreter()
  61. {
  62. }
  63. Value Interpreter::run(const Statement& statement, ArgumentVector arguments, ScopeType scope_type)
  64. {
  65. if (statement.is_program()) {
  66. if (m_call_stack.is_empty()) {
  67. CallFrame global_call_fram;
  68. global_call_fram.this_value = m_global_object;
  69. global_call_fram.function_name = "(global execution context)";
  70. global_call_fram.environment = heap().allocate<LexicalEnvironment>();
  71. m_call_stack.append(move(global_call_fram));
  72. }
  73. }
  74. if (!statement.is_scope_node())
  75. return statement.execute(*this);
  76. auto& block = static_cast<const ScopeNode&>(statement);
  77. enter_scope(block, move(arguments), scope_type);
  78. m_last_value = js_undefined();
  79. for (auto& node : block.children()) {
  80. m_last_value = node.execute(*this);
  81. if (m_unwind_until != ScopeType::None)
  82. break;
  83. }
  84. bool did_return = m_unwind_until == ScopeType::Function;
  85. if (m_unwind_until == scope_type)
  86. m_unwind_until = ScopeType::None;
  87. exit_scope(block);
  88. return did_return ? m_last_value : js_undefined();
  89. }
  90. void Interpreter::enter_scope(const ScopeNode& scope_node, ArgumentVector arguments, ScopeType scope_type)
  91. {
  92. if (scope_type == ScopeType::Function) {
  93. m_scope_stack.append({ scope_type, scope_node, false });
  94. return;
  95. }
  96. HashMap<FlyString, Variable> scope_variables_with_declaration_kind;
  97. scope_variables_with_declaration_kind.ensure_capacity(16);
  98. for (auto& declaration : scope_node.variables()) {
  99. for (auto& declarator : declaration.declarations()) {
  100. if (scope_node.is_program())
  101. global_object().put(declarator.id().string(), js_undefined());
  102. else
  103. scope_variables_with_declaration_kind.set(declarator.id().string(), { js_undefined(), declaration.declaration_kind() });
  104. }
  105. }
  106. for (auto& argument : arguments) {
  107. scope_variables_with_declaration_kind.set(argument.name, { argument.value, DeclarationKind::Var });
  108. }
  109. bool pushed_lexical_environment = false;
  110. if (!scope_variables_with_declaration_kind.is_empty()) {
  111. auto* block_lexical_environment = heap().allocate<LexicalEnvironment>(move(scope_variables_with_declaration_kind), current_environment());
  112. m_call_stack.last().environment = block_lexical_environment;
  113. pushed_lexical_environment = true;
  114. }
  115. m_scope_stack.append({ scope_type, scope_node, pushed_lexical_environment });
  116. }
  117. void Interpreter::exit_scope(const ScopeNode& scope_node)
  118. {
  119. while (!m_scope_stack.is_empty()) {
  120. auto popped_scope = m_scope_stack.take_last();
  121. if (popped_scope.pushed_environment)
  122. m_call_stack.last().environment = m_call_stack.last().environment->parent();
  123. if (popped_scope.scope_node.ptr() == &scope_node)
  124. break;
  125. }
  126. // If we unwind all the way, just reset m_unwind_until so that future "return" doesn't break.
  127. if (m_scope_stack.is_empty())
  128. m_unwind_until = ScopeType::None;
  129. }
  130. void Interpreter::set_variable(const FlyString& name, Value value, bool first_assignment)
  131. {
  132. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  133. auto possible_match = environment->get(name);
  134. if (possible_match.has_value()) {
  135. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  136. throw_exception<TypeError>("Assignment to constant variable");
  137. return;
  138. }
  139. environment->set(name, { value, possible_match.value().declaration_kind });
  140. return;
  141. }
  142. }
  143. global_object().put(move(name), move(value));
  144. }
  145. Optional<Value> Interpreter::get_variable(const FlyString& name)
  146. {
  147. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  148. auto possible_match = environment->get(name);
  149. if (possible_match.has_value())
  150. return possible_match.value().value;
  151. }
  152. return global_object().get(name);
  153. }
  154. void Interpreter::gather_roots(Badge<Heap>, HashTable<Cell*>& roots)
  155. {
  156. roots.set(m_empty_object_shape);
  157. roots.set(m_global_object);
  158. roots.set(m_exception);
  159. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName) \
  160. roots.set(m_##snake_name##_prototype);
  161. JS_ENUMERATE_BUILTIN_TYPES
  162. #undef __JS_ENUMERATE
  163. if (m_last_value.is_cell())
  164. roots.set(m_last_value.as_cell());
  165. for (auto& call_frame : m_call_stack) {
  166. if (call_frame.this_value.is_cell())
  167. roots.set(call_frame.this_value.as_cell());
  168. for (auto& argument : call_frame.arguments) {
  169. if (argument.is_cell())
  170. roots.set(argument.as_cell());
  171. }
  172. roots.set(call_frame.environment);
  173. }
  174. }
  175. Value Interpreter::call(Function* function, Value this_value, const Vector<Value>& arguments)
  176. {
  177. auto& call_frame = push_call_frame();
  178. call_frame.function_name = function->name();
  179. call_frame.this_value = this_value;
  180. call_frame.arguments = arguments;
  181. call_frame.environment = function->create_environment();
  182. auto result = function->call(*this);
  183. pop_call_frame();
  184. return result;
  185. }
  186. Value Interpreter::throw_exception(Exception* exception)
  187. {
  188. if (exception->value().is_object() && exception->value().as_object().is_error()) {
  189. auto& error = static_cast<Error&>(exception->value().as_object());
  190. dbg() << "Throwing JavaScript Error: " << error.name() << ", " << error.message();
  191. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  192. auto function_name = m_call_stack[i].function_name;
  193. if (function_name.is_empty())
  194. function_name = "<anonymous>";
  195. dbg() << " " << function_name;
  196. }
  197. }
  198. m_exception = exception;
  199. unwind(ScopeType::Try);
  200. return {};
  201. }
  202. GlobalObject& Interpreter::global_object()
  203. {
  204. return static_cast<GlobalObject&>(*m_global_object);
  205. }
  206. const GlobalObject& Interpreter::global_object() const
  207. {
  208. return static_cast<const GlobalObject&>(*m_global_object);
  209. }
  210. }