ASTCodegen.cpp 119 KB

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