Interpreter.cpp 15 KB

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