ASTCodegen.cpp 123 KB

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