Interpreter.cpp 14 KB

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