AST.cpp 188 KB

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