ASTCodegen.cpp 132 KB

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