ASTCodegen.cpp 149 KB

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