Generator.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. }
  29. TRY(node.generate_bytecode(generator));
  30. if (generator.is_in_generator_or_async_function()) {
  31. // Terminate all unterminated blocks with yield return
  32. for (auto& block : generator.m_root_basic_blocks) {
  33. if (block.is_terminated())
  34. continue;
  35. generator.switch_to_basic_block(block);
  36. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  37. generator.emit<Bytecode::Op::Yield>(nullptr);
  38. }
  39. }
  40. bool is_strict_mode = false;
  41. if (is<Program>(node))
  42. is_strict_mode = static_cast<Program const&>(node).is_strict_mode();
  43. else if (is<FunctionBody>(node))
  44. is_strict_mode = static_cast<FunctionBody const&>(node).in_strict_mode();
  45. else if (is<FunctionDeclaration>(node))
  46. is_strict_mode = static_cast<FunctionDeclaration const&>(node).is_strict_mode();
  47. else if (is<FunctionExpression>(node))
  48. is_strict_mode = static_cast<FunctionExpression const&>(node).is_strict_mode();
  49. return adopt_own(*new Executable {
  50. .name = {},
  51. .basic_blocks = move(generator.m_root_basic_blocks),
  52. .string_table = move(generator.m_string_table),
  53. .identifier_table = move(generator.m_identifier_table),
  54. .number_of_registers = generator.m_next_register,
  55. .is_strict_mode = is_strict_mode });
  56. }
  57. void Generator::grow(size_t additional_size)
  58. {
  59. VERIFY(m_current_basic_block);
  60. m_current_basic_block->grow(additional_size);
  61. }
  62. void* Generator::next_slot()
  63. {
  64. VERIFY(m_current_basic_block);
  65. return m_current_basic_block->next_slot();
  66. }
  67. Register Generator::allocate_register()
  68. {
  69. VERIFY(m_next_register != NumericLimits<u32>::max());
  70. return Register { m_next_register++ };
  71. }
  72. Label Generator::nearest_continuable_scope() const
  73. {
  74. return m_continuable_scopes.last().bytecode_target;
  75. }
  76. void Generator::begin_variable_scope(BindingMode mode, SurroundingScopeKind kind)
  77. {
  78. m_variable_scopes.append({ kind, mode, {} });
  79. if (mode != BindingMode::Global) {
  80. start_boundary(mode == BindingMode::Lexical ? BlockBoundaryType::LeaveLexicalEnvironment : BlockBoundaryType::LeaveVariableEnvironment);
  81. emit<Bytecode::Op::CreateEnvironment>(
  82. mode == BindingMode::Lexical
  83. ? Bytecode::Op::EnvironmentMode::Lexical
  84. : Bytecode::Op::EnvironmentMode::Var);
  85. }
  86. }
  87. void Generator::end_variable_scope()
  88. {
  89. auto mode = m_variable_scopes.take_last().mode;
  90. if (mode != BindingMode::Global) {
  91. end_boundary(mode == BindingMode::Lexical ? BlockBoundaryType::LeaveLexicalEnvironment : BlockBoundaryType::LeaveVariableEnvironment);
  92. if (!m_current_basic_block->is_terminated()) {
  93. emit<Bytecode::Op::LeaveEnvironment>(
  94. mode == BindingMode::Lexical
  95. ? Bytecode::Op::EnvironmentMode::Lexical
  96. : Bytecode::Op::EnvironmentMode::Var);
  97. }
  98. }
  99. }
  100. void Generator::begin_continuable_scope(Label continue_target, Vector<FlyString> const& language_label_set)
  101. {
  102. m_continuable_scopes.append({ continue_target, language_label_set });
  103. start_boundary(BlockBoundaryType::Continue);
  104. }
  105. void Generator::end_continuable_scope()
  106. {
  107. m_continuable_scopes.take_last();
  108. end_boundary(BlockBoundaryType::Continue);
  109. }
  110. Label Generator::nearest_breakable_scope() const
  111. {
  112. return m_breakable_scopes.last().bytecode_target;
  113. }
  114. void Generator::begin_breakable_scope(Label breakable_target, Vector<FlyString> const& language_label_set)
  115. {
  116. m_breakable_scopes.append({ breakable_target, language_label_set });
  117. start_boundary(BlockBoundaryType::Break);
  118. }
  119. void Generator::end_breakable_scope()
  120. {
  121. m_breakable_scopes.take_last();
  122. end_boundary(BlockBoundaryType::Break);
  123. }
  124. CodeGenerationErrorOr<void> Generator::emit_load_from_reference(JS::ASTNode const& node)
  125. {
  126. if (is<Identifier>(node)) {
  127. auto& identifier = static_cast<Identifier const&>(node);
  128. emit<Bytecode::Op::GetVariable>(intern_identifier(identifier.string()));
  129. return {};
  130. }
  131. if (is<MemberExpression>(node)) {
  132. auto& expression = static_cast<MemberExpression const&>(node);
  133. TRY(expression.object().generate_bytecode(*this));
  134. if (expression.is_computed()) {
  135. auto object_reg = allocate_register();
  136. emit<Bytecode::Op::Store>(object_reg);
  137. TRY(expression.property().generate_bytecode(*this));
  138. emit<Bytecode::Op::GetByValue>(object_reg);
  139. } else if (expression.property().is_identifier()) {
  140. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  141. emit<Bytecode::Op::GetById>(identifier_table_ref);
  142. } else {
  143. return CodeGenerationError {
  144. &expression,
  145. "Unimplemented non-computed member expression"sv
  146. };
  147. }
  148. return {};
  149. }
  150. VERIFY_NOT_REACHED();
  151. }
  152. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node)
  153. {
  154. if (is<Identifier>(node)) {
  155. auto& identifier = static_cast<Identifier const&>(node);
  156. emit<Bytecode::Op::SetVariable>(intern_identifier(identifier.string()));
  157. return {};
  158. }
  159. if (is<MemberExpression>(node)) {
  160. // NOTE: The value is in the accumulator, so we have to store that away first.
  161. auto value_reg = allocate_register();
  162. emit<Bytecode::Op::Store>(value_reg);
  163. auto& expression = static_cast<MemberExpression const&>(node);
  164. TRY(expression.object().generate_bytecode(*this));
  165. auto object_reg = allocate_register();
  166. emit<Bytecode::Op::Store>(object_reg);
  167. if (expression.is_computed()) {
  168. TRY(expression.property().generate_bytecode(*this));
  169. auto property_reg = allocate_register();
  170. emit<Bytecode::Op::Store>(property_reg);
  171. emit<Bytecode::Op::Load>(value_reg);
  172. emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  173. } else if (expression.property().is_identifier()) {
  174. emit<Bytecode::Op::Load>(value_reg);
  175. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  176. emit<Bytecode::Op::PutById>(object_reg, identifier_table_ref);
  177. } else {
  178. return CodeGenerationError {
  179. &expression,
  180. "Unimplemented non-computed member expression"sv
  181. };
  182. }
  183. return {};
  184. }
  185. return CodeGenerationError {
  186. &node,
  187. "Unimplemented/invalid node used a reference"sv
  188. };
  189. }
  190. CodeGenerationErrorOr<void> Generator::emit_delete_reference(JS::ASTNode const& node)
  191. {
  192. if (is<Identifier>(node)) {
  193. auto& identifier = static_cast<Identifier const&>(node);
  194. emit<Bytecode::Op::DeleteVariable>(intern_identifier(identifier.string()));
  195. return {};
  196. }
  197. if (is<MemberExpression>(node)) {
  198. auto& expression = static_cast<MemberExpression const&>(node);
  199. TRY(expression.object().generate_bytecode(*this));
  200. if (expression.is_computed()) {
  201. auto object_reg = allocate_register();
  202. emit<Bytecode::Op::Store>(object_reg);
  203. TRY(expression.property().generate_bytecode(*this));
  204. emit<Bytecode::Op::DeleteByValue>(object_reg);
  205. } else if (expression.property().is_identifier()) {
  206. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  207. emit<Bytecode::Op::DeleteById>(identifier_table_ref);
  208. } else {
  209. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  210. return CodeGenerationError {
  211. &expression,
  212. "Unimplemented non-computed member expression"sv
  213. };
  214. }
  215. return {};
  216. }
  217. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  218. // For example: delete a(); delete ++c.b; etc.
  219. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  220. // 1. Let ref be the result of evaluating UnaryExpression.
  221. // 2. ReturnIfAbrupt(ref).
  222. TRY(node.generate_bytecode(*this));
  223. // 3. If ref is not a Reference Record, return true.
  224. emit<Bytecode::Op::LoadImmediate>(Value(true));
  225. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  226. return {};
  227. }
  228. Label Generator::perform_needed_unwinds_for_labelled_break_and_return_target_block(FlyString const& break_label)
  229. {
  230. size_t current_boundary = m_boundaries.size();
  231. for (auto& breakable_scope : m_breakable_scopes.in_reverse()) {
  232. for (; current_boundary > 0; --current_boundary) {
  233. auto boundary = m_boundaries[current_boundary - 1];
  234. if (boundary == BlockBoundaryType::Unwind) {
  235. emit<Bytecode::Op::LeaveUnwindContext>();
  236. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  237. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  238. } else if (boundary == BlockBoundaryType::LeaveVariableEnvironment) {
  239. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  240. } else if (boundary == BlockBoundaryType::Break) {
  241. // Make sure we don't process this boundary twice if the current breakable scope doesn't contain the target label.
  242. --current_boundary;
  243. break;
  244. }
  245. }
  246. if (breakable_scope.language_label_set.contains_slow(break_label))
  247. return breakable_scope.bytecode_target;
  248. }
  249. // We must have a breakable scope available that contains the label, as this should be enforced by the parser.
  250. VERIFY_NOT_REACHED();
  251. }
  252. Label Generator::perform_needed_unwinds_for_labelled_continue_and_return_target_block(FlyString const& continue_label)
  253. {
  254. size_t current_boundary = m_boundaries.size();
  255. for (auto& continuable_scope : m_continuable_scopes.in_reverse()) {
  256. for (; current_boundary > 0; --current_boundary) {
  257. auto boundary = m_boundaries[current_boundary - 1];
  258. if (boundary == BlockBoundaryType::Unwind) {
  259. emit<Bytecode::Op::LeaveUnwindContext>();
  260. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  261. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  262. } else if (boundary == BlockBoundaryType::LeaveVariableEnvironment) {
  263. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  264. } else if (boundary == BlockBoundaryType::Continue) {
  265. // Make sure we don't process this boundary twice if the current continuable scope doesn't contain the target label.
  266. --current_boundary;
  267. break;
  268. }
  269. }
  270. if (continuable_scope.language_label_set.contains_slow(continue_label))
  271. return continuable_scope.bytecode_target;
  272. }
  273. // We must have a continuable scope available that contains the label, as this should be enforced by the parser.
  274. VERIFY_NOT_REACHED();
  275. }
  276. String CodeGenerationError::to_string()
  277. {
  278. return String::formatted("CodeGenerationError in {}: {}", failing_node ? failing_node->class_name() : "<unknown node>", reason_literal);
  279. }
  280. }