AST.cpp 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, David Tuin <davidot@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Demangle.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/HashTable.h>
  11. #include <AK/ScopeGuard.h>
  12. #include <AK/StringBuilder.h>
  13. #include <AK/TemporaryChange.h>
  14. #include <LibCrypto/BigInt/SignedBigInteger.h>
  15. #include <LibJS/AST.h>
  16. #include <LibJS/Interpreter.h>
  17. #include <LibJS/Runtime/AbstractOperations.h>
  18. #include <LibJS/Runtime/Accessor.h>
  19. #include <LibJS/Runtime/Array.h>
  20. #include <LibJS/Runtime/BigInt.h>
  21. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  22. #include <LibJS/Runtime/Error.h>
  23. #include <LibJS/Runtime/FunctionEnvironment.h>
  24. #include <LibJS/Runtime/GlobalObject.h>
  25. #include <LibJS/Runtime/IteratorOperations.h>
  26. #include <LibJS/Runtime/MarkedValueList.h>
  27. #include <LibJS/Runtime/NativeFunction.h>
  28. #include <LibJS/Runtime/ObjectEnvironment.h>
  29. #include <LibJS/Runtime/PrimitiveString.h>
  30. #include <LibJS/Runtime/PromiseConstructor.h>
  31. #include <LibJS/Runtime/PromiseReaction.h>
  32. #include <LibJS/Runtime/Reference.h>
  33. #include <LibJS/Runtime/RegExpObject.h>
  34. #include <LibJS/Runtime/Shape.h>
  35. #include <typeinfo>
  36. namespace JS {
  37. class InterpreterNodeScope {
  38. AK_MAKE_NONCOPYABLE(InterpreterNodeScope);
  39. AK_MAKE_NONMOVABLE(InterpreterNodeScope);
  40. public:
  41. InterpreterNodeScope(Interpreter& interpreter, ASTNode const& node)
  42. : m_interpreter(interpreter)
  43. , m_chain_node { nullptr, node }
  44. {
  45. m_interpreter.vm().running_execution_context().current_node = &node;
  46. m_interpreter.push_ast_node(m_chain_node);
  47. }
  48. ~InterpreterNodeScope()
  49. {
  50. m_interpreter.pop_ast_node();
  51. }
  52. private:
  53. Interpreter& m_interpreter;
  54. ExecutingASTNodeChain m_chain_node;
  55. };
  56. String ASTNode::class_name() const
  57. {
  58. // NOTE: We strip the "JS::" prefix.
  59. return demangle(typeid(*this).name()).substring(4);
  60. }
  61. static void print_indent(int indent)
  62. {
  63. out("{}", String::repeated(' ', indent * 2));
  64. }
  65. static void update_function_name(Value value, FlyString const& name)
  66. {
  67. if (!value.is_function())
  68. return;
  69. auto& function = value.as_function();
  70. if (is<ECMAScriptFunctionObject>(function) && function.name().is_empty())
  71. static_cast<ECMAScriptFunctionObject&>(function).set_name(name);
  72. }
  73. static ThrowCompletionOr<String> get_function_name(GlobalObject& global_object, Value value)
  74. {
  75. if (value.is_symbol())
  76. return String::formatted("[{}]", value.as_symbol().description());
  77. if (value.is_string())
  78. return value.as_string().string();
  79. return value.to_string(global_object);
  80. }
  81. // 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  82. // StatementList : StatementList StatementListItem
  83. Completion ScopeNode::evaluate_statements(Interpreter& interpreter, GlobalObject& global_object) const
  84. {
  85. auto completion = normal_completion({});
  86. for (auto const& node : children()) {
  87. completion = node.execute(interpreter, global_object).update_empty(completion.value());
  88. if (completion.is_abrupt())
  89. break;
  90. }
  91. return completion;
  92. }
  93. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  94. // BreakableStatement : IterationStatement
  95. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, IterationStatement const& statement, Vector<FlyString> const& label_set)
  96. {
  97. // 1. Let stmtResult be LoopEvaluation of IterationStatement with argument labelSet.
  98. auto result = statement.loop_evaluation(interpreter, global_object, label_set);
  99. // 2. If stmtResult.[[Type]] is break, then
  100. if (result.type() == Completion::Type::Break) {
  101. // a. If stmtResult.[[Target]] is empty, then
  102. if (!result.target().has_value()) {
  103. // i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
  104. // ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  105. result = normal_completion(result.value().value_or(js_undefined()));
  106. }
  107. }
  108. // 3. Return Completion(stmtResult).
  109. return result;
  110. }
  111. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  112. // BreakableStatement : SwitchStatement
  113. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, SwitchStatement const& statement, Vector<FlyString> const&)
  114. {
  115. // 1. Let stmtResult be the result of evaluating SwitchStatement.
  116. auto result = statement.execute_impl(interpreter, global_object);
  117. // 2. If stmtResult.[[Type]] is break, then
  118. if (result.type() == Completion::Type::Break) {
  119. // a. If stmtResult.[[Target]] is empty, then
  120. if (!result.target().has_value()) {
  121. // i. If stmtResult.[[Value]] is empty, set stmtResult to NormalCompletion(undefined).
  122. // ii. Else, set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  123. result = normal_completion(result.value().value_or(js_undefined()));
  124. }
  125. }
  126. // 3. Return Completion(stmtResult).
  127. return result;
  128. }
  129. // 14.13.4 Runtime Semantics: LabelledEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-labelledevaluation
  130. // LabelledStatement : LabelIdentifier : LabelledItem
  131. static Completion labelled_evaluation(Interpreter& interpreter, GlobalObject& global_object, LabelledStatement const& statement, Vector<FlyString> const& label_set)
  132. {
  133. auto const& labelled_item = *statement.labelled_item();
  134. // 1. Let label be the StringValue of LabelIdentifier.
  135. auto const& label = statement.label();
  136. // 2. Let newLabelSet be the list-concatenation of labelSet and « label ».
  137. // Optimization: Avoid vector copy if possible.
  138. Optional<Vector<FlyString>> new_label_set;
  139. if (is<IterationStatement>(labelled_item) || is<SwitchStatement>(labelled_item) || is<LabelledStatement>(labelled_item)) {
  140. new_label_set = label_set;
  141. new_label_set->append(label);
  142. }
  143. // 3. Let stmtResult be LabelledEvaluation of LabelledItem with argument newLabelSet.
  144. Completion result;
  145. if (is<IterationStatement>(labelled_item))
  146. result = labelled_evaluation(interpreter, global_object, static_cast<IterationStatement const&>(labelled_item), *new_label_set);
  147. else if (is<SwitchStatement>(labelled_item))
  148. result = labelled_evaluation(interpreter, global_object, static_cast<SwitchStatement const&>(labelled_item), *new_label_set);
  149. else if (is<LabelledStatement>(labelled_item))
  150. result = labelled_evaluation(interpreter, global_object, static_cast<LabelledStatement const&>(labelled_item), *new_label_set);
  151. else
  152. result = labelled_item.execute(interpreter, global_object);
  153. // 4. If stmtResult.[[Type]] is break and SameValue(stmtResult.[[Target]], label) is true, then
  154. if (result.type() == Completion::Type::Break && result.target() == label) {
  155. // a. Set stmtResult to NormalCompletion(stmtResult.[[Value]]).
  156. result = normal_completion(result.value());
  157. }
  158. // 5. Return Completion(stmtResult).
  159. return result;
  160. }
  161. // 14.13.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-labelled-statements-runtime-semantics-evaluation
  162. Completion LabelledStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  163. {
  164. InterpreterNodeScope node_scope { interpreter, *this };
  165. // 1. Let newLabelSet be a new empty List.
  166. // 2. Return LabelledEvaluation of this LabelledStatement with argument newLabelSet.
  167. return labelled_evaluation(interpreter, global_object, *this, {});
  168. }
  169. void LabelledStatement::dump(int indent) const
  170. {
  171. ASTNode::dump(indent);
  172. print_indent(indent + 1);
  173. outln("(Label)");
  174. print_indent(indent + 2);
  175. outln("\"{}\"", m_label);
  176. print_indent(indent + 1);
  177. outln("(Labelled item)");
  178. m_labelled_item->dump(indent + 2);
  179. }
  180. // 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
  181. Completion FunctionBody::execute(Interpreter& interpreter, GlobalObject& global_object) const
  182. {
  183. InterpreterNodeScope node_scope { interpreter, *this };
  184. // Note: Scoping should have already been set up by whoever is calling this FunctionBody.
  185. // 1. Return ? EvaluateFunctionBody of FunctionBody with arguments functionObject and argumentsList.
  186. return evaluate_statements(interpreter, global_object);
  187. }
  188. // 14.2.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-block-runtime-semantics-evaluation
  189. Completion BlockStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  190. {
  191. InterpreterNodeScope node_scope { interpreter, *this };
  192. auto& vm = interpreter.vm();
  193. Environment* old_environment { nullptr };
  194. ArmedScopeGuard restore_environment = [&] {
  195. vm.running_execution_context().lexical_environment = old_environment;
  196. };
  197. // Optimization: We only need a new lexical environment if there are any lexical declarations. :^)
  198. if (has_lexical_declarations()) {
  199. old_environment = vm.running_execution_context().lexical_environment;
  200. auto* block_environment = new_declarative_environment(*old_environment);
  201. block_declaration_instantiation(global_object, block_environment);
  202. vm.running_execution_context().lexical_environment = block_environment;
  203. } else {
  204. restore_environment.disarm();
  205. }
  206. return evaluate_statements(interpreter, global_object);
  207. }
  208. Completion Program::execute(Interpreter& interpreter, GlobalObject& global_object) const
  209. {
  210. // FIXME: This tries to be "ScriptEvaluation" and "evaluating scriptBody" at once. It shouldn't.
  211. // Clean this up and update perform_eval() / perform_shadow_realm_eval()
  212. InterpreterNodeScope node_scope { interpreter, *this };
  213. VERIFY(interpreter.lexical_environment() && interpreter.lexical_environment()->is_global_environment());
  214. auto& global_env = static_cast<GlobalEnvironment&>(*interpreter.lexical_environment());
  215. TRY(global_declaration_instantiation(interpreter, global_object, global_env));
  216. return evaluate_statements(interpreter, global_object);
  217. }
  218. // 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
  219. Completion FunctionDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  220. {
  221. InterpreterNodeScope node_scope { interpreter, *this };
  222. if (m_is_hoisted) {
  223. // Perform special annexB steps see step 3 of: https://tc39.es/ecma262/#sec-web-compat-functiondeclarationinstantiation
  224. auto* variable_environment = interpreter.vm().running_execution_context().variable_environment;
  225. auto* lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
  226. auto function_object = MUST(lexical_environment->get_binding_value(global_object, name(), false));
  227. MUST(variable_environment->set_mutable_binding(global_object, name(), function_object, false));
  228. }
  229. // 1. Return NormalCompletion(empty).
  230. return normal_completion({});
  231. }
  232. // 15.2.6 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-definitions-runtime-semantics-evaluation
  233. Completion FunctionExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  234. {
  235. InterpreterNodeScope node_scope { interpreter, *this };
  236. // 1. Return InstantiateOrdinaryFunctionExpression of FunctionExpression.
  237. return instantiate_ordinary_function_expression(interpreter, global_object, name());
  238. }
  239. // 15.2.5 Runtime Semantics: InstantiateOrdinaryFunctionExpression, https://tc39.es/ecma262/#sec-runtime-semantics-instantiateordinaryfunctionexpression
  240. Value FunctionExpression::instantiate_ordinary_function_expression(Interpreter& interpreter, GlobalObject& global_object, FlyString given_name) const
  241. {
  242. if (given_name.is_empty())
  243. given_name = "";
  244. auto has_own_name = !name().is_empty();
  245. auto const& used_name = has_own_name ? name() : given_name;
  246. auto* scope = interpreter.lexical_environment();
  247. if (has_own_name) {
  248. VERIFY(scope);
  249. scope = new_declarative_environment(*scope);
  250. MUST(scope->create_immutable_binding(global_object, name(), false));
  251. }
  252. auto* private_scope = interpreter.vm().running_execution_context().private_environment;
  253. auto closure = ECMAScriptFunctionObject::create(global_object, used_name, body(), parameters(), function_length(), scope, private_scope, kind(), is_strict_mode(), might_need_arguments_object(), contains_direct_call_to_eval(), is_arrow_function());
  254. // FIXME: 6. Perform SetFunctionName(closure, name).
  255. // FIXME: 7. Perform MakeConstructor(closure).
  256. if (has_own_name)
  257. MUST(scope->initialize_binding(global_object, name(), closure));
  258. return closure;
  259. }
  260. // 14.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-empty-statement-runtime-semantics-evaluation
  261. Completion EmptyStatement::execute(Interpreter&, GlobalObject&) const
  262. {
  263. // 1. Return NormalCompletion(empty).
  264. return normal_completion({});
  265. }
  266. // 14.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-expression-statement-runtime-semantics-evaluation
  267. Completion ExpressionStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  268. {
  269. InterpreterNodeScope node_scope { interpreter, *this };
  270. // 1. Let exprRef be the result of evaluating Expression.
  271. // 2. Return ? GetValue(exprRef).
  272. return m_expression->execute(interpreter, global_object);
  273. }
  274. // TODO: This shouldn't exist. Refactor into EvaluateCall.
  275. ThrowCompletionOr<CallExpression::ThisAndCallee> CallExpression::compute_this_and_callee(Interpreter& interpreter, GlobalObject& global_object, Reference const& callee_reference) const
  276. {
  277. if (callee_reference.is_property_reference()) {
  278. auto this_value = callee_reference.get_this_value();
  279. auto callee = TRY(callee_reference.get_value(global_object));
  280. return ThisAndCallee { this_value, callee };
  281. }
  282. // [[Call]] will handle that in non-strict mode the this value becomes the global object
  283. return ThisAndCallee {
  284. js_undefined(),
  285. callee_reference.is_unresolvable()
  286. ? TRY(m_callee->execute(interpreter, global_object)).release_value()
  287. : TRY(callee_reference.get_value(global_object))
  288. };
  289. }
  290. // 13.3.8.1 Runtime Semantics: ArgumentListEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-argumentlistevaluation
  291. static ThrowCompletionOr<void> argument_list_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<CallExpression::Argument> const& arguments, MarkedValueList& list)
  292. {
  293. list.ensure_capacity(arguments.size());
  294. for (auto& argument : arguments) {
  295. auto value = TRY(argument.value->execute(interpreter, global_object)).release_value();
  296. if (argument.is_spread) {
  297. auto result = TRY(get_iterator_values(global_object, value, [&](Value iterator_value) -> Optional<Completion> {
  298. list.append(iterator_value);
  299. return {};
  300. }));
  301. } else {
  302. list.append(value);
  303. }
  304. }
  305. return {};
  306. }
  307. // 13.3.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-new-operator-runtime-semantics-evaluation
  308. // 13.3.5.1.1 EvaluateNew ( constructExpr, arguments ), https://tc39.es/ecma262/#sec-evaluatenew
  309. Completion NewExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  310. {
  311. InterpreterNodeScope node_scope { interpreter, *this };
  312. auto& vm = interpreter.vm();
  313. // 1. Let ref be the result of evaluating constructExpr.
  314. // 2. Let constructor be ? GetValue(ref).
  315. auto constructor = TRY(m_callee->execute(interpreter, global_object)).release_value();
  316. // 3. If arguments is empty, let argList be a new empty List.
  317. // 4. Else,
  318. // a. Let argList be ? ArgumentListEvaluation of arguments.
  319. MarkedValueList arg_list(vm.heap());
  320. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  321. // 5. If IsConstructor(constructor) is false, throw a TypeError exception.
  322. if (!constructor.is_constructor())
  323. return throw_type_error_for_callee(interpreter, global_object, constructor, "constructor"sv);
  324. // 6. Return ? Construct(constructor, argList).
  325. return Value { TRY(construct(global_object, constructor.as_function(), move(arg_list))) };
  326. }
  327. Completion CallExpression::throw_type_error_for_callee(Interpreter& interpreter, GlobalObject& global_object, Value callee_value, StringView call_type) const
  328. {
  329. auto& vm = interpreter.vm();
  330. if (is<Identifier>(*m_callee) || is<MemberExpression>(*m_callee)) {
  331. String expression_string;
  332. if (is<Identifier>(*m_callee)) {
  333. expression_string = static_cast<Identifier const&>(*m_callee).string();
  334. } else {
  335. expression_string = static_cast<MemberExpression const&>(*m_callee).to_string_approximation();
  336. }
  337. return vm.throw_completion<TypeError>(global_object, ErrorType::IsNotAEvaluatedFrom, callee_value.to_string_without_side_effects(), call_type, expression_string);
  338. } else {
  339. return vm.throw_completion<TypeError>(global_object, ErrorType::IsNotA, callee_value.to_string_without_side_effects(), call_type);
  340. }
  341. }
  342. // 13.3.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-function-calls-runtime-semantics-evaluation
  343. Completion CallExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  344. {
  345. InterpreterNodeScope node_scope { interpreter, *this };
  346. auto& vm = interpreter.vm();
  347. auto callee_reference = TRY(m_callee->to_reference(interpreter, global_object));
  348. auto [this_value, callee] = TRY(compute_this_and_callee(interpreter, global_object, callee_reference));
  349. VERIFY(!callee.is_empty());
  350. MarkedValueList arg_list(vm.heap());
  351. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  352. if (!callee.is_function())
  353. return throw_type_error_for_callee(interpreter, global_object, callee, "function"sv);
  354. auto& function = callee.as_function();
  355. if (&function == global_object.eval_function()
  356. && callee_reference.is_environment_reference()
  357. && callee_reference.name().is_string()
  358. && callee_reference.name().as_string() == vm.names.eval.as_string()) {
  359. auto script_value = arg_list.size() == 0 ? js_undefined() : arg_list[0];
  360. return perform_eval(script_value, global_object, vm.in_strict_mode() ? CallerMode::Strict : CallerMode::NonStrict, EvalMode::Direct);
  361. }
  362. return vm.call(function, this_value, move(arg_list));
  363. }
  364. // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  365. // SuperCall : super Arguments
  366. Completion SuperCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  367. {
  368. InterpreterNodeScope node_scope { interpreter, *this };
  369. auto& vm = interpreter.vm();
  370. // 1. Let newTarget be GetNewTarget().
  371. auto new_target = vm.get_new_target();
  372. // 2. Assert: Type(newTarget) is Object.
  373. VERIFY(new_target.is_function());
  374. // 3. Let func be ! GetSuperConstructor().
  375. auto* func = get_super_constructor(interpreter.vm());
  376. VERIFY(!vm.exception());
  377. // 4. Let argList be ? ArgumentListEvaluation of Arguments.
  378. MarkedValueList arg_list(vm.heap());
  379. TRY(argument_list_evaluation(interpreter, global_object, m_arguments, arg_list));
  380. // 5. If IsConstructor(func) is false, throw a TypeError exception.
  381. if (!func || !Value(func).is_constructor())
  382. return vm.throw_completion<TypeError>(global_object, ErrorType::NotAConstructor, "Super constructor");
  383. // 6. Let result be ? Construct(func, argList, newTarget).
  384. auto* result = TRY(construct(global_object, static_cast<FunctionObject&>(*func), move(arg_list), &new_target.as_function()));
  385. // 7. Let thisER be GetThisEnvironment().
  386. auto& this_er = verify_cast<FunctionEnvironment>(get_this_environment(interpreter.vm()));
  387. // 8. Perform ? thisER.BindThisValue(result).
  388. TRY(this_er.bind_this_value(global_object, result));
  389. // 9. Let F be thisER.[[FunctionObject]].
  390. // 10. Assert: F is an ECMAScript function object. (NOTE: This is implied by the strong C++ type.)
  391. [[maybe_unused]] auto& f = this_er.function_object();
  392. // 11. Perform ? InitializeInstanceElements(result, F).
  393. TRY(vm.initialize_instance_elements(*result, f));
  394. // 12. Return result.
  395. return Value { result };
  396. }
  397. // 15.5.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-generator-function-definitions-runtime-semantics-evaluation
  398. Completion YieldExpression::execute(Interpreter&, GlobalObject&) const
  399. {
  400. // This should be transformed to a return.
  401. VERIFY_NOT_REACHED();
  402. }
  403. // 15.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-async-function-definitions-runtime-semantics-evaluation
  404. Completion AwaitExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  405. {
  406. InterpreterNodeScope node_scope { interpreter, *this };
  407. // 1. Let exprRef be the result of evaluating UnaryExpression.
  408. // 2. Let value be ? GetValue(exprRef).
  409. auto value = TRY(m_argument->execute(interpreter, global_object)).release_value();
  410. // 3. Return ? Await(value).
  411. return await(global_object, value);
  412. }
  413. // 14.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-return-statement-runtime-semantics-evaluation
  414. Completion ReturnStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  415. {
  416. InterpreterNodeScope node_scope { interpreter, *this };
  417. // ReturnStatement : return ;
  418. if (!m_argument) {
  419. // 1. Return Completion { [[Type]]: return, [[Value]]: undefined, [[Target]]: empty }.
  420. return { Completion::Type::Return, js_undefined(), {} };
  421. }
  422. // ReturnStatement : return Expression ;
  423. // 1. Let exprRef be the result of evaluating Expression.
  424. // 2. Let exprValue be ? GetValue(exprRef).
  425. auto value = TRY(m_argument->execute(interpreter, global_object));
  426. // NOTE: Generators are not supported in the AST interpreter
  427. // 3. If ! GetGeneratorKind() is async, set exprValue to ? Await(exprValue).
  428. // 4. Return Completion { [[Type]]: return, [[Value]]: exprValue, [[Target]]: empty }.
  429. return { Completion::Type::Return, value, {} };
  430. }
  431. // 14.6.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-if-statement-runtime-semantics-evaluation
  432. Completion IfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  433. {
  434. InterpreterNodeScope node_scope { interpreter, *this };
  435. // IfStatement : if ( Expression ) Statement else Statement
  436. // 1. Let exprRef be the result of evaluating Expression.
  437. // 2. Let exprValue be ! ToBoolean(? GetValue(exprRef)).
  438. auto predicate_result = TRY(m_predicate->execute(interpreter, global_object)).release_value();
  439. // 3. If exprValue is true, then
  440. if (predicate_result.to_boolean()) {
  441. // a. Let stmtCompletion be the result of evaluating the first Statement.
  442. // 5. Return Completion(UpdateEmpty(stmtCompletion, undefined)).
  443. return m_consequent->execute(interpreter, global_object).update_empty(js_undefined());
  444. }
  445. // 4. Else,
  446. if (m_alternate) {
  447. // a. Let stmtCompletion be the result of evaluating the second Statement.
  448. // 5. Return Completion(UpdateEmpty(stmtCompletion, undefined)).
  449. return m_alternate->execute(interpreter, global_object).update_empty(js_undefined());
  450. }
  451. // IfStatement : if ( Expression ) Statement
  452. // 3. If exprValue is false, then
  453. // a. Return NormalCompletion(undefined).
  454. return normal_completion(js_undefined());
  455. }
  456. // 14.11.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-with-statement-runtime-semantics-evaluation
  457. // WithStatement : with ( Expression ) Statement
  458. Completion WithStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  459. {
  460. InterpreterNodeScope node_scope { interpreter, *this };
  461. // 1. Let value be the result of evaluating Expression.
  462. auto value = TRY(m_object->execute(interpreter, global_object)).release_value();
  463. // 2. Let obj be ? ToObject(? GetValue(value)).
  464. auto* object = TRY(value.to_object(global_object));
  465. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  466. auto* old_environment = interpreter.vm().running_execution_context().lexical_environment;
  467. // 4. Let newEnv be NewObjectEnvironment(obj, true, oldEnv).
  468. auto* new_environment = new_object_environment(*object, true, old_environment);
  469. // 5. Set the running execution context's LexicalEnvironment to newEnv.
  470. interpreter.vm().running_execution_context().lexical_environment = new_environment;
  471. // 6. Let C be the result of evaluating Statement.
  472. auto result = m_body->execute(interpreter, global_object);
  473. // 7. Set the running execution context's LexicalEnvironment to oldEnv.
  474. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  475. // 8. Return Completion(UpdateEmpty(C, undefined)).
  476. return result.update_empty(js_undefined());
  477. }
  478. // 14.7.1.1 LoopContinues ( completion, labelSet ), https://tc39.es/ecma262/#sec-loopcontinues
  479. static bool loop_continues(Completion const& completion, Vector<FlyString> const& label_set)
  480. {
  481. // 1. If completion.[[Type]] is normal, return true.
  482. if (completion.type() == Completion::Type::Normal)
  483. return true;
  484. // 2. If completion.[[Type]] is not continue, return false.
  485. if (completion.type() != Completion::Type::Continue)
  486. return false;
  487. // 3. If completion.[[Target]] is empty, return true.
  488. if (!completion.target().has_value())
  489. return true;
  490. // 4. If completion.[[Target]] is an element of labelSet, return true.
  491. if (label_set.contains_slow(*completion.target()))
  492. return true;
  493. // 5. Return false.
  494. return false;
  495. }
  496. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  497. // BreakableStatement : IterationStatement
  498. Completion WhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  499. {
  500. // 1. Let newLabelSet be a new empty List.
  501. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  502. return labelled_evaluation(interpreter, global_object, *this, {});
  503. }
  504. // 14.7.3.2 Runtime Semantics: WhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-whileloopevaluation
  505. Completion WhileStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  506. {
  507. InterpreterNodeScope node_scope { interpreter, *this };
  508. // 1. Let V be undefined.
  509. auto last_value = js_undefined();
  510. // 2. Repeat,
  511. for (;;) {
  512. // a. Let exprRef be the result of evaluating Expression.
  513. // b. Let exprValue be ? GetValue(exprRef).
  514. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  515. // c. If ! ToBoolean(exprValue) is false, return NormalCompletion(V).
  516. if (!test_result.to_boolean())
  517. return normal_completion(last_value);
  518. // d. Let stmtResult be the result of evaluating Statement.
  519. auto body_result = m_body->execute(interpreter, global_object);
  520. // e. If LoopContinues(stmtResult, labelSet) is false, return Completion(UpdateEmpty(stmtResult, V)).
  521. if (!loop_continues(body_result, label_set))
  522. return body_result.update_empty(last_value);
  523. // f. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
  524. if (body_result.value().has_value())
  525. last_value = *body_result.value();
  526. }
  527. VERIFY_NOT_REACHED();
  528. }
  529. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  530. // BreakableStatement : IterationStatement
  531. Completion DoWhileStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  532. {
  533. // 1. Let newLabelSet be a new empty List.
  534. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  535. return labelled_evaluation(interpreter, global_object, *this, {});
  536. }
  537. // 14.7.2.2 Runtime Semantics: DoWhileLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-dowhileloopevaluation
  538. Completion DoWhileStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  539. {
  540. InterpreterNodeScope node_scope { interpreter, *this };
  541. // 1. Let V be undefined.
  542. auto last_value = js_undefined();
  543. // 2. Repeat,
  544. for (;;) {
  545. // a. Let stmtResult be the result of evaluating Statement.
  546. auto body_result = m_body->execute(interpreter, global_object);
  547. // b. If LoopContinues(stmtResult, labelSet) is false, return Completion(UpdateEmpty(stmtResult, V)).
  548. if (!loop_continues(body_result, label_set))
  549. return body_result.update_empty(last_value);
  550. // c. If stmtResult.[[Value]] is not empty, set V to stmtResult.[[Value]].
  551. if (body_result.value().has_value())
  552. last_value = *body_result.value();
  553. // d. Let exprRef be the result of evaluating Expression.
  554. // e. Let exprValue be ? GetValue(exprRef).
  555. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  556. // f. If ! ToBoolean(exprValue) is false, return NormalCompletion(V).
  557. if (!test_result.to_boolean())
  558. return normal_completion(last_value);
  559. }
  560. VERIFY_NOT_REACHED();
  561. }
  562. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  563. // BreakableStatement : IterationStatement
  564. Completion ForStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  565. {
  566. // 1. Let newLabelSet be a new empty List.
  567. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  568. return labelled_evaluation(interpreter, global_object, *this, {});
  569. }
  570. // 14.7.4.2 Runtime Semantics: ForLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forloopevaluation
  571. Completion ForStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  572. {
  573. InterpreterNodeScope node_scope { interpreter, *this };
  574. // Note we don't always set a new environment but to use RAII we must do this here.
  575. auto* old_environment = interpreter.lexical_environment();
  576. ScopeGuard restore_old_environment = [&] {
  577. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  578. };
  579. Vector<FlyString> let_declarations;
  580. if (m_init) {
  581. if (is<VariableDeclaration>(*m_init) && static_cast<VariableDeclaration const&>(*m_init).declaration_kind() != DeclarationKind::Var) {
  582. auto* loop_environment = new_declarative_environment(*old_environment);
  583. auto& declaration = static_cast<VariableDeclaration const&>(*m_init);
  584. declaration.for_each_bound_name([&](auto const& name) {
  585. if (declaration.declaration_kind() == DeclarationKind::Const) {
  586. MUST(loop_environment->create_immutable_binding(global_object, name, true));
  587. } else {
  588. MUST(loop_environment->create_mutable_binding(global_object, name, false));
  589. let_declarations.append(name);
  590. }
  591. });
  592. interpreter.vm().running_execution_context().lexical_environment = loop_environment;
  593. }
  594. (void)TRY(m_init->execute(interpreter, global_object));
  595. }
  596. // 14.7.4.4 CreatePerIterationEnvironment ( perIterationBindings ), https://tc39.es/ecma262/#sec-createperiterationenvironment
  597. auto create_per_iteration_environment = [&]() -> ThrowCompletionOr<void> {
  598. // 1. If perIterationBindings has any elements, then
  599. if (let_declarations.is_empty())
  600. return {};
  601. // a. Let lastIterationEnv be the running execution context's LexicalEnvironment.
  602. auto* last_iteration_env = interpreter.lexical_environment();
  603. // b. Let outer be lastIterationEnv.[[OuterEnv]].
  604. auto* outer = last_iteration_env->outer_environment();
  605. // c. Assert: outer is not null.
  606. VERIFY(outer);
  607. // d. Let thisIterationEnv be NewDeclarativeEnvironment(outer).
  608. auto* this_iteration_env = new_declarative_environment(*outer);
  609. // e. For each element bn of perIterationBindings, do
  610. for (auto& name : let_declarations) {
  611. // i. Perform ! thisIterationEnv.CreateMutableBinding(bn, false).
  612. MUST(this_iteration_env->create_mutable_binding(global_object, name, false));
  613. // ii. Let lastValue be ? lastIterationEnv.GetBindingValue(bn, true).
  614. auto last_value = TRY(last_iteration_env->get_binding_value(global_object, name, true));
  615. VERIFY(!last_value.is_empty());
  616. // iii. Perform thisIterationEnv.InitializeBinding(bn, lastValue).
  617. MUST(this_iteration_env->initialize_binding(global_object, name, last_value));
  618. }
  619. // f. Set the running execution context's LexicalEnvironment to thisIterationEnv.
  620. interpreter.vm().running_execution_context().lexical_environment = this_iteration_env;
  621. // 2. Return undefined.
  622. return {};
  623. };
  624. // 14.7.4.3 ForBodyEvaluation ( test, increment, stmt, perIterationBindings, labelSet ), https://tc39.es/ecma262/#sec-forbodyevaluation
  625. // 1. Let V be undefined.
  626. auto last_value = js_undefined();
  627. // 2. Perform ? CreatePerIterationEnvironment(perIterationBindings).
  628. TRY(create_per_iteration_environment());
  629. // 3. Repeat,
  630. while (true) {
  631. // a. If test is not [empty], then
  632. if (m_test) {
  633. // i. Let testRef be the result of evaluating test.
  634. // ii. Let testValue be ? GetValue(testRef).
  635. auto test_value = TRY(m_test->execute(interpreter, global_object)).release_value();
  636. // iii. If ! ToBoolean(testValue) is false, return NormalCompletion(V).
  637. if (!test_value.to_boolean())
  638. return normal_completion(last_value);
  639. }
  640. // b. Let result be the result of evaluating stmt.
  641. auto result = m_body->execute(interpreter, global_object);
  642. // c. If LoopContinues(result, labelSet) is false, return Completion(UpdateEmpty(result, V)).
  643. if (!loop_continues(result, label_set))
  644. return result.update_empty(last_value);
  645. // d. If result.[[Value]] is not empty, set V to result.[[Value]].
  646. if (result.value().has_value())
  647. last_value = *result.value();
  648. // e. Perform ? CreatePerIterationEnvironment(perIterationBindings).
  649. TRY(create_per_iteration_environment());
  650. // f. If increment is not [empty], then
  651. if (m_update) {
  652. // i. Let incRef be the result of evaluating increment.
  653. // ii. Perform ? GetValue(incRef).
  654. (void)TRY(m_update->execute(interpreter, global_object));
  655. }
  656. }
  657. VERIFY_NOT_REACHED();
  658. }
  659. struct ForInOfHeadState {
  660. explicit ForInOfHeadState(Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs)
  661. {
  662. lhs.visit(
  663. [&](NonnullRefPtr<ASTNode>& ast_node) {
  664. expression_lhs = ast_node.ptr();
  665. },
  666. [&](NonnullRefPtr<BindingPattern>& pattern) {
  667. pattern_lhs = pattern.ptr();
  668. destructuring = true;
  669. lhs_kind = Assignment;
  670. });
  671. }
  672. ASTNode* expression_lhs = nullptr;
  673. BindingPattern* pattern_lhs = nullptr;
  674. enum LhsKind {
  675. Assignment,
  676. VarBinding,
  677. LexicalBinding
  678. };
  679. LhsKind lhs_kind = Assignment;
  680. bool destructuring = false;
  681. Value rhs_value;
  682. // 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
  683. // Note: This is only steps 6.g through 6.j of the method because we currently implement for-in without an iterator so to prevent duplicated code we do this part here.
  684. ThrowCompletionOr<void> execute_head(Interpreter& interpreter, GlobalObject& global_object, Value next_value) const
  685. {
  686. VERIFY(!next_value.is_empty());
  687. Optional<Reference> lhs_reference;
  688. Environment* iteration_environment = nullptr;
  689. // g. If lhsKind is either assignment or varBinding, then
  690. if (lhs_kind == Assignment || lhs_kind == VarBinding) {
  691. if (!destructuring) {
  692. VERIFY(expression_lhs);
  693. if (is<VariableDeclaration>(*expression_lhs)) {
  694. auto& declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  695. VERIFY(declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  696. lhs_reference = TRY(declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->to_reference(interpreter, global_object));
  697. } else {
  698. VERIFY(is<Identifier>(*expression_lhs) || is<MemberExpression>(*expression_lhs));
  699. auto& expression = static_cast<Expression const&>(*expression_lhs);
  700. lhs_reference = TRY(expression.to_reference(interpreter, global_object));
  701. }
  702. }
  703. }
  704. // h. Else,
  705. else {
  706. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  707. iteration_environment = new_declarative_environment(*interpreter.lexical_environment());
  708. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  709. for_declaration.for_each_bound_name([&](auto const& name) {
  710. if (for_declaration.declaration_kind() == DeclarationKind::Const)
  711. MUST(iteration_environment->create_immutable_binding(global_object, name, false));
  712. else
  713. MUST(iteration_environment->create_mutable_binding(global_object, name, true));
  714. });
  715. interpreter.vm().running_execution_context().lexical_environment = iteration_environment;
  716. if (!destructuring) {
  717. VERIFY(for_declaration.declarations().first().target().has<NonnullRefPtr<Identifier>>());
  718. lhs_reference = MUST(interpreter.vm().resolve_binding(for_declaration.declarations().first().target().get<NonnullRefPtr<Identifier>>()->string()));
  719. }
  720. }
  721. // i. If destructuring is false, then
  722. if (!destructuring) {
  723. VERIFY(lhs_reference.has_value());
  724. if (lhs_kind == LexicalBinding)
  725. return lhs_reference->initialize_referenced_binding(global_object, next_value);
  726. else
  727. return lhs_reference->put_value(global_object, next_value);
  728. }
  729. // j. Else,
  730. if (lhs_kind == Assignment) {
  731. VERIFY(pattern_lhs);
  732. return interpreter.vm().destructuring_assignment_evaluation(*pattern_lhs, next_value, global_object);
  733. }
  734. VERIFY(expression_lhs && is<VariableDeclaration>(*expression_lhs));
  735. auto& for_declaration = static_cast<VariableDeclaration const&>(*expression_lhs);
  736. auto& binding_pattern = for_declaration.declarations().first().target().get<NonnullRefPtr<BindingPattern>>();
  737. VERIFY(lhs_kind == VarBinding || iteration_environment);
  738. // At this point iteration_environment is undefined if lhs_kind == VarBinding which means this does both
  739. // branch j.ii and j.iii because ForBindingInitialization is just a forwarding call to BindingInitialization.
  740. return interpreter.vm().binding_initialization(binding_pattern, next_value, iteration_environment, global_object);
  741. }
  742. };
  743. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  744. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  745. // This method combines ForInOfLoopEvaluation and ForIn/OfHeadEvaluation for similar reason as ForIn/OfBodyEvaluation, to prevent code duplication.
  746. // For the same reason we also skip step 6 and 7 of ForIn/OfHeadEvaluation as this is done by the appropriate for loop type.
  747. static ThrowCompletionOr<ForInOfHeadState> for_in_of_head_execute(Interpreter& interpreter, GlobalObject& global_object, Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> lhs, Expression const& rhs)
  748. {
  749. ForInOfHeadState state(lhs);
  750. if (auto* ast_ptr = lhs.get_pointer<NonnullRefPtr<ASTNode>>(); ast_ptr && is<VariableDeclaration>(*(*ast_ptr))) {
  751. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  752. // ForInOfStatement : for ( var ForBinding in Expression ) Statement
  753. // ForInOfStatement : for ( ForDeclaration in Expression ) Statement
  754. // ForInOfStatement : for ( var ForBinding of AssignmentExpression ) Statement
  755. // ForInOfStatement : for ( ForDeclaration of AssignmentExpression ) Statement
  756. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  757. Environment* new_environment = nullptr;
  758. auto& variable_declaration = static_cast<VariableDeclaration const&>(*(*ast_ptr));
  759. VERIFY(variable_declaration.declarations().size() == 1);
  760. state.destructuring = variable_declaration.declarations().first().target().has<NonnullRefPtr<BindingPattern>>();
  761. if (variable_declaration.declaration_kind() == DeclarationKind::Var) {
  762. state.lhs_kind = ForInOfHeadState::VarBinding;
  763. auto& variable = variable_declaration.declarations().first();
  764. // B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  765. if (variable.init()) {
  766. VERIFY(variable.target().has<NonnullRefPtr<Identifier>>());
  767. auto& binding_id = variable.target().get<NonnullRefPtr<Identifier>>()->string();
  768. auto reference = TRY(interpreter.vm().resolve_binding(binding_id));
  769. auto result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *variable.init(), binding_id));
  770. TRY(reference.put_value(global_object, result));
  771. }
  772. } else {
  773. state.lhs_kind = ForInOfHeadState::LexicalBinding;
  774. new_environment = new_declarative_environment(*interpreter.lexical_environment());
  775. variable_declaration.for_each_bound_name([&](auto const& name) {
  776. MUST(new_environment->create_mutable_binding(global_object, name, false));
  777. });
  778. }
  779. if (new_environment) {
  780. // 2.d Set the running execution context's LexicalEnvironment to newEnv.
  781. TemporaryChange<Environment*> scope_change(interpreter.vm().running_execution_context().lexical_environment, new_environment);
  782. // 3. Let exprRef be the result of evaluating expr.
  783. // 5. Let exprValue be ? GetValue(exprRef).
  784. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  785. // Note that since a reference stores its environment it doesn't matter we only reset
  786. // this after step 5. (Also we have no way of separating these steps at this point)
  787. // 4. Set the running execution context's LexicalEnvironment to oldEnv.
  788. } else {
  789. // 3. Let exprRef be the result of evaluating expr.
  790. // 5. Let exprValue be ? GetValue(exprRef).
  791. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  792. }
  793. return state;
  794. }
  795. // Runtime Semantics: ForInOfLoopEvaluation, for any of:
  796. // ForInOfStatement : for ( LeftHandSideExpression in Expression ) Statement
  797. // ForInOfStatement : for ( LeftHandSideExpression of AssignmentExpression ) Statement
  798. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  799. // We can skip step 1, 2 and 4 here (on top of already skipping step 6 and 7).
  800. // 3. Let exprRef be the result of evaluating expr.
  801. // 5. Let exprValue be ? GetValue(exprRef).
  802. state.rhs_value = TRY(rhs.execute(interpreter, global_object)).release_value();
  803. return state;
  804. }
  805. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  806. // BreakableStatement : IterationStatement
  807. Completion ForInStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  808. {
  809. // 1. Let newLabelSet be a new empty List.
  810. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  811. return labelled_evaluation(interpreter, global_object, *this, {});
  812. }
  813. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  814. Completion ForInStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  815. {
  816. InterpreterNodeScope node_scope { interpreter, *this };
  817. auto for_in_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, *m_rhs));
  818. auto rhs_result = for_in_head_state.rhs_value;
  819. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  820. // a. If exprValue is undefined or null, then
  821. if (rhs_result.is_nullish()) {
  822. // i. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  823. return { Completion::Type::Break, {}, {} };
  824. }
  825. // b. Let obj be ! ToObject(exprValue).
  826. auto* object = MUST(rhs_result.to_object(global_object));
  827. // 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
  828. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  829. Environment* old_environment = interpreter.lexical_environment();
  830. auto restore_scope = ScopeGuard([&] {
  831. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  832. });
  833. // 3. Let V be undefined.
  834. auto last_value = js_undefined();
  835. while (object) {
  836. auto property_names = TRY(object->enumerable_own_property_names(Object::PropertyKind::Key));
  837. for (auto& value : property_names) {
  838. TRY(for_in_head_state.execute_head(interpreter, global_object, value));
  839. // l. Let result be the result of evaluating stmt.
  840. auto result = m_body->execute(interpreter, global_object);
  841. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  842. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  843. // n. If LoopContinues(result, labelSet) is false, then
  844. if (!loop_continues(result, label_set)) {
  845. // 1. Return Completion(UpdateEmpty(result, V)).
  846. return result.update_empty(last_value);
  847. }
  848. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  849. if (result.value().has_value())
  850. last_value = *result.value();
  851. }
  852. object = TRY(object->internal_get_prototype_of());
  853. }
  854. return last_value;
  855. }
  856. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  857. // BreakableStatement : IterationStatement
  858. Completion ForOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  859. {
  860. // 1. Let newLabelSet be a new empty List.
  861. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  862. return labelled_evaluation(interpreter, global_object, *this, {});
  863. }
  864. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  865. Completion ForOfStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  866. {
  867. InterpreterNodeScope node_scope { interpreter, *this };
  868. auto for_of_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs));
  869. auto rhs_result = for_of_head_state.rhs_value;
  870. // 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
  871. // We use get_iterator_values which behaves like ForIn/OfBodyEvaluation with iteratorKind iterate.
  872. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  873. Environment* old_environment = interpreter.lexical_environment();
  874. auto restore_scope = ScopeGuard([&] {
  875. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  876. });
  877. // 3. Let V be undefined.
  878. auto last_value = js_undefined();
  879. Optional<Completion> status;
  880. (void)TRY(get_iterator_values(global_object, rhs_result, [&](Value value) -> Optional<Completion> {
  881. TRY(for_of_head_state.execute_head(interpreter, global_object, value));
  882. // l. Let result be the result of evaluating stmt.
  883. auto result = m_body->execute(interpreter, global_object);
  884. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  885. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  886. // n. If LoopContinues(result, labelSet) is false, then
  887. if (!loop_continues(result, label_set)) {
  888. // 2. Set status to UpdateEmpty(result, V).
  889. status = result.update_empty(last_value);
  890. // 4. Return ? IteratorClose(iteratorRecord, status).
  891. // NOTE: This is done by returning a completion from the callback.
  892. return status;
  893. }
  894. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  895. if (result.value().has_value())
  896. last_value = *result.value();
  897. return {};
  898. }));
  899. // Return `status` set during step n.2. in the callback, or...
  900. // e. If done is true, return NormalCompletion(V).
  901. return status.value_or(normal_completion(last_value));
  902. }
  903. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  904. // BreakableStatement : IterationStatement
  905. Completion ForAwaitOfStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  906. {
  907. // 1. Let newLabelSet be a new empty List.
  908. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  909. return labelled_evaluation(interpreter, global_object, *this, {});
  910. }
  911. // 14.7.5.5 Runtime Semantics: ForInOfLoopEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-forinofloopevaluation
  912. Completion ForAwaitOfStatement::loop_evaluation(Interpreter& interpreter, GlobalObject& global_object, Vector<FlyString> const& label_set) const
  913. {
  914. InterpreterNodeScope node_scope { interpreter, *this };
  915. // 14.7.5.6 ForIn/OfHeadEvaluation ( uninitializedBoundNames, expr, iterationKind ), https://tc39.es/ecma262/#sec-runtime-semantics-forinofheadevaluation
  916. // Note: Performs only steps 1 through 5.
  917. auto for_of_head_state = TRY(for_in_of_head_execute(interpreter, global_object, m_lhs, m_rhs));
  918. auto rhs_result = for_of_head_state.rhs_value;
  919. // NOTE: Perform step 7 from ForIn/OfHeadEvaluation. And since this is always async we only have to do step 7.d.
  920. // d. Return ? GetIterator(exprValue, iteratorHint).
  921. auto* iterator = TRY(get_iterator(global_object, rhs_result, IteratorHint::Async));
  922. VERIFY(iterator);
  923. auto& vm = interpreter.vm();
  924. // 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
  925. // NOTE: Here iteratorKind is always async.
  926. // 2. Let oldEnv be the running execution context's LexicalEnvironment.
  927. Environment* old_environment = interpreter.lexical_environment();
  928. auto restore_scope = ScopeGuard([&] {
  929. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  930. });
  931. // 3. Let V be undefined.
  932. auto last_value = js_undefined();
  933. // NOTE: Step 4 and 5 are just extracting properties from the head which is done already in for_in_of_head_execute.
  934. // And these are only used in step 6.g through 6.k which is done with for_of_head_state.execute_head.
  935. // 6. Repeat,
  936. while (true) {
  937. // NOTE: Since we don't have iterator records yet we have to extract the function first.
  938. auto next_method = TRY(iterator->get(vm.names.next));
  939. if (!next_method.is_function())
  940. return vm.throw_completion<TypeError>(global_object, ErrorType::IterableNextNotAFunction);
  941. // a. Let nextResult be ? Call(iteratorRecord.[[NextMethod]], iteratorRecord.[[Iterator]]).
  942. auto next_result = TRY(call(global_object, next_method, iterator));
  943. // b. If iteratorKind is async, set nextResult to ? Await(nextResult).
  944. next_result = TRY(await(global_object, next_result));
  945. // c. If Type(nextResult) is not Object, throw a TypeError exception.
  946. if (!next_result.is_object())
  947. return vm.throw_completion<TypeError>(global_object, ErrorType::IterableNextBadReturn);
  948. // d. Let done be ? IteratorComplete(nextResult).
  949. auto done = TRY(iterator_complete(global_object, next_result.as_object()));
  950. // e. If done is true, return NormalCompletion(V).
  951. if (done)
  952. return last_value;
  953. // f. Let nextValue be ? IteratorValue(nextResult).
  954. auto next_value = TRY(iterator_value(global_object, next_result.as_object()));
  955. // NOTE: This performs steps g. through to k.
  956. TRY(for_of_head_state.execute_head(interpreter, global_object, next_value));
  957. // l. Let result be the result of evaluating stmt.
  958. auto result = m_body->execute(interpreter, global_object);
  959. // m. Set the running execution context's LexicalEnvironment to oldEnv.
  960. interpreter.vm().running_execution_context().lexical_environment = old_environment;
  961. // n. If LoopContinues(result, labelSet) is false, then
  962. if (!loop_continues(result, label_set)) {
  963. // 2. Set status to UpdateEmpty(result, V).
  964. auto status = result.update_empty(last_value);
  965. // 3. If iteratorKind is async, return ? AsyncIteratorClose(iteratorRecord, status).
  966. return async_iterator_close(*iterator, move(status));
  967. }
  968. // o. If result.[[Value]] is not empty, set V to result.[[Value]].
  969. if (result.value().has_value())
  970. last_value = *result.value();
  971. }
  972. VERIFY_NOT_REACHED();
  973. }
  974. // 13.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-exp-operator-runtime-semantics-evaluation
  975. // 13.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-multiplicative-operators-runtime-semantics-evaluation
  976. // 13.8.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-addition-operator-plus-runtime-semantics-evaluation
  977. // 13.8.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-subtraction-operator-minus-runtime-semantics-evaluation
  978. // 13.9.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-left-shift-operator-runtime-semantics-evaluation
  979. // 13.9.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-signed-right-shift-operator-runtime-semantics-evaluation
  980. // 13.9.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unsigned-right-shift-operator-runtime-semantics-evaluation
  981. // 13.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
  982. // 13.11.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-equality-operators-runtime-semantics-evaluation
  983. Completion BinaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  984. {
  985. InterpreterNodeScope node_scope { interpreter, *this };
  986. // Special case in which we cannot execute the lhs. RelationalExpression : PrivateIdentifier in ShiftExpression
  987. // RelationalExpression : PrivateIdentifier in ShiftExpression, https://tc39.es/ecma262/#sec-relational-operators-runtime-semantics-evaluation
  988. if (m_op == BinaryOp::In && is<PrivateIdentifier>(*m_lhs)) {
  989. auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_lhs).string();
  990. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  991. if (!rhs_result.is_object())
  992. return interpreter.vm().throw_completion<TypeError>(global_object, ErrorType::InOperatorWithObject);
  993. auto* private_environment = interpreter.vm().running_execution_context().private_environment;
  994. VERIFY(private_environment);
  995. auto private_name = private_environment->resolve_private_identifier(private_identifier);
  996. return Value(rhs_result.as_object().private_element_find(private_name) != nullptr);
  997. }
  998. auto lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  999. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  1000. switch (m_op) {
  1001. case BinaryOp::Addition:
  1002. return TRY(add(global_object, lhs_result, rhs_result));
  1003. case BinaryOp::Subtraction:
  1004. return TRY(sub(global_object, lhs_result, rhs_result));
  1005. case BinaryOp::Multiplication:
  1006. return TRY(mul(global_object, lhs_result, rhs_result));
  1007. case BinaryOp::Division:
  1008. return TRY(div(global_object, lhs_result, rhs_result));
  1009. case BinaryOp::Modulo:
  1010. return TRY(mod(global_object, lhs_result, rhs_result));
  1011. case BinaryOp::Exponentiation:
  1012. return TRY(exp(global_object, lhs_result, rhs_result));
  1013. case BinaryOp::StrictlyEquals:
  1014. return Value(is_strictly_equal(lhs_result, rhs_result));
  1015. case BinaryOp::StrictlyInequals:
  1016. return Value(!is_strictly_equal(lhs_result, rhs_result));
  1017. case BinaryOp::LooselyEquals:
  1018. return Value(TRY(is_loosely_equal(global_object, lhs_result, rhs_result)));
  1019. case BinaryOp::LooselyInequals:
  1020. return Value(!TRY(is_loosely_equal(global_object, lhs_result, rhs_result)));
  1021. case BinaryOp::GreaterThan:
  1022. return TRY(greater_than(global_object, lhs_result, rhs_result));
  1023. case BinaryOp::GreaterThanEquals:
  1024. return TRY(greater_than_equals(global_object, lhs_result, rhs_result));
  1025. case BinaryOp::LessThan:
  1026. return TRY(less_than(global_object, lhs_result, rhs_result));
  1027. case BinaryOp::LessThanEquals:
  1028. return TRY(less_than_equals(global_object, lhs_result, rhs_result));
  1029. case BinaryOp::BitwiseAnd:
  1030. return TRY(bitwise_and(global_object, lhs_result, rhs_result));
  1031. case BinaryOp::BitwiseOr:
  1032. return TRY(bitwise_or(global_object, lhs_result, rhs_result));
  1033. case BinaryOp::BitwiseXor:
  1034. return TRY(bitwise_xor(global_object, lhs_result, rhs_result));
  1035. case BinaryOp::LeftShift:
  1036. return TRY(left_shift(global_object, lhs_result, rhs_result));
  1037. case BinaryOp::RightShift:
  1038. return TRY(right_shift(global_object, lhs_result, rhs_result));
  1039. case BinaryOp::UnsignedRightShift:
  1040. return TRY(unsigned_right_shift(global_object, lhs_result, rhs_result));
  1041. case BinaryOp::In:
  1042. return TRY(in(global_object, lhs_result, rhs_result));
  1043. case BinaryOp::InstanceOf:
  1044. return TRY(instance_of(global_object, lhs_result, rhs_result));
  1045. }
  1046. VERIFY_NOT_REACHED();
  1047. }
  1048. // 13.13.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-binary-logical-operators-runtime-semantics-evaluation
  1049. Completion LogicalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1050. {
  1051. InterpreterNodeScope node_scope { interpreter, *this };
  1052. // 1. Let lref be the result of evaluating <Expression>.
  1053. // 2. Let lval be ? GetValue(lref).
  1054. auto lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  1055. switch (m_op) {
  1056. // LogicalANDExpression : LogicalANDExpression && BitwiseORExpression
  1057. case LogicalOp::And:
  1058. // 3. Let lbool be ! ToBoolean(lval).
  1059. // 4. If lbool is false, return lval.
  1060. if (!lhs_result.to_boolean())
  1061. return lhs_result;
  1062. // 5. Let rref be the result of evaluating BitwiseORExpression.
  1063. // 6. Return ? GetValue(rref).
  1064. return m_rhs->execute(interpreter, global_object);
  1065. // LogicalORExpression : LogicalORExpression || LogicalANDExpression
  1066. case LogicalOp::Or:
  1067. // 3. Let lbool be ! ToBoolean(lval).
  1068. // 4. If lbool is true, return lval.
  1069. if (lhs_result.to_boolean())
  1070. return lhs_result;
  1071. // 5. Let rref be the result of evaluating LogicalANDExpression.
  1072. // 6. Return ? GetValue(rref).
  1073. return m_rhs->execute(interpreter, global_object);
  1074. // CoalesceExpression : CoalesceExpressionHead ?? BitwiseORExpression
  1075. case LogicalOp::NullishCoalescing:
  1076. // 3. If lval is undefined or null, then
  1077. if (lhs_result.is_nullish()) {
  1078. // a. Let rref be the result of evaluating BitwiseORExpression.
  1079. // b. Return ? GetValue(rref).
  1080. return m_rhs->execute(interpreter, global_object);
  1081. }
  1082. // 4. Otherwise, return lval.
  1083. return lhs_result;
  1084. }
  1085. VERIFY_NOT_REACHED();
  1086. }
  1087. ThrowCompletionOr<Reference> Expression::to_reference(Interpreter&, GlobalObject&) const
  1088. {
  1089. return Reference {};
  1090. }
  1091. ThrowCompletionOr<Reference> Identifier::to_reference(Interpreter& interpreter, GlobalObject&) const
  1092. {
  1093. if (m_cached_environment_coordinate.has_value()) {
  1094. auto* environment = interpreter.vm().running_execution_context().lexical_environment;
  1095. for (size_t i = 0; i < m_cached_environment_coordinate->hops; ++i)
  1096. environment = environment->outer_environment();
  1097. VERIFY(environment);
  1098. VERIFY(environment->is_declarative_environment());
  1099. if (!environment->is_permanently_screwed_by_eval()) {
  1100. return Reference { *environment, string(), interpreter.vm().in_strict_mode(), m_cached_environment_coordinate };
  1101. }
  1102. m_cached_environment_coordinate = {};
  1103. }
  1104. auto reference = TRY(interpreter.vm().resolve_binding(string()));
  1105. if (reference.environment_coordinate().has_value())
  1106. m_cached_environment_coordinate = reference.environment_coordinate();
  1107. return reference;
  1108. }
  1109. ThrowCompletionOr<Reference> MemberExpression::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  1110. {
  1111. // 13.3.7.1 Runtime Semantics: Evaluation
  1112. // SuperProperty : super [ Expression ]
  1113. // SuperProperty : super . IdentifierName
  1114. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  1115. if (is<SuperExpression>(object())) {
  1116. // 1. Let env be GetThisEnvironment().
  1117. auto& environment = get_this_environment(interpreter.vm());
  1118. // 2. Let actualThis be ? env.GetThisBinding().
  1119. auto actual_this = TRY(environment.get_this_binding(global_object));
  1120. PropertyKey property_key;
  1121. if (is_computed()) {
  1122. // SuperProperty : super [ Expression ]
  1123. // 3. Let propertyNameReference be the result of evaluating Expression.
  1124. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  1125. auto property_name_value = TRY(m_property->execute(interpreter, global_object)).release_value();
  1126. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  1127. property_key = TRY(property_name_value.to_property_key(global_object));
  1128. } else {
  1129. // SuperProperty : super . IdentifierName
  1130. // 3. Let propertyKey be StringValue of IdentifierName.
  1131. VERIFY(is<Identifier>(property()));
  1132. property_key = static_cast<Identifier const&>(property()).string();
  1133. }
  1134. // 6. If the code matched by this SuperProperty is strict mode code, let strict be true; else let strict be false.
  1135. bool strict = interpreter.vm().in_strict_mode();
  1136. // 7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  1137. return TRY(make_super_property_reference(global_object, actual_this, property_key, strict));
  1138. }
  1139. auto base_reference = TRY(m_object->to_reference(interpreter, global_object));
  1140. Value base_value;
  1141. if (base_reference.is_valid_reference())
  1142. base_value = TRY(base_reference.get_value(global_object));
  1143. else
  1144. base_value = TRY(m_object->execute(interpreter, global_object)).release_value();
  1145. VERIFY(!base_value.is_empty());
  1146. // From here on equivalent to
  1147. // 13.3.4 EvaluatePropertyAccessWithIdentifierKey ( baseValue, identifierName, strict ), https://tc39.es/ecma262/#sec-evaluate-property-access-with-identifier-key
  1148. PropertyKey property_name;
  1149. if (is_computed()) {
  1150. // Weird order which I can't quite find from the specs.
  1151. auto value = TRY(m_property->execute(interpreter, global_object)).release_value();
  1152. VERIFY(!value.is_empty());
  1153. TRY(require_object_coercible(global_object, base_value));
  1154. property_name = TRY(PropertyKey::from_value(global_object, value));
  1155. } else if (is<PrivateIdentifier>(*m_property)) {
  1156. auto& private_identifier = static_cast<PrivateIdentifier const&>(*m_property);
  1157. return make_private_reference(interpreter.vm(), base_value, private_identifier.string());
  1158. } else {
  1159. property_name = verify_cast<Identifier>(*m_property).string();
  1160. TRY(require_object_coercible(global_object, base_value));
  1161. }
  1162. if (!property_name.is_valid())
  1163. return Reference {};
  1164. auto strict = interpreter.vm().in_strict_mode();
  1165. return Reference { base_value, move(property_name), {}, strict };
  1166. }
  1167. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  1168. // 13.5.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-void-operator-runtime-semantics-evaluation
  1169. // 13.5.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-typeof-operator-runtime-semantics-evaluation
  1170. // 13.5.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-plus-operator-runtime-semantics-evaluation
  1171. // 13.5.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-unary-minus-operator-runtime-semantics-evaluation
  1172. // 13.5.6.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-bitwise-not-operator-runtime-semantics-evaluation
  1173. // 13.5.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-logical-not-operator-runtime-semantics-evaluation
  1174. Completion UnaryExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1175. {
  1176. InterpreterNodeScope node_scope { interpreter, *this };
  1177. auto& vm = interpreter.vm();
  1178. if (m_op == UnaryOp::Delete) {
  1179. auto reference = TRY(m_lhs->to_reference(interpreter, global_object));
  1180. return Value(TRY(reference.delete_(global_object)));
  1181. }
  1182. Value lhs_result;
  1183. if (m_op == UnaryOp::Typeof && is<Identifier>(*m_lhs)) {
  1184. auto reference = TRY(m_lhs->to_reference(interpreter, global_object));
  1185. if (reference.is_unresolvable())
  1186. lhs_result = js_undefined();
  1187. else
  1188. lhs_result = TRY(reference.get_value(global_object));
  1189. VERIFY(!lhs_result.is_empty());
  1190. } else {
  1191. // 1. Let expr be the result of evaluating UnaryExpression.
  1192. lhs_result = TRY(m_lhs->execute(interpreter, global_object)).release_value();
  1193. }
  1194. switch (m_op) {
  1195. case UnaryOp::BitwiseNot:
  1196. return TRY(bitwise_not(global_object, lhs_result));
  1197. case UnaryOp::Not:
  1198. return Value(!lhs_result.to_boolean());
  1199. case UnaryOp::Plus:
  1200. return TRY(unary_plus(global_object, lhs_result));
  1201. case UnaryOp::Minus:
  1202. return TRY(unary_minus(global_object, lhs_result));
  1203. case UnaryOp::Typeof:
  1204. return Value { js_string(vm, lhs_result.typeof()) };
  1205. case UnaryOp::Void:
  1206. return js_undefined();
  1207. case UnaryOp::Delete:
  1208. VERIFY_NOT_REACHED();
  1209. }
  1210. VERIFY_NOT_REACHED();
  1211. }
  1212. Completion SuperExpression::execute(Interpreter&, GlobalObject&) const
  1213. {
  1214. // The semantics for SuperExpression are handled in CallExpression and SuperCall.
  1215. VERIFY_NOT_REACHED();
  1216. }
  1217. Completion ClassElement::execute(Interpreter&, GlobalObject&) const
  1218. {
  1219. // Note: The semantics of class element are handled in class_element_evaluation
  1220. VERIFY_NOT_REACHED();
  1221. }
  1222. static ThrowCompletionOr<ClassElement::ClassElementName> class_key_to_property_name(Interpreter& interpreter, GlobalObject& global_object, Expression const& key)
  1223. {
  1224. if (is<PrivateIdentifier>(key)) {
  1225. auto& private_identifier = static_cast<PrivateIdentifier const&>(key);
  1226. auto* private_environment = interpreter.vm().running_execution_context().private_environment;
  1227. VERIFY(private_environment);
  1228. return ClassElement::ClassElementName { private_environment->resolve_private_identifier(private_identifier.string()) };
  1229. }
  1230. auto prop_key = TRY(key.execute(interpreter, global_object)).release_value();
  1231. if (prop_key.is_object())
  1232. prop_key = TRY(prop_key.to_primitive(global_object, Value::PreferredType::String));
  1233. auto property_key = TRY(PropertyKey::from_value(global_object, prop_key));
  1234. return ClassElement::ClassElementName { property_key };
  1235. }
  1236. // 15.4.5 Runtime Semantics: MethodDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-methoddefinitionevaluation
  1237. ThrowCompletionOr<ClassElement::ClassValue> ClassMethod::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& target) const
  1238. {
  1239. auto property_key = TRY(class_key_to_property_name(interpreter, global_object, *m_key));
  1240. auto method_value = TRY(m_function->execute(interpreter, global_object)).release_value();
  1241. auto& method_function = static_cast<ECMAScriptFunctionObject&>(method_value.as_function());
  1242. method_function.make_method(target);
  1243. auto set_function_name = [&](String prefix = "") {
  1244. auto property_name = property_key.visit(
  1245. [&](PropertyKey const& property_name) -> String {
  1246. if (property_name.is_symbol()) {
  1247. auto description = property_name.as_symbol()->description();
  1248. if (description.is_empty())
  1249. return "";
  1250. return String::formatted("[{}]", description);
  1251. } else {
  1252. return property_name.to_string();
  1253. }
  1254. },
  1255. [&](PrivateName const& private_name) -> String {
  1256. return private_name.description;
  1257. });
  1258. update_function_name(method_value, String::formatted("{}{}{}", prefix, prefix.is_empty() ? "" : " ", property_name));
  1259. };
  1260. if (property_key.has<PropertyKey>()) {
  1261. auto& property_name = property_key.get<PropertyKey>();
  1262. switch (kind()) {
  1263. case ClassMethod::Kind::Method:
  1264. set_function_name();
  1265. TRY(target.define_property_or_throw(property_name, { .value = method_value, .writable = true, .enumerable = false, .configurable = true }));
  1266. break;
  1267. case ClassMethod::Kind::Getter:
  1268. set_function_name("get");
  1269. TRY(target.define_property_or_throw(property_name, { .get = &method_function, .enumerable = true, .configurable = true }));
  1270. break;
  1271. case ClassMethod::Kind::Setter:
  1272. set_function_name("set");
  1273. TRY(target.define_property_or_throw(property_name, { .set = &method_function, .enumerable = true, .configurable = true }));
  1274. break;
  1275. default:
  1276. VERIFY_NOT_REACHED();
  1277. }
  1278. return ClassValue { normal_completion({}) };
  1279. } else {
  1280. auto& private_name = property_key.get<PrivateName>();
  1281. switch (kind()) {
  1282. case Kind::Method:
  1283. set_function_name();
  1284. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Method, method_value } };
  1285. case Kind::Getter:
  1286. set_function_name("get");
  1287. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Accessor::create(interpreter.vm(), &method_function, nullptr) } };
  1288. case Kind::Setter:
  1289. set_function_name("set");
  1290. return ClassValue { PrivateElement { private_name, PrivateElement::Kind::Accessor, Accessor::create(interpreter.vm(), nullptr, &method_function) } };
  1291. default:
  1292. VERIFY_NOT_REACHED();
  1293. }
  1294. }
  1295. }
  1296. // We use this class to mimic Initializer : = AssignmentExpression of
  1297. // 10.2.1.3 Runtime Semantics: EvaluateBody, https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
  1298. class ClassFieldInitializerStatement : public Statement {
  1299. public:
  1300. ClassFieldInitializerStatement(SourceRange source_range, NonnullRefPtr<Expression> expression, FlyString field_name)
  1301. : Statement(source_range)
  1302. , m_expression(move(expression))
  1303. , m_class_field_identifier_name(move(field_name))
  1304. {
  1305. }
  1306. Completion execute(Interpreter& interpreter, GlobalObject& global_object) const override
  1307. {
  1308. // 1. Assert: argumentsList is empty.
  1309. VERIFY(interpreter.vm().argument_count() == 0);
  1310. // 2. Assert: functionObject.[[ClassFieldInitializerName]] is not empty.
  1311. VERIFY(!m_class_field_identifier_name.is_empty());
  1312. // 3. If IsAnonymousFunctionDefinition(AssignmentExpression) is true, then
  1313. // a. Let value be NamedEvaluation of Initializer with argument functionObject.[[ClassFieldInitializerName]].
  1314. // 4. Else,
  1315. // a. Let rhs be the result of evaluating AssignmentExpression.
  1316. // b. Let value be ? GetValue(rhs).
  1317. auto value = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_expression, m_class_field_identifier_name));
  1318. // 5. Return Completion { [[Type]]: return, [[Value]]: value, [[Target]]: empty }.
  1319. return { Completion::Type::Return, value, {} };
  1320. }
  1321. void dump(int) const override
  1322. {
  1323. // This should not be dumped as it is never part of an actual AST.
  1324. VERIFY_NOT_REACHED();
  1325. }
  1326. private:
  1327. NonnullRefPtr<Expression> m_expression;
  1328. FlyString m_class_field_identifier_name; // [[ClassFieldIdentifierName]]
  1329. };
  1330. // 15.7.10 Runtime Semantics: ClassFieldDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classfielddefinitionevaluation
  1331. ThrowCompletionOr<ClassElement::ClassValue> ClassField::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& target) const
  1332. {
  1333. auto property_key = TRY(class_key_to_property_name(interpreter, global_object, *m_key));
  1334. ECMAScriptFunctionObject* initializer = nullptr;
  1335. if (m_initializer) {
  1336. auto copy_initializer = m_initializer;
  1337. auto name = property_key.visit(
  1338. [&](PropertyKey const& property_name) -> String {
  1339. return property_name.is_number() ? property_name.to_string() : property_name.to_string_or_symbol().to_display_string();
  1340. },
  1341. [&](PrivateName const& private_name) -> String {
  1342. return private_name.description;
  1343. });
  1344. // FIXME: A potential optimization is not creating the functions here since these are never directly accessible.
  1345. auto function_code = create_ast_node<ClassFieldInitializerStatement>(m_initializer->source_range(), copy_initializer.release_nonnull(), name);
  1346. initializer = ECMAScriptFunctionObject::create(interpreter.global_object(), String::empty(), *function_code, {}, 0, interpreter.lexical_environment(), interpreter.vm().running_execution_context().private_environment, FunctionKind::Regular, true, false, m_contains_direct_call_to_eval, false);
  1347. initializer->make_method(target);
  1348. }
  1349. return ClassValue {
  1350. ClassFieldDefinition {
  1351. property_key,
  1352. initializer,
  1353. }
  1354. };
  1355. }
  1356. static Optional<FlyString> nullopt_or_private_identifier_description(Expression const& expression)
  1357. {
  1358. if (is<PrivateIdentifier>(expression))
  1359. return static_cast<PrivateIdentifier const&>(expression).string();
  1360. return {};
  1361. }
  1362. Optional<FlyString> ClassField::private_bound_identifier() const
  1363. {
  1364. return nullopt_or_private_identifier_description(*m_key);
  1365. }
  1366. Optional<FlyString> ClassMethod::private_bound_identifier() const
  1367. {
  1368. return nullopt_or_private_identifier_description(*m_key);
  1369. }
  1370. // 15.7.11 Runtime Semantics: ClassStaticBlockDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classstaticblockdefinitionevaluation
  1371. ThrowCompletionOr<ClassElement::ClassValue> StaticInitializer::class_element_evaluation(Interpreter& interpreter, GlobalObject& global_object, Object& home_object) const
  1372. {
  1373. // 1. Let lex be the running execution context's LexicalEnvironment.
  1374. auto* lexical_environment = interpreter.vm().running_execution_context().lexical_environment;
  1375. // 2. Let privateScope be the running execution context's PrivateEnvironment.
  1376. auto* private_scope = interpreter.vm().running_execution_context().private_environment;
  1377. // 3. Let sourceText be the empty sequence of Unicode code points.
  1378. // 4. Let formalParameters be an instance of the production FormalParameters : [empty] .
  1379. // 5. Let bodyFunction be OrdinaryFunctionCreate(%Function.prototype%, sourceText, formalParameters, ClassStaticBlockBody, non-lexical-this, lex, privateScope).
  1380. // Note: The function bodyFunction is never directly accessible to ECMAScript code.
  1381. auto* body_function = ECMAScriptFunctionObject::create(global_object, "", *m_function_body, {}, 0, lexical_environment, private_scope, FunctionKind::Regular, true, false, m_contains_direct_call_to_eval, false);
  1382. // 6. Perform MakeMethod(bodyFunction, homeObject).
  1383. body_function->make_method(home_object);
  1384. // 7. Return the ClassStaticBlockDefinition Record { [[BodyFunction]]: bodyFunction }.
  1385. return ClassValue { normal_completion(body_function) };
  1386. }
  1387. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1388. // ClassExpression : class BindingIdentifier ClassTail
  1389. Completion ClassExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1390. {
  1391. InterpreterNodeScope node_scope { interpreter, *this };
  1392. // 1. Let className be StringValue of BindingIdentifier.
  1393. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1394. auto value = TRY(class_definition_evaluation(interpreter, global_object, m_name, m_name.is_null() ? "" : m_name));
  1395. // FIXME:
  1396. // 3. Set value.[[SourceText]] to the source text matched by ClassExpression.
  1397. // 4. Return value.
  1398. return value;
  1399. }
  1400. // 15.7.16 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-class-definitions-runtime-semantics-evaluation
  1401. // ClassDeclaration : class BindingIdentifier ClassTail
  1402. Completion ClassDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  1403. {
  1404. InterpreterNodeScope node_scope { interpreter, *this };
  1405. // 1. Perform ? BindingClassDeclarationEvaluation of this ClassDeclaration.
  1406. (void)TRY(binding_class_declaration_evaluation(interpreter, global_object));
  1407. // 2. Return NormalCompletion(empty).
  1408. return normal_completion({});
  1409. }
  1410. // 15.7.14 Runtime Semantics: ClassDefinitionEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-classdefinitionevaluation
  1411. ThrowCompletionOr<Value> ClassExpression::class_definition_evaluation(Interpreter& interpreter, GlobalObject& global_object, FlyString const& binding_name, FlyString const& class_name) const
  1412. {
  1413. auto& vm = interpreter.vm();
  1414. auto* environment = vm.lexical_environment();
  1415. VERIFY(environment);
  1416. auto* class_scope = new_declarative_environment(*environment);
  1417. // We might not set the lexical environment but we always want to restore it eventually.
  1418. ArmedScopeGuard restore_environment = [&] {
  1419. vm.running_execution_context().lexical_environment = environment;
  1420. };
  1421. if (!binding_name.is_null())
  1422. MUST(class_scope->create_immutable_binding(global_object, binding_name, true));
  1423. auto* outer_private_environment = vm.running_execution_context().private_environment;
  1424. auto* class_private_environment = new_private_environment(vm, outer_private_environment);
  1425. for (auto const& element : m_elements) {
  1426. auto opt_private_name = element.private_bound_identifier();
  1427. if (opt_private_name.has_value())
  1428. class_private_environment->add_private_name({}, opt_private_name.release_value());
  1429. }
  1430. auto* proto_parent = vm.current_realm()->global_object().object_prototype();
  1431. auto* constructor_parent = vm.current_realm()->global_object().function_prototype();
  1432. if (!m_super_class.is_null()) {
  1433. vm.running_execution_context().lexical_environment = class_scope;
  1434. // Note: Since our execute does evaluation and GetValue in once we must check for a valid reference first
  1435. Value super_class;
  1436. auto reference = TRY(m_super_class->to_reference(interpreter, global_object));
  1437. if (reference.is_valid_reference()) {
  1438. super_class = TRY(reference.get_value(global_object));
  1439. } else {
  1440. super_class = TRY(m_super_class->execute(interpreter, global_object)).release_value();
  1441. }
  1442. vm.running_execution_context().lexical_environment = environment;
  1443. if (super_class.is_null()) {
  1444. proto_parent = nullptr;
  1445. } else if (!super_class.is_constructor()) {
  1446. return vm.throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueNotAConstructorOrNull, super_class.to_string_without_side_effects());
  1447. } else {
  1448. auto super_class_prototype = TRY(super_class.get(global_object, vm.names.prototype));
  1449. if (!super_class_prototype.is_null() && !super_class_prototype.is_object())
  1450. return vm.throw_completion<TypeError>(global_object, ErrorType::ClassExtendsValueInvalidPrototype, super_class_prototype.to_string_without_side_effects());
  1451. if (super_class_prototype.is_null())
  1452. proto_parent = nullptr;
  1453. else
  1454. proto_parent = &super_class_prototype.as_object();
  1455. constructor_parent = &super_class.as_object();
  1456. }
  1457. }
  1458. auto* prototype = Object::create(global_object, proto_parent);
  1459. VERIFY(prototype);
  1460. vm.running_execution_context().lexical_environment = class_scope;
  1461. vm.running_execution_context().private_environment = class_private_environment;
  1462. ScopeGuard restore_private_environment = [&] {
  1463. vm.running_execution_context().private_environment = outer_private_environment;
  1464. };
  1465. // FIXME: Step 14.a is done in the parser. But maybe it shouldn't?
  1466. auto class_constructor_value = TRY(m_constructor->execute(interpreter, global_object)).release_value();
  1467. update_function_name(class_constructor_value, class_name);
  1468. VERIFY(class_constructor_value.is_function() && is<ECMAScriptFunctionObject>(class_constructor_value.as_function()));
  1469. auto* class_constructor = static_cast<ECMAScriptFunctionObject*>(&class_constructor_value.as_function());
  1470. class_constructor->set_home_object(prototype);
  1471. class_constructor->set_is_class_constructor();
  1472. class_constructor->define_direct_property(vm.names.prototype, prototype, Attribute::Writable);
  1473. TRY(class_constructor->internal_set_prototype_of(constructor_parent));
  1474. if (!m_super_class.is_null())
  1475. class_constructor->set_constructor_kind(ECMAScriptFunctionObject::ConstructorKind::Derived);
  1476. prototype->define_direct_property(vm.names.constructor, class_constructor, Attribute::Writable | Attribute::Configurable);
  1477. using StaticElement = Variant<ClassElement::ClassFieldDefinition, ECMAScriptFunctionObject*>;
  1478. Vector<PrivateElement> static_private_methods;
  1479. Vector<PrivateElement> instance_private_methods;
  1480. Vector<ClassElement::ClassFieldDefinition> instance_fields;
  1481. Vector<StaticElement> static_elements;
  1482. for (auto const& element : m_elements) {
  1483. // Note: All ClassElementEvaluation start with evaluating the name (or we fake it).
  1484. auto element_value = TRY(element.class_element_evaluation(interpreter, global_object, element.is_static() ? *class_constructor : *prototype));
  1485. if (element_value.has<PrivateElement>()) {
  1486. auto& container = element.is_static() ? static_private_methods : instance_private_methods;
  1487. auto& private_element = element_value.get<PrivateElement>();
  1488. auto added_to_existing = false;
  1489. // FIXME: We can skip this loop in most cases.
  1490. for (auto& existing : container) {
  1491. if (existing.key == private_element.key) {
  1492. VERIFY(existing.kind == PrivateElement::Kind::Accessor);
  1493. VERIFY(private_element.kind == PrivateElement::Kind::Accessor);
  1494. auto& accessor = private_element.value.as_accessor();
  1495. if (!accessor.getter())
  1496. existing.value.as_accessor().set_setter(accessor.setter());
  1497. else
  1498. existing.value.as_accessor().set_getter(accessor.getter());
  1499. added_to_existing = true;
  1500. }
  1501. }
  1502. if (!added_to_existing)
  1503. container.append(move(element_value.get<PrivateElement>()));
  1504. } else if (auto* class_field_definition_ptr = element_value.get_pointer<ClassElement::ClassFieldDefinition>()) {
  1505. if (element.is_static())
  1506. static_elements.append(move(*class_field_definition_ptr));
  1507. else
  1508. instance_fields.append(move(*class_field_definition_ptr));
  1509. } else if (element.class_element_kind() == ClassElement::ElementKind::StaticInitializer) {
  1510. // We use Completion to hold the ClassStaticBlockDefinition Record.
  1511. VERIFY(element_value.has<Completion>() && element_value.get<Completion>().value().has_value());
  1512. auto& element_object = element_value.get<Completion>().value()->as_object();
  1513. VERIFY(is<ECMAScriptFunctionObject>(element_object));
  1514. static_elements.append(static_cast<ECMAScriptFunctionObject*>(&element_object));
  1515. }
  1516. }
  1517. vm.running_execution_context().lexical_environment = environment;
  1518. restore_environment.disarm();
  1519. if (!binding_name.is_null())
  1520. MUST(class_scope->initialize_binding(global_object, binding_name, class_constructor));
  1521. for (auto& field : instance_fields)
  1522. class_constructor->add_field(field.name, field.initializer);
  1523. for (auto& private_method : instance_private_methods)
  1524. class_constructor->add_private_method(private_method);
  1525. for (auto& method : static_private_methods)
  1526. class_constructor->private_method_or_accessor_add(move(method));
  1527. for (auto& element : static_elements) {
  1528. TRY(element.visit(
  1529. [&](ClassElement::ClassFieldDefinition const& field) -> ThrowCompletionOr<void> {
  1530. return TRY(class_constructor->define_field(field.name, field.initializer));
  1531. },
  1532. [&](ECMAScriptFunctionObject* static_block_function) -> ThrowCompletionOr<void> {
  1533. // We discard any value returned here.
  1534. TRY(call(global_object, static_block_function, class_constructor_value));
  1535. return {};
  1536. }));
  1537. }
  1538. return Value(class_constructor);
  1539. }
  1540. // 15.7.15 Runtime Semantics: BindingClassDeclarationEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-bindingclassdeclarationevaluation
  1541. ThrowCompletionOr<Value> ClassDeclaration::binding_class_declaration_evaluation(Interpreter& interpreter, GlobalObject& global_object) const
  1542. {
  1543. // 1. Let className be StringValue of BindingIdentifier.
  1544. auto class_name = m_class_expression->name();
  1545. VERIFY(!class_name.is_empty());
  1546. // 2. Let value be ? ClassDefinitionEvaluation of ClassTail with arguments className and className.
  1547. auto value = TRY(m_class_expression->class_definition_evaluation(interpreter, global_object, class_name, class_name));
  1548. // FIXME:
  1549. // 3. Set value.[[SourceText]] to the source text matched by ClassDeclaration.
  1550. // 4. Let env be the running execution context's LexicalEnvironment.
  1551. auto* env = interpreter.lexical_environment();
  1552. // 5. Perform ? InitializeBoundName(className, value, env).
  1553. TRY(initialize_bound_name(global_object, class_name, value, env));
  1554. // 6. Return value.
  1555. return value;
  1556. }
  1557. void ASTNode::dump(int indent) const
  1558. {
  1559. print_indent(indent);
  1560. outln("{}", class_name());
  1561. }
  1562. void ScopeNode::dump(int indent) const
  1563. {
  1564. ASTNode::dump(indent);
  1565. if (!m_lexical_declarations.is_empty()) {
  1566. print_indent(indent + 1);
  1567. outln("(Lexical declarations)");
  1568. for (auto& declaration : m_lexical_declarations)
  1569. declaration.dump(indent + 2);
  1570. }
  1571. if (!m_var_declarations.is_empty()) {
  1572. print_indent(indent + 1);
  1573. outln("(Variable declarations)");
  1574. for (auto& declaration : m_var_declarations)
  1575. declaration.dump(indent + 2);
  1576. }
  1577. if (!m_functions_hoistable_with_annexB_extension.is_empty()) {
  1578. print_indent(indent + 1);
  1579. outln("(Hoisted functions via annexB extension)");
  1580. for (auto& declaration : m_functions_hoistable_with_annexB_extension)
  1581. declaration.dump(indent + 2);
  1582. }
  1583. if (!m_children.is_empty()) {
  1584. print_indent(indent + 1);
  1585. outln("(Children)");
  1586. for (auto& child : children())
  1587. child.dump(indent + 2);
  1588. }
  1589. }
  1590. void BinaryExpression::dump(int indent) const
  1591. {
  1592. const char* op_string = nullptr;
  1593. switch (m_op) {
  1594. case BinaryOp::Addition:
  1595. op_string = "+";
  1596. break;
  1597. case BinaryOp::Subtraction:
  1598. op_string = "-";
  1599. break;
  1600. case BinaryOp::Multiplication:
  1601. op_string = "*";
  1602. break;
  1603. case BinaryOp::Division:
  1604. op_string = "/";
  1605. break;
  1606. case BinaryOp::Modulo:
  1607. op_string = "%";
  1608. break;
  1609. case BinaryOp::Exponentiation:
  1610. op_string = "**";
  1611. break;
  1612. case BinaryOp::StrictlyEquals:
  1613. op_string = "===";
  1614. break;
  1615. case BinaryOp::StrictlyInequals:
  1616. op_string = "!==";
  1617. break;
  1618. case BinaryOp::LooselyEquals:
  1619. op_string = "==";
  1620. break;
  1621. case BinaryOp::LooselyInequals:
  1622. op_string = "!=";
  1623. break;
  1624. case BinaryOp::GreaterThan:
  1625. op_string = ">";
  1626. break;
  1627. case BinaryOp::GreaterThanEquals:
  1628. op_string = ">=";
  1629. break;
  1630. case BinaryOp::LessThan:
  1631. op_string = "<";
  1632. break;
  1633. case BinaryOp::LessThanEquals:
  1634. op_string = "<=";
  1635. break;
  1636. case BinaryOp::BitwiseAnd:
  1637. op_string = "&";
  1638. break;
  1639. case BinaryOp::BitwiseOr:
  1640. op_string = "|";
  1641. break;
  1642. case BinaryOp::BitwiseXor:
  1643. op_string = "^";
  1644. break;
  1645. case BinaryOp::LeftShift:
  1646. op_string = "<<";
  1647. break;
  1648. case BinaryOp::RightShift:
  1649. op_string = ">>";
  1650. break;
  1651. case BinaryOp::UnsignedRightShift:
  1652. op_string = ">>>";
  1653. break;
  1654. case BinaryOp::In:
  1655. op_string = "in";
  1656. break;
  1657. case BinaryOp::InstanceOf:
  1658. op_string = "instanceof";
  1659. break;
  1660. }
  1661. print_indent(indent);
  1662. outln("{}", class_name());
  1663. m_lhs->dump(indent + 1);
  1664. print_indent(indent + 1);
  1665. outln("{}", op_string);
  1666. m_rhs->dump(indent + 1);
  1667. }
  1668. void LogicalExpression::dump(int indent) const
  1669. {
  1670. const char* op_string = nullptr;
  1671. switch (m_op) {
  1672. case LogicalOp::And:
  1673. op_string = "&&";
  1674. break;
  1675. case LogicalOp::Or:
  1676. op_string = "||";
  1677. break;
  1678. case LogicalOp::NullishCoalescing:
  1679. op_string = "??";
  1680. break;
  1681. }
  1682. print_indent(indent);
  1683. outln("{}", class_name());
  1684. m_lhs->dump(indent + 1);
  1685. print_indent(indent + 1);
  1686. outln("{}", op_string);
  1687. m_rhs->dump(indent + 1);
  1688. }
  1689. void UnaryExpression::dump(int indent) const
  1690. {
  1691. const char* op_string = nullptr;
  1692. switch (m_op) {
  1693. case UnaryOp::BitwiseNot:
  1694. op_string = "~";
  1695. break;
  1696. case UnaryOp::Not:
  1697. op_string = "!";
  1698. break;
  1699. case UnaryOp::Plus:
  1700. op_string = "+";
  1701. break;
  1702. case UnaryOp::Minus:
  1703. op_string = "-";
  1704. break;
  1705. case UnaryOp::Typeof:
  1706. op_string = "typeof ";
  1707. break;
  1708. case UnaryOp::Void:
  1709. op_string = "void ";
  1710. break;
  1711. case UnaryOp::Delete:
  1712. op_string = "delete ";
  1713. break;
  1714. }
  1715. print_indent(indent);
  1716. outln("{}", class_name());
  1717. print_indent(indent + 1);
  1718. outln("{}", op_string);
  1719. m_lhs->dump(indent + 1);
  1720. }
  1721. void CallExpression::dump(int indent) const
  1722. {
  1723. print_indent(indent);
  1724. if (is<NewExpression>(*this))
  1725. outln("CallExpression [new]");
  1726. else
  1727. outln("CallExpression");
  1728. m_callee->dump(indent + 1);
  1729. for (auto& argument : m_arguments)
  1730. argument.value->dump(indent + 1);
  1731. }
  1732. void SuperCall::dump(int indent) const
  1733. {
  1734. print_indent(indent);
  1735. outln("SuperCall");
  1736. for (auto& argument : m_arguments)
  1737. argument.value->dump(indent + 1);
  1738. }
  1739. void ClassDeclaration::dump(int indent) const
  1740. {
  1741. ASTNode::dump(indent);
  1742. m_class_expression->dump(indent + 1);
  1743. }
  1744. void ClassDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1745. {
  1746. if (!m_class_expression->name().is_empty())
  1747. callback(m_class_expression->name());
  1748. }
  1749. void ClassExpression::dump(int indent) const
  1750. {
  1751. print_indent(indent);
  1752. outln("ClassExpression: \"{}\"", m_name);
  1753. print_indent(indent);
  1754. outln("(Constructor)");
  1755. m_constructor->dump(indent + 1);
  1756. if (!m_super_class.is_null()) {
  1757. print_indent(indent);
  1758. outln("(Super Class)");
  1759. m_super_class->dump(indent + 1);
  1760. }
  1761. print_indent(indent);
  1762. outln("(Elements)");
  1763. for (auto& method : m_elements)
  1764. method.dump(indent + 1);
  1765. }
  1766. void ClassMethod::dump(int indent) const
  1767. {
  1768. ASTNode::dump(indent);
  1769. print_indent(indent);
  1770. outln("(Key)");
  1771. m_key->dump(indent + 1);
  1772. const char* kind_string = nullptr;
  1773. switch (m_kind) {
  1774. case Kind::Method:
  1775. kind_string = "Method";
  1776. break;
  1777. case Kind::Getter:
  1778. kind_string = "Getter";
  1779. break;
  1780. case Kind::Setter:
  1781. kind_string = "Setter";
  1782. break;
  1783. }
  1784. print_indent(indent);
  1785. outln("Kind: {}", kind_string);
  1786. print_indent(indent);
  1787. outln("Static: {}", is_static());
  1788. print_indent(indent);
  1789. outln("(Function)");
  1790. m_function->dump(indent + 1);
  1791. }
  1792. void ClassField::dump(int indent) const
  1793. {
  1794. ASTNode::dump(indent);
  1795. print_indent(indent);
  1796. outln("(Key)");
  1797. m_key->dump(indent + 1);
  1798. print_indent(indent);
  1799. outln("Static: {}", is_static());
  1800. if (m_initializer) {
  1801. print_indent(indent);
  1802. outln("(Initializer)");
  1803. m_initializer->dump(indent + 1);
  1804. }
  1805. }
  1806. void StaticInitializer::dump(int indent) const
  1807. {
  1808. ASTNode::dump(indent);
  1809. m_function_body->dump(indent + 1);
  1810. }
  1811. void StringLiteral::dump(int indent) const
  1812. {
  1813. print_indent(indent);
  1814. outln("StringLiteral \"{}\"", m_value);
  1815. }
  1816. void SuperExpression::dump(int indent) const
  1817. {
  1818. print_indent(indent);
  1819. outln("super");
  1820. }
  1821. void NumericLiteral::dump(int indent) const
  1822. {
  1823. print_indent(indent);
  1824. outln("NumericLiteral {}", m_value);
  1825. }
  1826. void BigIntLiteral::dump(int indent) const
  1827. {
  1828. print_indent(indent);
  1829. outln("BigIntLiteral {}", m_value);
  1830. }
  1831. void BooleanLiteral::dump(int indent) const
  1832. {
  1833. print_indent(indent);
  1834. outln("BooleanLiteral {}", m_value);
  1835. }
  1836. void NullLiteral::dump(int indent) const
  1837. {
  1838. print_indent(indent);
  1839. outln("null");
  1840. }
  1841. bool BindingPattern::contains_expression() const
  1842. {
  1843. for (auto& entry : entries) {
  1844. if (entry.initializer)
  1845. return true;
  1846. if (auto binding_ptr = entry.alias.get_pointer<NonnullRefPtr<BindingPattern>>(); binding_ptr && (*binding_ptr)->contains_expression())
  1847. return true;
  1848. }
  1849. return false;
  1850. }
  1851. void BindingPattern::dump(int indent) const
  1852. {
  1853. print_indent(indent);
  1854. outln("BindingPattern {}", kind == Kind::Array ? "Array" : "Object");
  1855. for (auto& entry : entries) {
  1856. print_indent(indent + 1);
  1857. outln("(Property)");
  1858. if (kind == Kind::Object) {
  1859. print_indent(indent + 2);
  1860. outln("(Identifier)");
  1861. if (entry.name.has<NonnullRefPtr<Identifier>>()) {
  1862. entry.name.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1863. } else {
  1864. entry.name.get<NonnullRefPtr<Expression>>()->dump(indent + 3);
  1865. }
  1866. } else if (entry.is_elision()) {
  1867. print_indent(indent + 2);
  1868. outln("(Elision)");
  1869. continue;
  1870. }
  1871. print_indent(indent + 2);
  1872. outln("(Pattern{})", entry.is_rest ? " rest=true" : "");
  1873. if (entry.alias.has<NonnullRefPtr<Identifier>>()) {
  1874. entry.alias.get<NonnullRefPtr<Identifier>>()->dump(indent + 3);
  1875. } else if (entry.alias.has<NonnullRefPtr<BindingPattern>>()) {
  1876. entry.alias.get<NonnullRefPtr<BindingPattern>>()->dump(indent + 3);
  1877. } else if (entry.alias.has<NonnullRefPtr<MemberExpression>>()) {
  1878. entry.alias.get<NonnullRefPtr<MemberExpression>>()->dump(indent + 3);
  1879. } else {
  1880. print_indent(indent + 3);
  1881. outln("<empty>");
  1882. }
  1883. if (entry.initializer) {
  1884. print_indent(indent + 2);
  1885. outln("(Initializer)");
  1886. entry.initializer->dump(indent + 3);
  1887. }
  1888. }
  1889. }
  1890. void FunctionNode::dump(int indent, String const& class_name) const
  1891. {
  1892. print_indent(indent);
  1893. auto is_async = m_kind == FunctionKind::Async || m_kind == FunctionKind::AsyncGenerator;
  1894. auto is_generator = m_kind == FunctionKind::Generator || m_kind == FunctionKind::AsyncGenerator;
  1895. outln("{}{}{} '{}'", class_name, is_async ? " async" : "", is_generator ? "*" : "", name());
  1896. if (m_contains_direct_call_to_eval) {
  1897. print_indent(indent + 1);
  1898. outln("\033[31;1m(direct eval)\033[0m");
  1899. }
  1900. if (!m_parameters.is_empty()) {
  1901. print_indent(indent + 1);
  1902. outln("(Parameters)");
  1903. for (auto& parameter : m_parameters) {
  1904. print_indent(indent + 2);
  1905. if (parameter.is_rest)
  1906. out("...");
  1907. parameter.binding.visit(
  1908. [&](FlyString const& name) {
  1909. outln("{}", name);
  1910. },
  1911. [&](BindingPattern const& pattern) {
  1912. pattern.dump(indent + 2);
  1913. });
  1914. if (parameter.default_value)
  1915. parameter.default_value->dump(indent + 3);
  1916. }
  1917. }
  1918. print_indent(indent + 1);
  1919. outln("(Body)");
  1920. body().dump(indent + 2);
  1921. }
  1922. void FunctionDeclaration::dump(int indent) const
  1923. {
  1924. FunctionNode::dump(indent, class_name());
  1925. }
  1926. void FunctionDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  1927. {
  1928. if (!name().is_empty())
  1929. callback(name());
  1930. }
  1931. void FunctionExpression::dump(int indent) const
  1932. {
  1933. FunctionNode::dump(indent, class_name());
  1934. }
  1935. void YieldExpression::dump(int indent) const
  1936. {
  1937. ASTNode::dump(indent);
  1938. if (argument())
  1939. argument()->dump(indent + 1);
  1940. }
  1941. void AwaitExpression::dump(int indent) const
  1942. {
  1943. ASTNode::dump(indent);
  1944. m_argument->dump(indent + 1);
  1945. }
  1946. void ReturnStatement::dump(int indent) const
  1947. {
  1948. ASTNode::dump(indent);
  1949. if (argument())
  1950. argument()->dump(indent + 1);
  1951. }
  1952. void IfStatement::dump(int indent) const
  1953. {
  1954. ASTNode::dump(indent);
  1955. print_indent(indent);
  1956. outln("If");
  1957. predicate().dump(indent + 1);
  1958. consequent().dump(indent + 1);
  1959. if (alternate()) {
  1960. print_indent(indent);
  1961. outln("Else");
  1962. alternate()->dump(indent + 1);
  1963. }
  1964. }
  1965. void WhileStatement::dump(int indent) const
  1966. {
  1967. ASTNode::dump(indent);
  1968. print_indent(indent);
  1969. outln("While");
  1970. test().dump(indent + 1);
  1971. body().dump(indent + 1);
  1972. }
  1973. void WithStatement::dump(int indent) const
  1974. {
  1975. ASTNode::dump(indent);
  1976. print_indent(indent + 1);
  1977. outln("Object");
  1978. object().dump(indent + 2);
  1979. print_indent(indent + 1);
  1980. outln("Body");
  1981. body().dump(indent + 2);
  1982. }
  1983. void DoWhileStatement::dump(int indent) const
  1984. {
  1985. ASTNode::dump(indent);
  1986. print_indent(indent);
  1987. outln("DoWhile");
  1988. test().dump(indent + 1);
  1989. body().dump(indent + 1);
  1990. }
  1991. void ForStatement::dump(int indent) const
  1992. {
  1993. ASTNode::dump(indent);
  1994. print_indent(indent);
  1995. outln("For");
  1996. if (init())
  1997. init()->dump(indent + 1);
  1998. if (test())
  1999. test()->dump(indent + 1);
  2000. if (update())
  2001. update()->dump(indent + 1);
  2002. body().dump(indent + 1);
  2003. }
  2004. void ForInStatement::dump(int indent) const
  2005. {
  2006. ASTNode::dump(indent);
  2007. print_indent(indent);
  2008. outln("ForIn");
  2009. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2010. rhs().dump(indent + 1);
  2011. body().dump(indent + 1);
  2012. }
  2013. void ForOfStatement::dump(int indent) const
  2014. {
  2015. ASTNode::dump(indent);
  2016. print_indent(indent);
  2017. outln("ForOf");
  2018. lhs().visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2019. rhs().dump(indent + 1);
  2020. body().dump(indent + 1);
  2021. }
  2022. void ForAwaitOfStatement::dump(int indent) const
  2023. {
  2024. ASTNode::dump(indent);
  2025. print_indent(indent);
  2026. outln("ForAwaitOf");
  2027. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2028. m_rhs->dump(indent + 1);
  2029. m_body->dump(indent + 1);
  2030. }
  2031. // 13.1.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-identifiers-runtime-semantics-evaluation
  2032. Completion Identifier::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2033. {
  2034. InterpreterNodeScope node_scope { interpreter, *this };
  2035. // 1. Return ? ResolveBinding(StringValue of Identifier).
  2036. auto reference = TRY(interpreter.vm().resolve_binding(m_string));
  2037. // NOTE: The spec wants us to return the reference directly; this is not possible with ASTNode::execute() (short of letting it return a variant).
  2038. // So, instead of calling GetValue at the call site, we do it here.
  2039. return TRY(reference.get_value(global_object));
  2040. }
  2041. void Identifier::dump(int indent) const
  2042. {
  2043. print_indent(indent);
  2044. outln("Identifier \"{}\"", m_string);
  2045. }
  2046. Completion PrivateIdentifier::execute(Interpreter&, GlobalObject&) const
  2047. {
  2048. // Note: This should be handled by either the member expression this is part of
  2049. // or the binary expression in the case of `#foo in bar`.
  2050. VERIFY_NOT_REACHED();
  2051. }
  2052. void PrivateIdentifier::dump(int indent) const
  2053. {
  2054. print_indent(indent);
  2055. outln("PrivateIdentifier \"{}\"", m_string);
  2056. }
  2057. void SpreadExpression::dump(int indent) const
  2058. {
  2059. ASTNode::dump(indent);
  2060. m_target->dump(indent + 1);
  2061. }
  2062. Completion SpreadExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2063. {
  2064. InterpreterNodeScope node_scope { interpreter, *this };
  2065. return m_target->execute(interpreter, global_object);
  2066. }
  2067. // 13.2.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-this-keyword-runtime-semantics-evaluation
  2068. Completion ThisExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2069. {
  2070. InterpreterNodeScope node_scope { interpreter, *this };
  2071. // 1. Return ? ResolveThisBinding().
  2072. return interpreter.vm().resolve_this_binding(global_object);
  2073. }
  2074. void ThisExpression::dump(int indent) const
  2075. {
  2076. ASTNode::dump(indent);
  2077. }
  2078. // 13.15.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation
  2079. Completion AssignmentExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2080. {
  2081. InterpreterNodeScope node_scope { interpreter, *this };
  2082. if (m_op == AssignmentOp::Assignment) {
  2083. // AssignmentExpression : LeftHandSideExpression = AssignmentExpression
  2084. return m_lhs.visit(
  2085. // 1. If LeftHandSideExpression is neither an ObjectLiteral nor an ArrayLiteral, then
  2086. [&](NonnullRefPtr<Expression>& lhs) -> ThrowCompletionOr<Value> {
  2087. // a. Let lref be the result of evaluating LeftHandSideExpression.
  2088. // b. ReturnIfAbrupt(lref).
  2089. auto reference = TRY(lhs->to_reference(interpreter, global_object));
  2090. Value rhs_result;
  2091. // c. If IsAnonymousFunctionDefinition(AssignmentExpression) and IsIdentifierRef of LeftHandSideExpression are both true, then
  2092. if (lhs->is_identifier()) {
  2093. // i. Let rval be NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2094. auto& identifier_name = static_cast<Identifier const&>(*lhs).string();
  2095. rhs_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  2096. }
  2097. // d. Else,
  2098. else {
  2099. // i. Let rref be the result of evaluating AssignmentExpression.
  2100. // ii. Let rval be ? GetValue(rref).
  2101. rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2102. }
  2103. // e. Perform ? PutValue(lref, rval).
  2104. TRY(reference.put_value(global_object, rhs_result));
  2105. // f. Return rval.
  2106. return rhs_result;
  2107. },
  2108. // 2. Let assignmentPattern be the AssignmentPattern that is covered by LeftHandSideExpression.
  2109. [&](NonnullRefPtr<BindingPattern>& pattern) -> ThrowCompletionOr<Value> {
  2110. // 3. Let rref be the result of evaluating AssignmentExpression.
  2111. // 4. Let rval be ? GetValue(rref).
  2112. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2113. // 5. Perform ? DestructuringAssignmentEvaluation of assignmentPattern using rval as the argument.
  2114. TRY(interpreter.vm().destructuring_assignment_evaluation(pattern, rhs_result, global_object));
  2115. // 6. Return rval.
  2116. return rhs_result;
  2117. });
  2118. }
  2119. VERIFY(m_lhs.has<NonnullRefPtr<Expression>>());
  2120. // 1. Let lref be the result of evaluating LeftHandSideExpression.
  2121. auto& lhs_expression = *m_lhs.get<NonnullRefPtr<Expression>>();
  2122. auto reference = TRY(lhs_expression.to_reference(interpreter, global_object));
  2123. // 2. Let lval be ? GetValue(lref).
  2124. auto lhs_result = TRY(reference.get_value(global_object));
  2125. // AssignmentExpression : LeftHandSideExpression {&&=, ||=, ??=} AssignmentExpression
  2126. if (m_op == AssignmentOp::AndAssignment || m_op == AssignmentOp::OrAssignment || m_op == AssignmentOp::NullishAssignment) {
  2127. switch (m_op) {
  2128. // AssignmentExpression : LeftHandSideExpression &&= AssignmentExpression
  2129. case AssignmentOp::AndAssignment:
  2130. // 3. Let lbool be ! ToBoolean(lval).
  2131. // 4. If lbool is false, return lval.
  2132. if (!lhs_result.to_boolean())
  2133. return lhs_result;
  2134. break;
  2135. // AssignmentExpression : LeftHandSideExpression ||= AssignmentExpression
  2136. case AssignmentOp::OrAssignment:
  2137. // 3. Let lbool be ! ToBoolean(lval).
  2138. // 4. If lbool is true, return lval.
  2139. if (lhs_result.to_boolean())
  2140. return lhs_result;
  2141. break;
  2142. // AssignmentExpression : LeftHandSideExpression ??= AssignmentExpression
  2143. case AssignmentOp::NullishAssignment:
  2144. // 3. If lval is neither undefined nor null, return lval.
  2145. if (!lhs_result.is_nullish())
  2146. return lhs_result;
  2147. break;
  2148. default:
  2149. VERIFY_NOT_REACHED();
  2150. }
  2151. Value rhs_result;
  2152. // 5. If IsAnonymousFunctionDefinition(AssignmentExpression) is true and IsIdentifierRef of LeftHandSideExpression is true, then
  2153. if (lhs_expression.is_identifier()) {
  2154. // a. Let rval be NamedEvaluation of AssignmentExpression with argument lref.[[ReferencedName]].
  2155. auto& identifier_name = static_cast<Identifier const&>(lhs_expression).string();
  2156. rhs_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, m_rhs, identifier_name));
  2157. }
  2158. // 6. Else,
  2159. else {
  2160. // a. Let rref be the result of evaluating AssignmentExpression.
  2161. // b. Let rval be ? GetValue(rref).
  2162. rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2163. }
  2164. // 7. Perform ? PutValue(lref, rval).
  2165. TRY(reference.put_value(global_object, rhs_result));
  2166. // 8. Return rval.
  2167. return rhs_result;
  2168. }
  2169. // AssignmentExpression : LeftHandSideExpression AssignmentOperator AssignmentExpression
  2170. // 3. Let rref be the result of evaluating AssignmentExpression.
  2171. // 4. Let rval be ? GetValue(rref).
  2172. auto rhs_result = TRY(m_rhs->execute(interpreter, global_object)).release_value();
  2173. // 5. Let assignmentOpText be the source text matched by AssignmentOperator.
  2174. // 6. Let opText be the sequence of Unicode code points associated with assignmentOpText in the following table:
  2175. // 7. Let r be ApplyStringOrNumericBinaryOperator(lval, opText, rval).
  2176. switch (m_op) {
  2177. case AssignmentOp::AdditionAssignment:
  2178. rhs_result = TRY(add(global_object, lhs_result, rhs_result));
  2179. break;
  2180. case AssignmentOp::SubtractionAssignment:
  2181. rhs_result = TRY(sub(global_object, lhs_result, rhs_result));
  2182. break;
  2183. case AssignmentOp::MultiplicationAssignment:
  2184. rhs_result = TRY(mul(global_object, lhs_result, rhs_result));
  2185. break;
  2186. case AssignmentOp::DivisionAssignment:
  2187. rhs_result = TRY(div(global_object, lhs_result, rhs_result));
  2188. break;
  2189. case AssignmentOp::ModuloAssignment:
  2190. rhs_result = TRY(mod(global_object, lhs_result, rhs_result));
  2191. break;
  2192. case AssignmentOp::ExponentiationAssignment:
  2193. rhs_result = TRY(exp(global_object, lhs_result, rhs_result));
  2194. break;
  2195. case AssignmentOp::BitwiseAndAssignment:
  2196. rhs_result = TRY(bitwise_and(global_object, lhs_result, rhs_result));
  2197. break;
  2198. case AssignmentOp::BitwiseOrAssignment:
  2199. rhs_result = TRY(bitwise_or(global_object, lhs_result, rhs_result));
  2200. break;
  2201. case AssignmentOp::BitwiseXorAssignment:
  2202. rhs_result = TRY(bitwise_xor(global_object, lhs_result, rhs_result));
  2203. break;
  2204. case AssignmentOp::LeftShiftAssignment:
  2205. rhs_result = TRY(left_shift(global_object, lhs_result, rhs_result));
  2206. break;
  2207. case AssignmentOp::RightShiftAssignment:
  2208. rhs_result = TRY(right_shift(global_object, lhs_result, rhs_result));
  2209. break;
  2210. case AssignmentOp::UnsignedRightShiftAssignment:
  2211. rhs_result = TRY(unsigned_right_shift(global_object, lhs_result, rhs_result));
  2212. break;
  2213. case AssignmentOp::Assignment:
  2214. case AssignmentOp::AndAssignment:
  2215. case AssignmentOp::OrAssignment:
  2216. case AssignmentOp::NullishAssignment:
  2217. VERIFY_NOT_REACHED();
  2218. }
  2219. // 8. Perform ? PutValue(lref, r).
  2220. TRY(reference.put_value(global_object, rhs_result));
  2221. // 9. Return r.
  2222. return rhs_result;
  2223. }
  2224. // 13.4.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-increment-operator-runtime-semantics-evaluation
  2225. // 13.4.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-postfix-decrement-operator-runtime-semantics-evaluation
  2226. // 13.4.4.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-increment-operator-runtime-semantics-evaluation
  2227. // 13.4.5.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-prefix-decrement-operator-runtime-semantics-evaluation
  2228. Completion UpdateExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2229. {
  2230. InterpreterNodeScope node_scope { interpreter, *this };
  2231. // 1. Let expr be the result of evaluating <Expression>.
  2232. auto reference = TRY(m_argument->to_reference(interpreter, global_object));
  2233. // 2. Let oldValue be ? ToNumeric(? GetValue(expr)).
  2234. auto old_value = TRY(reference.get_value(global_object));
  2235. old_value = TRY(old_value.to_numeric(global_object));
  2236. Value new_value;
  2237. switch (m_op) {
  2238. case UpdateOp::Increment:
  2239. // 3. If Type(oldValue) is Number, then
  2240. if (old_value.is_number()) {
  2241. // a. Let newValue be ! Number::add(oldValue, 1𝔽).
  2242. new_value = Value(old_value.as_double() + 1);
  2243. }
  2244. // 4. Else,
  2245. else {
  2246. // a. Assert: Type(oldValue) is BigInt.
  2247. // b. Let newValue be ! BigInt::add(oldValue, 1ℤ).
  2248. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().plus(Crypto::SignedBigInteger { 1 }));
  2249. }
  2250. break;
  2251. case UpdateOp::Decrement:
  2252. // 3. If Type(oldValue) is Number, then
  2253. if (old_value.is_number()) {
  2254. // a. Let newValue be ! Number::subtract(oldValue, 1𝔽).
  2255. new_value = Value(old_value.as_double() - 1);
  2256. }
  2257. // 4. Else,
  2258. else {
  2259. // a. Assert: Type(oldValue) is BigInt.
  2260. // b. Let newValue be ! BigInt::subtract(oldValue, 1ℤ).
  2261. new_value = js_bigint(interpreter.heap(), old_value.as_bigint().big_integer().minus(Crypto::SignedBigInteger { 1 }));
  2262. }
  2263. break;
  2264. default:
  2265. VERIFY_NOT_REACHED();
  2266. }
  2267. // 5. Perform ? PutValue(expr, newValue).
  2268. TRY(reference.put_value(global_object, new_value));
  2269. // 6. Return newValue.
  2270. // 6. Return oldValue.
  2271. return m_prefixed ? new_value : old_value;
  2272. }
  2273. void AssignmentExpression::dump(int indent) const
  2274. {
  2275. const char* op_string = nullptr;
  2276. switch (m_op) {
  2277. case AssignmentOp::Assignment:
  2278. op_string = "=";
  2279. break;
  2280. case AssignmentOp::AdditionAssignment:
  2281. op_string = "+=";
  2282. break;
  2283. case AssignmentOp::SubtractionAssignment:
  2284. op_string = "-=";
  2285. break;
  2286. case AssignmentOp::MultiplicationAssignment:
  2287. op_string = "*=";
  2288. break;
  2289. case AssignmentOp::DivisionAssignment:
  2290. op_string = "/=";
  2291. break;
  2292. case AssignmentOp::ModuloAssignment:
  2293. op_string = "%=";
  2294. break;
  2295. case AssignmentOp::ExponentiationAssignment:
  2296. op_string = "**=";
  2297. break;
  2298. case AssignmentOp::BitwiseAndAssignment:
  2299. op_string = "&=";
  2300. break;
  2301. case AssignmentOp::BitwiseOrAssignment:
  2302. op_string = "|=";
  2303. break;
  2304. case AssignmentOp::BitwiseXorAssignment:
  2305. op_string = "^=";
  2306. break;
  2307. case AssignmentOp::LeftShiftAssignment:
  2308. op_string = "<<=";
  2309. break;
  2310. case AssignmentOp::RightShiftAssignment:
  2311. op_string = ">>=";
  2312. break;
  2313. case AssignmentOp::UnsignedRightShiftAssignment:
  2314. op_string = ">>>=";
  2315. break;
  2316. case AssignmentOp::AndAssignment:
  2317. op_string = "&&=";
  2318. break;
  2319. case AssignmentOp::OrAssignment:
  2320. op_string = "||=";
  2321. break;
  2322. case AssignmentOp::NullishAssignment:
  2323. op_string = "\?\?=";
  2324. break;
  2325. }
  2326. ASTNode::dump(indent);
  2327. print_indent(indent + 1);
  2328. outln("{}", op_string);
  2329. m_lhs.visit([&](auto& lhs) { lhs->dump(indent + 1); });
  2330. m_rhs->dump(indent + 1);
  2331. }
  2332. void UpdateExpression::dump(int indent) const
  2333. {
  2334. const char* op_string = nullptr;
  2335. switch (m_op) {
  2336. case UpdateOp::Increment:
  2337. op_string = "++";
  2338. break;
  2339. case UpdateOp::Decrement:
  2340. op_string = "--";
  2341. break;
  2342. }
  2343. ASTNode::dump(indent);
  2344. if (m_prefixed) {
  2345. print_indent(indent + 1);
  2346. outln("{}", op_string);
  2347. }
  2348. m_argument->dump(indent + 1);
  2349. if (!m_prefixed) {
  2350. print_indent(indent + 1);
  2351. outln("{}", op_string);
  2352. }
  2353. }
  2354. // 14.3.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-let-and-const-declarations-runtime-semantics-evaluation
  2355. // 14.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-variable-statement-runtime-semantics-evaluation
  2356. Completion VariableDeclaration::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2357. {
  2358. InterpreterNodeScope node_scope { interpreter, *this };
  2359. for (auto& declarator : m_declarations) {
  2360. if (auto* init = declarator.init()) {
  2361. TRY(declarator.target().visit(
  2362. [&](NonnullRefPtr<Identifier> const& id) -> ThrowCompletionOr<void> {
  2363. auto reference = TRY(id->to_reference(interpreter, global_object));
  2364. auto initializer_result = TRY(interpreter.vm().named_evaluation_if_anonymous_function(global_object, *init, id->string()));
  2365. VERIFY(!initializer_result.is_empty());
  2366. if (m_declaration_kind == DeclarationKind::Var)
  2367. return reference.put_value(global_object, initializer_result);
  2368. else
  2369. return reference.initialize_referenced_binding(global_object, initializer_result);
  2370. },
  2371. [&](NonnullRefPtr<BindingPattern> const& pattern) -> ThrowCompletionOr<void> {
  2372. auto initializer_result = TRY(init->execute(interpreter, global_object)).release_value();
  2373. Environment* environment = m_declaration_kind == DeclarationKind::Var ? nullptr : interpreter.lexical_environment();
  2374. return interpreter.vm().binding_initialization(pattern, initializer_result, environment, global_object);
  2375. }));
  2376. } else if (m_declaration_kind != DeclarationKind::Var) {
  2377. VERIFY(declarator.target().has<NonnullRefPtr<Identifier>>());
  2378. auto& identifier = declarator.target().get<NonnullRefPtr<Identifier>>();
  2379. auto reference = TRY(identifier->to_reference(interpreter, global_object));
  2380. TRY(reference.initialize_referenced_binding(global_object, js_undefined()));
  2381. }
  2382. }
  2383. return normal_completion({});
  2384. }
  2385. Completion VariableDeclarator::execute(Interpreter& interpreter, GlobalObject&) const
  2386. {
  2387. InterpreterNodeScope node_scope { interpreter, *this };
  2388. // NOTE: VariableDeclarator execution is handled by VariableDeclaration.
  2389. VERIFY_NOT_REACHED();
  2390. }
  2391. void VariableDeclaration::for_each_bound_name(IteratorOrVoidFunction<FlyString const&> callback) const
  2392. {
  2393. for (auto& entry : declarations()) {
  2394. entry.target().template visit(
  2395. [&](const NonnullRefPtr<Identifier>& id) {
  2396. callback(id->string());
  2397. },
  2398. [&](const NonnullRefPtr<BindingPattern>& binding) {
  2399. binding->for_each_bound_name([&](const auto& name) {
  2400. callback(name);
  2401. });
  2402. });
  2403. }
  2404. }
  2405. void VariableDeclaration::dump(int indent) const
  2406. {
  2407. const char* declaration_kind_string = nullptr;
  2408. switch (m_declaration_kind) {
  2409. case DeclarationKind::Let:
  2410. declaration_kind_string = "Let";
  2411. break;
  2412. case DeclarationKind::Var:
  2413. declaration_kind_string = "Var";
  2414. break;
  2415. case DeclarationKind::Const:
  2416. declaration_kind_string = "Const";
  2417. break;
  2418. }
  2419. ASTNode::dump(indent);
  2420. print_indent(indent + 1);
  2421. outln("{}", declaration_kind_string);
  2422. for (auto& declarator : m_declarations)
  2423. declarator.dump(indent + 1);
  2424. }
  2425. void VariableDeclarator::dump(int indent) const
  2426. {
  2427. ASTNode::dump(indent);
  2428. m_target.visit([indent](const auto& value) { value->dump(indent + 1); });
  2429. if (m_init)
  2430. m_init->dump(indent + 1);
  2431. }
  2432. void ObjectProperty::dump(int indent) const
  2433. {
  2434. ASTNode::dump(indent);
  2435. if (m_property_type == Type::Spread) {
  2436. print_indent(indent + 1);
  2437. outln("...Spreading");
  2438. m_key->dump(indent + 1);
  2439. } else {
  2440. m_key->dump(indent + 1);
  2441. m_value->dump(indent + 1);
  2442. }
  2443. }
  2444. void ObjectExpression::dump(int indent) const
  2445. {
  2446. ASTNode::dump(indent);
  2447. for (auto& property : m_properties) {
  2448. property.dump(indent + 1);
  2449. }
  2450. }
  2451. void ExpressionStatement::dump(int indent) const
  2452. {
  2453. ASTNode::dump(indent);
  2454. m_expression->dump(indent + 1);
  2455. }
  2456. Completion ObjectProperty::execute(Interpreter& interpreter, GlobalObject&) const
  2457. {
  2458. InterpreterNodeScope node_scope { interpreter, *this };
  2459. // NOTE: ObjectProperty execution is handled by ObjectExpression.
  2460. VERIFY_NOT_REACHED();
  2461. }
  2462. // 13.2.5.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-object-initializer-runtime-semantics-evaluation
  2463. Completion ObjectExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2464. {
  2465. InterpreterNodeScope node_scope { interpreter, *this };
  2466. // 1. Let obj be ! OrdinaryObjectCreate(%Object.prototype%).
  2467. auto* object = Object::create(global_object, global_object.object_prototype());
  2468. // 2. Perform ? PropertyDefinitionEvaluation of PropertyDefinitionList with argument obj.
  2469. for (auto& property : m_properties) {
  2470. auto key = TRY(property.key().execute(interpreter, global_object)).release_value();
  2471. if (property.type() == ObjectProperty::Type::Spread) {
  2472. if (key.is_object() && is<Array>(key.as_object())) {
  2473. auto& array_to_spread = static_cast<Array&>(key.as_object());
  2474. for (auto& entry : array_to_spread.indexed_properties()) {
  2475. auto value = TRY(array_to_spread.get(entry.index()));
  2476. object->indexed_properties().put(entry.index(), value);
  2477. }
  2478. } else if (key.is_object()) {
  2479. auto& obj_to_spread = key.as_object();
  2480. for (auto& it : obj_to_spread.shape().property_table_ordered()) {
  2481. if (it.value.attributes.is_enumerable()) {
  2482. auto value = TRY(obj_to_spread.get(it.key));
  2483. object->define_direct_property(it.key, value, JS::default_attributes);
  2484. }
  2485. }
  2486. } else if (key.is_string()) {
  2487. auto& str_to_spread = key.as_string().string();
  2488. for (size_t i = 0; i < str_to_spread.length(); i++)
  2489. object->define_direct_property(i, js_string(interpreter.heap(), str_to_spread.substring(i, 1)), JS::default_attributes);
  2490. }
  2491. continue;
  2492. }
  2493. auto value = TRY(property.value().execute(interpreter, global_object)).release_value();
  2494. if (value.is_function() && property.is_method())
  2495. static_cast<ECMAScriptFunctionObject&>(value.as_function()).set_home_object(object);
  2496. auto name = TRY(get_function_name(global_object, key));
  2497. if (property.type() == ObjectProperty::Type::Getter) {
  2498. name = String::formatted("get {}", name);
  2499. } else if (property.type() == ObjectProperty::Type::Setter) {
  2500. name = String::formatted("set {}", name);
  2501. }
  2502. update_function_name(value, name);
  2503. switch (property.type()) {
  2504. case ObjectProperty::Type::Getter:
  2505. VERIFY(value.is_function());
  2506. object->define_direct_accessor(TRY(PropertyKey::from_value(global_object, key)), &value.as_function(), nullptr, Attribute::Configurable | Attribute::Enumerable);
  2507. break;
  2508. case ObjectProperty::Type::Setter:
  2509. VERIFY(value.is_function());
  2510. object->define_direct_accessor(TRY(PropertyKey::from_value(global_object, key)), nullptr, &value.as_function(), Attribute::Configurable | Attribute::Enumerable);
  2511. break;
  2512. case ObjectProperty::Type::KeyValue:
  2513. object->define_direct_property(TRY(PropertyKey::from_value(global_object, key)), value, JS::default_attributes);
  2514. break;
  2515. case ObjectProperty::Type::Spread:
  2516. default:
  2517. VERIFY_NOT_REACHED();
  2518. }
  2519. }
  2520. // 3. Return obj.
  2521. return Value { object };
  2522. }
  2523. void MemberExpression::dump(int indent) const
  2524. {
  2525. print_indent(indent);
  2526. outln("{}(computed={})", class_name(), is_computed());
  2527. m_object->dump(indent + 1);
  2528. m_property->dump(indent + 1);
  2529. }
  2530. String MemberExpression::to_string_approximation() const
  2531. {
  2532. String object_string = "<object>";
  2533. if (is<Identifier>(*m_object))
  2534. object_string = static_cast<Identifier const&>(*m_object).string();
  2535. if (is_computed())
  2536. return String::formatted("{}[<computed>]", object_string);
  2537. return String::formatted("{}.{}", object_string, verify_cast<Identifier>(*m_property).string());
  2538. }
  2539. // 13.3.2.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-property-accessors-runtime-semantics-evaluation
  2540. Completion MemberExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2541. {
  2542. InterpreterNodeScope node_scope { interpreter, *this };
  2543. auto reference = TRY(to_reference(interpreter, global_object));
  2544. return TRY(reference.get_value(global_object));
  2545. }
  2546. bool MemberExpression::ends_in_private_name() const
  2547. {
  2548. if (is_computed())
  2549. return false;
  2550. if (is<PrivateIdentifier>(*m_property))
  2551. return true;
  2552. if (is<MemberExpression>(*m_property))
  2553. return static_cast<MemberExpression const&>(*m_property).ends_in_private_name();
  2554. return false;
  2555. }
  2556. void OptionalChain::dump(int indent) const
  2557. {
  2558. print_indent(indent);
  2559. outln("{}", class_name());
  2560. m_base->dump(indent + 1);
  2561. for (auto& reference : m_references) {
  2562. reference.visit(
  2563. [&](Call const& call) {
  2564. print_indent(indent + 1);
  2565. outln("Call({})", call.mode == Mode::Optional ? "Optional" : "Not Optional");
  2566. for (auto& argument : call.arguments)
  2567. argument.value->dump(indent + 2);
  2568. },
  2569. [&](ComputedReference const& ref) {
  2570. print_indent(indent + 1);
  2571. outln("ComputedReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2572. ref.expression->dump(indent + 2);
  2573. },
  2574. [&](MemberReference const& ref) {
  2575. print_indent(indent + 1);
  2576. outln("MemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2577. ref.identifier->dump(indent + 2);
  2578. },
  2579. [&](PrivateMemberReference const& ref) {
  2580. print_indent(indent + 1);
  2581. outln("PrivateMemberReference({})", ref.mode == Mode::Optional ? "Optional" : "Not Optional");
  2582. ref.private_identifier->dump(indent + 2);
  2583. });
  2584. }
  2585. }
  2586. ThrowCompletionOr<OptionalChain::ReferenceAndValue> OptionalChain::to_reference_and_value(JS::Interpreter& interpreter, JS::GlobalObject& global_object) const
  2587. {
  2588. auto base_reference = TRY(m_base->to_reference(interpreter, global_object));
  2589. auto base = base_reference.is_unresolvable()
  2590. ? TRY(m_base->execute(interpreter, global_object)).release_value()
  2591. : TRY(base_reference.get_value(global_object));
  2592. for (auto& reference : m_references) {
  2593. auto is_optional = reference.visit([](auto& ref) { return ref.mode; }) == Mode::Optional;
  2594. if (is_optional && base.is_nullish())
  2595. return ReferenceAndValue { {}, js_undefined() };
  2596. auto expression = reference.visit(
  2597. [&](Call const& call) -> NonnullRefPtr<Expression> {
  2598. return create_ast_node<CallExpression>(source_range(),
  2599. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2600. call.arguments);
  2601. },
  2602. [&](ComputedReference const& ref) -> NonnullRefPtr<Expression> {
  2603. return create_ast_node<MemberExpression>(source_range(),
  2604. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2605. ref.expression,
  2606. true);
  2607. },
  2608. [&](MemberReference const& ref) -> NonnullRefPtr<Expression> {
  2609. return create_ast_node<MemberExpression>(source_range(),
  2610. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2611. ref.identifier,
  2612. false);
  2613. },
  2614. [&](PrivateMemberReference const& ref) -> NonnullRefPtr<Expression> {
  2615. return create_ast_node<MemberExpression>(source_range(),
  2616. create_ast_node<SyntheticReferenceExpression>(source_range(), base_reference, base),
  2617. ref.private_identifier,
  2618. false);
  2619. });
  2620. if (is<CallExpression>(*expression)) {
  2621. base_reference = JS::Reference {};
  2622. base = TRY(expression->execute(interpreter, global_object)).release_value();
  2623. } else {
  2624. base_reference = TRY(expression->to_reference(interpreter, global_object));
  2625. base = TRY(base_reference.get_value(global_object));
  2626. }
  2627. }
  2628. return ReferenceAndValue { move(base_reference), base };
  2629. }
  2630. // 13.3.9.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-optional-chaining-evaluation
  2631. Completion OptionalChain::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2632. {
  2633. InterpreterNodeScope node_scope { interpreter, *this };
  2634. return TRY(to_reference_and_value(interpreter, global_object)).value;
  2635. }
  2636. ThrowCompletionOr<JS::Reference> OptionalChain::to_reference(Interpreter& interpreter, GlobalObject& global_object) const
  2637. {
  2638. return TRY(to_reference_and_value(interpreter, global_object)).reference;
  2639. }
  2640. void MetaProperty::dump(int indent) const
  2641. {
  2642. String name;
  2643. if (m_type == MetaProperty::Type::NewTarget)
  2644. name = "new.target";
  2645. else if (m_type == MetaProperty::Type::ImportMeta)
  2646. name = "import.meta";
  2647. else
  2648. VERIFY_NOT_REACHED();
  2649. print_indent(indent);
  2650. outln("{} {}", class_name(), name);
  2651. }
  2652. // 13.3.12.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-meta-properties-runtime-semantics-evaluation
  2653. Completion MetaProperty::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2654. {
  2655. InterpreterNodeScope node_scope { interpreter, *this };
  2656. // NewTarget : new . target
  2657. if (m_type == MetaProperty::Type::NewTarget) {
  2658. // 1. Return GetNewTarget().
  2659. return interpreter.vm().get_new_target();
  2660. }
  2661. // ImportMeta : import . meta
  2662. if (m_type == MetaProperty::Type::ImportMeta) {
  2663. // TODO: Implement me :^)
  2664. return interpreter.vm().throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "'import.meta' in modules");
  2665. }
  2666. VERIFY_NOT_REACHED();
  2667. }
  2668. void ImportCall::dump(int indent) const
  2669. {
  2670. ASTNode::dump(indent);
  2671. print_indent(indent);
  2672. outln("(Specifier)");
  2673. m_specifier->dump(indent + 1);
  2674. if (m_options) {
  2675. outln("(Options)");
  2676. m_options->dump(indent + 1);
  2677. }
  2678. }
  2679. // 13.3.10.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-import-call-runtime-semantics-evaluation
  2680. Completion ImportCall::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2681. {
  2682. InterpreterNodeScope node_scope { interpreter, *this };
  2683. return interpreter.vm().throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "'import(...)' in modules");
  2684. }
  2685. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2686. Completion StringLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2687. {
  2688. InterpreterNodeScope node_scope { interpreter, *this };
  2689. // 1. Return the SV of StringLiteral as defined in 12.8.4.2.
  2690. return Value { js_string(interpreter.heap(), m_value) };
  2691. }
  2692. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2693. Completion NumericLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2694. {
  2695. InterpreterNodeScope node_scope { interpreter, *this };
  2696. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  2697. return Value(m_value);
  2698. }
  2699. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2700. Completion BigIntLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2701. {
  2702. InterpreterNodeScope node_scope { interpreter, *this };
  2703. // 1. Return the NumericValue of NumericLiteral as defined in 12.8.3.
  2704. Crypto::SignedBigInteger integer;
  2705. if (m_value[0] == '0' && m_value.length() >= 3) {
  2706. if (m_value[1] == 'x' || m_value[1] == 'X') {
  2707. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(16, m_value.substring(2, m_value.length() - 3))) };
  2708. } else if (m_value[1] == 'o' || m_value[1] == 'O') {
  2709. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(8, m_value.substring(2, m_value.length() - 3))) };
  2710. } else if (m_value[1] == 'b' || m_value[1] == 'B') {
  2711. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(2, m_value.substring(2, m_value.length() - 3))) };
  2712. }
  2713. }
  2714. return Value { js_bigint(interpreter.heap(), Crypto::SignedBigInteger::from_base(10, m_value.substring(0, m_value.length() - 1))) };
  2715. }
  2716. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2717. Completion BooleanLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2718. {
  2719. InterpreterNodeScope node_scope { interpreter, *this };
  2720. // 1. If BooleanLiteral is the token false, return false.
  2721. // 2. If BooleanLiteral is the token true, return true.
  2722. return Value(m_value);
  2723. }
  2724. // 13.2.3.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-literals-runtime-semantics-evaluation
  2725. Completion NullLiteral::execute(Interpreter& interpreter, GlobalObject&) const
  2726. {
  2727. InterpreterNodeScope node_scope { interpreter, *this };
  2728. // 1. Return null.
  2729. return js_null();
  2730. }
  2731. void RegExpLiteral::dump(int indent) const
  2732. {
  2733. print_indent(indent);
  2734. outln("{} (/{}/{})", class_name(), pattern(), flags());
  2735. }
  2736. // 13.2.7.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-regular-expression-literals-runtime-semantics-evaluation
  2737. Completion RegExpLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2738. {
  2739. InterpreterNodeScope node_scope { interpreter, *this };
  2740. // 1. Let pattern be ! CodePointsToString(BodyText of RegularExpressionLiteral).
  2741. auto pattern = this->pattern();
  2742. // 2. Let flags be ! CodePointsToString(FlagText of RegularExpressionLiteral).
  2743. auto flags = this->flags();
  2744. // 3. Return RegExpCreate(pattern, flags).
  2745. Regex<ECMA262> regex(parsed_regex(), parsed_pattern(), parsed_flags());
  2746. return Value { RegExpObject::create(global_object, move(regex), move(pattern), move(flags)) };
  2747. }
  2748. void ArrayExpression::dump(int indent) const
  2749. {
  2750. ASTNode::dump(indent);
  2751. for (auto& element : m_elements) {
  2752. if (element) {
  2753. element->dump(indent + 1);
  2754. } else {
  2755. print_indent(indent + 1);
  2756. outln("<empty>");
  2757. }
  2758. }
  2759. }
  2760. // 13.2.4.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-array-initializer-runtime-semantics-evaluation
  2761. Completion ArrayExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2762. {
  2763. InterpreterNodeScope node_scope { interpreter, *this };
  2764. // 1. Let array be ! ArrayCreate(0).
  2765. auto* array = MUST(Array::create(global_object, 0));
  2766. // 2. Let len be the result of performing ArrayAccumulation of ElementList with arguments array and 0.
  2767. // 3. ReturnIfAbrupt(len).
  2768. array->indexed_properties();
  2769. size_t index = 0;
  2770. for (auto& element : m_elements) {
  2771. auto value = Value();
  2772. if (element) {
  2773. value = TRY(element->execute(interpreter, global_object)).release_value();
  2774. if (is<SpreadExpression>(*element)) {
  2775. (void)TRY(get_iterator_values(global_object, value, [&](Value iterator_value) -> Optional<Completion> {
  2776. array->indexed_properties().put(index++, iterator_value, default_attributes);
  2777. return {};
  2778. }));
  2779. continue;
  2780. }
  2781. }
  2782. array->indexed_properties().put(index++, value, default_attributes);
  2783. }
  2784. // 4. Return array.
  2785. return Value { array };
  2786. }
  2787. void TemplateLiteral::dump(int indent) const
  2788. {
  2789. ASTNode::dump(indent);
  2790. for (auto& expression : m_expressions)
  2791. expression.dump(indent + 1);
  2792. }
  2793. // 13.2.8.5 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-template-literals-runtime-semantics-evaluation
  2794. Completion TemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2795. {
  2796. InterpreterNodeScope node_scope { interpreter, *this };
  2797. StringBuilder string_builder;
  2798. for (auto& expression : m_expressions) {
  2799. // 1. Let head be the TV of TemplateHead as defined in 12.8.6.
  2800. // 2. Let subRef be the result of evaluating Expression.
  2801. // 3. Let sub be ? GetValue(subRef).
  2802. auto sub = TRY(expression.execute(interpreter, global_object)).release_value();
  2803. // 4. Let middle be ? ToString(sub).
  2804. auto string = TRY(sub.to_string(global_object));
  2805. string_builder.append(string);
  2806. // 5. Let tail be the result of evaluating TemplateSpans.
  2807. // 6. ReturnIfAbrupt(tail).
  2808. }
  2809. // 7. Return the string-concatenation of head, middle, and tail.
  2810. return Value { js_string(interpreter.heap(), string_builder.build()) };
  2811. }
  2812. void TaggedTemplateLiteral::dump(int indent) const
  2813. {
  2814. ASTNode::dump(indent);
  2815. print_indent(indent + 1);
  2816. outln("(Tag)");
  2817. m_tag->dump(indent + 2);
  2818. print_indent(indent + 1);
  2819. outln("(Template Literal)");
  2820. m_template_literal->dump(indent + 2);
  2821. }
  2822. // 13.3.11.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-tagged-templates-runtime-semantics-evaluation
  2823. Completion TaggedTemplateLiteral::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2824. {
  2825. InterpreterNodeScope node_scope { interpreter, *this };
  2826. auto& vm = interpreter.vm();
  2827. auto tag = TRY(m_tag->execute(interpreter, global_object)).release_value();
  2828. auto& expressions = m_template_literal->expressions();
  2829. auto* strings = MUST(Array::create(global_object, 0));
  2830. MarkedValueList arguments(vm.heap());
  2831. arguments.append(strings);
  2832. for (size_t i = 0; i < expressions.size(); ++i) {
  2833. auto value = TRY(expressions[i].execute(interpreter, global_object)).release_value();
  2834. // tag`${foo}` -> "", foo, "" -> tag(["", ""], foo)
  2835. // tag`foo${bar}baz${qux}` -> "foo", bar, "baz", qux, "" -> tag(["foo", "baz", ""], bar, qux)
  2836. if (i % 2 == 0) {
  2837. strings->indexed_properties().append(value);
  2838. } else {
  2839. arguments.append(value);
  2840. }
  2841. }
  2842. auto* raw_strings = MUST(Array::create(global_object, 0));
  2843. for (auto& raw_string : m_template_literal->raw_strings()) {
  2844. auto value = TRY(raw_string.execute(interpreter, global_object)).release_value();
  2845. raw_strings->indexed_properties().append(value);
  2846. }
  2847. strings->define_direct_property(vm.names.raw, raw_strings, 0);
  2848. return call(global_object, tag, js_undefined(), move(arguments));
  2849. }
  2850. void TryStatement::dump(int indent) const
  2851. {
  2852. ASTNode::dump(indent);
  2853. print_indent(indent);
  2854. outln("(Block)");
  2855. block().dump(indent + 1);
  2856. if (handler()) {
  2857. print_indent(indent);
  2858. outln("(Handler)");
  2859. handler()->dump(indent + 1);
  2860. }
  2861. if (finalizer()) {
  2862. print_indent(indent);
  2863. outln("(Finalizer)");
  2864. finalizer()->dump(indent + 1);
  2865. }
  2866. }
  2867. void CatchClause::dump(int indent) const
  2868. {
  2869. print_indent(indent);
  2870. m_parameter.visit(
  2871. [&](FlyString const& parameter) {
  2872. if (parameter.is_null())
  2873. outln("CatchClause");
  2874. else
  2875. outln("CatchClause ({})", parameter);
  2876. },
  2877. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2878. outln("CatchClause");
  2879. print_indent(indent);
  2880. outln("(Parameter)");
  2881. pattern->dump(indent + 2);
  2882. });
  2883. body().dump(indent + 1);
  2884. }
  2885. void ThrowStatement::dump(int indent) const
  2886. {
  2887. ASTNode::dump(indent);
  2888. argument().dump(indent + 1);
  2889. }
  2890. // 14.15.3 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-try-statement-runtime-semantics-evaluation
  2891. Completion TryStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2892. {
  2893. InterpreterNodeScope node_scope { interpreter, *this };
  2894. auto& vm = interpreter.vm();
  2895. // 14.15.2 Runtime Semantics: CatchClauseEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-catchclauseevaluation
  2896. auto catch_clause_evaluation = [&](Value thrown_value) {
  2897. // 1. Let oldEnv be the running execution context's LexicalEnvironment.
  2898. auto* old_environment = vm.running_execution_context().lexical_environment;
  2899. // 2. Let catchEnv be NewDeclarativeEnvironment(oldEnv).
  2900. auto* catch_environment = new_declarative_environment(*old_environment);
  2901. m_handler->parameter().visit(
  2902. [&](FlyString const& parameter) {
  2903. // 3. For each element argName of the BoundNames of CatchParameter, do
  2904. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  2905. MUST(catch_environment->create_mutable_binding(global_object, parameter, false));
  2906. },
  2907. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2908. // 3. For each element argName of the BoundNames of CatchParameter, do
  2909. pattern->for_each_bound_name([&](auto& name) {
  2910. // a. Perform ! catchEnv.CreateMutableBinding(argName, false).
  2911. MUST(catch_environment->create_mutable_binding(global_object, name, false));
  2912. });
  2913. });
  2914. // 4. Set the running execution context's LexicalEnvironment to catchEnv.
  2915. vm.running_execution_context().lexical_environment = catch_environment;
  2916. // 5. Let status be BindingInitialization of CatchParameter with arguments thrownValue and catchEnv.
  2917. auto status = m_handler->parameter().visit(
  2918. [&](FlyString const& parameter) {
  2919. return catch_environment->initialize_binding(global_object, parameter, thrown_value);
  2920. },
  2921. [&](NonnullRefPtr<BindingPattern> const& pattern) {
  2922. return vm.binding_initialization(pattern, thrown_value, catch_environment, global_object);
  2923. });
  2924. // 6. If status is an abrupt completion, then
  2925. if (status.is_error()) {
  2926. // a. Set the running execution context's LexicalEnvironment to oldEnv.
  2927. vm.running_execution_context().lexical_environment = old_environment;
  2928. // b. Return Completion(status).
  2929. return status.release_error();
  2930. }
  2931. // 7. Let B be the result of evaluating Block.
  2932. auto handler_result = m_handler->body().execute(interpreter, global_object);
  2933. // 8. Set the running execution context's LexicalEnvironment to oldEnv.
  2934. vm.running_execution_context().lexical_environment = old_environment;
  2935. // 9. Return Completion(B).
  2936. return handler_result;
  2937. };
  2938. Completion result;
  2939. // 1. Let B be the result of evaluating Block.
  2940. auto block_result = m_block->execute(interpreter, global_object);
  2941. // TryStatement : try Block Catch
  2942. // TryStatement : try Block Catch Finally
  2943. if (m_handler) {
  2944. vm.clear_exception();
  2945. // 2. If B.[[Type]] is throw, let C be CatchClauseEvaluation of Catch with argument B.[[Value]].
  2946. if (block_result.type() == Completion::Type::Throw)
  2947. result = catch_clause_evaluation(*block_result.value());
  2948. // 3. Else, let C be B.
  2949. else
  2950. result = move(block_result);
  2951. } else {
  2952. // TryStatement : try Block Finally
  2953. // This variant doesn't have C & uses B in the finalizer step.
  2954. result = move(block_result);
  2955. }
  2956. // TryStatement : try Block Finally
  2957. // TryStatement : try Block Catch Finally
  2958. if (m_finalizer) {
  2959. // NOTE: Temporary until VM::exception() is removed
  2960. // Keep, if any, and then clear the current exception so we can
  2961. // execute() the finalizer without an exception in our way.
  2962. auto* previous_exception = vm.exception();
  2963. vm.clear_exception();
  2964. // 4. Let F be the result of evaluating Finally.
  2965. auto finalizer_result = m_finalizer->execute(interpreter, global_object);
  2966. // 5. If F.[[Type]] is normal, set F to C.
  2967. if (finalizer_result.type() == Completion::Type::Normal)
  2968. finalizer_result = move(result);
  2969. // NOTE: Temporary until VM::exception() is removed
  2970. // If we previously had an exception and we're carrying over
  2971. // the catch block completion, restore it.
  2972. if (finalizer_result.type() == Completion::Type::Normal && previous_exception)
  2973. vm.set_exception(*previous_exception);
  2974. // 6. Return Completion(UpdateEmpty(F, undefined)).
  2975. return finalizer_result.update_empty(js_undefined());
  2976. }
  2977. // 4. Return Completion(UpdateEmpty(C, undefined)).
  2978. return result.update_empty(js_undefined());
  2979. }
  2980. Completion CatchClause::execute(Interpreter& interpreter, GlobalObject&) const
  2981. {
  2982. InterpreterNodeScope node_scope { interpreter, *this };
  2983. // NOTE: CatchClause execution is handled by TryStatement.
  2984. VERIFY_NOT_REACHED();
  2985. return {};
  2986. }
  2987. // 14.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-throw-statement-runtime-semantics-evaluation
  2988. Completion ThrowStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  2989. {
  2990. InterpreterNodeScope node_scope { interpreter, *this };
  2991. // 1. Let exprRef be the result of evaluating Expression.
  2992. // 2. Let exprValue be ? GetValue(exprRef).
  2993. auto value = TRY(m_argument->execute(interpreter, global_object)).release_value();
  2994. // 3. Return ThrowCompletion(exprValue).
  2995. // TODO: Remove this once we get rid of VM::exception()
  2996. interpreter.vm().throw_exception(global_object, value);
  2997. return throw_completion(value);
  2998. }
  2999. // 14.1.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-statement-semantics-runtime-semantics-evaluation
  3000. // BreakableStatement : SwitchStatement
  3001. Completion SwitchStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3002. {
  3003. // 1. Let newLabelSet be a new empty List.
  3004. // 2. Return the result of performing LabelledEvaluation of this BreakableStatement with argument newLabelSet.
  3005. return labelled_evaluation(interpreter, global_object, *this, {});
  3006. }
  3007. // NOTE: Since we don't have the 'BreakableStatement' from the spec as a separate ASTNode that wraps IterationStatement / SwitchStatement,
  3008. // execute() needs to take care of LabelledEvaluation, which in turn calls execute_impl().
  3009. // 14.12.4 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-switch-statement-runtime-semantics-evaluation
  3010. Completion SwitchStatement::execute_impl(Interpreter& interpreter, GlobalObject& global_object) const
  3011. {
  3012. InterpreterNodeScope node_scope { interpreter, *this };
  3013. auto& vm = interpreter.vm();
  3014. // 14.12.3 CaseClauseIsSelected ( C, input ), https://tc39.es/ecma262/#sec-runtime-semantics-caseclauseisselected
  3015. auto case_clause_is_selected = [&](auto const& case_clause, auto input) -> ThrowCompletionOr<bool> {
  3016. // 1. Assert: C is an instance of the production CaseClause : case Expression : StatementList[opt] .
  3017. VERIFY(case_clause.test());
  3018. // 2. Let exprRef be the result of evaluating the Expression of C.
  3019. // 3. Let clauseSelector be ? GetValue(exprRef).
  3020. auto clause_selector = TRY(case_clause.test()->execute(interpreter, global_object)).release_value();
  3021. // 4. Return IsStrictlyEqual(input, clauseSelector).
  3022. return is_strictly_equal(input, clause_selector);
  3023. };
  3024. // 14.12.2 Runtime Semantics: CaseBlockEvaluation, https://tc39.es/ecma262/#sec-runtime-semantics-caseblockevaluation
  3025. auto case_block_evaluation = [&](auto input) {
  3026. // CaseBlock : { }
  3027. if (m_cases.is_empty()) {
  3028. // 1. Return NormalCompletion(undefined).
  3029. return normal_completion(js_undefined());
  3030. }
  3031. NonnullRefPtrVector<SwitchCase> case_clauses_1;
  3032. NonnullRefPtrVector<SwitchCase> case_clauses_2;
  3033. RefPtr<SwitchCase> default_clause;
  3034. for (auto const& switch_case : m_cases) {
  3035. if (!switch_case.test())
  3036. default_clause = switch_case;
  3037. else if (!default_clause)
  3038. case_clauses_1.append(switch_case);
  3039. else
  3040. case_clauses_2.append(switch_case);
  3041. }
  3042. // CaseBlock : { CaseClauses }
  3043. if (!default_clause) {
  3044. VERIFY(!case_clauses_1.is_empty());
  3045. VERIFY(case_clauses_2.is_empty());
  3046. // 1. Let V be undefined.
  3047. auto last_value = js_undefined();
  3048. // 2. Let A be the List of CaseClause items in CaseClauses, in source text order.
  3049. // NOTE: A is case_clauses_1.
  3050. // 3. Let found be false.
  3051. auto found = false;
  3052. // 4. For each CaseClause C of A, do
  3053. for (auto const& case_clause : case_clauses_1) {
  3054. // a. If found is false, then
  3055. if (!found) {
  3056. // i. Set found to ? CaseClauseIsSelected(C, input).
  3057. found = TRY(case_clause_is_selected(case_clause, input));
  3058. }
  3059. // b. If found is true, then
  3060. if (found) {
  3061. // i. Let R be the result of evaluating C.
  3062. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3063. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3064. if (result.value().has_value())
  3065. last_value = *result.value();
  3066. // iii. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3067. if (result.is_abrupt())
  3068. return result.update_empty(last_value);
  3069. }
  3070. }
  3071. // 5. Return NormalCompletion(V).
  3072. return normal_completion(last_value);
  3073. }
  3074. // CaseBlock : { CaseClauses[opt] DefaultClause CaseClauses[opt] }
  3075. else {
  3076. // 1. Let V be undefined.
  3077. auto last_value = js_undefined();
  3078. // 2. If the first CaseClauses is present, then
  3079. // a. Let A be the List of CaseClause items in the first CaseClauses, in source text order.
  3080. // 3. Else,
  3081. // a. Let A be « ».
  3082. // NOTE: A is case_clauses_1.
  3083. // 4. Let found be false.
  3084. auto found = false;
  3085. // 5. For each CaseClause C of A, do
  3086. for (auto const& case_clause : case_clauses_1) {
  3087. // a. If found is false, then
  3088. if (!found) {
  3089. // i. Set found to ? CaseClauseIsSelected(C, input).
  3090. found = TRY(case_clause_is_selected(case_clause, input));
  3091. }
  3092. // b. If found is true, then
  3093. if (found) {
  3094. // i. Let R be the result of evaluating C.
  3095. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3096. // ii. If R.[[Value]] is not empty, set V to R.[[Value]].
  3097. if (result.value().has_value())
  3098. last_value = *result.value();
  3099. // iii. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3100. if (result.is_abrupt())
  3101. return result.update_empty(last_value);
  3102. }
  3103. }
  3104. // 6. Let foundInB be false.
  3105. auto found_in_b = false;
  3106. // 7. If the second CaseClauses is present, then
  3107. // a. Let B be the List of CaseClause items in the second CaseClauses, in source text order.
  3108. // 8. Else,
  3109. // a. Let B be « ».
  3110. // NOTE: B is case_clauses_2.
  3111. // 9. If found is false, then
  3112. if (!found) {
  3113. // a. For each CaseClause C of B, do
  3114. for (auto const& case_clause : case_clauses_2) {
  3115. // i. If foundInB is false, then
  3116. if (!found_in_b) {
  3117. // 1. Set foundInB to ? CaseClauseIsSelected(C, input).
  3118. found_in_b = TRY(case_clause_is_selected(case_clause, input));
  3119. }
  3120. // ii. If foundInB is true, then
  3121. if (found_in_b) {
  3122. // 1. Let R be the result of evaluating CaseClause C.
  3123. auto result = case_clause.evaluate_statements(interpreter, global_object);
  3124. // 2. If R.[[Value]] is not empty, set V to R.[[Value]].
  3125. if (result.value().has_value())
  3126. last_value = *result.value();
  3127. // 3. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3128. if (result.is_abrupt())
  3129. return result.update_empty(last_value);
  3130. }
  3131. }
  3132. }
  3133. // 10. If foundInB is true, return NormalCompletion(V).
  3134. if (found_in_b)
  3135. return normal_completion(last_value);
  3136. // 11. Let R be the result of evaluating DefaultClause.
  3137. auto result = default_clause->evaluate_statements(interpreter, global_object);
  3138. // 12. If R.[[Value]] is not empty, set V to R.[[Value]].
  3139. if (result.value().has_value())
  3140. last_value = *result.value();
  3141. // 13. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3142. if (result.is_abrupt())
  3143. return result.update_empty(last_value);
  3144. // 14. NOTE: The following is another complete iteration of the second CaseClauses.
  3145. // 15. For each CaseClause C of B, do
  3146. for (auto const& case_clause : case_clauses_2) {
  3147. // a. Let R be the result of evaluating CaseClause C.
  3148. result = case_clause.evaluate_statements(interpreter, global_object);
  3149. // b. If R.[[Value]] is not empty, set V to R.[[Value]].
  3150. if (result.value().has_value())
  3151. last_value = *result.value();
  3152. // c. If R is an abrupt completion, return Completion(UpdateEmpty(R, V)).
  3153. if (result.is_abrupt())
  3154. return result.update_empty(last_value);
  3155. }
  3156. // 16. Return NormalCompletion(V).
  3157. return normal_completion(last_value);
  3158. }
  3159. VERIFY_NOT_REACHED();
  3160. };
  3161. // SwitchStatement : switch ( Expression ) CaseBlock
  3162. // 1. Let exprRef be the result of evaluating Expression.
  3163. // 2. Let switchValue be ? GetValue(exprRef).
  3164. auto switch_value = TRY(m_discriminant->execute(interpreter, global_object)).release_value();
  3165. // 3. Let oldEnv be the running execution context's LexicalEnvironment.
  3166. auto* old_environment = interpreter.lexical_environment();
  3167. // Optimization: Avoid creating a lexical environment if there are no lexical declarations.
  3168. if (has_lexical_declarations()) {
  3169. // 4. Let blockEnv be NewDeclarativeEnvironment(oldEnv).
  3170. auto* block_environment = new_declarative_environment(*old_environment);
  3171. // 5. Perform BlockDeclarationInstantiation(CaseBlock, blockEnv).
  3172. block_declaration_instantiation(global_object, block_environment);
  3173. // 6. Set the running execution context's LexicalEnvironment to blockEnv.
  3174. vm.running_execution_context().lexical_environment = block_environment;
  3175. }
  3176. // 7. Let R be CaseBlockEvaluation of CaseBlock with argument switchValue.
  3177. auto result = case_block_evaluation(switch_value);
  3178. // 8. Set the running execution context's LexicalEnvironment to oldEnv.
  3179. vm.running_execution_context().lexical_environment = old_environment;
  3180. // 9. Return R.
  3181. return result;
  3182. }
  3183. Completion SwitchCase::execute(Interpreter& interpreter, GlobalObject&) const
  3184. {
  3185. InterpreterNodeScope node_scope { interpreter, *this };
  3186. // NOTE: SwitchCase execution is handled by SwitchStatement.
  3187. VERIFY_NOT_REACHED();
  3188. return {};
  3189. }
  3190. // 14.9.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-break-statement-runtime-semantics-evaluation
  3191. Completion BreakStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3192. {
  3193. InterpreterNodeScope node_scope { interpreter, *this };
  3194. // BreakStatement : break ;
  3195. if (m_target_label.is_null()) {
  3196. // 1. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: empty }.
  3197. return { Completion::Type::Break, {}, {} };
  3198. }
  3199. // BreakStatement : break LabelIdentifier ;
  3200. // 1. Let label be the StringValue of LabelIdentifier.
  3201. // 2. Return Completion { [[Type]]: break, [[Value]]: empty, [[Target]]: label }.
  3202. return { Completion::Type::Break, {}, m_target_label };
  3203. }
  3204. // 14.8.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-continue-statement-runtime-semantics-evaluation
  3205. Completion ContinueStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3206. {
  3207. InterpreterNodeScope node_scope { interpreter, *this };
  3208. // ContinueStatement : continue ;
  3209. if (m_target_label.is_null()) {
  3210. // 1. Return Completion { [[Type]]: continue, [[Value]]: empty, [[Target]]: empty }.
  3211. return { Completion::Type::Continue, {}, {} };
  3212. }
  3213. // ContinueStatement : continue LabelIdentifier ;
  3214. // 1. Let label be the StringValue of LabelIdentifier.
  3215. // 2. Return Completion { [[Type]]: continue, [[Value]]: empty, [[Target]]: label }.
  3216. return { Completion::Type::Continue, {}, m_target_label };
  3217. }
  3218. void SwitchStatement::dump(int indent) const
  3219. {
  3220. ASTNode::dump(indent);
  3221. m_discriminant->dump(indent + 1);
  3222. for (auto& switch_case : m_cases) {
  3223. switch_case.dump(indent + 1);
  3224. }
  3225. }
  3226. void SwitchCase::dump(int indent) const
  3227. {
  3228. print_indent(indent + 1);
  3229. if (m_test) {
  3230. outln("(Test)");
  3231. m_test->dump(indent + 2);
  3232. } else {
  3233. outln("(Default)");
  3234. }
  3235. print_indent(indent + 1);
  3236. outln("(Consequent)");
  3237. ScopeNode::dump(indent + 2);
  3238. }
  3239. // 13.14.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-conditional-operator-runtime-semantics-evaluation
  3240. Completion ConditionalExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3241. {
  3242. InterpreterNodeScope node_scope { interpreter, *this };
  3243. // 1. Let lref be the result of evaluating ShortCircuitExpression.
  3244. // 2. Let lval be ! ToBoolean(? GetValue(lref)).
  3245. auto test_result = TRY(m_test->execute(interpreter, global_object)).release_value();
  3246. // 3. If lval is true, then
  3247. if (test_result.to_boolean()) {
  3248. // a. Let trueRef be the result of evaluating the first AssignmentExpression.
  3249. // b. Return ? GetValue(trueRef).
  3250. return m_consequent->execute(interpreter, global_object);
  3251. }
  3252. // 4. Else,
  3253. else {
  3254. // a. Let falseRef be the result of evaluating the second AssignmentExpression.
  3255. // b. Return ? GetValue(falseRef).
  3256. return m_alternate->execute(interpreter, global_object);
  3257. }
  3258. }
  3259. void ConditionalExpression::dump(int indent) const
  3260. {
  3261. ASTNode::dump(indent);
  3262. print_indent(indent + 1);
  3263. outln("(Test)");
  3264. m_test->dump(indent + 2);
  3265. print_indent(indent + 1);
  3266. outln("(Consequent)");
  3267. m_consequent->dump(indent + 2);
  3268. print_indent(indent + 1);
  3269. outln("(Alternate)");
  3270. m_alternate->dump(indent + 2);
  3271. }
  3272. void SequenceExpression::dump(int indent) const
  3273. {
  3274. ASTNode::dump(indent);
  3275. for (auto& expression : m_expressions)
  3276. expression.dump(indent + 1);
  3277. }
  3278. // 13.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-comma-operator-runtime-semantics-evaluation
  3279. Completion SequenceExpression::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3280. {
  3281. InterpreterNodeScope node_scope { interpreter, *this };
  3282. // NOTE: Not sure why the last node is an AssignmentExpression in the spec :yakfused:
  3283. // 1. Let lref be the result of evaluating Expression.
  3284. // 2. Perform ? GetValue(lref).
  3285. // 3. Let rref be the result of evaluating AssignmentExpression.
  3286. // 4. Return ? GetValue(rref).
  3287. Value last_value;
  3288. for (auto const& expression : m_expressions)
  3289. last_value = TRY(expression.execute(interpreter, global_object)).release_value();
  3290. return { move(last_value) };
  3291. }
  3292. // 14.16.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-debugger-statement-runtime-semantics-evaluation
  3293. Completion DebuggerStatement::execute(Interpreter& interpreter, GlobalObject&) const
  3294. {
  3295. InterpreterNodeScope node_scope { interpreter, *this };
  3296. Completion result;
  3297. // 1. If an implementation-defined debugging facility is available and enabled, then
  3298. if (false) {
  3299. // a. Perform an implementation-defined debugging action.
  3300. // b. Let result be an implementation-defined Completion value.
  3301. }
  3302. // 2. Else,
  3303. else {
  3304. // a. Let result be NormalCompletion(empty).
  3305. result = normal_completion({});
  3306. }
  3307. // 3. Return result.
  3308. return result;
  3309. }
  3310. void ScopeNode::for_each_lexically_scoped_declaration(IteratorOrVoidFunction<Declaration const&>&& callback) const
  3311. {
  3312. for (auto& declaration : m_lexical_declarations) {
  3313. if (callback(declaration) == IterationDecision::Break)
  3314. break;
  3315. }
  3316. }
  3317. void ScopeNode::for_each_lexically_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  3318. {
  3319. auto running = true;
  3320. for (auto& declaration : m_lexical_declarations) {
  3321. declaration.for_each_bound_name([&](auto const& name) {
  3322. if (callback(name) == IterationDecision::Break) {
  3323. running = false;
  3324. return IterationDecision::Break;
  3325. }
  3326. return IterationDecision::Continue;
  3327. });
  3328. if (!running)
  3329. break;
  3330. }
  3331. }
  3332. void ScopeNode::for_each_var_declared_name(IteratorOrVoidFunction<FlyString const&>&& callback) const
  3333. {
  3334. auto running = true;
  3335. for (auto& declaration : m_var_declarations) {
  3336. declaration.for_each_bound_name([&](auto const& name) {
  3337. if (callback(name) == IterationDecision::Break) {
  3338. running = false;
  3339. return IterationDecision::Break;
  3340. }
  3341. return IterationDecision::Continue;
  3342. });
  3343. if (!running)
  3344. break;
  3345. }
  3346. }
  3347. void ScopeNode::for_each_var_function_declaration_in_reverse_order(IteratorOrVoidFunction<FunctionDeclaration const&>&& callback) const
  3348. {
  3349. for (ssize_t i = m_var_declarations.size() - 1; i >= 0; i--) {
  3350. auto& declaration = m_var_declarations[i];
  3351. if (is<FunctionDeclaration>(declaration)) {
  3352. if (callback(static_cast<FunctionDeclaration const&>(declaration)) == IterationDecision::Break)
  3353. break;
  3354. }
  3355. }
  3356. }
  3357. void ScopeNode::for_each_var_scoped_variable_declaration(IteratorOrVoidFunction<VariableDeclaration const&>&& callback) const
  3358. {
  3359. for (auto& declaration : m_var_declarations) {
  3360. if (!is<FunctionDeclaration>(declaration)) {
  3361. VERIFY(is<VariableDeclaration>(declaration));
  3362. if (callback(static_cast<VariableDeclaration const&>(declaration)) == IterationDecision::Break)
  3363. break;
  3364. }
  3365. }
  3366. }
  3367. void ScopeNode::for_each_function_hoistable_with_annexB_extension(IteratorOrVoidFunction<FunctionDeclaration&>&& callback) const
  3368. {
  3369. for (auto& function : m_functions_hoistable_with_annexB_extension) {
  3370. // We need const_cast here since it might have to set a property on function declaration.
  3371. if (callback(const_cast<FunctionDeclaration&>(function)) == IterationDecision::Break)
  3372. break;
  3373. }
  3374. }
  3375. void ScopeNode::add_lexical_declaration(NonnullRefPtr<Declaration> declaration)
  3376. {
  3377. m_lexical_declarations.append(move(declaration));
  3378. }
  3379. void ScopeNode::add_var_scoped_declaration(NonnullRefPtr<Declaration> declaration)
  3380. {
  3381. m_var_declarations.append(move(declaration));
  3382. }
  3383. void ScopeNode::add_hoisted_function(NonnullRefPtr<FunctionDeclaration> declaration)
  3384. {
  3385. m_functions_hoistable_with_annexB_extension.append(move(declaration));
  3386. }
  3387. // 16.2.1.11 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-module-semantics-runtime-semantics-evaluation
  3388. Completion ImportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3389. {
  3390. InterpreterNodeScope node_scope { interpreter, *this };
  3391. dbgln("Modules are not fully supported yet!");
  3392. return interpreter.vm().throw_completion<InternalError>(global_object, ErrorType::NotImplemented, "'import' in modules");
  3393. }
  3394. // 16.2.3.7 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-exports-runtime-semantics-evaluation
  3395. Completion ExportStatement::execute(Interpreter& interpreter, GlobalObject& global_object) const
  3396. {
  3397. InterpreterNodeScope node_scope { interpreter, *this };
  3398. if (m_statement) {
  3399. // 1. Return the result of evaluating <Thing>.
  3400. return m_statement->execute(interpreter, global_object);
  3401. }
  3402. // 1. Return NormalCompletion(empty).
  3403. return normal_completion({});
  3404. }
  3405. static void dump_assert_clauses(ModuleRequest const& request)
  3406. {
  3407. if (!request.assertions.is_empty()) {
  3408. out("[ ");
  3409. for (auto& assertion : request.assertions)
  3410. out("{}: {}, ", assertion.key, assertion.value);
  3411. out(" ]");
  3412. }
  3413. }
  3414. void ExportStatement::dump(int indent) const
  3415. {
  3416. ASTNode::dump(indent);
  3417. print_indent(indent + 1);
  3418. outln("(ExportEntries)");
  3419. auto string_or_null = [](String const& string) -> String {
  3420. if (string.is_empty()) {
  3421. return "null";
  3422. }
  3423. return String::formatted("\"{}\"", string);
  3424. };
  3425. for (auto& entry : m_entries) {
  3426. print_indent(indent + 2);
  3427. out("ModuleRequest: {}", entry.module_request.module_specifier);
  3428. dump_assert_clauses(entry.module_request);
  3429. outln(", ImportName: {}, LocalName: {}, ExportName: {}",
  3430. entry.kind == ExportEntry::Kind::ModuleRequest ? string_or_null(entry.local_or_import_name) : "null",
  3431. entry.kind != ExportEntry::Kind::ModuleRequest ? string_or_null(entry.local_or_import_name) : "null",
  3432. string_or_null(entry.export_name));
  3433. }
  3434. }
  3435. void ImportStatement::dump(int indent) const
  3436. {
  3437. ASTNode::dump(indent);
  3438. print_indent(indent + 1);
  3439. if (m_entries.is_empty()) {
  3440. // direct from "module" import
  3441. outln("Entire module '{}'", m_module_request.module_specifier);
  3442. dump_assert_clauses(m_module_request);
  3443. } else {
  3444. outln("(ExportEntries) from {}", m_module_request.module_specifier);
  3445. dump_assert_clauses(m_module_request);
  3446. for (auto& entry : m_entries) {
  3447. print_indent(indent + 2);
  3448. outln("ImportName: {}, LocalName: {}", entry.import_name, entry.local_name);
  3449. }
  3450. }
  3451. }
  3452. bool ExportStatement::has_export(StringView export_name) const
  3453. {
  3454. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3455. return entry.export_name == export_name;
  3456. });
  3457. }
  3458. bool ImportStatement::has_bound_name(StringView name) const
  3459. {
  3460. return any_of(m_entries.begin(), m_entries.end(), [&](auto& entry) {
  3461. return entry.local_name == name;
  3462. });
  3463. }
  3464. // 14.2.3 BlockDeclarationInstantiation ( code, env ), https://tc39.es/ecma262/#sec-blockdeclarationinstantiation
  3465. void ScopeNode::block_declaration_instantiation(GlobalObject& global_object, Environment* environment) const
  3466. {
  3467. // See also B.3.2.6 Changes to BlockDeclarationInstantiation, https://tc39.es/ecma262/#sec-web-compat-blockdeclarationinstantiation
  3468. VERIFY(environment);
  3469. auto* private_environment = global_object.vm().running_execution_context().private_environment;
  3470. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  3471. auto is_constant_declaration = declaration.is_constant_declaration();
  3472. declaration.for_each_bound_name([&](auto const& name) {
  3473. if (is_constant_declaration) {
  3474. MUST(environment->create_immutable_binding(global_object, name, true));
  3475. } else {
  3476. if (!MUST(environment->has_binding(name)))
  3477. MUST(environment->create_mutable_binding(global_object, name, false));
  3478. }
  3479. });
  3480. if (is<FunctionDeclaration>(declaration)) {
  3481. auto& function_declaration = static_cast<FunctionDeclaration const&>(declaration);
  3482. auto* function = ECMAScriptFunctionObject::create(global_object, function_declaration.name(), function_declaration.body(), function_declaration.parameters(), function_declaration.function_length(), environment, private_environment, function_declaration.kind(), function_declaration.is_strict_mode(), function_declaration.might_need_arguments_object(), function_declaration.contains_direct_call_to_eval());
  3483. VERIFY(is<DeclarativeEnvironment>(*environment));
  3484. static_cast<DeclarativeEnvironment&>(*environment).initialize_or_set_mutable_binding({}, global_object, function_declaration.name(), function);
  3485. }
  3486. });
  3487. }
  3488. // 16.1.7 GlobalDeclarationInstantiation ( script, env ), https://tc39.es/ecma262/#sec-globaldeclarationinstantiation
  3489. ThrowCompletionOr<void> Program::global_declaration_instantiation(Interpreter& interpreter, GlobalObject& global_object, GlobalEnvironment& global_environment) const
  3490. {
  3491. for_each_lexically_declared_name([&](FlyString const& name) {
  3492. if (global_environment.has_var_declaration(name) || global_environment.has_lexical_declaration(name)) {
  3493. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  3494. return IterationDecision::Break;
  3495. }
  3496. auto restricted_global_or_error = global_environment.has_restricted_global_property(name);
  3497. if (restricted_global_or_error.is_error())
  3498. return IterationDecision::Break;
  3499. auto restricted_global = restricted_global_or_error.release_value();
  3500. if (restricted_global)
  3501. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::RestrictedGlobalProperty, name);
  3502. return IterationDecision::Continue;
  3503. });
  3504. if (auto* exception = interpreter.exception())
  3505. return throw_completion(exception->value());
  3506. for_each_var_declared_name([&](auto const& name) {
  3507. if (global_environment.has_lexical_declaration(name)) {
  3508. interpreter.vm().throw_exception<SyntaxError>(global_object, ErrorType::TopLevelVariableAlreadyDeclared, name);
  3509. return IterationDecision::Break;
  3510. }
  3511. return IterationDecision::Continue;
  3512. });
  3513. if (auto* exception = interpreter.exception())
  3514. return throw_completion(exception->value());
  3515. HashTable<FlyString> declared_function_names;
  3516. Vector<FunctionDeclaration const&> functions_to_initialize;
  3517. for_each_var_function_declaration_in_reverse_order([&](FunctionDeclaration const& function) {
  3518. if (declared_function_names.set(function.name()) != AK::HashSetResult::InsertedNewEntry)
  3519. return IterationDecision::Continue;
  3520. auto function_definable_or_error = global_environment.can_declare_global_function(function.name());
  3521. if (function_definable_or_error.is_error())
  3522. return IterationDecision::Break;
  3523. auto function_definable = function_definable_or_error.release_value();
  3524. if (!function_definable) {
  3525. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function.name());
  3526. return IterationDecision::Break;
  3527. }
  3528. functions_to_initialize.append(function);
  3529. return IterationDecision::Continue;
  3530. });
  3531. if (auto* exception = interpreter.exception())
  3532. return throw_completion(exception->value());
  3533. HashTable<FlyString> declared_var_names;
  3534. for_each_var_scoped_variable_declaration([&](Declaration const& declaration) {
  3535. declaration.for_each_bound_name([&](auto const& name) {
  3536. if (declared_function_names.contains(name))
  3537. return IterationDecision::Continue;
  3538. auto var_definable_or_error = global_environment.can_declare_global_var(name);
  3539. if (var_definable_or_error.is_error())
  3540. return IterationDecision::Break;
  3541. auto var_definable = var_definable_or_error.release_value();
  3542. if (!var_definable) {
  3543. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalVariable, name);
  3544. return IterationDecision::Break;
  3545. }
  3546. declared_var_names.set(name);
  3547. return IterationDecision::Continue;
  3548. });
  3549. if (interpreter.exception())
  3550. return IterationDecision::Break;
  3551. return IterationDecision::Continue;
  3552. });
  3553. if (auto* exception = interpreter.exception())
  3554. return throw_completion(exception->value());
  3555. if (!m_is_strict_mode) {
  3556. for_each_function_hoistable_with_annexB_extension([&](FunctionDeclaration& function_declaration) {
  3557. auto& function_name = function_declaration.name();
  3558. if (global_environment.has_lexical_declaration(function_name))
  3559. return IterationDecision::Continue;
  3560. auto function_definable_or_error = global_environment.can_declare_global_function(function_name);
  3561. if (function_definable_or_error.is_error())
  3562. return IterationDecision::Break;
  3563. auto function_definable = function_definable_or_error.release_value();
  3564. if (!function_definable) {
  3565. interpreter.vm().throw_exception<TypeError>(global_object, ErrorType::CannotDeclareGlobalFunction, function_name);
  3566. return IterationDecision::Break;
  3567. }
  3568. if (!declared_function_names.contains(function_name) && !declared_var_names.contains(function_name)) {
  3569. auto result = global_environment.create_global_var_binding(function_name, false);
  3570. if (result.is_error())
  3571. return IterationDecision::Break;
  3572. declared_function_names.set(function_name);
  3573. }
  3574. function_declaration.set_should_do_additional_annexB_steps();
  3575. return IterationDecision::Continue;
  3576. });
  3577. if (auto* exception = interpreter.exception())
  3578. return throw_completion(exception->value());
  3579. // We should not use declared function names below here anymore since these functions are not in there in the spec.
  3580. declared_function_names.clear();
  3581. }
  3582. PrivateEnvironment* private_environment = nullptr;
  3583. for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  3584. declaration.for_each_bound_name([&](auto const& name) {
  3585. if (declaration.is_constant_declaration())
  3586. (void)global_environment.create_immutable_binding(global_object, name, true);
  3587. else
  3588. (void)global_environment.create_mutable_binding(global_object, name, false);
  3589. if (interpreter.exception())
  3590. return IterationDecision::Break;
  3591. return IterationDecision::Continue;
  3592. });
  3593. if (interpreter.exception())
  3594. return IterationDecision::Break;
  3595. return IterationDecision::Continue;
  3596. });
  3597. for (auto& declaration : functions_to_initialize) {
  3598. auto* function = ECMAScriptFunctionObject::create(global_object, declaration.name(), declaration.body(), declaration.parameters(), declaration.function_length(), &global_environment, private_environment, declaration.kind(), declaration.is_strict_mode(), declaration.might_need_arguments_object(), declaration.contains_direct_call_to_eval());
  3599. TRY(global_environment.create_global_function_binding(declaration.name(), function, false));
  3600. }
  3601. for (auto& var_name : declared_var_names)
  3602. TRY(global_environment.create_global_var_binding(var_name, false));
  3603. return {};
  3604. }
  3605. }