ASTCodegen.cpp 150 KB

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