ASTCodegen.cpp 163 KB

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