ASTCodegen.cpp 145 KB

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