Interpreter.cpp 13 KB

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