Interpreter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. //#define INTERPRETER_DEBUG
  42. namespace JS {
  43. Interpreter::Interpreter()
  44. : m_heap(*this)
  45. , m_console(*this)
  46. {
  47. }
  48. Interpreter::~Interpreter()
  49. {
  50. }
  51. Value Interpreter::run(GlobalObject& global_object, const Statement& statement, ArgumentVector arguments, ScopeType scope_type)
  52. {
  53. if (statement.is_program()) {
  54. if (m_call_stack.is_empty()) {
  55. CallFrame global_call_frame;
  56. global_call_frame.this_value = &global_object;
  57. global_call_frame.function_name = "(global execution context)";
  58. global_call_frame.environment = heap().allocate<LexicalEnvironment>(global_object, LexicalEnvironment::EnvironmentRecordType::Global);
  59. global_call_frame.environment->bind_this_value(&global_object);
  60. if (exception())
  61. return {};
  62. m_call_stack.append(move(global_call_frame));
  63. }
  64. }
  65. if (!statement.is_scope_node())
  66. return statement.execute(*this, global_object);
  67. auto& block = static_cast<const ScopeNode&>(statement);
  68. enter_scope(block, move(arguments), scope_type, global_object);
  69. if (block.children().is_empty())
  70. m_last_value = js_undefined();
  71. for (auto& node : block.children()) {
  72. m_last_value = node.execute(*this, global_object);
  73. if (should_unwind()) {
  74. if (should_unwind_until(ScopeType::Breakable, block.label()))
  75. stop_unwind();
  76. break;
  77. }
  78. }
  79. bool did_return = m_unwind_until == ScopeType::Function;
  80. if (m_unwind_until == scope_type)
  81. m_unwind_until = ScopeType::None;
  82. exit_scope(block);
  83. return did_return ? m_last_value : js_undefined();
  84. }
  85. void Interpreter::enter_scope(const ScopeNode& scope_node, ArgumentVector arguments, ScopeType scope_type, GlobalObject& global_object)
  86. {
  87. for (auto& declaration : scope_node.functions()) {
  88. auto* function = ScriptFunction::create(global_object, declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), current_environment());
  89. set_variable(declaration.name(), function, global_object);
  90. }
  91. if (scope_type == ScopeType::Function) {
  92. m_scope_stack.append({ scope_type, scope_node, false });
  93. return;
  94. }
  95. HashMap<FlyString, Variable> scope_variables_with_declaration_kind;
  96. scope_variables_with_declaration_kind.ensure_capacity(16);
  97. for (auto& declaration : scope_node.variables()) {
  98. for (auto& declarator : declaration.declarations()) {
  99. if (scope_node.is_program()) {
  100. global_object.put(declarator.id().string(), js_undefined());
  101. if (exception())
  102. return;
  103. } else {
  104. scope_variables_with_declaration_kind.set(declarator.id().string(), { js_undefined(), declaration.declaration_kind() });
  105. }
  106. }
  107. }
  108. for (auto& argument : arguments) {
  109. scope_variables_with_declaration_kind.set(argument.name, { argument.value, DeclarationKind::Var });
  110. }
  111. bool pushed_lexical_environment = false;
  112. if (!scope_variables_with_declaration_kind.is_empty()) {
  113. auto* block_lexical_environment = heap().allocate<LexicalEnvironment>(global_object, move(scope_variables_with_declaration_kind), current_environment());
  114. m_call_stack.last().environment = block_lexical_environment;
  115. pushed_lexical_environment = true;
  116. }
  117. m_scope_stack.append({ scope_type, scope_node, pushed_lexical_environment });
  118. }
  119. void Interpreter::exit_scope(const ScopeNode& scope_node)
  120. {
  121. while (!m_scope_stack.is_empty()) {
  122. auto popped_scope = m_scope_stack.take_last();
  123. if (popped_scope.pushed_environment)
  124. m_call_stack.last().environment = m_call_stack.last().environment->parent();
  125. if (popped_scope.scope_node.ptr() == &scope_node)
  126. break;
  127. }
  128. // If we unwind all the way, just reset m_unwind_until so that future "return" doesn't break.
  129. if (m_scope_stack.is_empty())
  130. m_unwind_until = ScopeType::None;
  131. }
  132. void Interpreter::set_variable(const FlyString& name, Value value, GlobalObject& global_object, bool first_assignment)
  133. {
  134. if (m_call_stack.size()) {
  135. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  136. auto possible_match = environment->get(name);
  137. if (possible_match.has_value()) {
  138. if (!first_assignment && possible_match.value().declaration_kind == DeclarationKind::Const) {
  139. throw_exception<TypeError>(ErrorType::InvalidAssignToConst);
  140. return;
  141. }
  142. environment->set(name, { value, possible_match.value().declaration_kind });
  143. return;
  144. }
  145. }
  146. }
  147. global_object.put(move(name), move(value));
  148. }
  149. Value Interpreter::get_variable(const FlyString& name, GlobalObject& global_object)
  150. {
  151. if (m_call_stack.size()) {
  152. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  153. auto possible_match = environment->get(name);
  154. if (possible_match.has_value())
  155. return possible_match.value().value;
  156. }
  157. }
  158. auto value = global_object.get(name);
  159. if (m_underscore_is_last_value && name == "_" && value.is_empty())
  160. return m_last_value;
  161. return value;
  162. }
  163. Reference Interpreter::get_reference(const FlyString& name)
  164. {
  165. if (m_call_stack.size()) {
  166. for (auto* environment = current_environment(); environment; environment = environment->parent()) {
  167. auto possible_match = environment->get(name);
  168. if (possible_match.has_value())
  169. return { Reference::LocalVariable, name };
  170. }
  171. }
  172. return { Reference::GlobalVariable, name };
  173. }
  174. void Interpreter::gather_roots(Badge<Heap>, HashTable<Cell*>& roots)
  175. {
  176. roots.set(m_global_object);
  177. roots.set(m_exception);
  178. if (m_last_value.is_cell())
  179. roots.set(m_last_value.as_cell());
  180. for (auto& call_frame : m_call_stack) {
  181. if (call_frame.this_value.is_cell())
  182. roots.set(call_frame.this_value.as_cell());
  183. for (auto& argument : call_frame.arguments) {
  184. if (argument.is_cell())
  185. roots.set(argument.as_cell());
  186. }
  187. roots.set(call_frame.environment);
  188. }
  189. SymbolObject::gather_symbol_roots(roots);
  190. }
  191. Value Interpreter::call(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  192. {
  193. auto& call_frame = push_call_frame();
  194. call_frame.function_name = function.name();
  195. call_frame.this_value = function.bound_this().value_or(this_value);
  196. call_frame.arguments = function.bound_arguments();
  197. if (arguments.has_value())
  198. call_frame.arguments.append(arguments.value().values());
  199. call_frame.environment = function.create_environment();
  200. ASSERT(call_frame.environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  201. call_frame.environment->bind_this_value(call_frame.this_value);
  202. auto result = function.call(*this);
  203. pop_call_frame();
  204. return result;
  205. }
  206. Value Interpreter::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
  207. {
  208. auto& call_frame = push_call_frame();
  209. call_frame.function_name = function.name();
  210. call_frame.arguments = function.bound_arguments();
  211. if (arguments.has_value())
  212. call_frame.arguments.append(arguments.value().values());
  213. call_frame.environment = function.create_environment();
  214. current_environment()->set_new_target(&new_target);
  215. Object* new_object = nullptr;
  216. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  217. new_object = Object::create_empty(*this, global_object);
  218. current_environment()->bind_this_value(new_object);
  219. if (exception())
  220. return {};
  221. auto prototype = new_target.get("prototype");
  222. if (exception())
  223. return {};
  224. if (prototype.is_object()) {
  225. new_object->set_prototype(&prototype.as_object());
  226. if (exception())
  227. return {};
  228. }
  229. }
  230. // If we are a Derived constructor, |this| has not been constructed before super is called.
  231. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  232. call_frame.this_value = this_value;
  233. auto result = function.construct(*this, new_target);
  234. this_value = current_environment()->get_this_binding();
  235. pop_call_frame();
  236. // If we are constructing an instance of a derived class,
  237. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  238. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  239. current_environment()->replace_this_binding(result);
  240. auto prototype = new_target.get("prototype");
  241. if (exception())
  242. return {};
  243. if (prototype.is_object()) {
  244. result.as_object().set_prototype(&prototype.as_object());
  245. if (exception())
  246. return {};
  247. }
  248. return result;
  249. }
  250. if (exception())
  251. return {};
  252. if (result.is_object())
  253. return result;
  254. return this_value;
  255. }
  256. Value Interpreter::throw_exception(Exception* exception)
  257. {
  258. #ifdef INTERPRETER_DEBUG
  259. if (exception->value().is_object() && exception->value().as_object().is_error()) {
  260. auto& error = static_cast<Error&>(exception->value().as_object());
  261. dbg() << "Throwing JavaScript Error: " << error.name() << ", " << error.message();
  262. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  263. auto function_name = m_call_stack[i].function_name;
  264. if (function_name.is_empty())
  265. function_name = "<anonymous>";
  266. dbg() << " " << function_name;
  267. }
  268. }
  269. #endif
  270. m_exception = exception;
  271. unwind(ScopeType::Try);
  272. return {};
  273. }
  274. GlobalObject& Interpreter::global_object()
  275. {
  276. return static_cast<GlobalObject&>(*m_global_object);
  277. }
  278. const GlobalObject& Interpreter::global_object() const
  279. {
  280. return static_cast<const GlobalObject&>(*m_global_object);
  281. }
  282. String Interpreter::join_arguments() const
  283. {
  284. StringBuilder joined_arguments;
  285. for (size_t i = 0; i < argument_count(); ++i) {
  286. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  287. if (i != argument_count() - 1)
  288. joined_arguments.append(' ');
  289. }
  290. return joined_arguments.build();
  291. }
  292. Value Interpreter::resolve_this_binding() const
  293. {
  294. return get_this_environment()->get_this_binding();
  295. }
  296. const LexicalEnvironment* Interpreter::get_this_environment() const
  297. {
  298. // We will always return because the Global environment will always be reached, which has a |this| binding.
  299. for (const LexicalEnvironment* environment = current_environment(); environment; environment = environment->parent()) {
  300. if (environment->has_this_binding())
  301. return environment;
  302. }
  303. ASSERT_NOT_REACHED();
  304. }
  305. Value Interpreter::get_new_target() const
  306. {
  307. return get_this_environment()->new_target();
  308. }
  309. }