Generator.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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::block_declaration_instantiation(ScopeNode const& scope_node)
  80. {
  81. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  82. emit<Bytecode::Op::BlockDeclarationInstantiation>(scope_node);
  83. }
  84. void Generator::begin_variable_scope()
  85. {
  86. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  87. emit<Bytecode::Op::CreateLexicalEnvironment>();
  88. }
  89. void Generator::end_variable_scope()
  90. {
  91. end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  92. if (!m_current_basic_block->is_terminated()) {
  93. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  94. }
  95. }
  96. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  97. {
  98. m_continuable_scopes.append({ continue_target, language_label_set });
  99. start_boundary(BlockBoundaryType::Continue);
  100. }
  101. void Generator::end_continuable_scope()
  102. {
  103. m_continuable_scopes.take_last();
  104. end_boundary(BlockBoundaryType::Continue);
  105. }
  106. Label Generator::nearest_breakable_scope() const
  107. {
  108. return m_breakable_scopes.last().bytecode_target;
  109. }
  110. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  111. {
  112. m_breakable_scopes.append({ breakable_target, language_label_set });
  113. start_boundary(BlockBoundaryType::Break);
  114. }
  115. void Generator::end_breakable_scope()
  116. {
  117. m_breakable_scopes.take_last();
  118. end_boundary(BlockBoundaryType::Break);
  119. }
  120. CodeGenerationErrorOr<Generator::ReferenceRegisters> Generator::emit_super_reference(MemberExpression const& expression)
  121. {
  122. VERIFY(is<SuperExpression>(expression.object()));
  123. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  124. // 1. Let env be GetThisEnvironment().
  125. // 2. Let actualThis be ? env.GetThisBinding().
  126. auto actual_this_register = allocate_register();
  127. emit<Bytecode::Op::ResolveThisBinding>();
  128. emit<Bytecode::Op::Store>(actual_this_register);
  129. Optional<Bytecode::Register> computed_property_value_register;
  130. if (expression.is_computed()) {
  131. // SuperProperty : super [ Expression ]
  132. // 3. Let propertyNameReference be ? Evaluation of Expression.
  133. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  134. TRY(expression.property().generate_bytecode(*this));
  135. computed_property_value_register = allocate_register();
  136. emit<Bytecode::Op::Store>(*computed_property_value_register);
  137. }
  138. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  139. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  140. // 1. Let env be GetThisEnvironment().
  141. // 2. Assert: env.HasSuperBinding() is true.
  142. // 3. Let baseValue be ? env.GetSuperBase().
  143. auto super_base_register = allocate_register();
  144. emit<Bytecode::Op::ResolveSuperBase>();
  145. emit<Bytecode::Op::Store>(super_base_register);
  146. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  147. return ReferenceRegisters {
  148. .base = super_base_register,
  149. .referenced_name = move(computed_property_value_register),
  150. .this_value = actual_this_register,
  151. };
  152. }
  153. CodeGenerationErrorOr<void> Generator::emit_load_from_reference(JS::ASTNode const& node)
  154. {
  155. if (is<Identifier>(node)) {
  156. auto& identifier = static_cast<Identifier const&>(node);
  157. TRY(identifier.generate_bytecode(*this));
  158. return {};
  159. }
  160. if (is<MemberExpression>(node)) {
  161. auto& expression = static_cast<MemberExpression const&>(node);
  162. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  163. if (is<SuperExpression>(expression.object())) {
  164. auto super_reference = TRY(emit_super_reference(expression));
  165. if (super_reference.referenced_name.has_value()) {
  166. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  167. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  168. emit<Bytecode::Op::Load>(*super_reference.referenced_name);
  169. emit<Bytecode::Op::GetByValueWithThis>(super_reference.base, super_reference.this_value);
  170. } else {
  171. // 3. Let propertyKey be StringValue of IdentifierName.
  172. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  173. emit<Bytecode::Op::GetByIdWithThis>(identifier_table_ref, super_reference.this_value);
  174. }
  175. } else {
  176. TRY(expression.object().generate_bytecode(*this));
  177. if (expression.is_computed()) {
  178. auto object_reg = allocate_register();
  179. emit<Bytecode::Op::Store>(object_reg);
  180. TRY(expression.property().generate_bytecode(*this));
  181. emit<Bytecode::Op::GetByValue>(object_reg);
  182. } else if (expression.property().is_identifier()) {
  183. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  184. emit<Bytecode::Op::GetById>(identifier_table_ref);
  185. } else if (expression.property().is_private_identifier()) {
  186. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  187. emit<Bytecode::Op::GetPrivateById>(identifier_table_ref);
  188. } else {
  189. return CodeGenerationError {
  190. &expression,
  191. "Unimplemented non-computed member expression"sv
  192. };
  193. }
  194. }
  195. return {};
  196. }
  197. VERIFY_NOT_REACHED();
  198. }
  199. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node)
  200. {
  201. if (is<Identifier>(node)) {
  202. auto& identifier = static_cast<Identifier const&>(node);
  203. emit_set_variable(identifier);
  204. return {};
  205. }
  206. if (is<MemberExpression>(node)) {
  207. // NOTE: The value is in the accumulator, so we have to store that away first.
  208. auto value_reg = allocate_register();
  209. emit<Bytecode::Op::Store>(value_reg);
  210. auto& expression = static_cast<MemberExpression const&>(node);
  211. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  212. if (is<SuperExpression>(expression.object())) {
  213. auto super_reference = TRY(emit_super_reference(expression));
  214. emit<Bytecode::Op::Load>(value_reg);
  215. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  216. if (super_reference.referenced_name.has_value()) {
  217. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  218. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  219. emit<Bytecode::Op::PutByValueWithThis>(super_reference.base, *super_reference.referenced_name, super_reference.this_value);
  220. } else {
  221. // 3. Let propertyKey be StringValue of IdentifierName.
  222. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  223. emit<Bytecode::Op::PutByIdWithThis>(super_reference.base, super_reference.this_value, identifier_table_ref);
  224. }
  225. } else {
  226. TRY(expression.object().generate_bytecode(*this));
  227. auto object_reg = allocate_register();
  228. emit<Bytecode::Op::Store>(object_reg);
  229. if (expression.is_computed()) {
  230. TRY(expression.property().generate_bytecode(*this));
  231. auto property_reg = allocate_register();
  232. emit<Bytecode::Op::Store>(property_reg);
  233. emit<Bytecode::Op::Load>(value_reg);
  234. emit<Bytecode::Op::PutByValue>(object_reg, property_reg);
  235. } else if (expression.property().is_identifier()) {
  236. emit<Bytecode::Op::Load>(value_reg);
  237. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  238. emit<Bytecode::Op::PutById>(object_reg, identifier_table_ref);
  239. } else if (expression.property().is_private_identifier()) {
  240. emit<Bytecode::Op::Load>(value_reg);
  241. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  242. emit<Bytecode::Op::PutPrivateById>(object_reg, identifier_table_ref);
  243. } else {
  244. return CodeGenerationError {
  245. &expression,
  246. "Unimplemented non-computed member expression"sv
  247. };
  248. }
  249. }
  250. return {};
  251. }
  252. return CodeGenerationError {
  253. &node,
  254. "Unimplemented/invalid node used a reference"sv
  255. };
  256. }
  257. CodeGenerationErrorOr<void> Generator::emit_delete_reference(JS::ASTNode const& node)
  258. {
  259. if (is<Identifier>(node)) {
  260. auto& identifier = static_cast<Identifier const&>(node);
  261. if (identifier.is_local())
  262. emit<Bytecode::Op::LoadImmediate>(Value(false));
  263. else
  264. emit<Bytecode::Op::DeleteVariable>(intern_identifier(identifier.string()));
  265. return {};
  266. }
  267. if (is<MemberExpression>(node)) {
  268. auto& expression = static_cast<MemberExpression const&>(node);
  269. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  270. if (is<SuperExpression>(expression.object())) {
  271. auto super_reference = TRY(emit_super_reference(expression));
  272. if (super_reference.referenced_name.has_value()) {
  273. emit<Bytecode::Op::DeleteByValueWithThis>(super_reference.this_value, *super_reference.referenced_name);
  274. } else {
  275. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  276. emit<Bytecode::Op::DeleteByIdWithThis>(super_reference.this_value, identifier_table_ref);
  277. }
  278. return {};
  279. }
  280. TRY(expression.object().generate_bytecode(*this));
  281. if (expression.is_computed()) {
  282. auto object_reg = allocate_register();
  283. emit<Bytecode::Op::Store>(object_reg);
  284. TRY(expression.property().generate_bytecode(*this));
  285. emit<Bytecode::Op::DeleteByValue>(object_reg);
  286. } else if (expression.property().is_identifier()) {
  287. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  288. emit<Bytecode::Op::DeleteById>(identifier_table_ref);
  289. } else {
  290. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  291. return CodeGenerationError {
  292. &expression,
  293. "Unimplemented non-computed member expression"sv
  294. };
  295. }
  296. return {};
  297. }
  298. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  299. // For example: delete a(); delete ++c.b; etc.
  300. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  301. // 1. Let ref be the result of evaluating UnaryExpression.
  302. // 2. ReturnIfAbrupt(ref).
  303. TRY(node.generate_bytecode(*this));
  304. // 3. If ref is not a Reference Record, return true.
  305. emit<Bytecode::Op::LoadImmediate>(Value(true));
  306. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  307. return {};
  308. }
  309. void Generator::emit_set_variable(JS::Identifier const& identifier, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Op::EnvironmentMode mode)
  310. {
  311. if (identifier.is_local()) {
  312. emit<Bytecode::Op::SetLocal>(identifier.local_variable_index());
  313. } else {
  314. emit<Bytecode::Op::SetVariable>(intern_identifier(identifier.string()), initialization_mode, mode);
  315. }
  316. }
  317. void Generator::generate_break()
  318. {
  319. bool last_was_finally = false;
  320. // FIXME: Reduce code duplication
  321. for (size_t i = m_boundaries.size(); i > 0; --i) {
  322. auto boundary = m_boundaries[i - 1];
  323. using enum BlockBoundaryType;
  324. switch (boundary) {
  325. case Break:
  326. emit<Op::Jump>().set_targets(nearest_breakable_scope(), {});
  327. return;
  328. case Unwind:
  329. if (!last_was_finally)
  330. emit<Bytecode::Op::LeaveUnwindContext>();
  331. last_was_finally = false;
  332. break;
  333. case LeaveLexicalEnvironment:
  334. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  335. break;
  336. case Continue:
  337. break;
  338. case ReturnToFinally: {
  339. auto& block = make_block(DeprecatedString::formatted("{}.break", current_block().name()));
  340. emit<Op::ScheduleJump>(Label { block });
  341. switch_to_basic_block(block);
  342. last_was_finally = true;
  343. break;
  344. };
  345. }
  346. }
  347. VERIFY_NOT_REACHED();
  348. }
  349. void Generator::generate_break(DeprecatedFlyString const& break_label)
  350. {
  351. size_t current_boundary = m_boundaries.size();
  352. bool last_was_finally = false;
  353. for (auto const& breakable_scope : m_breakable_scopes.in_reverse()) {
  354. for (; current_boundary > 0; --current_boundary) {
  355. auto boundary = m_boundaries[current_boundary - 1];
  356. if (boundary == BlockBoundaryType::Unwind) {
  357. if (!last_was_finally)
  358. emit<Bytecode::Op::LeaveUnwindContext>();
  359. last_was_finally = false;
  360. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  361. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  362. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  363. auto& block = make_block(DeprecatedString::formatted("{}.break", current_block().name()));
  364. emit<Op::ScheduleJump>(Label { block });
  365. switch_to_basic_block(block);
  366. last_was_finally = true;
  367. } else if (boundary == BlockBoundaryType::Break) {
  368. // Make sure we don't process this boundary twice if the current breakable scope doesn't contain the target label.
  369. --current_boundary;
  370. break;
  371. }
  372. }
  373. if (breakable_scope.language_label_set.contains_slow(break_label)) {
  374. emit<Op::Jump>().set_targets(breakable_scope.bytecode_target, {});
  375. return;
  376. }
  377. }
  378. // We must have a breakable scope available that contains the label, as this should be enforced by the parser.
  379. VERIFY_NOT_REACHED();
  380. }
  381. void Generator::generate_continue()
  382. {
  383. bool last_was_finally = false;
  384. // FIXME: Reduce code duplication
  385. for (size_t i = m_boundaries.size(); i > 0; --i) {
  386. auto boundary = m_boundaries[i - 1];
  387. using enum BlockBoundaryType;
  388. switch (boundary) {
  389. case Continue:
  390. emit<Op::Jump>().set_targets(nearest_continuable_scope(), {});
  391. return;
  392. case Unwind:
  393. if (!last_was_finally)
  394. emit<Bytecode::Op::LeaveUnwindContext>();
  395. last_was_finally = false;
  396. break;
  397. case LeaveLexicalEnvironment:
  398. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  399. break;
  400. case Break:
  401. break;
  402. case ReturnToFinally: {
  403. auto& block = make_block(DeprecatedString::formatted("{}.continue", current_block().name()));
  404. emit<Op::ScheduleJump>(Label { block });
  405. switch_to_basic_block(block);
  406. last_was_finally = true;
  407. break;
  408. };
  409. }
  410. }
  411. VERIFY_NOT_REACHED();
  412. }
  413. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  414. {
  415. size_t current_boundary = m_boundaries.size();
  416. bool last_was_finally = false;
  417. for (auto const& continuable_scope : m_continuable_scopes.in_reverse()) {
  418. for (; current_boundary > 0; --current_boundary) {
  419. auto boundary = m_boundaries[current_boundary - 1];
  420. if (boundary == BlockBoundaryType::Unwind) {
  421. if (!last_was_finally)
  422. emit<Bytecode::Op::LeaveUnwindContext>();
  423. last_was_finally = false;
  424. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  425. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  426. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  427. auto& block = make_block(DeprecatedString::formatted("{}.continue", current_block().name()));
  428. emit<Op::ScheduleJump>(Label { block });
  429. switch_to_basic_block(block);
  430. last_was_finally = true;
  431. } else if (boundary == BlockBoundaryType::Continue) {
  432. // Make sure we don't process this boundary twice if the current continuable scope doesn't contain the target label.
  433. --current_boundary;
  434. break;
  435. }
  436. }
  437. if (continuable_scope.language_label_set.contains_slow(continue_label)) {
  438. emit<Op::Jump>().set_targets(continuable_scope.bytecode_target, {});
  439. return;
  440. }
  441. }
  442. // We must have a continuable scope available that contains the label, as this should be enforced by the parser.
  443. VERIFY_NOT_REACHED();
  444. }
  445. void Generator::push_home_object(Register register_)
  446. {
  447. m_home_objects.append(register_);
  448. }
  449. void Generator::pop_home_object()
  450. {
  451. m_home_objects.take_last();
  452. }
  453. void Generator::emit_new_function(FunctionExpression const& function_node, Optional<IdentifierTableIndex> lhs_name)
  454. {
  455. if (m_home_objects.is_empty())
  456. emit<Op::NewFunction>(function_node, lhs_name);
  457. else
  458. emit<Op::NewFunction>(function_node, lhs_name, m_home_objects.last());
  459. }
  460. CodeGenerationErrorOr<void> Generator::emit_named_evaluation_if_anonymous_function(Expression const& expression, Optional<IdentifierTableIndex> lhs_name)
  461. {
  462. if (is<FunctionExpression>(expression)) {
  463. auto const& function_expression = static_cast<FunctionExpression const&>(expression);
  464. if (!function_expression.has_name()) {
  465. TRY(function_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name)));
  466. return {};
  467. }
  468. }
  469. if (is<ClassExpression>(expression)) {
  470. auto const& class_expression = static_cast<ClassExpression const&>(expression);
  471. if (!class_expression.has_name()) {
  472. TRY(class_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name)));
  473. return {};
  474. }
  475. }
  476. TRY(expression.generate_bytecode(*this));
  477. return {};
  478. }
  479. }