ASTCodegen.cpp 135 KB

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