Generator.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/AST.h>
  7. #include <LibJS/Bytecode/BasicBlock.h>
  8. #include <LibJS/Bytecode/Generator.h>
  9. #include <LibJS/Bytecode/Instruction.h>
  10. #include <LibJS/Bytecode/Op.h>
  11. #include <LibJS/Bytecode/Register.h>
  12. namespace JS::Bytecode {
  13. Generator::Generator()
  14. : m_string_table(make<StringTable>())
  15. , m_identifier_table(make<IdentifierTable>())
  16. {
  17. }
  18. CodeGenerationErrorOr<NonnullOwnPtr<Executable>> Generator::generate(ASTNode const& node, FunctionKind enclosing_function_kind)
  19. {
  20. Generator generator;
  21. generator.switch_to_basic_block(generator.make_block());
  22. generator.m_enclosing_function_kind = enclosing_function_kind;
  23. if (generator.is_in_generator_or_async_function()) {
  24. // Immediately yield with no value.
  25. auto& start_block = generator.make_block();
  26. generator.emit<Bytecode::Op::Yield>(Label { start_block });
  27. generator.switch_to_basic_block(start_block);
  28. // NOTE: This doesn't have to handle received throw/return completions, as GeneratorObject::resume_abrupt
  29. // will not enter the generator from the SuspendedStart state and immediately completes the generator.
  30. }
  31. TRY(node.generate_bytecode(generator));
  32. if (generator.is_in_generator_or_async_function()) {
  33. // Terminate all unterminated blocks with yield return
  34. for (auto& block : generator.m_root_basic_blocks) {
  35. if (block->is_terminated())
  36. continue;
  37. generator.switch_to_basic_block(*block);
  38. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  39. generator.emit<Bytecode::Op::Yield>(nullptr);
  40. }
  41. }
  42. bool is_strict_mode = false;
  43. if (is<Program>(node))
  44. is_strict_mode = static_cast<Program const&>(node).is_strict_mode();
  45. else if (is<FunctionBody>(node))
  46. is_strict_mode = static_cast<FunctionBody const&>(node).in_strict_mode();
  47. else if (is<FunctionDeclaration>(node))
  48. is_strict_mode = static_cast<FunctionDeclaration const&>(node).is_strict_mode();
  49. else if (is<FunctionExpression>(node))
  50. is_strict_mode = static_cast<FunctionExpression const&>(node).is_strict_mode();
  51. return adopt_own(*new Executable {
  52. .name = {},
  53. .basic_blocks = move(generator.m_root_basic_blocks),
  54. .string_table = move(generator.m_string_table),
  55. .identifier_table = move(generator.m_identifier_table),
  56. .number_of_registers = generator.m_next_register,
  57. .is_strict_mode = is_strict_mode });
  58. }
  59. void Generator::grow(size_t additional_size)
  60. {
  61. VERIFY(m_current_basic_block);
  62. m_current_basic_block->grow(additional_size);
  63. }
  64. void* Generator::next_slot()
  65. {
  66. VERIFY(m_current_basic_block);
  67. return m_current_basic_block->next_slot();
  68. }
  69. Register Generator::allocate_register()
  70. {
  71. VERIFY(m_next_register != NumericLimits<u32>::max());
  72. return Register { m_next_register++ };
  73. }
  74. Label Generator::nearest_continuable_scope() const
  75. {
  76. return m_continuable_scopes.last().bytecode_target;
  77. }
  78. void Generator::begin_variable_scope(BindingMode mode, SurroundingScopeKind kind)
  79. {
  80. m_variable_scopes.append({ kind, mode, {} });
  81. if (mode != BindingMode::Global) {
  82. start_boundary(mode == BindingMode::Lexical ? BlockBoundaryType::LeaveLexicalEnvironment : BlockBoundaryType::LeaveVariableEnvironment);
  83. emit<Bytecode::Op::CreateEnvironment>(
  84. mode == BindingMode::Lexical
  85. ? Bytecode::Op::EnvironmentMode::Lexical
  86. : Bytecode::Op::EnvironmentMode::Var);
  87. }
  88. }
  89. void Generator::end_variable_scope()
  90. {
  91. auto mode = m_variable_scopes.take_last().mode;
  92. if (mode != BindingMode::Global) {
  93. end_boundary(mode == BindingMode::Lexical ? BlockBoundaryType::LeaveLexicalEnvironment : BlockBoundaryType::LeaveVariableEnvironment);
  94. if (!m_current_basic_block->is_terminated()) {
  95. emit<Bytecode::Op::LeaveEnvironment>(
  96. mode == BindingMode::Lexical
  97. ? Bytecode::Op::EnvironmentMode::Lexical
  98. : Bytecode::Op::EnvironmentMode::Var);
  99. }
  100. }
  101. }
  102. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  103. {
  104. m_continuable_scopes.append({ continue_target, language_label_set });
  105. start_boundary(BlockBoundaryType::Continue);
  106. }
  107. void Generator::end_continuable_scope()
  108. {
  109. m_continuable_scopes.take_last();
  110. end_boundary(BlockBoundaryType::Continue);
  111. }
  112. Label Generator::nearest_breakable_scope() const
  113. {
  114. return m_breakable_scopes.last().bytecode_target;
  115. }
  116. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  117. {
  118. m_breakable_scopes.append({ breakable_target, language_label_set });
  119. start_boundary(BlockBoundaryType::Break);
  120. }
  121. void Generator::end_breakable_scope()
  122. {
  123. m_breakable_scopes.take_last();
  124. end_boundary(BlockBoundaryType::Break);
  125. }
  126. CodeGenerationErrorOr<void> Generator::emit_load_from_reference(JS::ASTNode const& node)
  127. {
  128. if (is<Identifier>(node)) {
  129. auto& identifier = static_cast<Identifier const&>(node);
  130. emit<Bytecode::Op::GetVariable>(intern_identifier(identifier.string()));
  131. return {};
  132. }
  133. if (is<MemberExpression>(node)) {
  134. auto& expression = static_cast<MemberExpression const&>(node);
  135. TRY(expression.object().generate_bytecode(*this));
  136. if (expression.is_computed()) {
  137. auto object_reg = allocate_register();
  138. emit<Bytecode::Op::Store>(object_reg);
  139. TRY(expression.property().generate_bytecode(*this));
  140. emit<Bytecode::Op::GetByValue>(object_reg);
  141. } else if (expression.property().is_identifier()) {
  142. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  143. emit<Bytecode::Op::GetById>(identifier_table_ref);
  144. } else {
  145. return CodeGenerationError {
  146. &expression,
  147. "Unimplemented non-computed member expression"sv
  148. };
  149. }
  150. return {};
  151. }
  152. VERIFY_NOT_REACHED();
  153. }
  154. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node)
  155. {
  156. if (is<Identifier>(node)) {
  157. auto& identifier = static_cast<Identifier const&>(node);
  158. emit<Bytecode::Op::SetVariable>(intern_identifier(identifier.string()));
  159. return {};
  160. }
  161. if (is<MemberExpression>(node)) {
  162. // NOTE: The value is in the accumulator, so we have to store that away first.
  163. auto value_reg = allocate_register();
  164. emit<Bytecode::Op::Store>(value_reg);
  165. auto& expression = static_cast<MemberExpression const&>(node);
  166. TRY(expression.object().generate_bytecode(*this));
  167. auto object_reg = allocate_register();
  168. emit<Bytecode::Op::Store>(object_reg);
  169. if (expression.is_computed()) {
  170. TRY(expression.property().generate_bytecode(*this));
  171. auto property_reg = allocate_register();
  172. emit<Bytecode::Op::Store>(property_reg);
  173. emit<Bytecode::Op::Load>(value_reg);
  174. emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  175. } else if (expression.property().is_identifier()) {
  176. emit<Bytecode::Op::Load>(value_reg);
  177. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  178. emit<Bytecode::Op::PutById>(object_reg, identifier_table_ref);
  179. } else {
  180. return CodeGenerationError {
  181. &expression,
  182. "Unimplemented non-computed member expression"sv
  183. };
  184. }
  185. return {};
  186. }
  187. return CodeGenerationError {
  188. &node,
  189. "Unimplemented/invalid node used a reference"sv
  190. };
  191. }
  192. CodeGenerationErrorOr<void> Generator::emit_delete_reference(JS::ASTNode const& node)
  193. {
  194. if (is<Identifier>(node)) {
  195. auto& identifier = static_cast<Identifier const&>(node);
  196. emit<Bytecode::Op::DeleteVariable>(intern_identifier(identifier.string()));
  197. return {};
  198. }
  199. if (is<MemberExpression>(node)) {
  200. auto& expression = static_cast<MemberExpression const&>(node);
  201. TRY(expression.object().generate_bytecode(*this));
  202. if (expression.is_computed()) {
  203. auto object_reg = allocate_register();
  204. emit<Bytecode::Op::Store>(object_reg);
  205. TRY(expression.property().generate_bytecode(*this));
  206. emit<Bytecode::Op::DeleteByValue>(object_reg);
  207. } else if (expression.property().is_identifier()) {
  208. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  209. emit<Bytecode::Op::DeleteById>(identifier_table_ref);
  210. } else {
  211. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  212. return CodeGenerationError {
  213. &expression,
  214. "Unimplemented non-computed member expression"sv
  215. };
  216. }
  217. return {};
  218. }
  219. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  220. // For example: delete a(); delete ++c.b; etc.
  221. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  222. // 1. Let ref be the result of evaluating UnaryExpression.
  223. // 2. ReturnIfAbrupt(ref).
  224. TRY(node.generate_bytecode(*this));
  225. // 3. If ref is not a Reference Record, return true.
  226. emit<Bytecode::Op::LoadImmediate>(Value(true));
  227. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  228. return {};
  229. }
  230. void Generator::generate_break()
  231. {
  232. bool last_was_finally = false;
  233. // FIXME: Reduce code duplication
  234. for (size_t i = m_boundaries.size(); i > 0; --i) {
  235. auto boundary = m_boundaries[i - 1];
  236. using enum BlockBoundaryType;
  237. switch (boundary) {
  238. case Break:
  239. emit<Op::Jump>().set_targets(nearest_breakable_scope(), {});
  240. return;
  241. case Unwind:
  242. if (!last_was_finally)
  243. emit<Bytecode::Op::LeaveUnwindContext>();
  244. last_was_finally = false;
  245. break;
  246. case LeaveLexicalEnvironment:
  247. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  248. break;
  249. case LeaveVariableEnvironment:
  250. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  251. break;
  252. case Continue:
  253. break;
  254. case ReturnToFinally: {
  255. auto& block = make_block(DeprecatedString::formatted("{}.break", current_block().name()));
  256. emit<Op::ScheduleJump>(Label { block });
  257. switch_to_basic_block(block);
  258. last_was_finally = true;
  259. break;
  260. };
  261. }
  262. }
  263. VERIFY_NOT_REACHED();
  264. }
  265. void Generator::generate_break(DeprecatedFlyString const& break_label)
  266. {
  267. size_t current_boundary = m_boundaries.size();
  268. bool last_was_finally = false;
  269. for (auto const& breakable_scope : m_breakable_scopes.in_reverse()) {
  270. for (; current_boundary > 0; --current_boundary) {
  271. auto boundary = m_boundaries[current_boundary - 1];
  272. if (boundary == BlockBoundaryType::Unwind) {
  273. if (!last_was_finally)
  274. emit<Bytecode::Op::LeaveUnwindContext>();
  275. last_was_finally = false;
  276. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  277. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  278. } else if (boundary == BlockBoundaryType::LeaveVariableEnvironment) {
  279. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  280. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  281. auto& block = make_block(DeprecatedString::formatted("{}.break", current_block().name()));
  282. emit<Op::ScheduleJump>(Label { block });
  283. switch_to_basic_block(block);
  284. last_was_finally = true;
  285. } else if (boundary == BlockBoundaryType::Break) {
  286. // Make sure we don't process this boundary twice if the current breakable scope doesn't contain the target label.
  287. --current_boundary;
  288. break;
  289. }
  290. }
  291. if (breakable_scope.language_label_set.contains_slow(break_label)) {
  292. emit<Op::Jump>().set_targets(breakable_scope.bytecode_target, {});
  293. return;
  294. }
  295. }
  296. // We must have a breakable scope available that contains the label, as this should be enforced by the parser.
  297. VERIFY_NOT_REACHED();
  298. }
  299. void Generator::generate_continue()
  300. {
  301. bool last_was_finally = false;
  302. // FIXME: Reduce code duplication
  303. for (size_t i = m_boundaries.size(); i > 0; --i) {
  304. auto boundary = m_boundaries[i - 1];
  305. using enum BlockBoundaryType;
  306. switch (boundary) {
  307. case Continue:
  308. emit<Op::Jump>().set_targets(nearest_continuable_scope(), {});
  309. return;
  310. case Unwind:
  311. if (!last_was_finally)
  312. emit<Bytecode::Op::LeaveUnwindContext>();
  313. last_was_finally = false;
  314. break;
  315. case LeaveLexicalEnvironment:
  316. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  317. break;
  318. case LeaveVariableEnvironment:
  319. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  320. break;
  321. case Break:
  322. break;
  323. case ReturnToFinally: {
  324. auto& block = make_block(DeprecatedString::formatted("{}.continue", current_block().name()));
  325. emit<Op::ScheduleJump>(Label { block });
  326. switch_to_basic_block(block);
  327. last_was_finally = true;
  328. break;
  329. };
  330. }
  331. }
  332. VERIFY_NOT_REACHED();
  333. }
  334. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  335. {
  336. size_t current_boundary = m_boundaries.size();
  337. bool last_was_finally = false;
  338. for (auto const& continuable_scope : m_continuable_scopes.in_reverse()) {
  339. for (; current_boundary > 0; --current_boundary) {
  340. auto boundary = m_boundaries[current_boundary - 1];
  341. if (boundary == BlockBoundaryType::Unwind) {
  342. if (!last_was_finally)
  343. emit<Bytecode::Op::LeaveUnwindContext>();
  344. last_was_finally = false;
  345. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  346. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  347. } else if (boundary == BlockBoundaryType::LeaveVariableEnvironment) {
  348. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  349. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  350. auto& block = make_block(DeprecatedString::formatted("{}.continue", current_block().name()));
  351. emit<Op::ScheduleJump>(Label { block });
  352. switch_to_basic_block(block);
  353. last_was_finally = true;
  354. } else if (boundary == BlockBoundaryType::Continue) {
  355. // Make sure we don't process this boundary twice if the current continuable scope doesn't contain the target label.
  356. --current_boundary;
  357. break;
  358. }
  359. }
  360. if (continuable_scope.language_label_set.contains_slow(continue_label)) {
  361. emit<Op::Jump>().set_targets(continuable_scope.bytecode_target, {});
  362. return;
  363. }
  364. }
  365. // We must have a continuable scope available that contains the label, as this should be enforced by the parser.
  366. VERIFY_NOT_REACHED();
  367. }
  368. }