ASTCodegen.cpp 163 KB

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