Interpreter.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 Statement& statement, ArgumentVector arguments, ScopeType scope_type)
  56. {
  57. if (statement.is_program()) {
  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. }
  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 (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. Symbol* Interpreter::get_global_symbol(const String& description)
  179. {
  180. auto result = m_global_symbol_map.get(description);
  181. if (result.has_value())
  182. return result.value();
  183. auto new_global_symbol = js_symbol(*this, description, true);
  184. m_global_symbol_map.set(description, new_global_symbol);
  185. return new_global_symbol;
  186. }
  187. void Interpreter::gather_roots(Badge<Heap>, HashTable<Cell*>& roots)
  188. {
  189. roots.set(m_global_object);
  190. roots.set(m_exception);
  191. if (m_last_value.is_cell())
  192. roots.set(m_last_value.as_cell());
  193. for (auto& call_frame : m_call_stack) {
  194. if (call_frame.this_value.is_cell())
  195. roots.set(call_frame.this_value.as_cell());
  196. for (auto& argument : call_frame.arguments) {
  197. if (argument.is_cell())
  198. roots.set(argument.as_cell());
  199. }
  200. roots.set(call_frame.environment);
  201. }
  202. #define __JS_ENUMERATE(SymbolName, snake_name) \
  203. roots.set(well_known_symbol_##snake_name());
  204. JS_ENUMERATE_WELL_KNOWN_SYMBOLS
  205. #undef __JS_ENUMERATE
  206. for (auto& symbol : m_global_symbol_map)
  207. roots.set(symbol.value);
  208. }
  209. Value Interpreter::call(Function& function, Value this_value, Optional<MarkedValueList> arguments)
  210. {
  211. auto& call_frame = push_call_frame();
  212. call_frame.function_name = function.name();
  213. call_frame.this_value = function.bound_this().value_or(this_value);
  214. call_frame.arguments = function.bound_arguments();
  215. if (arguments.has_value())
  216. call_frame.arguments.append(arguments.value().values());
  217. call_frame.environment = function.create_environment();
  218. ASSERT(call_frame.environment->this_binding_status() == LexicalEnvironment::ThisBindingStatus::Uninitialized);
  219. call_frame.environment->bind_this_value(call_frame.this_value);
  220. auto result = function.call(*this);
  221. pop_call_frame();
  222. return result;
  223. }
  224. Value Interpreter::construct(Function& function, Function& new_target, Optional<MarkedValueList> arguments, GlobalObject& global_object)
  225. {
  226. auto& call_frame = push_call_frame();
  227. call_frame.function_name = function.name();
  228. call_frame.arguments = function.bound_arguments();
  229. if (arguments.has_value())
  230. call_frame.arguments.append(arguments.value().values());
  231. call_frame.environment = function.create_environment();
  232. current_environment()->set_new_target(&new_target);
  233. Object* new_object = nullptr;
  234. if (function.constructor_kind() == Function::ConstructorKind::Base) {
  235. new_object = Object::create_empty(global_object);
  236. current_environment()->bind_this_value(new_object);
  237. if (exception())
  238. return {};
  239. auto prototype = new_target.get("prototype");
  240. if (exception())
  241. return {};
  242. if (prototype.is_object()) {
  243. new_object->set_prototype(&prototype.as_object());
  244. if (exception())
  245. return {};
  246. }
  247. }
  248. // If we are a Derived constructor, |this| has not been constructed before super is called.
  249. Value this_value = function.constructor_kind() == Function::ConstructorKind::Base ? new_object : Value {};
  250. call_frame.this_value = this_value;
  251. auto result = function.construct(*this, new_target);
  252. this_value = current_environment()->get_this_binding();
  253. pop_call_frame();
  254. // If we are constructing an instance of a derived class,
  255. // set the prototype on objects created by constructors that return an object (i.e. NativeFunction subclasses).
  256. if (function.constructor_kind() == Function::ConstructorKind::Base && new_target.constructor_kind() == Function::ConstructorKind::Derived && result.is_object()) {
  257. current_environment()->replace_this_binding(result);
  258. auto prototype = new_target.get("prototype");
  259. if (exception())
  260. return {};
  261. if (prototype.is_object()) {
  262. result.as_object().set_prototype(&prototype.as_object());
  263. if (exception())
  264. return {};
  265. }
  266. return result;
  267. }
  268. if (exception())
  269. return {};
  270. if (result.is_object())
  271. return result;
  272. return this_value;
  273. }
  274. Value Interpreter::throw_exception(Exception* exception)
  275. {
  276. #ifdef INTERPRETER_DEBUG
  277. if (exception->value().is_object() && exception->value().as_object().is_error()) {
  278. auto& error = static_cast<Error&>(exception->value().as_object());
  279. dbg() << "Throwing JavaScript Error: " << error.name() << ", " << error.message();
  280. for (ssize_t i = m_call_stack.size() - 1; i >= 0; --i) {
  281. auto function_name = m_call_stack[i].function_name;
  282. if (function_name.is_empty())
  283. function_name = "<anonymous>";
  284. dbg() << " " << function_name;
  285. }
  286. }
  287. #endif
  288. m_exception = exception;
  289. unwind(ScopeType::Try);
  290. return {};
  291. }
  292. GlobalObject& Interpreter::global_object()
  293. {
  294. return static_cast<GlobalObject&>(*m_global_object);
  295. }
  296. const GlobalObject& Interpreter::global_object() const
  297. {
  298. return static_cast<const GlobalObject&>(*m_global_object);
  299. }
  300. String Interpreter::join_arguments() const
  301. {
  302. StringBuilder joined_arguments;
  303. for (size_t i = 0; i < argument_count(); ++i) {
  304. joined_arguments.append(argument(i).to_string_without_side_effects().characters());
  305. if (i != argument_count() - 1)
  306. joined_arguments.append(' ');
  307. }
  308. return joined_arguments.build();
  309. }
  310. Value Interpreter::resolve_this_binding() const
  311. {
  312. return get_this_environment()->get_this_binding();
  313. }
  314. const LexicalEnvironment* Interpreter::get_this_environment() const
  315. {
  316. // We will always return because the Global environment will always be reached, which has a |this| binding.
  317. for (const LexicalEnvironment* environment = current_environment(); environment; environment = environment->parent()) {
  318. if (environment->has_this_binding())
  319. return environment;
  320. }
  321. ASSERT_NOT_REACHED();
  322. }
  323. Value Interpreter::get_new_target() const
  324. {
  325. return get_this_environment()->new_target();
  326. }
  327. }