Generator.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. }
  60. void Generator::grow(size_t additional_size)
  61. {
  62. VERIFY(m_current_basic_block);
  63. m_current_basic_block->grow(additional_size);
  64. }
  65. void* Generator::next_slot()
  66. {
  67. VERIFY(m_current_basic_block);
  68. return m_current_basic_block->next_slot();
  69. }
  70. Register Generator::allocate_register()
  71. {
  72. VERIFY(m_next_register != NumericLimits<u32>::max());
  73. return Register { m_next_register++ };
  74. }
  75. Label Generator::nearest_continuable_scope() const
  76. {
  77. return m_continuable_scopes.last().bytecode_target;
  78. }
  79. void Generator::begin_variable_scope(BindingMode mode, SurroundingScopeKind kind)
  80. {
  81. m_variable_scopes.append({ kind, mode, {} });
  82. if (mode != BindingMode::Global) {
  83. start_boundary(mode == BindingMode::Lexical ? BlockBoundaryType::LeaveLexicalEnvironment : BlockBoundaryType::LeaveVariableEnvironment);
  84. emit<Bytecode::Op::CreateEnvironment>(
  85. mode == BindingMode::Lexical
  86. ? Bytecode::Op::EnvironmentMode::Lexical
  87. : Bytecode::Op::EnvironmentMode::Var);
  88. }
  89. }
  90. void Generator::end_variable_scope()
  91. {
  92. auto mode = m_variable_scopes.take_last().mode;
  93. if (mode != BindingMode::Global) {
  94. end_boundary(mode == BindingMode::Lexical ? BlockBoundaryType::LeaveLexicalEnvironment : BlockBoundaryType::LeaveVariableEnvironment);
  95. if (!m_current_basic_block->is_terminated()) {
  96. emit<Bytecode::Op::LeaveEnvironment>(
  97. mode == BindingMode::Lexical
  98. ? Bytecode::Op::EnvironmentMode::Lexical
  99. : Bytecode::Op::EnvironmentMode::Var);
  100. }
  101. }
  102. }
  103. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  104. {
  105. m_continuable_scopes.append({ continue_target, language_label_set });
  106. start_boundary(BlockBoundaryType::Continue);
  107. }
  108. void Generator::end_continuable_scope()
  109. {
  110. m_continuable_scopes.take_last();
  111. end_boundary(BlockBoundaryType::Continue);
  112. }
  113. Label Generator::nearest_breakable_scope() const
  114. {
  115. return m_breakable_scopes.last().bytecode_target;
  116. }
  117. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  118. {
  119. m_breakable_scopes.append({ breakable_target, language_label_set });
  120. start_boundary(BlockBoundaryType::Break);
  121. }
  122. void Generator::end_breakable_scope()
  123. {
  124. m_breakable_scopes.take_last();
  125. end_boundary(BlockBoundaryType::Break);
  126. }
  127. CodeGenerationErrorOr<void> Generator::emit_load_from_reference(JS::ASTNode const& node)
  128. {
  129. if (is<Identifier>(node)) {
  130. auto& identifier = static_cast<Identifier const&>(node);
  131. emit<Bytecode::Op::GetVariable>(intern_identifier(identifier.string()));
  132. return {};
  133. }
  134. if (is<MemberExpression>(node)) {
  135. auto& expression = static_cast<MemberExpression const&>(node);
  136. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  137. if (is<SuperExpression>(expression.object())) {
  138. // 1. Let env be GetThisEnvironment().
  139. // 2. Let actualThis be ? env.GetThisBinding().
  140. // NOTE: Whilst this isn't used, it's still observable (e.g. it throws if super() hasn't been called)
  141. emit<Bytecode::Op::ResolveThisBinding>();
  142. Optional<Bytecode::Register> computed_property_value_register;
  143. if (expression.is_computed()) {
  144. // SuperProperty : super [ Expression ]
  145. // 3. Let propertyNameReference be ? Evaluation of Expression.
  146. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  147. TRY(expression.property().generate_bytecode(*this));
  148. computed_property_value_register = allocate_register();
  149. emit<Bytecode::Op::Store>(*computed_property_value_register);
  150. }
  151. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  152. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  153. // 1. Let env be GetThisEnvironment().
  154. // 2. Assert: env.HasSuperBinding() is true.
  155. // 3. Let baseValue be ? env.GetSuperBase().
  156. emit<Bytecode::Op::ResolveSuperBase>();
  157. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  158. if (computed_property_value_register.has_value()) {
  159. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  160. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  161. emit<Bytecode::Op::GetByValue>(*computed_property_value_register);
  162. } else {
  163. // 3. Let propertyKey be StringValue of IdentifierName.
  164. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  165. emit<Bytecode::Op::GetById>(identifier_table_ref);
  166. }
  167. } else {
  168. TRY(expression.object().generate_bytecode(*this));
  169. if (expression.is_computed()) {
  170. auto object_reg = allocate_register();
  171. emit<Bytecode::Op::Store>(object_reg);
  172. TRY(expression.property().generate_bytecode(*this));
  173. emit<Bytecode::Op::GetByValue>(object_reg);
  174. } else if (expression.property().is_identifier()) {
  175. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  176. emit<Bytecode::Op::GetById>(identifier_table_ref);
  177. } else {
  178. return CodeGenerationError {
  179. &expression,
  180. "Unimplemented non-computed member expression"sv
  181. };
  182. }
  183. }
  184. return {};
  185. }
  186. VERIFY_NOT_REACHED();
  187. }
  188. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node)
  189. {
  190. if (is<Identifier>(node)) {
  191. auto& identifier = static_cast<Identifier const&>(node);
  192. emit<Bytecode::Op::SetVariable>(intern_identifier(identifier.string()));
  193. return {};
  194. }
  195. if (is<MemberExpression>(node)) {
  196. // NOTE: The value is in the accumulator, so we have to store that away first.
  197. auto value_reg = allocate_register();
  198. emit<Bytecode::Op::Store>(value_reg);
  199. auto& expression = static_cast<MemberExpression const&>(node);
  200. TRY(expression.object().generate_bytecode(*this));
  201. auto object_reg = allocate_register();
  202. emit<Bytecode::Op::Store>(object_reg);
  203. if (expression.is_computed()) {
  204. TRY(expression.property().generate_bytecode(*this));
  205. auto property_reg = allocate_register();
  206. emit<Bytecode::Op::Store>(property_reg);
  207. emit<Bytecode::Op::Load>(value_reg);
  208. emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  209. } else if (expression.property().is_identifier()) {
  210. emit<Bytecode::Op::Load>(value_reg);
  211. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  212. emit<Bytecode::Op::PutById>(object_reg, identifier_table_ref);
  213. } else {
  214. return CodeGenerationError {
  215. &expression,
  216. "Unimplemented non-computed member expression"sv
  217. };
  218. }
  219. return {};
  220. }
  221. return CodeGenerationError {
  222. &node,
  223. "Unimplemented/invalid node used a reference"sv
  224. };
  225. }
  226. CodeGenerationErrorOr<void> Generator::emit_delete_reference(JS::ASTNode const& node)
  227. {
  228. if (is<Identifier>(node)) {
  229. auto& identifier = static_cast<Identifier const&>(node);
  230. emit<Bytecode::Op::DeleteVariable>(intern_identifier(identifier.string()));
  231. return {};
  232. }
  233. if (is<MemberExpression>(node)) {
  234. auto& expression = static_cast<MemberExpression const&>(node);
  235. TRY(expression.object().generate_bytecode(*this));
  236. if (expression.is_computed()) {
  237. auto object_reg = allocate_register();
  238. emit<Bytecode::Op::Store>(object_reg);
  239. TRY(expression.property().generate_bytecode(*this));
  240. emit<Bytecode::Op::DeleteByValue>(object_reg);
  241. } else if (expression.property().is_identifier()) {
  242. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  243. emit<Bytecode::Op::DeleteById>(identifier_table_ref);
  244. } else {
  245. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  246. return CodeGenerationError {
  247. &expression,
  248. "Unimplemented non-computed member expression"sv
  249. };
  250. }
  251. return {};
  252. }
  253. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  254. // For example: delete a(); delete ++c.b; etc.
  255. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  256. // 1. Let ref be the result of evaluating UnaryExpression.
  257. // 2. ReturnIfAbrupt(ref).
  258. TRY(node.generate_bytecode(*this));
  259. // 3. If ref is not a Reference Record, return true.
  260. emit<Bytecode::Op::LoadImmediate>(Value(true));
  261. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  262. return {};
  263. }
  264. void Generator::generate_break()
  265. {
  266. bool last_was_finally = false;
  267. // FIXME: Reduce code duplication
  268. for (size_t i = m_boundaries.size(); i > 0; --i) {
  269. auto boundary = m_boundaries[i - 1];
  270. using enum BlockBoundaryType;
  271. switch (boundary) {
  272. case Break:
  273. emit<Op::Jump>().set_targets(nearest_breakable_scope(), {});
  274. return;
  275. case Unwind:
  276. if (!last_was_finally)
  277. emit<Bytecode::Op::LeaveUnwindContext>();
  278. last_was_finally = false;
  279. break;
  280. case LeaveLexicalEnvironment:
  281. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  282. break;
  283. case LeaveVariableEnvironment:
  284. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  285. break;
  286. case Continue:
  287. break;
  288. case ReturnToFinally: {
  289. auto& block = make_block(DeprecatedString::formatted("{}.break", current_block().name()));
  290. emit<Op::ScheduleJump>(Label { block });
  291. switch_to_basic_block(block);
  292. last_was_finally = true;
  293. break;
  294. };
  295. }
  296. }
  297. VERIFY_NOT_REACHED();
  298. }
  299. void Generator::generate_break(DeprecatedFlyString const& break_label)
  300. {
  301. size_t current_boundary = m_boundaries.size();
  302. bool last_was_finally = false;
  303. for (auto const& breakable_scope : m_breakable_scopes.in_reverse()) {
  304. for (; current_boundary > 0; --current_boundary) {
  305. auto boundary = m_boundaries[current_boundary - 1];
  306. if (boundary == BlockBoundaryType::Unwind) {
  307. if (!last_was_finally)
  308. emit<Bytecode::Op::LeaveUnwindContext>();
  309. last_was_finally = false;
  310. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  311. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  312. } else if (boundary == BlockBoundaryType::LeaveVariableEnvironment) {
  313. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  314. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  315. auto& block = make_block(DeprecatedString::formatted("{}.break", current_block().name()));
  316. emit<Op::ScheduleJump>(Label { block });
  317. switch_to_basic_block(block);
  318. last_was_finally = true;
  319. } else if (boundary == BlockBoundaryType::Break) {
  320. // Make sure we don't process this boundary twice if the current breakable scope doesn't contain the target label.
  321. --current_boundary;
  322. break;
  323. }
  324. }
  325. if (breakable_scope.language_label_set.contains_slow(break_label)) {
  326. emit<Op::Jump>().set_targets(breakable_scope.bytecode_target, {});
  327. return;
  328. }
  329. }
  330. // We must have a breakable scope available that contains the label, as this should be enforced by the parser.
  331. VERIFY_NOT_REACHED();
  332. }
  333. void Generator::generate_continue()
  334. {
  335. bool last_was_finally = false;
  336. // FIXME: Reduce code duplication
  337. for (size_t i = m_boundaries.size(); i > 0; --i) {
  338. auto boundary = m_boundaries[i - 1];
  339. using enum BlockBoundaryType;
  340. switch (boundary) {
  341. case Continue:
  342. emit<Op::Jump>().set_targets(nearest_continuable_scope(), {});
  343. return;
  344. case Unwind:
  345. if (!last_was_finally)
  346. emit<Bytecode::Op::LeaveUnwindContext>();
  347. last_was_finally = false;
  348. break;
  349. case LeaveLexicalEnvironment:
  350. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  351. break;
  352. case LeaveVariableEnvironment:
  353. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  354. break;
  355. case Break:
  356. break;
  357. case ReturnToFinally: {
  358. auto& block = make_block(DeprecatedString::formatted("{}.continue", current_block().name()));
  359. emit<Op::ScheduleJump>(Label { block });
  360. switch_to_basic_block(block);
  361. last_was_finally = true;
  362. break;
  363. };
  364. }
  365. }
  366. VERIFY_NOT_REACHED();
  367. }
  368. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  369. {
  370. size_t current_boundary = m_boundaries.size();
  371. bool last_was_finally = false;
  372. for (auto const& continuable_scope : m_continuable_scopes.in_reverse()) {
  373. for (; current_boundary > 0; --current_boundary) {
  374. auto boundary = m_boundaries[current_boundary - 1];
  375. if (boundary == BlockBoundaryType::Unwind) {
  376. if (!last_was_finally)
  377. emit<Bytecode::Op::LeaveUnwindContext>();
  378. last_was_finally = false;
  379. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  380. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  381. } else if (boundary == BlockBoundaryType::LeaveVariableEnvironment) {
  382. emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Var);
  383. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  384. auto& block = make_block(DeprecatedString::formatted("{}.continue", current_block().name()));
  385. emit<Op::ScheduleJump>(Label { block });
  386. switch_to_basic_block(block);
  387. last_was_finally = true;
  388. } else if (boundary == BlockBoundaryType::Continue) {
  389. // Make sure we don't process this boundary twice if the current continuable scope doesn't contain the target label.
  390. --current_boundary;
  391. break;
  392. }
  393. }
  394. if (continuable_scope.language_label_set.contains_slow(continue_label)) {
  395. emit<Op::Jump>().set_targets(continuable_scope.bytecode_target, {});
  396. return;
  397. }
  398. }
  399. // We must have a continuable scope available that contains the label, as this should be enforced by the parser.
  400. VERIFY_NOT_REACHED();
  401. }
  402. }