Interpreter.cpp 13 KB

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