AST.cpp 193 KB

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