AST.cpp 198 KB

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