ASTCodegen.cpp 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627
  1. /*
  2. * Copyright (c) 2021-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Gunnar Beutner <gbeutner@serenityos.org>
  5. * Copyright (c) 2021, Marcin Gasperowicz <xnooga@gmail.com>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Find.h>
  10. #include <LibJS/AST.h>
  11. #include <LibJS/Bytecode/Generator.h>
  12. #include <LibJS/Bytecode/Instruction.h>
  13. #include <LibJS/Bytecode/Op.h>
  14. #include <LibJS/Bytecode/Register.h>
  15. #include <LibJS/Bytecode/StringTable.h>
  16. #include <LibJS/Runtime/Environment.h>
  17. #include <LibJS/Runtime/ErrorTypes.h>
  18. namespace JS {
  19. Bytecode::CodeGenerationErrorOr<void> ASTNode::generate_bytecode(Bytecode::Generator&) const
  20. {
  21. return Bytecode::CodeGenerationError {
  22. this,
  23. "Missing generate_bytecode()"sv,
  24. };
  25. }
  26. Bytecode::CodeGenerationErrorOr<void> ScopeNode::generate_bytecode(Bytecode::Generator& generator) const
  27. {
  28. Optional<Bytecode::CodeGenerationError> maybe_error;
  29. size_t pushed_scope_count = 0;
  30. auto const failing_completion = Completion(Completion::Type::Throw, {}, {});
  31. // Note: SwitchStatement has its own codegen, but still calls into this function to handle the scoping of the switch body.
  32. auto is_switch_statement = is<SwitchStatement>(*this);
  33. if (is<BlockStatement>(*this) || is_switch_statement) {
  34. // Perform the steps of BlockDeclarationInstantiation.
  35. if (has_lexical_declarations()) {
  36. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  37. pushed_scope_count++;
  38. }
  39. (void)for_each_lexically_scoped_declaration([&](Declaration const& declaration) -> ThrowCompletionOr<void> {
  40. auto is_constant_declaration = declaration.is_constant_declaration();
  41. // NOTE: Nothing in the callback throws an exception.
  42. MUST(declaration.for_each_bound_name([&](auto const& name) {
  43. auto index = generator.intern_identifier(name);
  44. // NOTE: BlockDeclarationInstantiation takes as input the new lexical environment that was created and checks if there is a binding for the current name only in this new scope.
  45. // For example: `{ let a = 1; { let a = 2; } }`. The second `a` will shadow the first `a` instead of re-initializing or setting it.
  46. if (is_constant_declaration || !generator.has_binding_in_current_scope(index)) {
  47. generator.register_binding(index);
  48. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_constant_declaration);
  49. }
  50. }));
  51. if (is<FunctionDeclaration>(declaration)) {
  52. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  53. auto const& name = function_declaration.name();
  54. auto index = generator.intern_identifier(name);
  55. generator.emit<Bytecode::Op::NewFunction>(function_declaration);
  56. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::InitializeOrSet);
  57. }
  58. return {};
  59. });
  60. if (is_switch_statement)
  61. return {};
  62. } else if (is<Program>(*this)) {
  63. // GlobalDeclarationInstantiation is handled by the C++ AO.
  64. } else {
  65. // FunctionDeclarationInstantiation is handled by the C++ AO.
  66. }
  67. if (maybe_error.has_value())
  68. return maybe_error.release_value();
  69. for (auto& child : children()) {
  70. TRY(child->generate_bytecode(generator));
  71. if (generator.is_current_block_terminated())
  72. break;
  73. }
  74. for (size_t i = 0; i < pushed_scope_count; ++i)
  75. generator.end_variable_scope();
  76. return {};
  77. }
  78. Bytecode::CodeGenerationErrorOr<void> EmptyStatement::generate_bytecode(Bytecode::Generator&) const
  79. {
  80. return {};
  81. }
  82. Bytecode::CodeGenerationErrorOr<void> ExpressionStatement::generate_bytecode(Bytecode::Generator& generator) const
  83. {
  84. return m_expression->generate_bytecode(generator);
  85. }
  86. Bytecode::CodeGenerationErrorOr<void> BinaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  87. {
  88. TRY(m_lhs->generate_bytecode(generator));
  89. auto lhs_reg = generator.allocate_register();
  90. generator.emit<Bytecode::Op::Store>(lhs_reg);
  91. TRY(m_rhs->generate_bytecode(generator));
  92. switch (m_op) {
  93. case BinaryOp::Addition:
  94. generator.emit<Bytecode::Op::Add>(lhs_reg);
  95. break;
  96. case BinaryOp::Subtraction:
  97. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  98. break;
  99. case BinaryOp::Multiplication:
  100. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  101. break;
  102. case BinaryOp::Division:
  103. generator.emit<Bytecode::Op::Div>(lhs_reg);
  104. break;
  105. case BinaryOp::Modulo:
  106. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  107. break;
  108. case BinaryOp::Exponentiation:
  109. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  110. break;
  111. case BinaryOp::GreaterThan:
  112. generator.emit<Bytecode::Op::GreaterThan>(lhs_reg);
  113. break;
  114. case BinaryOp::GreaterThanEquals:
  115. generator.emit<Bytecode::Op::GreaterThanEquals>(lhs_reg);
  116. break;
  117. case BinaryOp::LessThan:
  118. generator.emit<Bytecode::Op::LessThan>(lhs_reg);
  119. break;
  120. case BinaryOp::LessThanEquals:
  121. generator.emit<Bytecode::Op::LessThanEquals>(lhs_reg);
  122. break;
  123. case BinaryOp::LooselyInequals:
  124. generator.emit<Bytecode::Op::LooselyInequals>(lhs_reg);
  125. break;
  126. case BinaryOp::LooselyEquals:
  127. generator.emit<Bytecode::Op::LooselyEquals>(lhs_reg);
  128. break;
  129. case BinaryOp::StrictlyInequals:
  130. generator.emit<Bytecode::Op::StrictlyInequals>(lhs_reg);
  131. break;
  132. case BinaryOp::StrictlyEquals:
  133. generator.emit<Bytecode::Op::StrictlyEquals>(lhs_reg);
  134. break;
  135. case BinaryOp::BitwiseAnd:
  136. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  137. break;
  138. case BinaryOp::BitwiseOr:
  139. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  140. break;
  141. case BinaryOp::BitwiseXor:
  142. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  143. break;
  144. case BinaryOp::LeftShift:
  145. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  146. break;
  147. case BinaryOp::RightShift:
  148. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  149. break;
  150. case BinaryOp::UnsignedRightShift:
  151. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  152. break;
  153. case BinaryOp::In:
  154. generator.emit<Bytecode::Op::In>(lhs_reg);
  155. break;
  156. case BinaryOp::InstanceOf:
  157. generator.emit<Bytecode::Op::InstanceOf>(lhs_reg);
  158. break;
  159. default:
  160. VERIFY_NOT_REACHED();
  161. }
  162. return {};
  163. }
  164. Bytecode::CodeGenerationErrorOr<void> LogicalExpression::generate_bytecode(Bytecode::Generator& generator) const
  165. {
  166. TRY(m_lhs->generate_bytecode(generator));
  167. // lhs
  168. // jump op (true) end (false) rhs
  169. // rhs
  170. // jump always (true) end
  171. // end
  172. auto& rhs_block = generator.make_block();
  173. auto& end_block = generator.make_block();
  174. switch (m_op) {
  175. case LogicalOp::And:
  176. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  177. Bytecode::Label { rhs_block },
  178. Bytecode::Label { end_block });
  179. break;
  180. case LogicalOp::Or:
  181. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  182. Bytecode::Label { end_block },
  183. Bytecode::Label { rhs_block });
  184. break;
  185. case LogicalOp::NullishCoalescing:
  186. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  187. Bytecode::Label { rhs_block },
  188. Bytecode::Label { end_block });
  189. break;
  190. default:
  191. VERIFY_NOT_REACHED();
  192. }
  193. generator.switch_to_basic_block(rhs_block);
  194. TRY(m_rhs->generate_bytecode(generator));
  195. generator.emit<Bytecode::Op::Jump>().set_targets(
  196. Bytecode::Label { end_block },
  197. {});
  198. generator.switch_to_basic_block(end_block);
  199. return {};
  200. }
  201. Bytecode::CodeGenerationErrorOr<void> UnaryExpression::generate_bytecode(Bytecode::Generator& generator) const
  202. {
  203. if (m_op == UnaryOp::Delete)
  204. return generator.emit_delete_reference(m_lhs);
  205. // Typeof needs some special handling for when the LHS is an Identifier. Namely, it shouldn't throw on unresolvable references, but instead return "undefined".
  206. if (m_op != UnaryOp::Typeof)
  207. TRY(m_lhs->generate_bytecode(generator));
  208. switch (m_op) {
  209. case UnaryOp::BitwiseNot:
  210. generator.emit<Bytecode::Op::BitwiseNot>();
  211. break;
  212. case UnaryOp::Not:
  213. generator.emit<Bytecode::Op::Not>();
  214. break;
  215. case UnaryOp::Plus:
  216. generator.emit<Bytecode::Op::UnaryPlus>();
  217. break;
  218. case UnaryOp::Minus:
  219. generator.emit<Bytecode::Op::UnaryMinus>();
  220. break;
  221. case UnaryOp::Typeof:
  222. if (is<Identifier>(*m_lhs)) {
  223. auto& identifier = static_cast<Identifier const&>(*m_lhs);
  224. generator.emit<Bytecode::Op::TypeofVariable>(generator.intern_identifier(identifier.string()));
  225. break;
  226. }
  227. TRY(m_lhs->generate_bytecode(generator));
  228. generator.emit<Bytecode::Op::Typeof>();
  229. break;
  230. case UnaryOp::Void:
  231. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  232. break;
  233. case UnaryOp::Delete: // Delete is implemented above.
  234. default:
  235. VERIFY_NOT_REACHED();
  236. }
  237. return {};
  238. }
  239. Bytecode::CodeGenerationErrorOr<void> NumericLiteral::generate_bytecode(Bytecode::Generator& generator) const
  240. {
  241. generator.emit<Bytecode::Op::LoadImmediate>(m_value);
  242. return {};
  243. }
  244. Bytecode::CodeGenerationErrorOr<void> BooleanLiteral::generate_bytecode(Bytecode::Generator& generator) const
  245. {
  246. generator.emit<Bytecode::Op::LoadImmediate>(Value(m_value));
  247. return {};
  248. }
  249. Bytecode::CodeGenerationErrorOr<void> NullLiteral::generate_bytecode(Bytecode::Generator& generator) const
  250. {
  251. generator.emit<Bytecode::Op::LoadImmediate>(js_null());
  252. return {};
  253. }
  254. Bytecode::CodeGenerationErrorOr<void> BigIntLiteral::generate_bytecode(Bytecode::Generator& generator) const
  255. {
  256. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  257. auto integer = [&] {
  258. if (m_value[0] == '0' && m_value.length() >= 3)
  259. if (m_value[1] == 'x' || m_value[1] == 'X')
  260. return Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3));
  261. if (m_value[1] == 'o' || m_value[1] == 'O')
  262. return Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3));
  263. if (m_value[1] == 'b' || m_value[1] == 'B')
  264. return Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3));
  265. return Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1));
  266. }();
  267. generator.emit<Bytecode::Op::NewBigInt>(integer);
  268. return {};
  269. }
  270. Bytecode::CodeGenerationErrorOr<void> StringLiteral::generate_bytecode(Bytecode::Generator& generator) const
  271. {
  272. generator.emit<Bytecode::Op::NewString>(generator.intern_string(m_value));
  273. return {};
  274. }
  275. Bytecode::CodeGenerationErrorOr<void> RegExpLiteral::generate_bytecode(Bytecode::Generator& generator) const
  276. {
  277. auto source_index = generator.intern_string(m_pattern);
  278. auto flags_index = generator.intern_string(m_flags);
  279. generator.emit<Bytecode::Op::NewRegExp>(source_index, flags_index);
  280. return {};
  281. }
  282. Bytecode::CodeGenerationErrorOr<void> Identifier::generate_bytecode(Bytecode::Generator& generator) const
  283. {
  284. generator.emit<Bytecode::Op::GetVariable>(generator.intern_identifier(m_string));
  285. return {};
  286. }
  287. static Bytecode::CodeGenerationErrorOr<void> arguments_to_array_for_call(Bytecode::Generator& generator, ReadonlySpan<CallExpression::Argument> arguments)
  288. {
  289. if (arguments.is_empty()) {
  290. generator.emit<Bytecode::Op::NewArray>();
  291. return {};
  292. }
  293. auto first_spread = find_if(arguments.begin(), arguments.end(), [](auto el) { return el.is_spread; });
  294. Bytecode::Register args_start_reg { 0 };
  295. for (auto it = arguments.begin(); it != first_spread; ++it) {
  296. auto reg = generator.allocate_register();
  297. if (args_start_reg.index() == 0)
  298. args_start_reg = reg;
  299. }
  300. u32 i = 0;
  301. for (auto it = arguments.begin(); it != first_spread; ++it, ++i) {
  302. VERIFY(it->is_spread == false);
  303. Bytecode::Register reg { args_start_reg.index() + i };
  304. TRY(it->value->generate_bytecode(generator));
  305. generator.emit<Bytecode::Op::Store>(reg);
  306. }
  307. if (first_spread.index() != 0)
  308. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { args_start_reg, Bytecode::Register { args_start_reg.index() + static_cast<u32>(first_spread.index() - 1) } });
  309. else
  310. generator.emit<Bytecode::Op::NewArray>();
  311. if (first_spread != arguments.end()) {
  312. auto array_reg = generator.allocate_register();
  313. generator.emit<Bytecode::Op::Store>(array_reg);
  314. for (auto it = first_spread; it != arguments.end(); ++it) {
  315. TRY(it->value->generate_bytecode(generator));
  316. generator.emit<Bytecode::Op::Append>(array_reg, it->is_spread);
  317. }
  318. generator.emit<Bytecode::Op::Load>(array_reg);
  319. }
  320. return {};
  321. }
  322. Bytecode::CodeGenerationErrorOr<void> SuperCall::generate_bytecode(Bytecode::Generator& generator) const
  323. {
  324. if (m_is_synthetic == IsPartOfSyntheticConstructor::Yes) {
  325. // NOTE: This is the case where we have a fake constructor(...args) { super(...args); } which
  326. // shouldn't call @@iterator of %Array.prototype%.
  327. VERIFY(m_arguments.size() == 1);
  328. VERIFY(m_arguments[0].is_spread);
  329. auto const& argument = m_arguments[0];
  330. // This generates a single argument, which will be implicitly passed in accumulator
  331. MUST(argument.value->generate_bytecode(generator));
  332. } else {
  333. TRY(arguments_to_array_for_call(generator, m_arguments));
  334. }
  335. generator.emit<Bytecode::Op::SuperCall>(m_is_synthetic == IsPartOfSyntheticConstructor::Yes);
  336. return {};
  337. }
  338. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode, Bytecode::Register const& value_reg);
  339. Bytecode::CodeGenerationErrorOr<void> AssignmentExpression::generate_bytecode(Bytecode::Generator& generator) const
  340. {
  341. if (m_op == AssignmentOp::Assignment) {
  342. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  343. return m_lhs.visit(
  344. // 1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
  345. [&](NonnullRefPtr<Expression const> const& lhs) -> Bytecode::CodeGenerationErrorOr<void> {
  346. // a. Let lref be the result of evaluating LeftHandSideExpression.
  347. // b. ReturnIfAbrupt(lref).
  348. Optional<Bytecode::Register> base_object_register;
  349. Optional<Bytecode::Register> computed_property_register;
  350. if (is<MemberExpression>(*lhs)) {
  351. auto& expression = static_cast<MemberExpression const&>(*lhs);
  352. TRY(expression.object().generate_bytecode(generator));
  353. base_object_register = generator.allocate_register();
  354. generator.emit<Bytecode::Op::Store>(*base_object_register);
  355. if (expression.is_computed()) {
  356. TRY(expression.property().generate_bytecode(generator));
  357. computed_property_register = generator.allocate_register();
  358. generator.emit<Bytecode::Op::Store>(*computed_property_register);
  359. // To be continued later with PutByValue.
  360. } else if (expression.property().is_identifier()) {
  361. // Do nothing, this will be handled by PutById later.
  362. } else {
  363. return Bytecode::CodeGenerationError {
  364. &expression,
  365. "Unimplemented non-computed member expression"sv
  366. };
  367. }
  368. } else if (is<Identifier>(*lhs)) {
  369. // NOTE: For Identifiers, we cannot perform GetVariable and then write into the reference it retrieves, only SetVariable can do this.
  370. // FIXME: However, this breaks spec as we are doing variable lookup after evaluating the RHS. This is observable in an object environment, where we visibly perform HasOwnProperty and Get(@@unscopables) on the binded object.
  371. } else {
  372. TRY(lhs->generate_bytecode(generator));
  373. }
  374. // FIXME: c. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
  375. // i. Let rval be ? NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  376. // d. Else,
  377. // i. Let rref be the result of evaluating AssignmentExpression.
  378. // ii. Let rval be ? GetValue(rref).
  379. TRY(m_rhs->generate_bytecode(generator));
  380. // e. Perform ? PutValue(lref, rval).
  381. if (is<Identifier>(*lhs)) {
  382. auto& identifier = static_cast<Identifier const&>(*lhs);
  383. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier.string()));
  384. } else if (is<MemberExpression>(*lhs)) {
  385. auto& expression = static_cast<MemberExpression const&>(*lhs);
  386. if (expression.is_computed()) {
  387. generator.emit<Bytecode::Op::PutByValue>(*base_object_register, *computed_property_register);
  388. } else if (expression.property().is_identifier()) {
  389. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(expression.property()).string());
  390. generator.emit<Bytecode::Op::PutById>(*base_object_register, identifier_table_ref);
  391. } else {
  392. return Bytecode::CodeGenerationError {
  393. &expression,
  394. "Unimplemented non-computed member expression"sv
  395. };
  396. }
  397. } else {
  398. return Bytecode::CodeGenerationError {
  399. lhs,
  400. "Unimplemented/invalid node used a reference"sv
  401. };
  402. }
  403. // f. Return rval.
  404. // NOTE: This is already in the accumulator.
  405. return {};
  406. },
  407. // 2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  408. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  409. // 3. Let rref be the result of evaluating AssignmentExpression.
  410. // 4. Let rval be ? GetValue(rref).
  411. TRY(m_rhs->generate_bytecode(generator));
  412. auto value_register = generator.allocate_register();
  413. generator.emit<Bytecode::Op::Store>(value_register);
  414. // 5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern with argument rval.
  415. TRY(generate_binding_pattern_bytecode(generator, pattern, Bytecode::Op::SetVariable::InitializationMode::Set, value_register));
  416. // 6. Return rval.
  417. generator.emit<Bytecode::Op::Load>(value_register);
  418. return {};
  419. });
  420. }
  421. VERIFY(m_lhs.has<NonnullRefPtr<Expression const>>());
  422. auto& lhs = m_lhs.get<NonnullRefPtr<Expression const>>();
  423. TRY(generator.emit_load_from_reference(lhs));
  424. Bytecode::BasicBlock* rhs_block_ptr { nullptr };
  425. Bytecode::BasicBlock* end_block_ptr { nullptr };
  426. // Logical assignments short circuit.
  427. if (m_op == AssignmentOp::AndAssignment) { // &&=
  428. rhs_block_ptr = &generator.make_block();
  429. end_block_ptr = &generator.make_block();
  430. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  431. Bytecode::Label { *rhs_block_ptr },
  432. Bytecode::Label { *end_block_ptr });
  433. } else if (m_op == AssignmentOp::OrAssignment) { // ||=
  434. rhs_block_ptr = &generator.make_block();
  435. end_block_ptr = &generator.make_block();
  436. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  437. Bytecode::Label { *end_block_ptr },
  438. Bytecode::Label { *rhs_block_ptr });
  439. } else if (m_op == AssignmentOp::NullishAssignment) { // ??=
  440. rhs_block_ptr = &generator.make_block();
  441. end_block_ptr = &generator.make_block();
  442. generator.emit<Bytecode::Op::JumpNullish>().set_targets(
  443. Bytecode::Label { *rhs_block_ptr },
  444. Bytecode::Label { *end_block_ptr });
  445. }
  446. if (rhs_block_ptr)
  447. generator.switch_to_basic_block(*rhs_block_ptr);
  448. // lhs_reg is a part of the rhs_block because the store isn't necessary
  449. // if the logical assignment condition fails.
  450. auto lhs_reg = generator.allocate_register();
  451. generator.emit<Bytecode::Op::Store>(lhs_reg);
  452. TRY(m_rhs->generate_bytecode(generator));
  453. switch (m_op) {
  454. case AssignmentOp::AdditionAssignment:
  455. generator.emit<Bytecode::Op::Add>(lhs_reg);
  456. break;
  457. case AssignmentOp::SubtractionAssignment:
  458. generator.emit<Bytecode::Op::Sub>(lhs_reg);
  459. break;
  460. case AssignmentOp::MultiplicationAssignment:
  461. generator.emit<Bytecode::Op::Mul>(lhs_reg);
  462. break;
  463. case AssignmentOp::DivisionAssignment:
  464. generator.emit<Bytecode::Op::Div>(lhs_reg);
  465. break;
  466. case AssignmentOp::ModuloAssignment:
  467. generator.emit<Bytecode::Op::Mod>(lhs_reg);
  468. break;
  469. case AssignmentOp::ExponentiationAssignment:
  470. generator.emit<Bytecode::Op::Exp>(lhs_reg);
  471. break;
  472. case AssignmentOp::BitwiseAndAssignment:
  473. generator.emit<Bytecode::Op::BitwiseAnd>(lhs_reg);
  474. break;
  475. case AssignmentOp::BitwiseOrAssignment:
  476. generator.emit<Bytecode::Op::BitwiseOr>(lhs_reg);
  477. break;
  478. case AssignmentOp::BitwiseXorAssignment:
  479. generator.emit<Bytecode::Op::BitwiseXor>(lhs_reg);
  480. break;
  481. case AssignmentOp::LeftShiftAssignment:
  482. generator.emit<Bytecode::Op::LeftShift>(lhs_reg);
  483. break;
  484. case AssignmentOp::RightShiftAssignment:
  485. generator.emit<Bytecode::Op::RightShift>(lhs_reg);
  486. break;
  487. case AssignmentOp::UnsignedRightShiftAssignment:
  488. generator.emit<Bytecode::Op::UnsignedRightShift>(lhs_reg);
  489. break;
  490. case AssignmentOp::AndAssignment:
  491. case AssignmentOp::OrAssignment:
  492. case AssignmentOp::NullishAssignment:
  493. break; // These are handled above.
  494. default:
  495. return Bytecode::CodeGenerationError {
  496. this,
  497. "Unimplemented operation"sv,
  498. };
  499. }
  500. TRY(generator.emit_store_to_reference(lhs));
  501. if (end_block_ptr) {
  502. generator.emit<Bytecode::Op::Jump>().set_targets(
  503. Bytecode::Label { *end_block_ptr },
  504. {});
  505. generator.switch_to_basic_block(*end_block_ptr);
  506. }
  507. return {};
  508. }
  509. // 14.13.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-labelled-statements-runtime-semantics-evaluation
  510. // LabelledStatement : LabelIdentifier : LabelledItem
  511. Bytecode::CodeGenerationErrorOr<void> LabelledStatement::generate_bytecode(Bytecode::Generator& generator) const
  512. {
  513. // Return ? LabelledEvaluation of this LabelledStatement with argument « ».
  514. return generate_labelled_evaluation(generator, {});
  515. }
  516. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  517. // LabelledStatement : LabelIdentifier : LabelledItem
  518. Bytecode::CodeGenerationErrorOr<void> LabelledStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  519. {
  520. // Convert the m_labelled_item NNRP to a reference early so we don't have to do it every single time we want to use it.
  521. auto const& labelled_item = *m_labelled_item;
  522. // 1. Let label be the StringValue of LabelIdentifier.
  523. // NOTE: Not necessary, this is m_label.
  524. // 2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  525. // FIXME: Avoid copy here.
  526. auto new_label_set = label_set;
  527. new_label_set.append(m_label);
  528. // 3. Let stmtResult be LabelledEvaluation of LabelledItem with argument newLabelSet.
  529. // NOTE: stmtResult will be in the accumulator after running the generated bytecode.
  530. if (is<IterationStatement>(labelled_item)) {
  531. auto const& iteration_statement = static_cast<IterationStatement const&>(labelled_item);
  532. TRY(iteration_statement.generate_labelled_evaluation(generator, new_label_set));
  533. } else if (is<SwitchStatement>(labelled_item)) {
  534. auto const& switch_statement = static_cast<SwitchStatement const&>(labelled_item);
  535. TRY(switch_statement.generate_labelled_evaluation(generator, new_label_set));
  536. } else if (is<LabelledStatement>(labelled_item)) {
  537. auto const& labelled_statement = static_cast<LabelledStatement const&>(labelled_item);
  538. TRY(labelled_statement.generate_labelled_evaluation(generator, new_label_set));
  539. } else {
  540. auto& labelled_break_block = generator.make_block();
  541. // NOTE: We do not need a continuable scope as `continue;` is not allowed outside of iteration statements, throwing a SyntaxError in the parser.
  542. generator.begin_breakable_scope(Bytecode::Label { labelled_break_block }, new_label_set);
  543. TRY(labelled_item.generate_bytecode(generator));
  544. generator.end_breakable_scope();
  545. if (!generator.is_current_block_terminated()) {
  546. generator.emit<Bytecode::Op::Jump>().set_targets(
  547. Bytecode::Label { labelled_break_block },
  548. {});
  549. }
  550. generator.switch_to_basic_block(labelled_break_block);
  551. }
  552. // 4. If stmtResult.[[Type]] is break and SameValue(stmtResult.[[Target]], label) is true, then
  553. // a. Set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  554. // NOTE: These steps are performed by making labelled break jump straight to the appropriate break block, which preserves the statement result's value in the accumulator.
  555. // 5. Return Completion(stmtResult).
  556. // NOTE: This is in the accumulator.
  557. return {};
  558. }
  559. Bytecode::CodeGenerationErrorOr<void> IterationStatement::generate_labelled_evaluation(Bytecode::Generator&, Vector<DeprecatedFlyString> const&) const
  560. {
  561. return Bytecode::CodeGenerationError {
  562. this,
  563. "Missing generate_labelled_evaluation()"sv,
  564. };
  565. }
  566. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  567. {
  568. return generate_labelled_evaluation(generator, {});
  569. }
  570. Bytecode::CodeGenerationErrorOr<void> WhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  571. {
  572. // test
  573. // jump if_false (true) end (false) body
  574. // body
  575. // jump always (true) test
  576. // end
  577. auto& test_block = generator.make_block();
  578. auto& body_block = generator.make_block();
  579. auto& end_block = generator.make_block();
  580. // Init result register
  581. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  582. auto result_reg = generator.allocate_register();
  583. generator.emit<Bytecode::Op::Store>(result_reg);
  584. // jump to the test block
  585. generator.emit<Bytecode::Op::Jump>().set_targets(
  586. Bytecode::Label { test_block },
  587. {});
  588. generator.switch_to_basic_block(test_block);
  589. TRY(m_test->generate_bytecode(generator));
  590. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  591. Bytecode::Label { body_block },
  592. Bytecode::Label { end_block });
  593. generator.switch_to_basic_block(body_block);
  594. generator.begin_continuable_scope(Bytecode::Label { test_block }, label_set);
  595. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  596. TRY(m_body->generate_bytecode(generator));
  597. generator.end_breakable_scope();
  598. generator.end_continuable_scope();
  599. if (!generator.is_current_block_terminated()) {
  600. generator.emit<Bytecode::Op::Jump>().set_targets(
  601. Bytecode::Label { test_block },
  602. {});
  603. }
  604. generator.switch_to_basic_block(end_block);
  605. generator.emit<Bytecode::Op::Load>(result_reg);
  606. return {};
  607. }
  608. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_bytecode(Bytecode::Generator& generator) const
  609. {
  610. return generate_labelled_evaluation(generator, {});
  611. }
  612. Bytecode::CodeGenerationErrorOr<void> DoWhileStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  613. {
  614. // jump always (true) body
  615. // test
  616. // jump if_false (true) end (false) body
  617. // body
  618. // jump always (true) test
  619. // end
  620. auto& test_block = generator.make_block();
  621. auto& body_block = generator.make_block();
  622. auto& end_block = generator.make_block();
  623. // Init result register
  624. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  625. auto result_reg = generator.allocate_register();
  626. generator.emit<Bytecode::Op::Store>(result_reg);
  627. // jump to the body block
  628. generator.emit<Bytecode::Op::Jump>().set_targets(
  629. Bytecode::Label { body_block },
  630. {});
  631. generator.switch_to_basic_block(test_block);
  632. TRY(m_test->generate_bytecode(generator));
  633. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  634. Bytecode::Label { body_block },
  635. Bytecode::Label { end_block });
  636. generator.switch_to_basic_block(body_block);
  637. generator.begin_continuable_scope(Bytecode::Label { test_block }, label_set);
  638. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  639. TRY(m_body->generate_bytecode(generator));
  640. generator.end_breakable_scope();
  641. generator.end_continuable_scope();
  642. if (!generator.is_current_block_terminated()) {
  643. generator.emit<Bytecode::Op::Jump>().set_targets(
  644. Bytecode::Label { test_block },
  645. {});
  646. }
  647. generator.switch_to_basic_block(end_block);
  648. generator.emit<Bytecode::Op::Load>(result_reg);
  649. return {};
  650. }
  651. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_bytecode(Bytecode::Generator& generator) const
  652. {
  653. return generate_labelled_evaluation(generator, {});
  654. }
  655. Bytecode::CodeGenerationErrorOr<void> ForStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  656. {
  657. // init
  658. // jump always (true) test
  659. // test
  660. // jump if_true (true) body (false) end
  661. // body
  662. // jump always (true) update
  663. // update
  664. // jump always (true) test
  665. // end
  666. // If 'test' is missing, fuse the 'test' and 'body' basic blocks
  667. // If 'update' is missing, fuse the 'body' and 'update' basic blocks
  668. Bytecode::BasicBlock* test_block_ptr { nullptr };
  669. Bytecode::BasicBlock* body_block_ptr { nullptr };
  670. Bytecode::BasicBlock* update_block_ptr { nullptr };
  671. auto& end_block = generator.make_block();
  672. bool has_lexical_environment = false;
  673. if (m_init) {
  674. if (m_init->is_variable_declaration()) {
  675. auto& variable_declaration = verify_cast<VariableDeclaration>(*m_init);
  676. if (variable_declaration.is_lexical_declaration()) {
  677. has_lexical_environment = true;
  678. // FIXME: Is Block correct?
  679. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  680. bool is_const = variable_declaration.is_constant_declaration();
  681. // NOTE: Nothing in the callback throws an exception.
  682. MUST(variable_declaration.for_each_bound_name([&](auto const& name) {
  683. auto index = generator.intern_identifier(name);
  684. generator.register_binding(index);
  685. generator.emit<Bytecode::Op::CreateVariable>(index, Bytecode::Op::EnvironmentMode::Lexical, is_const);
  686. }));
  687. }
  688. }
  689. TRY(m_init->generate_bytecode(generator));
  690. }
  691. body_block_ptr = &generator.make_block();
  692. if (m_test)
  693. test_block_ptr = &generator.make_block();
  694. else
  695. test_block_ptr = body_block_ptr;
  696. if (m_update)
  697. update_block_ptr = &generator.make_block();
  698. else
  699. update_block_ptr = body_block_ptr;
  700. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  701. auto result_reg = generator.allocate_register();
  702. generator.emit<Bytecode::Op::Store>(result_reg);
  703. generator.emit<Bytecode::Op::Jump>().set_targets(
  704. Bytecode::Label { *test_block_ptr },
  705. {});
  706. if (m_test) {
  707. generator.switch_to_basic_block(*test_block_ptr);
  708. TRY(m_test->generate_bytecode(generator));
  709. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  710. Bytecode::Label { *body_block_ptr },
  711. Bytecode::Label { end_block });
  712. }
  713. if (m_update) {
  714. generator.switch_to_basic_block(*update_block_ptr);
  715. TRY(m_update->generate_bytecode(generator));
  716. generator.emit<Bytecode::Op::Jump>().set_targets(
  717. Bytecode::Label { *test_block_ptr },
  718. {});
  719. }
  720. generator.switch_to_basic_block(*body_block_ptr);
  721. generator.begin_continuable_scope(Bytecode::Label { m_update ? *update_block_ptr : *test_block_ptr }, label_set);
  722. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  723. TRY(m_body->generate_bytecode(generator));
  724. generator.end_breakable_scope();
  725. generator.end_continuable_scope();
  726. if (!generator.is_current_block_terminated()) {
  727. if (m_update) {
  728. generator.emit<Bytecode::Op::Jump>().set_targets(
  729. Bytecode::Label { *update_block_ptr },
  730. {});
  731. } else {
  732. generator.emit<Bytecode::Op::Jump>().set_targets(
  733. Bytecode::Label { *test_block_ptr },
  734. {});
  735. }
  736. }
  737. generator.switch_to_basic_block(end_block);
  738. generator.emit<Bytecode::Op::Load>(result_reg);
  739. if (has_lexical_environment)
  740. generator.end_variable_scope();
  741. return {};
  742. }
  743. Bytecode::CodeGenerationErrorOr<void> ObjectExpression::generate_bytecode(Bytecode::Generator& generator) const
  744. {
  745. generator.emit<Bytecode::Op::NewObject>();
  746. if (m_properties.is_empty())
  747. return {};
  748. auto object_reg = generator.allocate_register();
  749. generator.emit<Bytecode::Op::Store>(object_reg);
  750. for (auto& property : m_properties) {
  751. Bytecode::Op::PropertyKind property_kind;
  752. switch (property->type()) {
  753. case ObjectProperty::Type::KeyValue:
  754. property_kind = Bytecode::Op::PropertyKind::KeyValue;
  755. break;
  756. case ObjectProperty::Type::Getter:
  757. property_kind = Bytecode::Op::PropertyKind::Getter;
  758. break;
  759. case ObjectProperty::Type::Setter:
  760. property_kind = Bytecode::Op::PropertyKind::Setter;
  761. break;
  762. case ObjectProperty::Type::Spread:
  763. property_kind = Bytecode::Op::PropertyKind::Spread;
  764. break;
  765. case ObjectProperty::Type::ProtoSetter:
  766. property_kind = Bytecode::Op::PropertyKind::ProtoSetter;
  767. break;
  768. }
  769. if (is<StringLiteral>(property->key())) {
  770. auto& string_literal = static_cast<StringLiteral const&>(property->key());
  771. Bytecode::IdentifierTableIndex key_name = generator.intern_identifier(string_literal.value());
  772. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  773. TRY(property->value().generate_bytecode(generator));
  774. generator.emit<Bytecode::Op::PutById>(object_reg, key_name, property_kind);
  775. } else {
  776. TRY(property->key().generate_bytecode(generator));
  777. auto property_reg = generator.allocate_register();
  778. generator.emit<Bytecode::Op::Store>(property_reg);
  779. if (property_kind != Bytecode::Op::PropertyKind::Spread)
  780. TRY(property->value().generate_bytecode(generator));
  781. generator.emit<Bytecode::Op::PutByValue>(object_reg, property_reg, property_kind);
  782. }
  783. }
  784. generator.emit<Bytecode::Op::Load>(object_reg);
  785. return {};
  786. }
  787. Bytecode::CodeGenerationErrorOr<void> ArrayExpression::generate_bytecode(Bytecode::Generator& generator) const
  788. {
  789. if (m_elements.is_empty()) {
  790. generator.emit<Bytecode::Op::NewArray>();
  791. return {};
  792. }
  793. auto first_spread = find_if(m_elements.begin(), m_elements.end(), [](auto el) { return el && is<SpreadExpression>(*el); });
  794. Bytecode::Register args_start_reg { 0 };
  795. for (auto it = m_elements.begin(); it != first_spread; ++it) {
  796. auto reg = generator.allocate_register();
  797. if (args_start_reg.index() == 0)
  798. args_start_reg = reg;
  799. }
  800. u32 i = 0;
  801. for (auto it = m_elements.begin(); it != first_spread; ++it, ++i) {
  802. Bytecode::Register reg { args_start_reg.index() + i };
  803. if (!*it)
  804. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  805. else {
  806. TRY((*it)->generate_bytecode(generator));
  807. }
  808. generator.emit<Bytecode::Op::Store>(reg);
  809. }
  810. if (first_spread.index() != 0)
  811. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { args_start_reg, Bytecode::Register { args_start_reg.index() + static_cast<u32>(first_spread.index() - 1) } });
  812. else
  813. generator.emit<Bytecode::Op::NewArray>();
  814. if (first_spread != m_elements.end()) {
  815. auto array_reg = generator.allocate_register();
  816. generator.emit<Bytecode::Op::Store>(array_reg);
  817. for (auto it = first_spread; it != m_elements.end(); ++it) {
  818. if (!*it) {
  819. generator.emit<Bytecode::Op::LoadImmediate>(Value {});
  820. generator.emit<Bytecode::Op::Append>(array_reg, false);
  821. } else {
  822. TRY((*it)->generate_bytecode(generator));
  823. generator.emit<Bytecode::Op::Append>(array_reg, *it && is<SpreadExpression>(**it));
  824. }
  825. }
  826. generator.emit<Bytecode::Op::Load>(array_reg);
  827. }
  828. return {};
  829. }
  830. Bytecode::CodeGenerationErrorOr<void> MemberExpression::generate_bytecode(Bytecode::Generator& generator) const
  831. {
  832. return generator.emit_load_from_reference(*this);
  833. }
  834. Bytecode::CodeGenerationErrorOr<void> FunctionDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  835. {
  836. if (m_is_hoisted) {
  837. auto index = generator.intern_identifier(name());
  838. generator.emit<Bytecode::Op::GetVariable>(index);
  839. generator.emit<Bytecode::Op::SetVariable>(index, Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode::Var);
  840. }
  841. return {};
  842. }
  843. Bytecode::CodeGenerationErrorOr<void> FunctionExpression::generate_bytecode(Bytecode::Generator& generator) const
  844. {
  845. bool has_name = !name().is_empty();
  846. Optional<Bytecode::IdentifierTableIndex> name_identifier;
  847. if (has_name) {
  848. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  849. name_identifier = generator.intern_identifier(name());
  850. generator.emit<Bytecode::Op::CreateVariable>(*name_identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  851. }
  852. generator.emit<Bytecode::Op::NewFunction>(*this);
  853. if (has_name) {
  854. generator.emit<Bytecode::Op::SetVariable>(*name_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  855. generator.end_variable_scope();
  856. }
  857. return {};
  858. }
  859. static Bytecode::CodeGenerationErrorOr<void> generate_object_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
  860. {
  861. Vector<Bytecode::Register> excluded_property_names;
  862. auto has_rest = false;
  863. if (pattern.entries.size() > 0)
  864. has_rest = pattern.entries[pattern.entries.size() - 1].is_rest;
  865. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  866. if (is_rest) {
  867. VERIFY(name.has<NonnullRefPtr<Identifier const>>());
  868. VERIFY(alias.has<Empty>());
  869. VERIFY(!initializer);
  870. auto identifier = name.get<NonnullRefPtr<Identifier const>>()->string();
  871. auto interned_identifier = generator.intern_identifier(identifier);
  872. generator.emit_with_extra_register_slots<Bytecode::Op::CopyObjectExcludingProperties>(excluded_property_names.size(), value_reg, excluded_property_names);
  873. generator.emit<Bytecode::Op::SetVariable>(interned_identifier, initialization_mode);
  874. return {};
  875. }
  876. Bytecode::StringTableIndex name_index;
  877. if (name.has<NonnullRefPtr<Identifier const>>()) {
  878. auto identifier = name.get<NonnullRefPtr<Identifier const>>()->string();
  879. name_index = generator.intern_string(identifier);
  880. if (has_rest) {
  881. auto excluded_name_reg = generator.allocate_register();
  882. excluded_property_names.append(excluded_name_reg);
  883. generator.emit<Bytecode::Op::NewString>(name_index);
  884. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  885. }
  886. generator.emit<Bytecode::Op::Load>(value_reg);
  887. generator.emit<Bytecode::Op::GetById>(generator.intern_identifier(identifier));
  888. } else {
  889. auto expression = name.get<NonnullRefPtr<Expression const>>();
  890. TRY(expression->generate_bytecode(generator));
  891. if (has_rest) {
  892. auto excluded_name_reg = generator.allocate_register();
  893. excluded_property_names.append(excluded_name_reg);
  894. generator.emit<Bytecode::Op::Store>(excluded_name_reg);
  895. }
  896. generator.emit<Bytecode::Op::GetByValue>(value_reg);
  897. }
  898. if (initializer) {
  899. auto& if_undefined_block = generator.make_block();
  900. auto& if_not_undefined_block = generator.make_block();
  901. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  902. Bytecode::Label { if_undefined_block },
  903. Bytecode::Label { if_not_undefined_block });
  904. generator.switch_to_basic_block(if_undefined_block);
  905. TRY(initializer->generate_bytecode(generator));
  906. generator.emit<Bytecode::Op::Jump>().set_targets(
  907. Bytecode::Label { if_not_undefined_block },
  908. {});
  909. generator.switch_to_basic_block(if_not_undefined_block);
  910. }
  911. if (alias.has<NonnullRefPtr<BindingPattern const>>()) {
  912. auto& binding_pattern = *alias.get<NonnullRefPtr<BindingPattern const>>();
  913. auto nested_value_reg = generator.allocate_register();
  914. generator.emit<Bytecode::Op::Store>(nested_value_reg);
  915. TRY(generate_binding_pattern_bytecode(generator, binding_pattern, initialization_mode, nested_value_reg));
  916. } else if (alias.has<Empty>()) {
  917. if (name.has<NonnullRefPtr<Expression const>>()) {
  918. // This needs some sort of SetVariableByValue opcode, as it's a runtime binding
  919. return Bytecode::CodeGenerationError {
  920. name.get<NonnullRefPtr<Expression const>>().ptr(),
  921. "Unimplemented name/alias pair: Empty/Expression"sv,
  922. };
  923. }
  924. auto& identifier = name.get<NonnullRefPtr<Identifier const>>()->string();
  925. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  926. } else {
  927. auto& identifier = alias.get<NonnullRefPtr<Identifier const>>()->string();
  928. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(identifier), initialization_mode);
  929. }
  930. }
  931. return {};
  932. }
  933. static Bytecode::CodeGenerationErrorOr<void> generate_array_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
  934. {
  935. /*
  936. * Consider the following destructuring assignment:
  937. *
  938. * let [a, b, c, d, e] = o;
  939. *
  940. * It would be fairly trivial to just loop through this iterator, getting the value
  941. * at each step and assigning them to the binding sequentially. However, this is not
  942. * correct: once an iterator is exhausted, it must not be called again. This complicates
  943. * the bytecode. In order to accomplish this, we do the following:
  944. *
  945. * - Reserve a special boolean register which holds 'true' if the iterator is exhausted,
  946. * and false otherwise
  947. * - When we are retrieving the value which should be bound, we first check this register.
  948. * If it is 'true', we load undefined into the accumulator. Otherwise, we grab the next
  949. * value from the iterator and store it into the accumulator.
  950. *
  951. * Note that the is_exhausted register does not need to be loaded with false because the
  952. * first IteratorNext bytecode is _not_ proceeded by an exhausted check, as it is
  953. * unnecessary.
  954. */
  955. auto is_iterator_exhausted_register = generator.allocate_register();
  956. auto iterator_reg = generator.allocate_register();
  957. generator.emit<Bytecode::Op::Load>(value_reg);
  958. generator.emit<Bytecode::Op::GetIterator>();
  959. generator.emit<Bytecode::Op::Store>(iterator_reg);
  960. bool first = true;
  961. auto temp_iterator_result_reg = generator.allocate_register();
  962. auto assign_accumulator_to_alias = [&](auto& alias) {
  963. return alias.visit(
  964. [&](Empty) -> Bytecode::CodeGenerationErrorOr<void> {
  965. // This element is an elision
  966. return {};
  967. },
  968. [&](NonnullRefPtr<Identifier const> const& identifier) -> Bytecode::CodeGenerationErrorOr<void> {
  969. auto interned_index = generator.intern_identifier(identifier->string());
  970. generator.emit<Bytecode::Op::SetVariable>(interned_index, initialization_mode);
  971. return {};
  972. },
  973. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  974. // Store the accumulator value in a permanent register
  975. auto target_reg = generator.allocate_register();
  976. generator.emit<Bytecode::Op::Store>(target_reg);
  977. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, target_reg);
  978. },
  979. [&](NonnullRefPtr<MemberExpression const> const& expr) -> Bytecode::CodeGenerationErrorOr<void> {
  980. return generator.emit_store_to_reference(*expr);
  981. });
  982. };
  983. for (auto& [name, alias, initializer, is_rest] : pattern.entries) {
  984. VERIFY(name.has<Empty>());
  985. if (is_rest) {
  986. VERIFY(!initializer);
  987. if (first) {
  988. // The iterator has not been called, and is thus known to be not exhausted
  989. generator.emit<Bytecode::Op::Load>(iterator_reg);
  990. generator.emit<Bytecode::Op::IteratorToArray>();
  991. } else {
  992. auto& if_exhausted_block = generator.make_block();
  993. auto& if_not_exhausted_block = generator.make_block();
  994. auto& continuation_block = generator.make_block();
  995. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  996. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  997. Bytecode::Label { if_exhausted_block },
  998. Bytecode::Label { if_not_exhausted_block });
  999. generator.switch_to_basic_block(if_exhausted_block);
  1000. generator.emit<Bytecode::Op::NewArray>();
  1001. generator.emit<Bytecode::Op::Jump>().set_targets(
  1002. Bytecode::Label { continuation_block },
  1003. {});
  1004. generator.switch_to_basic_block(if_not_exhausted_block);
  1005. generator.emit<Bytecode::Op::Load>(iterator_reg);
  1006. generator.emit<Bytecode::Op::IteratorToArray>();
  1007. generator.emit<Bytecode::Op::Jump>().set_targets(
  1008. Bytecode::Label { continuation_block },
  1009. {});
  1010. generator.switch_to_basic_block(continuation_block);
  1011. }
  1012. return assign_accumulator_to_alias(alias);
  1013. }
  1014. // In the first iteration of the loop, a few things are true which can save
  1015. // us some bytecode:
  1016. // - the iterator result is still in the accumulator, so we can avoid a load
  1017. // - the iterator is not yet exhausted, which can save us a jump and some
  1018. // creation
  1019. auto& iterator_is_exhausted_block = generator.make_block();
  1020. if (!first) {
  1021. auto& iterator_is_not_exhausted_block = generator.make_block();
  1022. generator.emit<Bytecode::Op::Load>(is_iterator_exhausted_register);
  1023. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1024. Bytecode::Label { iterator_is_exhausted_block },
  1025. Bytecode::Label { iterator_is_not_exhausted_block });
  1026. generator.switch_to_basic_block(iterator_is_not_exhausted_block);
  1027. generator.emit<Bytecode::Op::Load>(iterator_reg);
  1028. }
  1029. generator.emit<Bytecode::Op::IteratorNext>();
  1030. generator.emit<Bytecode::Op::Store>(temp_iterator_result_reg);
  1031. generator.emit<Bytecode::Op::IteratorResultDone>();
  1032. generator.emit<Bytecode::Op::Store>(is_iterator_exhausted_register);
  1033. // We still have to check for exhaustion here. If the iterator is exhausted,
  1034. // we need to bail before trying to get the value
  1035. auto& no_bail_block = generator.make_block();
  1036. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1037. Bytecode::Label { iterator_is_exhausted_block },
  1038. Bytecode::Label { no_bail_block });
  1039. generator.switch_to_basic_block(no_bail_block);
  1040. // Get the next value in the iterator
  1041. generator.emit<Bytecode::Op::Load>(temp_iterator_result_reg);
  1042. generator.emit<Bytecode::Op::IteratorResultValue>();
  1043. auto& create_binding_block = generator.make_block();
  1044. generator.emit<Bytecode::Op::Jump>().set_targets(
  1045. Bytecode::Label { create_binding_block },
  1046. {});
  1047. // The iterator is exhausted, so we just load undefined and continue binding
  1048. generator.switch_to_basic_block(iterator_is_exhausted_block);
  1049. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1050. generator.emit<Bytecode::Op::Jump>().set_targets(
  1051. Bytecode::Label { create_binding_block },
  1052. {});
  1053. // Create the actual binding. The value which this entry must bind is now in the
  1054. // accumulator. We can proceed, processing the alias as a nested destructuring
  1055. // pattern if necessary.
  1056. generator.switch_to_basic_block(create_binding_block);
  1057. if (initializer) {
  1058. auto& value_is_undefined_block = generator.make_block();
  1059. auto& value_is_not_undefined_block = generator.make_block();
  1060. generator.emit<Bytecode::Op::JumpUndefined>().set_targets(
  1061. Bytecode::Label { value_is_undefined_block },
  1062. Bytecode::Label { value_is_not_undefined_block });
  1063. generator.switch_to_basic_block(value_is_undefined_block);
  1064. TRY(initializer->generate_bytecode(generator));
  1065. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { value_is_not_undefined_block });
  1066. generator.switch_to_basic_block(value_is_not_undefined_block);
  1067. }
  1068. TRY(assign_accumulator_to_alias(alias));
  1069. first = false;
  1070. }
  1071. return {};
  1072. }
  1073. static Bytecode::CodeGenerationErrorOr<void> generate_binding_pattern_bytecode(Bytecode::Generator& generator, BindingPattern const& pattern, Bytecode::Op::SetVariable::InitializationMode initialization_mode, Bytecode::Register const& value_reg)
  1074. {
  1075. if (pattern.kind == BindingPattern::Kind::Object)
  1076. return generate_object_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  1077. return generate_array_binding_pattern_bytecode(generator, pattern, initialization_mode, value_reg);
  1078. }
  1079. static Bytecode::CodeGenerationErrorOr<void> assign_accumulator_to_variable_declarator(Bytecode::Generator& generator, VariableDeclarator const& declarator, VariableDeclaration const& declaration)
  1080. {
  1081. auto initialization_mode = declaration.is_lexical_declaration() ? Bytecode::Op::SetVariable::InitializationMode::Initialize : Bytecode::Op::SetVariable::InitializationMode::Set;
  1082. return declarator.target().visit(
  1083. [&](NonnullRefPtr<Identifier const> const& id) -> Bytecode::CodeGenerationErrorOr<void> {
  1084. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(id->string()), initialization_mode);
  1085. return {};
  1086. },
  1087. [&](NonnullRefPtr<BindingPattern const> const& pattern) -> Bytecode::CodeGenerationErrorOr<void> {
  1088. auto value_register = generator.allocate_register();
  1089. generator.emit<Bytecode::Op::Store>(value_register);
  1090. return generate_binding_pattern_bytecode(generator, pattern, initialization_mode, value_register);
  1091. });
  1092. }
  1093. Bytecode::CodeGenerationErrorOr<void> VariableDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1094. {
  1095. for (auto& declarator : m_declarations) {
  1096. if (declarator->init())
  1097. TRY(declarator->init()->generate_bytecode(generator));
  1098. else
  1099. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1100. TRY(assign_accumulator_to_variable_declarator(generator, declarator, *this));
  1101. }
  1102. return {};
  1103. }
  1104. Bytecode::CodeGenerationErrorOr<void> CallExpression::generate_bytecode(Bytecode::Generator& generator) const
  1105. {
  1106. auto callee_reg = generator.allocate_register();
  1107. auto this_reg = generator.allocate_register();
  1108. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1109. generator.emit<Bytecode::Op::Store>(this_reg);
  1110. if (is<NewExpression>(this)) {
  1111. TRY(m_callee->generate_bytecode(generator));
  1112. generator.emit<Bytecode::Op::Store>(callee_reg);
  1113. } else if (is<MemberExpression>(*m_callee)) {
  1114. auto& member_expression = static_cast<MemberExpression const&>(*m_callee);
  1115. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1116. if (is<SuperExpression>(member_expression.object())) {
  1117. // 1. Let env be GetThisEnvironment().
  1118. // 2. Let actualThis be ? env.GetThisBinding().
  1119. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1120. generator.emit<Bytecode::Op::Store>(this_reg);
  1121. Optional<Bytecode::Register> computed_property_value_register;
  1122. if (member_expression.is_computed()) {
  1123. // SuperProperty : super [ Expression ]
  1124. // 3. Let propertyNameReference be ? Evaluation of Expression.
  1125. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  1126. TRY(member_expression.property().generate_bytecode(generator));
  1127. computed_property_value_register = generator.allocate_register();
  1128. generator.emit<Bytecode::Op::Store>(*computed_property_value_register);
  1129. }
  1130. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  1131. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  1132. // 1. Let env be GetThisEnvironment().
  1133. // 2. Assert: env.HasSuperBinding() is true.
  1134. // 3. Let baseValue be ? env.GetSuperBase().
  1135. generator.emit<Bytecode::Op::ResolveSuperBase>();
  1136. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  1137. if (computed_property_value_register.has_value()) {
  1138. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  1139. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  1140. generator.emit<Bytecode::Op::GetByValue>(*computed_property_value_register);
  1141. } else {
  1142. // 3. Let propertyKey be StringValue of IdentifierName.
  1143. auto identifier_table_ref = generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1144. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1145. }
  1146. } else {
  1147. TRY(member_expression.object().generate_bytecode(generator));
  1148. generator.emit<Bytecode::Op::Store>(this_reg);
  1149. if (member_expression.is_computed()) {
  1150. TRY(member_expression.property().generate_bytecode(generator));
  1151. generator.emit<Bytecode::Op::GetByValue>(this_reg);
  1152. } else {
  1153. auto identifier_table_ref = [&] {
  1154. if (is<PrivateIdentifier>(member_expression.property()))
  1155. return generator.intern_identifier(verify_cast<PrivateIdentifier>(member_expression.property()).string());
  1156. return generator.intern_identifier(verify_cast<Identifier>(member_expression.property()).string());
  1157. }();
  1158. generator.emit<Bytecode::Op::GetById>(identifier_table_ref);
  1159. }
  1160. }
  1161. generator.emit<Bytecode::Op::Store>(callee_reg);
  1162. } else {
  1163. // FIXME: this = global object in sloppy mode.
  1164. TRY(m_callee->generate_bytecode(generator));
  1165. generator.emit<Bytecode::Op::Store>(callee_reg);
  1166. }
  1167. TRY(arguments_to_array_for_call(generator, arguments()));
  1168. Bytecode::Op::Call::CallType call_type;
  1169. if (is<NewExpression>(*this)) {
  1170. call_type = Bytecode::Op::Call::CallType::Construct;
  1171. } else if (m_callee->is_identifier() && static_cast<Identifier const&>(*m_callee).string() == "eval"sv) {
  1172. call_type = Bytecode::Op::Call::CallType::DirectEval;
  1173. } else {
  1174. call_type = Bytecode::Op::Call::CallType::Call;
  1175. }
  1176. Optional<Bytecode::StringTableIndex> expression_string_index;
  1177. if (auto expression_string = this->expression_string(); expression_string.has_value())
  1178. expression_string_index = generator.intern_string(expression_string.release_value());
  1179. generator.emit<Bytecode::Op::Call>(call_type, callee_reg, this_reg, expression_string_index);
  1180. return {};
  1181. }
  1182. Bytecode::CodeGenerationErrorOr<void> ReturnStatement::generate_bytecode(Bytecode::Generator& generator) const
  1183. {
  1184. if (m_argument)
  1185. TRY(m_argument->generate_bytecode(generator));
  1186. else
  1187. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1188. if (generator.is_in_generator_or_async_function()) {
  1189. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1190. generator.emit<Bytecode::Op::Yield>(nullptr);
  1191. } else {
  1192. generator.perform_needed_unwinds<Bytecode::Op::Return>();
  1193. generator.emit<Bytecode::Op::Return>();
  1194. }
  1195. return {};
  1196. }
  1197. Bytecode::CodeGenerationErrorOr<void> YieldExpression::generate_bytecode(Bytecode::Generator& generator) const
  1198. {
  1199. VERIFY(generator.is_in_generator_function());
  1200. auto received_completion_register = generator.allocate_register();
  1201. auto received_completion_type_register = generator.allocate_register();
  1202. auto received_completion_value_register = generator.allocate_register();
  1203. auto type_identifier = generator.intern_identifier("type");
  1204. auto value_identifier = generator.intern_identifier("value");
  1205. auto get_received_completion_type_and_value = [&]() {
  1206. // The accumulator is set to an object, for example: { "type": 1 (normal), value: 1337 }
  1207. generator.emit<Bytecode::Op::Store>(received_completion_register);
  1208. generator.emit<Bytecode::Op::GetById>(type_identifier);
  1209. generator.emit<Bytecode::Op::Store>(received_completion_type_register);
  1210. generator.emit<Bytecode::Op::Load>(received_completion_register);
  1211. generator.emit<Bytecode::Op::GetById>(value_identifier);
  1212. generator.emit<Bytecode::Op::Store>(received_completion_value_register);
  1213. };
  1214. if (m_is_yield_from) {
  1215. // 15.5.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation
  1216. // FIXME: 1. Let generatorKind be GetGeneratorKind().
  1217. // 2. Let exprRef be ? Evaluation of AssignmentExpression.
  1218. // 3. Let value be ? GetValue(exprRef).
  1219. VERIFY(m_argument);
  1220. TRY(m_argument->generate_bytecode(generator));
  1221. // 4. Let iteratorRecord be ? GetIterator(value, generatorKind).
  1222. // FIXME: Consider generatorKind.
  1223. auto iterator_record_register = generator.allocate_register();
  1224. generator.emit<Bytecode::Op::GetIterator>();
  1225. generator.emit<Bytecode::Op::Store>(iterator_record_register);
  1226. // 5. Let iterator be iteratorRecord.[[Iterator]].
  1227. auto iterator_register = generator.allocate_register();
  1228. auto iterator_identifier = generator.intern_identifier("iterator");
  1229. generator.emit<Bytecode::Op::GetById>(iterator_identifier);
  1230. generator.emit<Bytecode::Op::Store>(iterator_register);
  1231. // Cache iteratorRecord.[[NextMethod]] for use in step 7.a.i.
  1232. auto next_method_register = generator.allocate_register();
  1233. auto next_method_identifier = generator.intern_identifier("next");
  1234. generator.emit<Bytecode::Op::Load>(iterator_record_register);
  1235. generator.emit<Bytecode::Op::GetById>(next_method_identifier);
  1236. generator.emit<Bytecode::Op::Store>(next_method_register);
  1237. // 6. Let received be NormalCompletion(undefined).
  1238. // See get_received_completion_type_and_value above.
  1239. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1240. generator.emit<Bytecode::Op::Store>(received_completion_type_register);
  1241. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1242. generator.emit<Bytecode::Op::Store>(received_completion_value_register);
  1243. // 7. Repeat,
  1244. auto& loop_block = generator.make_block();
  1245. auto& continuation_block = generator.make_block();
  1246. auto& loop_end_block = generator.make_block();
  1247. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_block });
  1248. generator.switch_to_basic_block(loop_block);
  1249. // a. If received.[[Type]] is normal, then
  1250. auto& type_is_normal_block = generator.make_block();
  1251. auto& is_type_throw_block = generator.make_block();
  1252. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1253. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1254. generator.emit<Bytecode::Op::JumpConditional>(
  1255. Bytecode::Label { type_is_normal_block },
  1256. Bytecode::Label { is_type_throw_block });
  1257. generator.switch_to_basic_block(type_is_normal_block);
  1258. // i. Let innerResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]], « received.[[Value]] »).
  1259. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { received_completion_value_register, received_completion_value_register });
  1260. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, next_method_register, iterator_register);
  1261. // FIXME: ii. If generatorKind is async, set innerResult to ? Await(innerResult).
  1262. // iii. If innerResult is not an Object, throw a TypeError exception.
  1263. generator.emit<Bytecode::Op::ThrowIfNotObject>();
  1264. auto inner_result_register = generator.allocate_register();
  1265. generator.emit<Bytecode::Op::Store>(inner_result_register);
  1266. // iv. Let done be ? IteratorComplete(innerResult).
  1267. generator.emit<Bytecode::Op::IteratorResultDone>();
  1268. // v. If done is true, then
  1269. auto& type_is_normal_done_block = generator.make_block();
  1270. auto& type_is_normal_not_done_block = generator.make_block();
  1271. generator.emit<Bytecode::Op::JumpConditional>(
  1272. Bytecode::Label { type_is_normal_done_block },
  1273. Bytecode::Label { type_is_normal_not_done_block });
  1274. generator.switch_to_basic_block(type_is_normal_done_block);
  1275. // 1. Return ? IteratorValue(innerResult).
  1276. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1277. generator.emit<Bytecode::Op::IteratorResultValue>();
  1278. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_end_block });
  1279. generator.switch_to_basic_block(type_is_normal_not_done_block);
  1280. // FIXME: vi. If generatorKind is async, set received to Completion(AsyncGeneratorYield(? IteratorValue(innerResult))).
  1281. // vii. Else, set received to Completion(GeneratorYield(innerResult)).
  1282. // FIXME: Else,
  1283. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1284. // FIXME: Yield currently only accepts a Value, not an object conforming to the IteratorResult interface, so we have to do an observable lookup of `value` here.
  1285. generator.emit<Bytecode::Op::IteratorResultValue>();
  1286. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1287. // b. Else if received.[[Type]] is throw, then
  1288. generator.switch_to_basic_block(is_type_throw_block);
  1289. auto& type_is_throw_block = generator.make_block();
  1290. auto& type_is_return_block = generator.make_block();
  1291. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Throw)));
  1292. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1293. generator.emit<Bytecode::Op::JumpConditional>(
  1294. Bytecode::Label { type_is_throw_block },
  1295. Bytecode::Label { type_is_return_block });
  1296. generator.switch_to_basic_block(type_is_throw_block);
  1297. // i. Let throw be ? GetMethod(iterator, "throw").
  1298. auto throw_method_register = generator.allocate_register();
  1299. auto throw_identifier = generator.intern_identifier("throw");
  1300. generator.emit<Bytecode::Op::Load>(iterator_register);
  1301. generator.emit<Bytecode::Op::GetMethod>(throw_identifier);
  1302. generator.emit<Bytecode::Op::Store>(throw_method_register);
  1303. // ii. If throw is not undefined, then
  1304. auto& throw_method_is_defined_block = generator.make_block();
  1305. auto& throw_method_is_undefined_block = generator.make_block();
  1306. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1307. generator.emit<Bytecode::Op::StrictlyInequals>(throw_method_register);
  1308. generator.emit<Bytecode::Op::JumpConditional>(
  1309. Bytecode::Label { throw_method_is_defined_block },
  1310. Bytecode::Label { throw_method_is_undefined_block });
  1311. generator.switch_to_basic_block(throw_method_is_defined_block);
  1312. // 1. Let innerResult be ? Call(throw, iterator, « received.[[Value]] »).
  1313. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { received_completion_value_register, received_completion_value_register });
  1314. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, throw_method_register, iterator_register);
  1315. // FIXME: 2. If generatorKind is async, set innerResult to ? Await(innerResult).
  1316. // 3. NOTE: Exceptions from the inner iterator throw method are propagated. Normal completions from an inner throw method are processed similarly to an inner next.
  1317. // 4. If innerResult is not an Object, throw a TypeError exception.
  1318. generator.emit<Bytecode::Op::ThrowIfNotObject>();
  1319. generator.emit<Bytecode::Op::Store>(inner_result_register);
  1320. // 5. Let done be ? IteratorComplete(innerResult).
  1321. generator.emit<Bytecode::Op::IteratorResultDone>();
  1322. // 6. If done is true, then
  1323. auto& type_is_throw_done_block = generator.make_block();
  1324. auto& type_is_throw_not_done_block = generator.make_block();
  1325. generator.emit<Bytecode::Op::JumpConditional>(
  1326. Bytecode::Label { type_is_throw_done_block },
  1327. Bytecode::Label { type_is_throw_not_done_block });
  1328. generator.switch_to_basic_block(type_is_throw_done_block);
  1329. // a. Return ? IteratorValue(innerResult).
  1330. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1331. generator.emit<Bytecode::Op::IteratorResultValue>();
  1332. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_end_block });
  1333. generator.switch_to_basic_block(type_is_throw_not_done_block);
  1334. // FIXME: 7. If generatorKind is async, set received to Completion(AsyncGeneratorYield(? IteratorValue(innerResult))).
  1335. // 8. Else, set received to Completion(GeneratorYield(innerResult)).
  1336. // FIXME: Else,
  1337. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1338. // FIXME: Yield currently only accepts a Value, not an object conforming to the IteratorResult interface, so we have to do an observable lookup of `value` here.
  1339. generator.emit<Bytecode::Op::IteratorResultValue>();
  1340. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1341. generator.switch_to_basic_block(throw_method_is_undefined_block);
  1342. // 1. NOTE: If iterator does not have a throw method, this throw is going to terminate the yield* loop. But first we need to give iterator a chance to clean up.
  1343. // 2. Let closeCompletion be Completion Record { [[Type]]: normal, [[Value]]: empty, [[Target]]: empty }.
  1344. // FIXME: 3. If generatorKind is async, perform ? AsyncIteratorClose(iteratorRecord, closeCompletion).
  1345. // 4. Else, perform ? IteratorClose(iteratorRecord, closeCompletion).
  1346. // FIXME: Else,
  1347. generator.emit<Bytecode::Op::Load>(iterator_record_register);
  1348. generator.emit<Bytecode::Op::IteratorClose>(Completion::Type::Normal, Optional<Value> {});
  1349. // 5. NOTE: The next step throws a TypeError to indicate that there was a yield* protocol violation: iterator does not have a throw method.
  1350. // 6. Throw a TypeError exception.
  1351. generator.emit<Bytecode::Op::NewTypeError>(generator.intern_string(ErrorType::YieldFromIteratorMissingThrowMethod.message()));
  1352. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1353. generator.emit<Bytecode::Op::Throw>();
  1354. // c. Else,
  1355. // i. Assert: received.[[Type]] is return.
  1356. generator.switch_to_basic_block(type_is_return_block);
  1357. // ii. Let return be ? GetMethod(iterator, "return").
  1358. auto return_method_register = generator.allocate_register();
  1359. auto return_identifier = generator.intern_identifier("return");
  1360. generator.emit<Bytecode::Op::Load>(iterator_register);
  1361. generator.emit<Bytecode::Op::GetMethod>(return_identifier);
  1362. generator.emit<Bytecode::Op::Store>(return_method_register);
  1363. // iii. If return is undefined, then
  1364. auto& return_is_undefined_block = generator.make_block();
  1365. auto& return_is_defined_block = generator.make_block();
  1366. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1367. generator.emit<Bytecode::Op::StrictlyEquals>(return_method_register);
  1368. generator.emit<Bytecode::Op::JumpConditional>(
  1369. Bytecode::Label { return_is_undefined_block },
  1370. Bytecode::Label { return_is_defined_block });
  1371. generator.switch_to_basic_block(return_is_undefined_block);
  1372. // FIXME: 1. If generatorKind is async, set received.[[Value]] to ? Await(received.[[Value]]).
  1373. // 2. Return ? received.
  1374. // NOTE: This will always be a return completion.
  1375. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1376. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1377. generator.emit<Bytecode::Op::Yield>(nullptr);
  1378. generator.switch_to_basic_block(return_is_defined_block);
  1379. // iv. Let innerReturnResult be ? Call(return, iterator, « received.[[Value]] »).
  1380. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { received_completion_value_register, received_completion_value_register });
  1381. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, return_method_register, iterator_register);
  1382. // FIXME: v. If generatorKind is async, set innerReturnResult to ? Await(innerReturnResult).
  1383. // vi. If innerReturnResult is not an Object, throw a TypeError exception.
  1384. generator.emit<Bytecode::Op::ThrowIfNotObject>();
  1385. auto inner_return_result_register = generator.allocate_register();
  1386. generator.emit<Bytecode::Op::Store>(inner_return_result_register);
  1387. // vii. Let done be ? IteratorComplete(innerReturnResult).
  1388. generator.emit<Bytecode::Op::IteratorResultDone>();
  1389. // viii. If done is true, then
  1390. auto& type_is_return_done_block = generator.make_block();
  1391. auto& type_is_return_not_done_block = generator.make_block();
  1392. generator.emit<Bytecode::Op::JumpConditional>(
  1393. Bytecode::Label { type_is_return_done_block },
  1394. Bytecode::Label { type_is_return_not_done_block });
  1395. generator.switch_to_basic_block(type_is_return_done_block);
  1396. // 1. Let value be ? IteratorValue(innerReturnResult).
  1397. generator.emit<Bytecode::Op::Load>(inner_result_register);
  1398. generator.emit<Bytecode::Op::IteratorResultValue>();
  1399. // 2. Return Completion Record { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  1400. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1401. generator.emit<Bytecode::Op::Yield>(nullptr);
  1402. generator.switch_to_basic_block(type_is_return_not_done_block);
  1403. // FIXME: ix. If generatorKind is async, set received to Completion(AsyncGeneratorYield(? IteratorValue(innerReturnResult))).
  1404. // x. Else, set received to Completion(GeneratorYield(innerReturnResult)).
  1405. // FIXME: Else,
  1406. generator.emit<Bytecode::Op::Load>(inner_return_result_register);
  1407. // FIXME: Yield currently only accepts a Value, not an object conforming to the IteratorResult interface, so we have to do an observable lookup of `value` here.
  1408. generator.emit<Bytecode::Op::IteratorResultValue>();
  1409. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1410. generator.switch_to_basic_block(continuation_block);
  1411. get_received_completion_type_and_value();
  1412. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_block });
  1413. generator.switch_to_basic_block(loop_end_block);
  1414. return {};
  1415. }
  1416. if (m_argument)
  1417. TRY(m_argument->generate_bytecode(generator));
  1418. else
  1419. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1420. auto& continuation_block = generator.make_block();
  1421. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1422. generator.switch_to_basic_block(continuation_block);
  1423. get_received_completion_type_and_value();
  1424. auto& normal_completion_continuation_block = generator.make_block();
  1425. auto& throw_completion_continuation_block = generator.make_block();
  1426. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1427. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1428. generator.emit<Bytecode::Op::JumpConditional>(
  1429. Bytecode::Label { normal_completion_continuation_block },
  1430. Bytecode::Label { throw_completion_continuation_block });
  1431. auto& throw_value_block = generator.make_block();
  1432. auto& return_value_block = generator.make_block();
  1433. generator.switch_to_basic_block(throw_completion_continuation_block);
  1434. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Throw)));
  1435. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1436. // If type is not equal to "throw" or "normal", assume it's "return".
  1437. generator.emit<Bytecode::Op::JumpConditional>(
  1438. Bytecode::Label { throw_value_block },
  1439. Bytecode::Label { return_value_block });
  1440. generator.switch_to_basic_block(throw_value_block);
  1441. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1442. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1443. generator.emit<Bytecode::Op::Throw>();
  1444. generator.switch_to_basic_block(return_value_block);
  1445. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1446. generator.perform_needed_unwinds<Bytecode::Op::Yield>();
  1447. generator.emit<Bytecode::Op::Yield>(nullptr);
  1448. generator.switch_to_basic_block(normal_completion_continuation_block);
  1449. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1450. return {};
  1451. }
  1452. Bytecode::CodeGenerationErrorOr<void> IfStatement::generate_bytecode(Bytecode::Generator& generator) const
  1453. {
  1454. // test
  1455. // jump if_true (true) true (false) false
  1456. // true
  1457. // jump always (true) end
  1458. // false
  1459. // jump always (true) end
  1460. // end
  1461. auto& true_block = generator.make_block();
  1462. auto& false_block = generator.make_block();
  1463. TRY(m_predicate->generate_bytecode(generator));
  1464. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1465. Bytecode::Label { true_block },
  1466. Bytecode::Label { false_block });
  1467. Bytecode::Op::Jump* true_block_jump { nullptr };
  1468. generator.switch_to_basic_block(true_block);
  1469. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1470. TRY(m_consequent->generate_bytecode(generator));
  1471. if (!generator.is_current_block_terminated())
  1472. true_block_jump = &generator.emit<Bytecode::Op::Jump>();
  1473. generator.switch_to_basic_block(false_block);
  1474. auto& end_block = generator.make_block();
  1475. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1476. if (m_alternate)
  1477. TRY(m_alternate->generate_bytecode(generator));
  1478. if (!generator.is_current_block_terminated())
  1479. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1480. if (true_block_jump)
  1481. true_block_jump->set_targets(Bytecode::Label { end_block }, {});
  1482. generator.switch_to_basic_block(end_block);
  1483. return {};
  1484. }
  1485. Bytecode::CodeGenerationErrorOr<void> ContinueStatement::generate_bytecode(Bytecode::Generator& generator) const
  1486. {
  1487. // FIXME: Handle finally blocks in a graceful manner
  1488. // We need to execute the finally block, but tell it to resume
  1489. // execution at the designated block
  1490. if (m_target_label.is_null()) {
  1491. generator.generate_continue();
  1492. return {};
  1493. }
  1494. generator.generate_continue(m_target_label);
  1495. return {};
  1496. }
  1497. Bytecode::CodeGenerationErrorOr<void> DebuggerStatement::generate_bytecode(Bytecode::Generator&) const
  1498. {
  1499. return {};
  1500. }
  1501. Bytecode::CodeGenerationErrorOr<void> ConditionalExpression::generate_bytecode(Bytecode::Generator& generator) const
  1502. {
  1503. // test
  1504. // jump if_true (true) true (false) false
  1505. // true
  1506. // jump always (true) end
  1507. // false
  1508. // jump always (true) end
  1509. // end
  1510. auto& true_block = generator.make_block();
  1511. auto& false_block = generator.make_block();
  1512. auto& end_block = generator.make_block();
  1513. TRY(m_test->generate_bytecode(generator));
  1514. generator.emit<Bytecode::Op::JumpConditional>().set_targets(
  1515. Bytecode::Label { true_block },
  1516. Bytecode::Label { false_block });
  1517. generator.switch_to_basic_block(true_block);
  1518. TRY(m_consequent->generate_bytecode(generator));
  1519. generator.emit<Bytecode::Op::Jump>().set_targets(
  1520. Bytecode::Label { end_block },
  1521. {});
  1522. generator.switch_to_basic_block(false_block);
  1523. TRY(m_alternate->generate_bytecode(generator));
  1524. generator.emit<Bytecode::Op::Jump>().set_targets(
  1525. Bytecode::Label { end_block },
  1526. {});
  1527. generator.switch_to_basic_block(end_block);
  1528. return {};
  1529. }
  1530. Bytecode::CodeGenerationErrorOr<void> SequenceExpression::generate_bytecode(Bytecode::Generator& generator) const
  1531. {
  1532. for (auto& expression : m_expressions)
  1533. TRY(expression->generate_bytecode(generator));
  1534. return {};
  1535. }
  1536. Bytecode::CodeGenerationErrorOr<void> TemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1537. {
  1538. auto string_reg = generator.allocate_register();
  1539. for (size_t i = 0; i < m_expressions.size(); i++) {
  1540. TRY(m_expressions[i]->generate_bytecode(generator));
  1541. if (i == 0) {
  1542. generator.emit<Bytecode::Op::Store>(string_reg);
  1543. } else {
  1544. generator.emit<Bytecode::Op::ConcatString>(string_reg);
  1545. }
  1546. }
  1547. generator.emit<Bytecode::Op::Load>(string_reg);
  1548. return {};
  1549. }
  1550. Bytecode::CodeGenerationErrorOr<void> TaggedTemplateLiteral::generate_bytecode(Bytecode::Generator& generator) const
  1551. {
  1552. TRY(m_tag->generate_bytecode(generator));
  1553. auto tag_reg = generator.allocate_register();
  1554. generator.emit<Bytecode::Op::Store>(tag_reg);
  1555. // FIXME: We only need to record the first and last register,
  1556. // due to packing everything in an array, same goes for argument_regs
  1557. Vector<Bytecode::Register> string_regs;
  1558. auto& expressions = m_template_literal->expressions();
  1559. for (size_t i = 0; i < expressions.size(); ++i) {
  1560. if (i % 2 != 0)
  1561. continue;
  1562. string_regs.append(generator.allocate_register());
  1563. }
  1564. size_t reg_index = 0;
  1565. for (size_t i = 0; i < expressions.size(); ++i) {
  1566. if (i % 2 != 0)
  1567. continue;
  1568. TRY(expressions[i]->generate_bytecode(generator));
  1569. auto string_reg = string_regs[reg_index++];
  1570. generator.emit<Bytecode::Op::Store>(string_reg);
  1571. }
  1572. if (string_regs.is_empty()) {
  1573. generator.emit<Bytecode::Op::NewArray>();
  1574. } else {
  1575. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { string_regs.first(), string_regs.last() });
  1576. }
  1577. auto strings_reg = generator.allocate_register();
  1578. generator.emit<Bytecode::Op::Store>(strings_reg);
  1579. Vector<Bytecode::Register> argument_regs;
  1580. argument_regs.append(strings_reg);
  1581. for (size_t i = 1; i < expressions.size(); i += 2)
  1582. argument_regs.append(generator.allocate_register());
  1583. for (size_t i = 1; i < expressions.size(); i += 2) {
  1584. auto string_reg = argument_regs[1 + i / 2];
  1585. TRY(expressions[i]->generate_bytecode(generator));
  1586. generator.emit<Bytecode::Op::Store>(string_reg);
  1587. }
  1588. Vector<Bytecode::Register> raw_string_regs;
  1589. for ([[maybe_unused]] auto& raw_string : m_template_literal->raw_strings())
  1590. string_regs.append(generator.allocate_register());
  1591. reg_index = 0;
  1592. for (auto& raw_string : m_template_literal->raw_strings()) {
  1593. TRY(raw_string->generate_bytecode(generator));
  1594. auto raw_string_reg = string_regs[reg_index++];
  1595. generator.emit<Bytecode::Op::Store>(raw_string_reg);
  1596. raw_string_regs.append(raw_string_reg);
  1597. }
  1598. if (raw_string_regs.is_empty()) {
  1599. generator.emit<Bytecode::Op::NewArray>();
  1600. } else {
  1601. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2u, AK::Array { raw_string_regs.first(), raw_string_regs.last() });
  1602. }
  1603. auto raw_strings_reg = generator.allocate_register();
  1604. generator.emit<Bytecode::Op::Store>(raw_strings_reg);
  1605. generator.emit<Bytecode::Op::PutById>(strings_reg, generator.intern_identifier("raw"));
  1606. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1607. auto this_reg = generator.allocate_register();
  1608. generator.emit<Bytecode::Op::Store>(this_reg);
  1609. if (!argument_regs.is_empty())
  1610. generator.emit_with_extra_register_slots<Bytecode::Op::NewArray>(2, AK::Array { argument_regs.first(), argument_regs.last() });
  1611. else
  1612. generator.emit<Bytecode::Op::NewArray>();
  1613. generator.emit<Bytecode::Op::Call>(Bytecode::Op::Call::CallType::Call, tag_reg, this_reg);
  1614. return {};
  1615. }
  1616. Bytecode::CodeGenerationErrorOr<void> UpdateExpression::generate_bytecode(Bytecode::Generator& generator) const
  1617. {
  1618. TRY(generator.emit_load_from_reference(*m_argument));
  1619. Optional<Bytecode::Register> previous_value_for_postfix_reg;
  1620. if (!m_prefixed) {
  1621. previous_value_for_postfix_reg = generator.allocate_register();
  1622. generator.emit<Bytecode::Op::Store>(*previous_value_for_postfix_reg);
  1623. }
  1624. if (m_op == UpdateOp::Increment)
  1625. generator.emit<Bytecode::Op::Increment>();
  1626. else
  1627. generator.emit<Bytecode::Op::Decrement>();
  1628. TRY(generator.emit_store_to_reference(*m_argument));
  1629. if (!m_prefixed)
  1630. generator.emit<Bytecode::Op::Load>(*previous_value_for_postfix_reg);
  1631. return {};
  1632. }
  1633. Bytecode::CodeGenerationErrorOr<void> ThrowStatement::generate_bytecode(Bytecode::Generator& generator) const
  1634. {
  1635. TRY(m_argument->generate_bytecode(generator));
  1636. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1637. generator.emit<Bytecode::Op::Throw>();
  1638. return {};
  1639. }
  1640. Bytecode::CodeGenerationErrorOr<void> BreakStatement::generate_bytecode(Bytecode::Generator& generator) const
  1641. {
  1642. // FIXME: Handle finally blocks in a graceful manner
  1643. // We need to execute the finally block, but tell it to resume
  1644. // execution at the designated block
  1645. if (m_target_label.is_null()) {
  1646. generator.generate_break();
  1647. return {};
  1648. }
  1649. generator.generate_break(m_target_label);
  1650. return {};
  1651. }
  1652. Bytecode::CodeGenerationErrorOr<void> TryStatement::generate_bytecode(Bytecode::Generator& generator) const
  1653. {
  1654. auto& saved_block = generator.current_block();
  1655. Optional<Bytecode::Label> handler_target;
  1656. Optional<Bytecode::Label> finalizer_target;
  1657. Bytecode::BasicBlock* next_block { nullptr };
  1658. if (m_finalizer) {
  1659. // FIXME: See notes in Op.h->ScheduleJump
  1660. auto& finalizer_block = generator.make_block();
  1661. generator.switch_to_basic_block(finalizer_block);
  1662. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1663. TRY(m_finalizer->generate_bytecode(generator));
  1664. if (!generator.is_current_block_terminated()) {
  1665. next_block = &generator.make_block();
  1666. auto next_target = Bytecode::Label { *next_block };
  1667. generator.emit<Bytecode::Op::ContinuePendingUnwind>(next_target);
  1668. }
  1669. finalizer_target = Bytecode::Label { finalizer_block };
  1670. }
  1671. if (m_finalizer)
  1672. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1673. if (m_handler) {
  1674. auto& handler_block = generator.make_block();
  1675. generator.switch_to_basic_block(handler_block);
  1676. if (!m_finalizer)
  1677. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1678. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical, Bytecode::Generator::SurroundingScopeKind::Block);
  1679. TRY(m_handler->parameter().visit(
  1680. [&](DeprecatedFlyString const& parameter) -> Bytecode::CodeGenerationErrorOr<void> {
  1681. if (!parameter.is_empty()) {
  1682. auto parameter_identifier = generator.intern_identifier(parameter);
  1683. generator.register_binding(parameter_identifier);
  1684. generator.emit<Bytecode::Op::CreateVariable>(parameter_identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1685. generator.emit<Bytecode::Op::SetVariable>(parameter_identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1686. }
  1687. return {};
  1688. },
  1689. [&](NonnullRefPtr<BindingPattern const> const&) -> Bytecode::CodeGenerationErrorOr<void> {
  1690. // FIXME: Implement this path when the above DeclarativeEnvironment issue is dealt with.
  1691. return Bytecode::CodeGenerationError {
  1692. this,
  1693. "Unimplemented catch argument: BindingPattern"sv,
  1694. };
  1695. }));
  1696. TRY(m_handler->body().generate_bytecode(generator));
  1697. handler_target = Bytecode::Label { handler_block };
  1698. generator.end_variable_scope();
  1699. if (!generator.is_current_block_terminated()) {
  1700. if (m_finalizer) {
  1701. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1702. } else {
  1703. VERIFY(!next_block);
  1704. next_block = &generator.make_block();
  1705. auto next_target = Bytecode::Label { *next_block };
  1706. generator.emit<Bytecode::Op::Jump>(next_target);
  1707. }
  1708. }
  1709. }
  1710. if (m_finalizer)
  1711. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1712. auto& target_block = generator.make_block();
  1713. generator.switch_to_basic_block(saved_block);
  1714. generator.emit<Bytecode::Op::EnterUnwindContext>(Bytecode::Label { target_block }, handler_target, finalizer_target);
  1715. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1716. if (m_finalizer)
  1717. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1718. generator.switch_to_basic_block(target_block);
  1719. TRY(m_block->generate_bytecode(generator));
  1720. if (!generator.is_current_block_terminated()) {
  1721. if (m_finalizer) {
  1722. generator.emit<Bytecode::Op::Jump>(finalizer_target);
  1723. } else {
  1724. if (!next_block)
  1725. next_block = &generator.make_block();
  1726. generator.emit<Bytecode::Op::LeaveUnwindContext>();
  1727. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { *next_block });
  1728. }
  1729. }
  1730. if (m_finalizer)
  1731. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::ReturnToFinally);
  1732. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::Unwind);
  1733. generator.switch_to_basic_block(next_block ? *next_block : saved_block);
  1734. return {};
  1735. }
  1736. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_bytecode(Bytecode::Generator& generator) const
  1737. {
  1738. return generate_labelled_evaluation(generator, {});
  1739. }
  1740. Bytecode::CodeGenerationErrorOr<void> SwitchStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  1741. {
  1742. auto discriminant_reg = generator.allocate_register();
  1743. TRY(m_discriminant->generate_bytecode(generator));
  1744. generator.emit<Bytecode::Op::Store>(discriminant_reg);
  1745. Vector<Bytecode::BasicBlock&> case_blocks;
  1746. Bytecode::BasicBlock* default_block { nullptr };
  1747. Bytecode::BasicBlock* next_test_block = &generator.make_block();
  1748. auto has_lexical_block = has_lexical_declarations();
  1749. // Note: This call ends up calling begin_variable_scope() if has_lexical_block is true, so we need to clean up after it at the end.
  1750. TRY(ScopeNode::generate_bytecode(generator));
  1751. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_test_block }, {});
  1752. for (auto& switch_case : m_cases) {
  1753. auto& case_block = generator.make_block();
  1754. if (switch_case->test()) {
  1755. generator.switch_to_basic_block(*next_test_block);
  1756. TRY(switch_case->test()->generate_bytecode(generator));
  1757. generator.emit<Bytecode::Op::StrictlyEquals>(discriminant_reg);
  1758. next_test_block = &generator.make_block();
  1759. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { case_block }, Bytecode::Label { *next_test_block });
  1760. } else {
  1761. default_block = &case_block;
  1762. }
  1763. case_blocks.append(case_block);
  1764. }
  1765. generator.switch_to_basic_block(*next_test_block);
  1766. auto& end_block = generator.make_block();
  1767. if (default_block != nullptr) {
  1768. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *default_block }, {});
  1769. } else {
  1770. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1771. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1772. }
  1773. auto current_block = case_blocks.begin();
  1774. generator.begin_breakable_scope(Bytecode::Label { end_block }, label_set);
  1775. for (auto& switch_case : m_cases) {
  1776. generator.switch_to_basic_block(*current_block);
  1777. generator.emit<Bytecode::Op::LoadImmediate>(js_undefined());
  1778. for (auto& statement : switch_case->children()) {
  1779. TRY(statement->generate_bytecode(generator));
  1780. if (generator.is_current_block_terminated())
  1781. break;
  1782. }
  1783. if (!generator.is_current_block_terminated()) {
  1784. auto next_block = current_block;
  1785. next_block++;
  1786. if (next_block.is_end()) {
  1787. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { end_block }, {});
  1788. } else {
  1789. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { *next_block }, {});
  1790. }
  1791. }
  1792. current_block++;
  1793. }
  1794. generator.end_breakable_scope();
  1795. if (has_lexical_block)
  1796. generator.end_variable_scope();
  1797. generator.switch_to_basic_block(end_block);
  1798. return {};
  1799. }
  1800. Bytecode::CodeGenerationErrorOr<void> ClassDeclaration::generate_bytecode(Bytecode::Generator& generator) const
  1801. {
  1802. TRY(m_class_expression->generate_bytecode(generator));
  1803. generator.emit<Bytecode::Op::SetVariable>(generator.intern_identifier(m_class_expression.ptr()->name()), Bytecode::Op::SetVariable::InitializationMode::Initialize);
  1804. return {};
  1805. }
  1806. Bytecode::CodeGenerationErrorOr<void> ClassExpression::generate_bytecode(Bytecode::Generator& generator) const
  1807. {
  1808. generator.emit<Bytecode::Op::NewClass>(*this);
  1809. return {};
  1810. }
  1811. Bytecode::CodeGenerationErrorOr<void> SpreadExpression::generate_bytecode(Bytecode::Generator& generator) const
  1812. {
  1813. // NOTE: All users of this should handle the behaviour of this on their own,
  1814. // assuming it returns an Array-like object
  1815. return m_target->generate_bytecode(generator);
  1816. }
  1817. Bytecode::CodeGenerationErrorOr<void> ThisExpression::generate_bytecode(Bytecode::Generator& generator) const
  1818. {
  1819. generator.emit<Bytecode::Op::ResolveThisBinding>();
  1820. return {};
  1821. }
  1822. Bytecode::CodeGenerationErrorOr<void> AwaitExpression::generate_bytecode(Bytecode::Generator& generator) const
  1823. {
  1824. VERIFY(generator.is_in_async_function());
  1825. // Transform `await expr` to `yield expr`, see AsyncFunctionDriverWrapper
  1826. // For that we just need to copy most of the code from YieldExpression
  1827. auto received_completion_register = generator.allocate_register();
  1828. auto received_completion_type_register = generator.allocate_register();
  1829. auto received_completion_value_register = generator.allocate_register();
  1830. auto type_identifier = generator.intern_identifier("type");
  1831. auto value_identifier = generator.intern_identifier("value");
  1832. TRY(m_argument->generate_bytecode(generator));
  1833. auto& continuation_block = generator.make_block();
  1834. generator.emit<Bytecode::Op::Yield>(Bytecode::Label { continuation_block });
  1835. generator.switch_to_basic_block(continuation_block);
  1836. // The accumulator is set to an object, for example: { "type": 1 (normal), value: 1337 }
  1837. generator.emit<Bytecode::Op::Store>(received_completion_register);
  1838. generator.emit<Bytecode::Op::GetById>(type_identifier);
  1839. generator.emit<Bytecode::Op::Store>(received_completion_type_register);
  1840. generator.emit<Bytecode::Op::Load>(received_completion_register);
  1841. generator.emit<Bytecode::Op::GetById>(value_identifier);
  1842. generator.emit<Bytecode::Op::Store>(received_completion_value_register);
  1843. auto& normal_completion_continuation_block = generator.make_block();
  1844. auto& throw_value_block = generator.make_block();
  1845. generator.emit<Bytecode::Op::LoadImmediate>(Value(to_underlying(Completion::Type::Normal)));
  1846. generator.emit<Bytecode::Op::StrictlyEquals>(received_completion_type_register);
  1847. generator.emit<Bytecode::Op::JumpConditional>(
  1848. Bytecode::Label { normal_completion_continuation_block },
  1849. Bytecode::Label { throw_value_block });
  1850. // Simplification: The only abrupt completion we receive from AsyncFunctionDriverWrapper is Type::Throw
  1851. // So we do not need to account for the Type::Return path
  1852. generator.switch_to_basic_block(throw_value_block);
  1853. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1854. generator.perform_needed_unwinds<Bytecode::Op::Throw>();
  1855. generator.emit<Bytecode::Op::Throw>();
  1856. generator.switch_to_basic_block(normal_completion_continuation_block);
  1857. generator.emit<Bytecode::Op::Load>(received_completion_value_register);
  1858. return {};
  1859. }
  1860. Bytecode::CodeGenerationErrorOr<void> WithStatement::generate_bytecode(Bytecode::Generator& generator) const
  1861. {
  1862. TRY(m_object->generate_bytecode(generator));
  1863. generator.emit<Bytecode::Op::EnterObjectEnvironment>();
  1864. // EnterObjectEnvironment sets the running execution context's lexical_environment to a new Object Environment.
  1865. generator.start_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1866. TRY(m_body->generate_bytecode(generator));
  1867. generator.end_boundary(Bytecode::Generator::BlockBoundaryType::LeaveLexicalEnvironment);
  1868. if (!generator.is_current_block_terminated())
  1869. generator.emit<Bytecode::Op::LeaveEnvironment>(Bytecode::Op::EnvironmentMode::Lexical);
  1870. return {};
  1871. }
  1872. enum class LHSKind {
  1873. Assignment,
  1874. VarBinding,
  1875. LexicalBinding,
  1876. };
  1877. enum class IterationKind {
  1878. Enumerate,
  1879. Iterate,
  1880. AsyncIterate,
  1881. };
  1882. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  1883. struct ForInOfHeadEvaluationResult {
  1884. bool is_destructuring { false };
  1885. LHSKind lhs_kind { LHSKind::Assignment };
  1886. };
  1887. static Bytecode::CodeGenerationErrorOr<ForInOfHeadEvaluationResult> for_in_of_head_evaluation(Bytecode::Generator& generator, IterationKind iteration_kind, Variant<NonnullRefPtr<ASTNode const>, NonnullRefPtr<BindingPattern const>> const& lhs, NonnullRefPtr<ASTNode const> const& rhs)
  1888. {
  1889. ForInOfHeadEvaluationResult result {};
  1890. bool entered_lexical_scope = false;
  1891. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode const>>(); ast_ptr && is<VariableDeclaration>(**ast_ptr)) {
  1892. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1893. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  1894. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  1895. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  1896. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  1897. auto& variable_declaration = static_cast<VariableDeclaration const&>(**ast_ptr);
  1898. result.is_destructuring = variable_declaration.declarations().first()->target().has<NonnullRefPtr<BindingPattern const>>();
  1899. result.lhs_kind = variable_declaration.is_lexical_declaration() ? LHSKind::LexicalBinding : LHSKind::VarBinding;
  1900. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  1901. // NOTE: 'uninitializedBoundNames' refers to the lexical bindings (i.e. Const/Let) present in the second and last form.
  1902. // 2. If uninitializedBoundNames is not an empty List, then
  1903. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  1904. entered_lexical_scope = true;
  1905. // a. Assert: uninitializedBoundNames has no duplicate entries.
  1906. // b. Let newEnv be NewDeclarativeEnvironment(oldEnv).
  1907. generator.begin_variable_scope();
  1908. // c. For each String name of uninitializedBoundNames, do
  1909. // NOTE: Nothing in the callback throws an exception.
  1910. MUST(variable_declaration.for_each_bound_name([&](auto const& name) {
  1911. // i. Perform ! newEnv.CreateMutableBinding(name, false).
  1912. auto identifier = generator.intern_identifier(name);
  1913. generator.register_binding(identifier);
  1914. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  1915. }));
  1916. // d. Set the running execution context's LexicalEnvironment to newEnv.
  1917. // NOTE: Done by CreateEnvironment.
  1918. }
  1919. } else {
  1920. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  1921. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  1922. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  1923. result.lhs_kind = LHSKind::Assignment;
  1924. }
  1925. // 3. Let exprRef be the result of evaluating expr.
  1926. TRY(rhs->generate_bytecode(generator));
  1927. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  1928. if (entered_lexical_scope)
  1929. generator.end_variable_scope();
  1930. // 5. Let exprValue be ? GetValue(exprRef).
  1931. // NOTE: No need to store this anywhere.
  1932. // 6. If iterationKind is enumerate, then
  1933. if (iteration_kind == IterationKind::Enumerate) {
  1934. // a. If exprValue is undefined or null, then
  1935. auto& nullish_block = generator.make_block();
  1936. auto& continuation_block = generator.make_block();
  1937. auto& jump = generator.emit<Bytecode::Op::JumpNullish>();
  1938. jump.set_targets(Bytecode::Label { nullish_block }, Bytecode::Label { continuation_block });
  1939. // i. Return Completion Record { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  1940. generator.switch_to_basic_block(nullish_block);
  1941. generator.generate_break();
  1942. generator.switch_to_basic_block(continuation_block);
  1943. // b. Let obj be ! ToObject(exprValue).
  1944. // NOTE: GetObjectPropertyIterator does this.
  1945. // c. Let iterator be EnumerateObjectProperties(obj).
  1946. // d. Let nextMethod be ! GetV(iterator, "next").
  1947. // e. Return the Iterator Record { [[Iterator]]: iterator, [[NextMethod]]: nextMethod, [[Done]]: false }.
  1948. generator.emit<Bytecode::Op::GetObjectPropertyIterator>();
  1949. }
  1950. // 7. Else,
  1951. else {
  1952. // a. Assert: iterationKind is iterate or async-iterate.
  1953. // b. If iterationKind is async-iterate, let iteratorHint be async.
  1954. if (iteration_kind == IterationKind::AsyncIterate) {
  1955. return Bytecode::CodeGenerationError {
  1956. rhs.ptr(),
  1957. "Unimplemented iteration mode: AsyncIterate"sv,
  1958. };
  1959. }
  1960. // c. Else, let iteratorHint be sync.
  1961. // d. Return ? GetIterator(exprValue, iteratorHint).
  1962. generator.emit<Bytecode::Op::GetIterator>();
  1963. }
  1964. return result;
  1965. }
  1966. // 14.7.5.7 ForIn/OfBodyEvaluation ( lhs, stmt, iteratorRecord, iterationKind, lhsKind, labelSet [ , iteratorKind ] ), https://tc39.es/ecma262/#sec-runtime-semantics-forin-div-ofbodyevaluation-lhs-stmt-iterator-lhskind-labelset
  1967. static Bytecode::CodeGenerationErrorOr<void> for_in_of_body_evaluation(Bytecode::Generator& generator, ASTNode const& node, Variant<NonnullRefPtr<ASTNode const>, NonnullRefPtr<BindingPattern const>> const& lhs, ASTNode const& body, ForInOfHeadEvaluationResult const& head_result, Vector<DeprecatedFlyString> const& label_set, Bytecode::BasicBlock& loop_end, Bytecode::BasicBlock& loop_update)
  1968. {
  1969. auto iterator_register = generator.allocate_register();
  1970. generator.emit<Bytecode::Op::Store>(iterator_register);
  1971. // FIXME: Implement this
  1972. // 1. If iteratorKind is not present, set iteratorKind to sync.
  1973. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  1974. bool has_lexical_binding = false;
  1975. // 3. Let V be undefined.
  1976. // NOTE: We don't need 'V' as the resulting value will naturally flow through via the accumulator register.
  1977. // 4. Let destructuring be IsDestructuring of lhs.
  1978. auto destructuring = head_result.is_destructuring;
  1979. // 5. If destructuring is true and if lhsKind is assignment, then
  1980. if (destructuring && head_result.lhs_kind == LHSKind::Assignment) {
  1981. // a. Assert: lhs is a LeftHandSideExpression.
  1982. // b. Let assignmentPattern be the AssignmentPattern that is covered by lhs.
  1983. // FIXME: Implement this.
  1984. return Bytecode::CodeGenerationError {
  1985. &node,
  1986. "Unimplemented: assignment destructuring in for/of"sv,
  1987. };
  1988. }
  1989. // 6. Repeat,
  1990. generator.emit<Bytecode::Op::Jump>(Bytecode::Label { loop_update });
  1991. generator.switch_to_basic_block(loop_update);
  1992. generator.begin_continuable_scope(Bytecode::Label { loop_update }, label_set);
  1993. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  1994. generator.emit<Bytecode::Op::Load>(iterator_register);
  1995. generator.emit<Bytecode::Op::IteratorNext>();
  1996. // FIXME: Implement this:
  1997. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  1998. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  1999. // NOTE: IteratorComplete already does this.
  2000. // d. Let done be ? IteratorComplete(nextResult).
  2001. auto iterator_result_register = generator.allocate_register();
  2002. generator.emit<Bytecode::Op::Store>(iterator_result_register);
  2003. generator.emit<Bytecode::Op::IteratorResultDone>();
  2004. // e. If done is true, return V.
  2005. auto& loop_continue = generator.make_block();
  2006. generator.emit<Bytecode::Op::JumpConditional>().set_targets(Bytecode::Label { loop_end }, Bytecode::Label { loop_continue });
  2007. generator.switch_to_basic_block(loop_continue);
  2008. // f. Let nextValue be ? IteratorValue(nextResult).
  2009. generator.emit<Bytecode::Op::Load>(iterator_result_register);
  2010. generator.emit<Bytecode::Op::IteratorResultValue>();
  2011. // g. If lhsKind is either assignment or varBinding, then
  2012. if (head_result.lhs_kind != LHSKind::LexicalBinding) {
  2013. // i. If destructuring is false, then
  2014. if (!destructuring) {
  2015. // 1. Let lhsRef be the result of evaluating lhs. (It may be evaluated repeatedly.)
  2016. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  2017. if (head_result.lhs_kind == LHSKind::VarBinding) {
  2018. auto& declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode const>>());
  2019. VERIFY(declaration.declarations().size() == 1);
  2020. TRY(assign_accumulator_to_variable_declarator(generator, declaration.declarations().first(), declaration));
  2021. } else {
  2022. if (auto ptr = lhs.get_pointer<NonnullRefPtr<ASTNode const>>()) {
  2023. TRY(generator.emit_store_to_reference(**ptr));
  2024. } else {
  2025. auto& binding_pattern = lhs.get<NonnullRefPtr<BindingPattern const>>();
  2026. auto value_register = generator.allocate_register();
  2027. generator.emit<Bytecode::Op::Store>(value_register);
  2028. TRY(generate_binding_pattern_bytecode(generator, *binding_pattern, Bytecode::Op::SetVariable::InitializationMode::Set, value_register));
  2029. }
  2030. }
  2031. }
  2032. }
  2033. // h. Else,
  2034. else {
  2035. // i. Assert: lhsKind is lexicalBinding.
  2036. // ii. Assert: lhs is a ForDeclaration.
  2037. // iii. Let iterationEnv be NewDeclarativeEnvironment(oldEnv).
  2038. // iv. Perform ForDeclarationBindingInstantiation of lhs with argument iterationEnv.
  2039. // v. Set the running execution context's LexicalEnvironment to iterationEnv.
  2040. generator.begin_variable_scope(Bytecode::Generator::BindingMode::Lexical);
  2041. has_lexical_binding = true;
  2042. // 14.7.5.4 Runtime Semantics: ForDeclarationBindingInstantiation, https://tc39.es/ecma262/#sec-runtime-semantics-fordeclarationbindinginstantiation
  2043. // 1. Assert: environment is a declarative Environment Record.
  2044. // NOTE: We just made it.
  2045. auto& variable_declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode const>>());
  2046. // 2. For each element name of the BoundNames of ForBinding, do
  2047. // NOTE: Nothing in the callback throws an exception.
  2048. MUST(variable_declaration.for_each_bound_name([&](auto const& name) {
  2049. auto identifier = generator.intern_identifier(name);
  2050. generator.register_binding(identifier, Bytecode::Generator::BindingMode::Lexical);
  2051. // a. If IsConstantDeclaration of LetOrConst is true, then
  2052. if (variable_declaration.is_constant_declaration()) {
  2053. // i. Perform ! environment.CreateImmutableBinding(name, true).
  2054. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, true);
  2055. }
  2056. // b. Else,
  2057. else {
  2058. // i. Perform ! environment.CreateMutableBinding(name, false).
  2059. generator.emit<Bytecode::Op::CreateVariable>(identifier, Bytecode::Op::EnvironmentMode::Lexical, false);
  2060. }
  2061. }));
  2062. // 3. Return unused.
  2063. // NOTE: No need to do that as we've inlined this.
  2064. // vi. If destructuring is false, then
  2065. if (!destructuring) {
  2066. // 1. Assert: lhs binds a single name.
  2067. // 2. Let lhsName be the sole element of BoundNames of lhs.
  2068. auto lhs_name = variable_declaration.declarations().first()->target().get<NonnullRefPtr<Identifier const>>()->string();
  2069. // 3. Let lhsRef be ! ResolveBinding(lhsName).
  2070. // NOTE: We're skipping all the completion stuff that the spec does, as the unwinding mechanism will take case of doing that.
  2071. auto identifier = generator.intern_identifier(lhs_name);
  2072. generator.emit<Bytecode::Op::SetVariable>(identifier, Bytecode::Op::SetVariable::InitializationMode::Initialize, Bytecode::Op::EnvironmentMode::Lexical);
  2073. }
  2074. }
  2075. // i. If destructuring is false, then
  2076. if (!destructuring) {
  2077. // i. If lhsRef is an abrupt completion, then
  2078. // 1. Let status be lhsRef.
  2079. // ii. Else if lhsKind is lexicalBinding, then
  2080. // 1. Let status be Completion(InitializeReferencedBinding(lhsRef, nextValue)).
  2081. // iii. Else,
  2082. // 1. Let status be Completion(PutValue(lhsRef, nextValue)).
  2083. // NOTE: This is performed above.
  2084. }
  2085. // j. Else,
  2086. else {
  2087. // FIXME: i. If lhsKind is assignment, then
  2088. // 1. Let status be Completion(DestructuringAssignmentEvaluation of assignmentPattern with argument nextValue).
  2089. // ii. Else if lhsKind is varBinding, then
  2090. // 1. Assert: lhs is a ForBinding.
  2091. // 2. Let status be Completion(BindingInitialization of lhs with arguments nextValue and undefined).
  2092. // iii. Else,
  2093. // 1. Assert: lhsKind is lexicalBinding.
  2094. // 2. Assert: lhs is a ForDeclaration.
  2095. // 3. Let status be Completion(ForDeclarationBindingInitialization of lhs with arguments nextValue and iterationEnv).
  2096. if (head_result.lhs_kind == LHSKind::VarBinding || head_result.lhs_kind == LHSKind::LexicalBinding) {
  2097. auto& declaration = static_cast<VariableDeclaration const&>(*lhs.get<NonnullRefPtr<ASTNode const>>());
  2098. VERIFY(declaration.declarations().size() == 1);
  2099. auto& binding_pattern = declaration.declarations().first()->target().get<NonnullRefPtr<BindingPattern const>>();
  2100. auto value_register = generator.allocate_register();
  2101. generator.emit<Bytecode::Op::Store>(value_register);
  2102. TRY(generate_binding_pattern_bytecode(generator, *binding_pattern, head_result.lhs_kind == LHSKind::VarBinding ? Bytecode::Op::SetVariable::InitializationMode::Set : Bytecode::Op::SetVariable::InitializationMode::Initialize, value_register));
  2103. } else {
  2104. return Bytecode::CodeGenerationError {
  2105. &node,
  2106. "Unimplemented: assignment destructuring in for/of"sv,
  2107. };
  2108. }
  2109. }
  2110. // FIXME: Implement iteration closure.
  2111. // k. If status is an abrupt completion, then
  2112. // i. Set the running execution context's LexicalEnvironment to oldEnv.
  2113. // ii. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  2114. // iii. If iterationKind is enumerate, then
  2115. // 1. Return ? status.
  2116. // iv. Else,
  2117. // 1. Assert: iterationKind is iterate.
  2118. // 2. Return ? IteratorClose(iteratorRecord, status).
  2119. // l. Let result be the result of evaluating stmt.
  2120. TRY(body.generate_bytecode(generator));
  2121. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  2122. if (has_lexical_binding)
  2123. generator.end_variable_scope();
  2124. generator.end_continuable_scope();
  2125. generator.end_breakable_scope();
  2126. // NOTE: If we're here, then the loop definitely continues.
  2127. // n. If LoopContinues(result, labelSet) is false, then
  2128. // i. If iterationKind is enumerate, then
  2129. // 1. Return ? UpdateEmpty(result, V).
  2130. // ii. Else,
  2131. // 1. Assert: iterationKind is iterate.
  2132. // 2. Set status to Completion(UpdateEmpty(result, V)).
  2133. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  2134. // 4. Return ? IteratorClose(iteratorRecord, status).
  2135. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  2136. // The body can contain an unconditional block terminator (e.g. return, throw), so we have to check for that before generating the Jump.
  2137. if (!generator.is_current_block_terminated())
  2138. generator.emit<Bytecode::Op::Jump>().set_targets(Bytecode::Label { loop_update }, {});
  2139. generator.switch_to_basic_block(loop_end);
  2140. return {};
  2141. }
  2142. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_bytecode(Bytecode::Generator& generator) const
  2143. {
  2144. return generate_labelled_evaluation(generator, {});
  2145. }
  2146. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  2147. Bytecode::CodeGenerationErrorOr<void> ForInStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  2148. {
  2149. auto& loop_end = generator.make_block();
  2150. auto& loop_update = generator.make_block();
  2151. generator.begin_breakable_scope(Bytecode::Label { loop_end }, label_set);
  2152. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Enumerate, m_lhs, m_rhs));
  2153. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  2154. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, label_set, loop_end, loop_update);
  2155. }
  2156. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_bytecode(Bytecode::Generator& generator) const
  2157. {
  2158. return generate_labelled_evaluation(generator, {});
  2159. }
  2160. Bytecode::CodeGenerationErrorOr<void> ForOfStatement::generate_labelled_evaluation(Bytecode::Generator& generator, Vector<DeprecatedFlyString> const& label_set) const
  2161. {
  2162. auto& loop_end = generator.make_block();
  2163. auto& loop_update = generator.make_block();
  2164. generator.begin_breakable_scope(Bytecode::Label { loop_end }, label_set);
  2165. auto head_result = TRY(for_in_of_head_evaluation(generator, IterationKind::Iterate, m_lhs, m_rhs));
  2166. // Now perform the rest of ForInOfLoopEvaluation, given that the accumulator holds the iterator we're supposed to iterate over.
  2167. return for_in_of_body_evaluation(generator, *this, m_lhs, body(), head_result, label_set, loop_end, loop_update);
  2168. }
  2169. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  2170. Bytecode::CodeGenerationErrorOr<void> MetaProperty::generate_bytecode(Bytecode::Generator& generator) const
  2171. {
  2172. // NewTarget : new . target
  2173. if (m_type == MetaProperty::Type::NewTarget) {
  2174. // 1. Return GetNewTarget().
  2175. generator.emit<Bytecode::Op::GetNewTarget>();
  2176. return {};
  2177. }
  2178. // ImportMeta : import . meta
  2179. if (m_type == MetaProperty::Type::ImportMeta) {
  2180. return Bytecode::CodeGenerationError {
  2181. this,
  2182. "Unimplemented meta property: import.meta"sv,
  2183. };
  2184. }
  2185. VERIFY_NOT_REACHED();
  2186. }
  2187. }