Interpreter.cpp 14 KB

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