Generator.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. /*
  2. * Copyright (c) 2021-2024, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/TemporaryChange.h>
  7. #include <LibJS/AST.h>
  8. #include <LibJS/Bytecode/BasicBlock.h>
  9. #include <LibJS/Bytecode/Generator.h>
  10. #include <LibJS/Bytecode/Instruction.h>
  11. #include <LibJS/Bytecode/Op.h>
  12. #include <LibJS/Bytecode/Register.h>
  13. #include <LibJS/Runtime/VM.h>
  14. namespace JS::Bytecode {
  15. Generator::Generator(VM& vm)
  16. : m_vm(vm)
  17. , m_string_table(make<StringTable>())
  18. , m_identifier_table(make<IdentifierTable>())
  19. , m_regex_table(make<RegexTable>())
  20. , m_constants(vm.heap())
  21. {
  22. }
  23. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::generate(VM& vm, ASTNode const& node, ReadonlySpan<FunctionParameter> parameters, FunctionKind enclosing_function_kind)
  24. {
  25. Generator generator(vm);
  26. for (auto const& parameter : parameters) {
  27. if (auto const* identifier = parameter.binding.get_pointer<NonnullRefPtr<Identifier const>>();
  28. identifier && (*identifier)->is_local()) {
  29. generator.set_local_initialized((*identifier)->local_variable_index());
  30. }
  31. }
  32. generator.switch_to_basic_block(generator.make_block());
  33. SourceLocationScope scope(generator, node);
  34. generator.m_enclosing_function_kind = enclosing_function_kind;
  35. if (generator.is_in_generator_or_async_function()) {
  36. // Immediately yield with no value.
  37. auto& start_block = generator.make_block();
  38. generator.emit<Bytecode::Op::Yield>(Label { start_block }, generator.add_constant(js_undefined()));
  39. generator.switch_to_basic_block(start_block);
  40. // NOTE: This doesn't have to handle received throw/return completions, as GeneratorObject::resume_abrupt
  41. // will not enter the generator from the SuspendedStart state and immediately completes the generator.
  42. }
  43. auto last_value = TRY(node.generate_bytecode(generator));
  44. if (!generator.current_block().is_terminated() && last_value.has_value()) {
  45. generator.emit<Bytecode::Op::End>(last_value.value());
  46. }
  47. if (generator.is_in_generator_or_async_function()) {
  48. // Terminate all unterminated blocks with yield return
  49. for (auto& block : generator.m_root_basic_blocks) {
  50. if (block->is_terminated())
  51. continue;
  52. generator.switch_to_basic_block(*block);
  53. generator.emit<Bytecode::Op::Yield>(nullptr, generator.add_constant(js_undefined()));
  54. }
  55. }
  56. bool is_strict_mode = false;
  57. if (is<Program>(node))
  58. is_strict_mode = static_cast<Program const&>(node).is_strict_mode();
  59. else if (is<FunctionBody>(node))
  60. is_strict_mode = static_cast<FunctionBody const&>(node).in_strict_mode();
  61. else if (is<FunctionDeclaration>(node))
  62. is_strict_mode = static_cast<FunctionDeclaration const&>(node).is_strict_mode();
  63. else if (is<FunctionExpression>(node))
  64. is_strict_mode = static_cast<FunctionExpression const&>(node).is_strict_mode();
  65. auto executable = vm.heap().allocate_without_realm<Executable>(
  66. move(generator.m_identifier_table),
  67. move(generator.m_string_table),
  68. move(generator.m_regex_table),
  69. move(generator.m_constants),
  70. node.source_code(),
  71. generator.m_next_property_lookup_cache,
  72. generator.m_next_global_variable_cache,
  73. generator.m_next_environment_variable_cache,
  74. generator.m_next_register,
  75. move(generator.m_root_basic_blocks),
  76. is_strict_mode);
  77. return executable;
  78. }
  79. void Generator::grow(size_t additional_size)
  80. {
  81. VERIFY(m_current_basic_block);
  82. m_current_basic_block->grow(additional_size);
  83. }
  84. Register Generator::allocate_register()
  85. {
  86. VERIFY(m_next_register != NumericLimits<u32>::max());
  87. return Register { m_next_register++ };
  88. }
  89. Generator::SourceLocationScope::SourceLocationScope(Generator& generator, ASTNode const& node)
  90. : m_generator(generator)
  91. , m_previous_node(m_generator.m_current_ast_node)
  92. {
  93. m_generator.m_current_ast_node = &node;
  94. }
  95. Generator::SourceLocationScope::~SourceLocationScope()
  96. {
  97. m_generator.m_current_ast_node = m_previous_node;
  98. }
  99. Generator::UnwindContext::UnwindContext(Generator& generator, Optional<Label> finalizer)
  100. : m_generator(generator)
  101. , m_finalizer(finalizer)
  102. , m_previous_context(m_generator.m_current_unwind_context)
  103. {
  104. m_generator.m_current_unwind_context = this;
  105. }
  106. Generator::UnwindContext::~UnwindContext()
  107. {
  108. VERIFY(m_generator.m_current_unwind_context == this);
  109. m_generator.m_current_unwind_context = m_previous_context;
  110. }
  111. Label Generator::nearest_continuable_scope() const
  112. {
  113. return m_continuable_scopes.last().bytecode_target;
  114. }
  115. void Generator::block_declaration_instantiation(ScopeNode const& scope_node)
  116. {
  117. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  118. emit<Bytecode::Op::BlockDeclarationInstantiation>(scope_node);
  119. }
  120. void Generator::begin_variable_scope()
  121. {
  122. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  123. emit<Bytecode::Op::CreateLexicalEnvironment>();
  124. }
  125. void Generator::end_variable_scope()
  126. {
  127. end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  128. if (!m_current_basic_block->is_terminated()) {
  129. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  130. }
  131. }
  132. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  133. {
  134. m_continuable_scopes.append({ continue_target, language_label_set });
  135. start_boundary(BlockBoundaryType::Continue);
  136. }
  137. void Generator::end_continuable_scope()
  138. {
  139. m_continuable_scopes.take_last();
  140. end_boundary(BlockBoundaryType::Continue);
  141. }
  142. Label Generator::nearest_breakable_scope() const
  143. {
  144. return m_breakable_scopes.last().bytecode_target;
  145. }
  146. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  147. {
  148. m_breakable_scopes.append({ breakable_target, language_label_set });
  149. start_boundary(BlockBoundaryType::Break);
  150. }
  151. void Generator::end_breakable_scope()
  152. {
  153. m_breakable_scopes.take_last();
  154. end_boundary(BlockBoundaryType::Break);
  155. }
  156. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_super_reference(MemberExpression const& expression)
  157. {
  158. VERIFY(is<SuperExpression>(expression.object()));
  159. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  160. // 1. Let env be GetThisEnvironment().
  161. // 2. Let actualThis be ? env.GetThisBinding().
  162. auto actual_this = Operand(allocate_register());
  163. emit<Bytecode::Op::ResolveThisBinding>(actual_this);
  164. Optional<Bytecode::Operand> computed_property_value;
  165. if (expression.is_computed()) {
  166. // SuperProperty : super [ Expression ]
  167. // 3. Let propertyNameReference be ? Evaluation of Expression.
  168. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  169. computed_property_value = TRY(expression.property().generate_bytecode(*this)).value();
  170. }
  171. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  172. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  173. // 1. Let env be GetThisEnvironment().
  174. // 2. Assert: env.HasSuperBinding() is true.
  175. // 3. Let baseValue be ? env.GetSuperBase().
  176. auto base_value = Operand(allocate_register());
  177. emit<Bytecode::Op::ResolveSuperBase>(base_value);
  178. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  179. return ReferenceOperands {
  180. .base = base_value,
  181. .referenced_name = computed_property_value,
  182. .this_value = actual_this,
  183. };
  184. }
  185. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_load_from_reference(JS::ASTNode const& node, Optional<Operand> preferred_dst)
  186. {
  187. if (is<Identifier>(node)) {
  188. auto& identifier = static_cast<Identifier const&>(node);
  189. auto loaded_value = TRY(identifier.generate_bytecode(*this, preferred_dst)).value();
  190. return ReferenceOperands {
  191. .loaded_value = loaded_value,
  192. };
  193. }
  194. if (!is<MemberExpression>(node)) {
  195. return CodeGenerationError {
  196. &node,
  197. "Unimplemented/invalid node used as a reference"sv
  198. };
  199. }
  200. auto& expression = static_cast<MemberExpression const&>(node);
  201. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  202. if (is<SuperExpression>(expression.object())) {
  203. auto super_reference = TRY(emit_super_reference(expression));
  204. auto dst = preferred_dst.has_value() ? preferred_dst.value() : Operand(allocate_register());
  205. if (super_reference.referenced_name.has_value()) {
  206. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  207. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  208. emit<Bytecode::Op::GetByValueWithThis>(dst, *super_reference.base, *super_reference.referenced_name, *super_reference.this_value);
  209. } else {
  210. // 3. Let propertyKey be StringValue of IdentifierName.
  211. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  212. emit_get_by_id_with_this(dst, *super_reference.base, identifier_table_ref, *super_reference.this_value);
  213. }
  214. super_reference.loaded_value = dst;
  215. return super_reference;
  216. }
  217. auto base = TRY(expression.object().generate_bytecode(*this)).value();
  218. auto base_identifier = intern_identifier_for_expression(expression.object());
  219. if (expression.is_computed()) {
  220. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  221. auto saved_property = Operand(allocate_register());
  222. emit<Bytecode::Op::Mov>(saved_property, property);
  223. auto dst = preferred_dst.has_value() ? preferred_dst.value() : Operand(allocate_register());
  224. emit<Bytecode::Op::GetByValue>(dst, base, property, move(base_identifier));
  225. return ReferenceOperands {
  226. .base = base,
  227. .referenced_name = saved_property,
  228. .this_value = base,
  229. .loaded_value = dst,
  230. };
  231. }
  232. if (expression.property().is_identifier()) {
  233. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  234. auto dst = preferred_dst.has_value() ? preferred_dst.value() : Operand(allocate_register());
  235. emit_get_by_id(dst, base, identifier_table_ref, move(base_identifier));
  236. return ReferenceOperands {
  237. .base = base,
  238. .referenced_identifier = identifier_table_ref,
  239. .this_value = base,
  240. .loaded_value = dst,
  241. };
  242. }
  243. if (expression.property().is_private_identifier()) {
  244. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  245. auto dst = preferred_dst.has_value() ? preferred_dst.value() : Operand(allocate_register());
  246. emit<Bytecode::Op::GetPrivateById>(dst, base, identifier_table_ref);
  247. return ReferenceOperands {
  248. .base = base,
  249. .referenced_private_identifier = identifier_table_ref,
  250. .this_value = base,
  251. .loaded_value = dst,
  252. };
  253. }
  254. return CodeGenerationError {
  255. &expression,
  256. "Unimplemented non-computed member expression"sv
  257. };
  258. }
  259. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node, Operand value)
  260. {
  261. if (is<Identifier>(node)) {
  262. auto& identifier = static_cast<Identifier const&>(node);
  263. emit_set_variable(identifier, value);
  264. return {};
  265. }
  266. if (is<MemberExpression>(node)) {
  267. auto& expression = static_cast<MemberExpression const&>(node);
  268. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  269. if (is<SuperExpression>(expression.object())) {
  270. auto super_reference = TRY(emit_super_reference(expression));
  271. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  272. if (super_reference.referenced_name.has_value()) {
  273. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  274. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  275. emit<Bytecode::Op::PutByValueWithThis>(*super_reference.base, *super_reference.referenced_name, *super_reference.this_value, value);
  276. } else {
  277. // 3. Let propertyKey be StringValue of IdentifierName.
  278. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  279. emit<Bytecode::Op::PutByIdWithThis>(*super_reference.base, *super_reference.this_value, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  280. }
  281. } else {
  282. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  283. if (expression.is_computed()) {
  284. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  285. emit<Bytecode::Op::PutByValue>(object, property, value);
  286. } else if (expression.property().is_identifier()) {
  287. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  288. emit<Bytecode::Op::PutById>(object, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  289. } else if (expression.property().is_private_identifier()) {
  290. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  291. emit<Bytecode::Op::PutPrivateById>(object, identifier_table_ref, value);
  292. } else {
  293. return CodeGenerationError {
  294. &expression,
  295. "Unimplemented non-computed member expression"sv
  296. };
  297. }
  298. }
  299. return {};
  300. }
  301. return CodeGenerationError {
  302. &node,
  303. "Unimplemented/invalid node used a reference"sv
  304. };
  305. }
  306. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(ReferenceOperands const& reference, Operand value)
  307. {
  308. if (reference.referenced_private_identifier.has_value()) {
  309. emit<Bytecode::Op::PutPrivateById>(*reference.base, *reference.referenced_private_identifier, value);
  310. return {};
  311. }
  312. if (reference.referenced_identifier.has_value()) {
  313. if (reference.base == reference.this_value)
  314. emit<Bytecode::Op::PutById>(*reference.base, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  315. else
  316. emit<Bytecode::Op::PutByIdWithThis>(*reference.base, *reference.this_value, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  317. return {};
  318. }
  319. if (reference.base == reference.this_value)
  320. emit<Bytecode::Op::PutByValue>(*reference.base, *reference.referenced_name, value);
  321. else
  322. emit<Bytecode::Op::PutByValueWithThis>(*reference.base, *reference.referenced_name, *reference.this_value, value);
  323. return {};
  324. }
  325. CodeGenerationErrorOr<Optional<Operand>> Generator::emit_delete_reference(JS::ASTNode const& node)
  326. {
  327. if (is<Identifier>(node)) {
  328. auto& identifier = static_cast<Identifier const&>(node);
  329. if (identifier.is_local()) {
  330. return add_constant(Value(false));
  331. }
  332. auto dst = Operand(allocate_register());
  333. emit<Bytecode::Op::DeleteVariable>(dst, intern_identifier(identifier.string()));
  334. return dst;
  335. }
  336. if (is<MemberExpression>(node)) {
  337. auto& expression = static_cast<MemberExpression const&>(node);
  338. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  339. if (is<SuperExpression>(expression.object())) {
  340. auto super_reference = TRY(emit_super_reference(expression));
  341. auto dst = Operand(allocate_register());
  342. if (super_reference.referenced_name.has_value()) {
  343. emit<Bytecode::Op::DeleteByValueWithThis>(dst, *super_reference.base, *super_reference.this_value, *super_reference.referenced_name);
  344. } else {
  345. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  346. emit<Bytecode::Op::DeleteByIdWithThis>(dst, *super_reference.base, *super_reference.this_value, identifier_table_ref);
  347. }
  348. return Optional<Operand> {};
  349. }
  350. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  351. auto dst = Operand(allocate_register());
  352. if (expression.is_computed()) {
  353. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  354. emit<Bytecode::Op::DeleteByValue>(dst, object, property);
  355. } else if (expression.property().is_identifier()) {
  356. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  357. emit<Bytecode::Op::DeleteById>(dst, object, identifier_table_ref);
  358. } else {
  359. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  360. return CodeGenerationError {
  361. &expression,
  362. "Unimplemented non-computed member expression"sv
  363. };
  364. }
  365. return dst;
  366. }
  367. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  368. // For example: delete a(); delete ++c.b; etc.
  369. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  370. // 1. Let ref be the result of evaluating UnaryExpression.
  371. // 2. ReturnIfAbrupt(ref).
  372. (void)TRY(node.generate_bytecode(*this));
  373. // 3. If ref is not a Reference Record, return true.
  374. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  375. return add_constant(Value(true));
  376. }
  377. void Generator::emit_set_variable(JS::Identifier const& identifier, Operand value, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Op::EnvironmentMode mode)
  378. {
  379. if (identifier.is_local()) {
  380. if (value.is_local() && value.index() == identifier.local_variable_index()) {
  381. // Moving a local to itself is a no-op.
  382. return;
  383. }
  384. emit<Bytecode::Op::SetLocal>(identifier.local_variable_index(), value);
  385. } else {
  386. emit<Bytecode::Op::SetVariable>(intern_identifier(identifier.string()), value, next_environment_variable_cache(), initialization_mode, mode);
  387. }
  388. }
  389. static Optional<ByteString> expression_identifier(Expression const& expression)
  390. {
  391. if (expression.is_identifier()) {
  392. auto const& identifier = static_cast<Identifier const&>(expression);
  393. return identifier.string();
  394. }
  395. if (expression.is_numeric_literal()) {
  396. auto const& literal = static_cast<NumericLiteral const&>(expression);
  397. return literal.value().to_string_without_side_effects().to_byte_string();
  398. }
  399. if (expression.is_string_literal()) {
  400. auto const& literal = static_cast<StringLiteral const&>(expression);
  401. return ByteString::formatted("'{}'", literal.value());
  402. }
  403. if (expression.is_member_expression()) {
  404. auto const& member_expression = static_cast<MemberExpression const&>(expression);
  405. StringBuilder builder;
  406. if (auto identifer = expression_identifier(member_expression.object()); identifer.has_value())
  407. builder.append(*identifer);
  408. if (auto identifer = expression_identifier(member_expression.property()); identifer.has_value()) {
  409. if (member_expression.is_computed())
  410. builder.appendff("[{}]", *identifer);
  411. else
  412. builder.appendff(".{}", *identifer);
  413. }
  414. return builder.to_byte_string();
  415. }
  416. return {};
  417. }
  418. Optional<IdentifierTableIndex> Generator::intern_identifier_for_expression(Expression const& expression)
  419. {
  420. if (auto identifer = expression_identifier(expression); identifer.has_value())
  421. return intern_identifier(identifer.release_value());
  422. return {};
  423. }
  424. void Generator::generate_scoped_jump(JumpType type)
  425. {
  426. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  427. bool last_was_finally = false;
  428. for (size_t i = m_boundaries.size(); i > 0; --i) {
  429. auto boundary = m_boundaries[i - 1];
  430. using enum BlockBoundaryType;
  431. switch (boundary) {
  432. case Break:
  433. if (type == JumpType::Break) {
  434. emit<Op::Jump>(nearest_breakable_scope());
  435. return;
  436. }
  437. break;
  438. case Continue:
  439. if (type == JumpType::Continue) {
  440. emit<Op::Jump>(nearest_continuable_scope());
  441. return;
  442. }
  443. break;
  444. case Unwind:
  445. VERIFY(last_was_finally || !m_current_unwind_context->finalizer().has_value());
  446. if (!last_was_finally) {
  447. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  448. emit<Bytecode::Op::LeaveUnwindContext>();
  449. m_current_unwind_context = m_current_unwind_context->previous();
  450. }
  451. last_was_finally = false;
  452. break;
  453. case LeaveLexicalEnvironment:
  454. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  455. break;
  456. case ReturnToFinally: {
  457. VERIFY(m_current_unwind_context->finalizer().has_value());
  458. m_current_unwind_context = m_current_unwind_context->previous();
  459. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  460. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  461. auto& block = make_block(block_name);
  462. emit<Op::ScheduleJump>(Label { block });
  463. switch_to_basic_block(block);
  464. last_was_finally = true;
  465. break;
  466. };
  467. }
  468. }
  469. VERIFY_NOT_REACHED();
  470. }
  471. void Generator::generate_labelled_jump(JumpType type, DeprecatedFlyString const& label)
  472. {
  473. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  474. size_t current_boundary = m_boundaries.size();
  475. bool last_was_finally = false;
  476. auto const& jumpable_scopes = type == JumpType::Continue ? m_continuable_scopes : m_breakable_scopes;
  477. for (auto const& jumpable_scope : jumpable_scopes.in_reverse()) {
  478. for (; current_boundary > 0; --current_boundary) {
  479. auto boundary = m_boundaries[current_boundary - 1];
  480. if (boundary == BlockBoundaryType::Unwind) {
  481. VERIFY(last_was_finally || !m_current_unwind_context->finalizer().has_value());
  482. if (!last_was_finally) {
  483. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  484. emit<Bytecode::Op::LeaveUnwindContext>();
  485. m_current_unwind_context = m_current_unwind_context->previous();
  486. }
  487. last_was_finally = false;
  488. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  489. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  490. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  491. VERIFY(m_current_unwind_context->finalizer().has_value());
  492. m_current_unwind_context = m_current_unwind_context->previous();
  493. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  494. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  495. auto& block = make_block(block_name);
  496. emit<Op::ScheduleJump>(Label { block });
  497. switch_to_basic_block(block);
  498. last_was_finally = true;
  499. } else if ((type == JumpType::Continue && boundary == BlockBoundaryType::Continue) || (type == JumpType::Break && boundary == BlockBoundaryType::Break)) {
  500. // Make sure we don't process this boundary twice if the current jumpable scope doesn't contain the target label.
  501. --current_boundary;
  502. break;
  503. }
  504. }
  505. if (jumpable_scope.language_label_set.contains_slow(label)) {
  506. emit<Op::Jump>(jumpable_scope.bytecode_target);
  507. return;
  508. }
  509. }
  510. // We must have a jumpable scope available that contains the label, as this should be enforced by the parser.
  511. VERIFY_NOT_REACHED();
  512. }
  513. void Generator::generate_break()
  514. {
  515. generate_scoped_jump(JumpType::Break);
  516. }
  517. void Generator::generate_break(DeprecatedFlyString const& break_label)
  518. {
  519. generate_labelled_jump(JumpType::Break, break_label);
  520. }
  521. void Generator::generate_continue()
  522. {
  523. generate_scoped_jump(JumpType::Continue);
  524. }
  525. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  526. {
  527. generate_labelled_jump(JumpType::Continue, continue_label);
  528. }
  529. void Generator::push_home_object(Operand object)
  530. {
  531. m_home_objects.append(object);
  532. }
  533. void Generator::pop_home_object()
  534. {
  535. m_home_objects.take_last();
  536. }
  537. void Generator::emit_new_function(Operand dst, FunctionExpression const& function_node, Optional<IdentifierTableIndex> lhs_name)
  538. {
  539. if (m_home_objects.is_empty()) {
  540. emit<Op::NewFunction>(dst, function_node, lhs_name);
  541. } else {
  542. emit<Op::NewFunction>(dst, function_node, lhs_name, m_home_objects.last());
  543. }
  544. }
  545. CodeGenerationErrorOr<Optional<Operand>> Generator::emit_named_evaluation_if_anonymous_function(Expression const& expression, Optional<IdentifierTableIndex> lhs_name, Optional<Operand> preferred_dst)
  546. {
  547. if (is<FunctionExpression>(expression)) {
  548. auto const& function_expression = static_cast<FunctionExpression const&>(expression);
  549. if (!function_expression.has_name()) {
  550. return TRY(function_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  551. }
  552. }
  553. if (is<ClassExpression>(expression)) {
  554. auto const& class_expression = static_cast<ClassExpression const&>(expression);
  555. if (!class_expression.has_name()) {
  556. return TRY(class_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  557. }
  558. }
  559. return expression.generate_bytecode(*this, preferred_dst);
  560. }
  561. void Generator::emit_get_by_id(Operand dst, Operand base, IdentifierTableIndex property_identifier, Optional<IdentifierTableIndex> base_identifier)
  562. {
  563. emit<Op::GetById>(dst, base, property_identifier, move(base_identifier), m_next_property_lookup_cache++);
  564. }
  565. void Generator::emit_get_by_id_with_this(Operand dst, Operand base, IdentifierTableIndex id, Operand this_value)
  566. {
  567. emit<Op::GetByIdWithThis>(dst, base, id, this_value, m_next_property_lookup_cache++);
  568. }
  569. void Generator::emit_iterator_value(Operand dst, Operand result)
  570. {
  571. emit_get_by_id(dst, result, intern_identifier("value"sv));
  572. }
  573. void Generator::emit_iterator_complete(Operand dst, Operand result)
  574. {
  575. emit_get_by_id(dst, result, intern_identifier("done"sv));
  576. }
  577. bool Generator::is_local_initialized(u32 local_index) const
  578. {
  579. return m_initialized_locals.find(local_index) != m_initialized_locals.end();
  580. }
  581. void Generator::set_local_initialized(u32 local_index)
  582. {
  583. m_initialized_locals.set(local_index);
  584. }
  585. }