ASTCodegen.cpp 162 KB

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