Interpreter.cpp 11 KB

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