AST.cpp 191 KB

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