Interpreter.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 <AK/StringBuilder.h>
  28. #include <LibJS/AST.h>
  29. #include <LibJS/Interpreter.h>
  30. #include <LibJS/Runtime/Error.h>
  31. #include <LibJS/Runtime/GlobalObject.h>
  32. #include <LibJS/Runtime/LexicalEnvironment.h>
  33. #include <LibJS/Runtime/MarkedValueList.h>
  34. #include <LibJS/Runtime/NativeFunction.h>
  35. #include <LibJS/Runtime/Object.h>
  36. #include <LibJS/Runtime/Reference.h>
  37. #include <LibJS/Runtime/Shape.h>
  38. #include <LibJS/Runtime/SymbolObject.h>
  39. #include <LibJS/Runtime/Value.h>
  40. namespace JS {
  41. Interpreter::Interpreter()
  42. : m_heap(*this)
  43. , m_console(*this)
  44. {
  45. }
  46. Interpreter::~Interpreter()
  47. {
  48. }
  49. Value Interpreter::run(const Statement& statement, ArgumentVector arguments, ScopeType scope_type)
  50. {
  51. if (statement.is_program()) {
  52. if (m_call_stack.is_empty()) {
  53. CallFrame global_call_frame;
  54. global_call_frame.this_value = m_global_object;
  55. global_call_frame.function_name = "(global execution context)";
  56. global_call_frame.environment = heap().allocate<LexicalEnvironment>();
  57. m_call_stack.append(move(global_call_frame));
  58. }
  59. }
  60. if (!statement.is_scope_node())
  61. return statement.execute(*this);
  62. auto& block = static_cast<const ScopeNode&>(statement);
  63. enter_scope(block, move(arguments), scope_type);
  64. m_last_value = js_undefined();
  65. for (auto& node : block.children()) {
  66. m_last_value = node.execute(*this);
  67. if (m_unwind_until != ScopeType::None)
  68. break;
  69. }
  70. bool did_return = m_unwind_until == ScopeType::Function;
  71. if (m_unwind_until == scope_type)
  72. m_unwind_until = ScopeType::None;
  73. exit_scope(block);
  74. return did_return ? m_last_value : js_undefined();
  75. }
  76. void Interpreter::enter_scope(const ScopeNode& scope_node, ArgumentVector arguments, ScopeType scope_type)
  77. {
  78. if (scope_type == ScopeType::Function) {
  79. m_scope_stack.append({ scope_type, scope_node, false });
  80. return;
  81. }
  82. HashMap<FlyString, Variable> scope_variables_with_declaration_kind;
  83. scope_variables_with_declaration_kind.ensure_capacity(16);
  84. for (auto& declaration : scope_node.variables()) {
  85. for (auto& declarator : declaration.declarations()) {
  86. if (scope_node.is_program())
  87. global_object().put(declarator.id().string(), js_undefined());
  88. else
  89. scope_variables_with_declaration_kind.set(declarator.id().string(), { js_undefined(), declaration.declaration_kind() });
  90. }
  91. }
  92. for (auto& argument : arguments) {
  93. scope_variables_with_declaration_kind.set(argument.name, { argument.value, DeclarationKind::Var });
  94. }
  95. bool pushed_lexical_environment = false;
  96. if (!scope_variables_with_declaration_kind.is_empty()) {
  97. auto* block_lexical_environment = heap().allocate<LexicalEnvironment>(move(scope_variables_with_declaration_kind), current_environment());
  98. m_call_stack.last().environment = block_lexical_environment;
  99. pushed_lexical_environment = true;
  100. }
  101. m_scope_stack.append({ scope_type, scope_node, pushed_lexical_environment });
  102. }
  103. void Interpreter::exit_scope(const ScopeNode& scope_node)
  104. {
  105. while (!m_scope_stack.is_empty()) {
  106. auto popped_scope = m_scope_stack.take_last();
  107. if (popped_scope.pushed_environment)
  108. m_call_stack.last().environment = m_call_stack.last().environment->parent();
  109. if (popped_scope.scope_node.ptr() == &scope_node)
  110. break;
  111. }
  112. // If we unwind all the way, just reset m_unwind_until so that future "return" doesn't break.
  113. if (m_scope_stack.is_empty())
  114. m_unwind_until = ScopeType::None;
  115. }
  116. void Interpreter::set_variable(const FlyString& name, Value value, bool first_assignment)
  117. {
  118. if (m_call_stack.size()) {
  119. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  120. auto possible_match = environment->get(name);
  121. if (possible_match.has_value()) {
  122. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  123. throw_exception<TypeError>("Assignment to constant variable");
  124. return;
  125. }
  126. environment->set(name, { value, possible_match.value().declaration_kind });
  127. return;
  128. }
  129. }
  130. }
  131. global_object().put(move(name), move(value));
  132. }
  133. Value Interpreter::get_variable(const FlyString& name)
  134. {
  135. if (m_call_stack.size()) {
  136. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  137. auto possible_match = environment->get(name);
  138. if (possible_match.has_value())
  139. return possible_match.value().value;
  140. }
  141. }
  142. return global_object().get(name);
  143. }
  144. Reference Interpreter::get_reference(const FlyString& name)
  145. {
  146. if (m_call_stack.size()) {
  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 { Reference::LocalVariable, name };
  151. }
  152. }
  153. return { Reference::GlobalVariable, name };
  154. }
  155. void Interpreter::gather_roots(Badge<Heap>, HashTable<Cell*>& roots)
  156. {
  157. roots.set(m_global_object);
  158. roots.set(m_exception);
  159. if (m_last_value.is_cell())
  160. roots.set(m_last_value.as_cell());
  161. for (auto& call_frame : m_call_stack) {
  162. if (call_frame.this_value.is_cell())
  163. roots.set(call_frame.this_value.as_cell());
  164. for (auto& argument : call_frame.arguments) {
  165. if (argument.is_cell())
  166. roots.set(argument.as_cell());
  167. }
  168. roots.set(call_frame.environment);
  169. }
  170. SymbolObject::gather_symbol_roots(roots);
  171. }
  172. Value Interpreter::call(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  173. {
  174. auto& call_frame = push_call_frame();
  175. call_frame.function_name = function.name();
  176. call_frame.this_value = this_value;
  177. if (arguments.has_value())
  178. call_frame.arguments = arguments.value().values();
  179. call_frame.environment = function.create_environment();
  180. auto result = function.call(*this);
  181. pop_call_frame();
  182. return result;
  183. }
  184. Value Interpreter::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments)
  185. {
  186. auto& call_frame = push_call_frame();
  187. call_frame.function_name = function.name();
  188. if (arguments.has_value())
  189. call_frame.arguments = arguments.value().values();
  190. call_frame.environment = function.create_environment();
  191. auto* new_object = Object::create_empty(*this, global_object());
  192. auto prototype = new_target.get("prototype");
  193. if (prototype.is_object())
  194. new_object->set_prototype(&prototype.as_object());
  195. call_frame.this_value = new_object;
  196. auto result = function.construct(*this);
  197. pop_call_frame();
  198. if (exception())
  199. return {};
  200. if (result.is_object())
  201. return result;
  202. return new_object;
  203. }
  204. Value Interpreter::throw_exception(Exception* exception)
  205. {
  206. if (exception->value().is_object() && exception->value().as_object().is_error()) {
  207. auto& error = static_cast<Error&>(exception->value().as_object());
  208. dbg() << "Throwing JavaScript Error: " << error.name() << ", " << error.message();
  209. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  210. auto function_name = m_call_stack[i].function_name;
  211. if (function_name.is_empty())
  212. function_name = "<anonymous>";
  213. dbg() << " " << function_name;
  214. }
  215. }
  216. m_exception = exception;
  217. unwind(ScopeType::Try);
  218. return {};
  219. }
  220. GlobalObject& Interpreter::global_object()
  221. {
  222. return static_cast<GlobalObject&>(*m_global_object);
  223. }
  224. const GlobalObject& Interpreter::global_object() const
  225. {
  226. return static_cast<const GlobalObject&>(*m_global_object);
  227. }
  228. String Interpreter::join_arguments() const
  229. {
  230. StringBuilder joined_arguments;
  231. for (size_t i = 0; i < argument_count(); ++i) {
  232. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  233. if (i != argument_count() - 1)
  234. joined_arguments.append(' ');
  235. }
  236. return joined_arguments.build();
  237. }
  238. Vector<String> Interpreter::get_trace() const
  239. {
  240. Vector<String> trace;
  241. // -2 to skip the console.trace() call frame
  242. for (ssize_t i = m_call_stack.size() - 2; i >= 0; --i)
  243. trace.append(m_call_stack[i].function_name);
  244. return trace;
  245. }
  246. }