Interpreter.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/TemporaryChange.h>
  8. #include <LibJS/AST.h>
  9. #include <LibJS/Bytecode/BasicBlock.h>
  10. #include <LibJS/Bytecode/Generator.h>
  11. #include <LibJS/Bytecode/Instruction.h>
  12. #include <LibJS/Bytecode/Interpreter.h>
  13. #include <LibJS/Bytecode/Op.h>
  14. #include <LibJS/Runtime/GlobalEnvironment.h>
  15. #include <LibJS/Runtime/GlobalObject.h>
  16. #include <LibJS/Runtime/Realm.h>
  17. namespace JS::Bytecode {
  18. bool g_dump_bytecode = false;
  19. Interpreter::Interpreter(VM& vm)
  20. : m_vm(vm)
  21. {
  22. }
  23. Interpreter::~Interpreter()
  24. {
  25. }
  26. void Interpreter::visit_edges(Cell::Visitor& visitor)
  27. {
  28. for (auto& frame : m_call_frames) {
  29. frame.visit([&](auto& value) { value->visit_edges(visitor); });
  30. }
  31. }
  32. // 16.1.6 ScriptEvaluation ( scriptRecord ), https://tc39.es/ecma262/#sec-runtime-semantics-scriptevaluation
  33. ThrowCompletionOr<Value> Interpreter::run(Script& script_record, JS::GCPtr<Environment> lexical_environment_override)
  34. {
  35. auto& vm = this->vm();
  36. // 1. Let globalEnv be scriptRecord.[[Realm]].[[GlobalEnv]].
  37. auto& global_environment = script_record.realm().global_environment();
  38. // 2. Let scriptContext be a new ECMAScript code execution context.
  39. ExecutionContext script_context(vm.heap());
  40. // 3. Set the Function of scriptContext to null.
  41. // NOTE: This was done during execution context construction.
  42. // 4. Set the Realm of scriptContext to scriptRecord.[[Realm]].
  43. script_context.realm = &script_record.realm();
  44. // 5. Set the ScriptOrModule of scriptContext to scriptRecord.
  45. script_context.script_or_module = NonnullGCPtr<Script>(script_record);
  46. // 6. Set the VariableEnvironment of scriptContext to globalEnv.
  47. script_context.variable_environment = &global_environment;
  48. // 7. Set the LexicalEnvironment of scriptContext to globalEnv.
  49. script_context.lexical_environment = &global_environment;
  50. // Non-standard: Override the lexical environment if requested.
  51. if (lexical_environment_override)
  52. script_context.lexical_environment = lexical_environment_override;
  53. // 8. Set the PrivateEnvironment of scriptContext to null.
  54. // NOTE: This isn't in the spec, but we require it.
  55. script_context.is_strict_mode = script_record.parse_node().is_strict_mode();
  56. // FIXME: 9. Suspend the currently running execution context.
  57. // 10. Push scriptContext onto the execution context stack; scriptContext is now the running execution context.
  58. TRY(vm.push_execution_context(script_context, {}));
  59. // 11. Let script be scriptRecord.[[ECMAScriptCode]].
  60. auto& script = script_record.parse_node();
  61. // 12. Let result be Completion(GlobalDeclarationInstantiation(script, globalEnv)).
  62. auto instantiation_result = script.global_declaration_instantiation(vm, global_environment);
  63. Completion result = instantiation_result.is_throw_completion() ? instantiation_result.throw_completion() : normal_completion({});
  64. // 13. If result.[[Type]] is normal, then
  65. if (result.type() == Completion::Type::Normal) {
  66. auto executable_result = JS::Bytecode::Generator::generate(script);
  67. if (executable_result.is_error()) {
  68. if (auto error_string = executable_result.error().to_string(); error_string.is_error())
  69. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  70. else if (error_string = String::formatted("TODO({})", error_string.value()); error_string.is_error())
  71. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  72. else
  73. result = JS::throw_completion(JS::InternalError::create(realm(), error_string.release_value()));
  74. } else {
  75. auto executable = executable_result.release_value();
  76. if (g_dump_bytecode)
  77. executable->dump();
  78. // a. Set result to the result of evaluating script.
  79. auto result_or_error = run_and_return_frame(*executable, nullptr);
  80. if (result_or_error.value.is_error())
  81. result = result_or_error.value.release_error();
  82. else
  83. result = result_or_error.frame->registers[0];
  84. }
  85. }
  86. // 14. If result.[[Type]] is normal and result.[[Value]] is empty, then
  87. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  88. // a. Set result to NormalCompletion(undefined).
  89. result = normal_completion(js_undefined());
  90. }
  91. // FIXME: 15. Suspend scriptContext and remove it from the execution context stack.
  92. vm.pop_execution_context();
  93. // 16. Assert: The execution context stack is not empty.
  94. VERIFY(!vm.execution_context_stack().is_empty());
  95. // FIXME: 17. Resume the context that is now on the top of the execution context stack as the running execution context.
  96. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  97. // in which case this is a no-op.
  98. // FIXME: These three should be moved out of Interpreter::run and give the host an option to run these, as it's up to the host when these get run.
  99. // https://tc39.es/ecma262/#sec-jobs for jobs and https://tc39.es/ecma262/#_ref_3508 for ClearKeptObjects
  100. // finish_execution_generation is particularly an issue for LibWeb, as the HTML spec wants to run it specifically after performing a microtask checkpoint.
  101. // The promise and registry cleanup queues don't cause LibWeb an issue, as LibWeb overrides the hooks that push onto these queues.
  102. vm.run_queued_promise_jobs();
  103. vm.run_queued_finalization_registry_cleanup_jobs();
  104. vm.finish_execution_generation();
  105. // 18. Return ? result.
  106. if (result.is_abrupt()) {
  107. VERIFY(result.type() == Completion::Type::Throw);
  108. return result.release_error();
  109. }
  110. VERIFY(result.value().has_value());
  111. return *result.value();
  112. }
  113. ThrowCompletionOr<Value> Interpreter::run(SourceTextModule& module)
  114. {
  115. // FIXME: This is not a entry point as defined in the spec, but is convenient.
  116. // To avoid work we use link_and_eval_module however that can already be
  117. // dangerous if the vm loaded other modules.
  118. auto& vm = this->vm();
  119. TRY(vm.link_and_eval_module(Badge<Bytecode::Interpreter> {}, module));
  120. vm.run_queued_promise_jobs();
  121. vm.run_queued_finalization_registry_cleanup_jobs();
  122. return js_undefined();
  123. }
  124. void Interpreter::run_bytecode()
  125. {
  126. for (;;) {
  127. start:
  128. auto pc = InstructionStreamIterator { m_current_block->instruction_stream(), m_current_executable };
  129. TemporaryChange temp_change { m_pc, Optional<InstructionStreamIterator&>(pc) };
  130. bool will_return = false;
  131. bool will_yield = false;
  132. while (!pc.at_end()) {
  133. auto& instruction = *pc;
  134. auto ran_or_error = instruction.execute(*this);
  135. if (ran_or_error.is_error()) [[unlikely]] {
  136. reg(Register::exception()) = *ran_or_error.throw_completion().value();
  137. if (unwind_contexts().is_empty())
  138. break;
  139. auto& unwind_context = unwind_contexts().last();
  140. if (unwind_context.executable != m_current_executable)
  141. break;
  142. if (unwind_context.handler && !unwind_context.handler_called) {
  143. vm().running_execution_context().lexical_environment = unwind_context.lexical_environment;
  144. m_current_block = unwind_context.handler;
  145. unwind_context.handler_called = true;
  146. accumulator() = reg(Register::exception());
  147. reg(Register::exception()) = {};
  148. goto start;
  149. }
  150. if (unwind_context.finalizer) {
  151. m_current_block = unwind_context.finalizer;
  152. // If an exception was thrown inside the corresponding `catch` block, we need to rethrow it
  153. // from the `finally` block. But if the exception is from the `try` block, and has already been
  154. // handled by `catch`, we swallow it.
  155. if (!unwind_context.handler_called)
  156. reg(Register::exception()) = {};
  157. goto start;
  158. }
  159. // An unwind context with no handler or finalizer? We have nowhere to jump, and continuing on will make us crash on the next `Call` to a non-native function if there's an exception! So let's crash here instead.
  160. // If you run into this, you probably forgot to remove the current unwind_context somewhere.
  161. VERIFY_NOT_REACHED();
  162. }
  163. if (m_pending_jump.has_value()) {
  164. m_current_block = m_pending_jump.release_value();
  165. goto start;
  166. }
  167. if (!reg(Register::return_value()).is_empty()) {
  168. will_return = true;
  169. // Note: A `yield` statement will not go through a finally statement,
  170. // hence we need to set a flag to not do so,
  171. // but we generate a Yield Operation in the case of returns in
  172. // generators as well, so we need to check if it will actually
  173. // continue or is a `return` in disguise
  174. will_yield = (instruction.type() == Instruction::Type::Yield && static_cast<Op::Yield const&>(instruction).continuation().has_value()) || instruction.type() == Instruction::Type::Await;
  175. break;
  176. }
  177. ++pc;
  178. }
  179. if (!unwind_contexts().is_empty() && !will_yield) {
  180. auto& unwind_context = unwind_contexts().last();
  181. if (unwind_context.executable == m_current_executable && unwind_context.finalizer) {
  182. reg(Register::saved_return_value()) = reg(Register::return_value());
  183. reg(Register::return_value()) = {};
  184. m_current_block = unwind_context.finalizer;
  185. // the unwind_context will be pop'ed when entering the finally block
  186. continue;
  187. }
  188. }
  189. if (pc.at_end())
  190. break;
  191. if (!reg(Register::exception()).is_empty())
  192. break;
  193. if (will_return)
  194. break;
  195. }
  196. }
  197. Interpreter::ValueAndFrame Interpreter::run_and_return_frame(Executable& executable, BasicBlock const* entry_point, CallFrame* in_frame)
  198. {
  199. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter will run unit {:p}", &executable);
  200. TemporaryChange restore_executable { m_current_executable, &executable };
  201. TemporaryChange restore_saved_jump { m_scheduled_jump, static_cast<BasicBlock const*>(nullptr) };
  202. VERIFY(!vm().execution_context_stack().is_empty());
  203. TemporaryChange restore_current_block { m_current_block, entry_point ?: executable.basic_blocks.first() };
  204. if (in_frame)
  205. push_call_frame(in_frame, executable.number_of_registers);
  206. else
  207. push_call_frame(make<CallFrame>(), executable.number_of_registers);
  208. run_bytecode();
  209. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  210. if constexpr (JS_BYTECODE_DEBUG) {
  211. for (size_t i = 0; i < registers().size(); ++i) {
  212. String value_string;
  213. if (registers()[i].is_empty())
  214. value_string = "(empty)"_string;
  215. else
  216. value_string = registers()[i].to_string_without_side_effects();
  217. dbgln("[{:3}] {}", i, value_string);
  218. }
  219. }
  220. auto return_value = js_undefined();
  221. if (!reg(Register::return_value()).is_empty())
  222. return_value = reg(Register::return_value());
  223. else if (!reg(Register::saved_return_value()).is_empty())
  224. return_value = reg(Register::saved_return_value());
  225. auto exception = reg(Register::exception());
  226. auto frame = pop_call_frame();
  227. // NOTE: The return value from a called function is put into $0 in the caller context.
  228. if (!m_call_frames.is_empty())
  229. call_frame().registers[0] = return_value;
  230. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  231. // in which case this is a no-op.
  232. vm().run_queued_promise_jobs();
  233. vm().finish_execution_generation();
  234. if (!exception.is_empty()) {
  235. if (auto* call_frame = frame.get_pointer<NonnullOwnPtr<CallFrame>>())
  236. return { throw_completion(exception), move(*call_frame) };
  237. return { throw_completion(exception), nullptr };
  238. }
  239. if (auto* call_frame = frame.get_pointer<NonnullOwnPtr<CallFrame>>())
  240. return { return_value, move(*call_frame) };
  241. return { return_value, nullptr };
  242. }
  243. void Interpreter::enter_unwind_context(Optional<Label> handler_target, Optional<Label> finalizer_target)
  244. {
  245. unwind_contexts().empend(
  246. m_current_executable,
  247. handler_target.has_value() ? &handler_target->block() : nullptr,
  248. finalizer_target.has_value() ? &finalizer_target->block() : nullptr,
  249. vm().running_execution_context().lexical_environment);
  250. }
  251. void Interpreter::leave_unwind_context()
  252. {
  253. unwind_contexts().take_last();
  254. }
  255. ThrowCompletionOr<void> Interpreter::continue_pending_unwind(Label const& resume_label)
  256. {
  257. if (auto exception = reg(Register::exception()); !exception.is_empty())
  258. return throw_completion(exception);
  259. if (!saved_return_value().is_empty()) {
  260. do_return(saved_return_value());
  261. return {};
  262. }
  263. if (m_scheduled_jump) {
  264. // FIXME: If we `break` or `continue` in the finally, we need to clear
  265. // this field
  266. jump(Label { *m_scheduled_jump });
  267. m_scheduled_jump = nullptr;
  268. } else {
  269. jump(resume_label);
  270. }
  271. return {};
  272. }
  273. ThrowCompletionOr<NonnullOwnPtr<Bytecode::Executable>> compile(VM& vm, ASTNode const& node, FunctionKind kind, DeprecatedFlyString const& name)
  274. {
  275. auto executable_result = Bytecode::Generator::generate(node, kind);
  276. if (executable_result.is_error())
  277. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
  278. auto bytecode_executable = executable_result.release_value();
  279. bytecode_executable->name = name;
  280. if (Bytecode::g_dump_bytecode)
  281. bytecode_executable->dump();
  282. return bytecode_executable;
  283. }
  284. Realm& Interpreter::realm()
  285. {
  286. return *m_vm.current_realm();
  287. }
  288. void Interpreter::push_call_frame(Variant<NonnullOwnPtr<CallFrame>, CallFrame*> frame, size_t register_count)
  289. {
  290. m_call_frames.append(move(frame));
  291. this->call_frame().registers.resize(register_count);
  292. m_current_call_frame = this->call_frame().registers;
  293. reg(Register::return_value()) = {};
  294. }
  295. Variant<NonnullOwnPtr<CallFrame>, CallFrame*> Interpreter::pop_call_frame()
  296. {
  297. auto frame = m_call_frames.take_last();
  298. m_current_call_frame = m_call_frames.is_empty() ? Span<Value> {} : this->call_frame().registers;
  299. return frame;
  300. }
  301. }