Parser.cpp 198 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021-2022, David Tuin <davidot@serenityos.org>
  5. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  6. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "Parser.h"
  11. #include <AK/Array.h>
  12. #include <AK/CharacterTypes.h>
  13. #include <AK/HashTable.h>
  14. #include <AK/ScopeGuard.h>
  15. #include <AK/StdLibExtras.h>
  16. #include <AK/TemporaryChange.h>
  17. #include <LibJS/Runtime/RegExpObject.h>
  18. #include <LibRegex/Regex.h>
  19. namespace JS {
  20. class ScopePusher {
  21. private:
  22. ScopePusher(Parser& parser, ScopeNode* node, bool is_top_level)
  23. : m_parser(parser)
  24. , m_is_top_level(is_top_level)
  25. {
  26. m_parent_scope = exchange(m_parser.m_state.current_scope_pusher, this);
  27. VERIFY(node || (m_parent_scope && !is_top_level));
  28. if (!node)
  29. m_node = m_parent_scope->m_node;
  30. else
  31. m_node = node;
  32. VERIFY(m_node);
  33. if (!is_top_level)
  34. m_top_level_scope = m_parent_scope->m_top_level_scope;
  35. else
  36. m_top_level_scope = this;
  37. }
  38. public:
  39. static ScopePusher function_scope(Parser& parser, FunctionBody& function_body, Vector<FunctionDeclaration::Parameter> const& parameters)
  40. {
  41. ScopePusher scope_pusher(parser, &function_body, true);
  42. scope_pusher.m_function_parameters = parameters;
  43. for (auto& parameter : parameters) {
  44. parameter.binding.visit(
  45. [&](FlyString const& name) {
  46. scope_pusher.m_forbidden_lexical_names.set(name);
  47. },
  48. [&](NonnullRefPtr<BindingPattern> const& binding_pattern) {
  49. binding_pattern->for_each_bound_name([&](auto const& name) {
  50. scope_pusher.m_forbidden_lexical_names.set(name);
  51. });
  52. });
  53. }
  54. return scope_pusher;
  55. }
  56. static ScopePusher program_scope(Parser& parser, Program& program)
  57. {
  58. return ScopePusher(parser, &program, true);
  59. }
  60. static ScopePusher block_scope(Parser& parser, ScopeNode& node)
  61. {
  62. return ScopePusher(parser, &node, false);
  63. }
  64. static ScopePusher for_loop_scope(Parser& parser, RefPtr<ASTNode> const& init)
  65. {
  66. ScopePusher scope_pusher(parser, nullptr, false);
  67. if (init && is<VariableDeclaration>(*init)) {
  68. auto& variable_declaration = static_cast<VariableDeclaration const&>(*init);
  69. if (variable_declaration.declaration_kind() != DeclarationKind::Var) {
  70. variable_declaration.for_each_bound_name([&](auto const& name) {
  71. scope_pusher.m_forbidden_var_names.set(name);
  72. });
  73. }
  74. }
  75. return scope_pusher;
  76. }
  77. static ScopePusher catch_scope(Parser& parser, RefPtr<BindingPattern> const& pattern, FlyString const& parameter)
  78. {
  79. ScopePusher scope_pusher(parser, nullptr, false);
  80. if (pattern) {
  81. pattern->for_each_bound_name([&](auto const& name) {
  82. scope_pusher.m_forbidden_var_names.set(name);
  83. });
  84. } else if (!parameter.is_empty()) {
  85. scope_pusher.m_var_names.set(parameter);
  86. }
  87. return scope_pusher;
  88. }
  89. static ScopePusher static_init_block_scope(Parser& parser, ScopeNode& node)
  90. {
  91. return ScopePusher(parser, &node, true);
  92. }
  93. static ScopePusher class_field_scope(Parser& parser)
  94. {
  95. return ScopePusher(parser, nullptr, false);
  96. }
  97. void add_declaration(NonnullRefPtr<Declaration> declaration)
  98. {
  99. if (declaration->is_lexical_declaration()) {
  100. declaration->for_each_bound_name([&](auto const& name) {
  101. if (m_var_names.contains(name) || m_forbidden_lexical_names.contains(name) || m_function_names.contains(name))
  102. throw_identifier_declared(name, declaration);
  103. if (m_lexical_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  104. throw_identifier_declared(name, declaration);
  105. });
  106. m_node->add_lexical_declaration(move(declaration));
  107. } else if (!declaration->is_function_declaration()) {
  108. declaration->for_each_bound_name([&](auto const& name) {
  109. ScopePusher* pusher = this;
  110. while (true) {
  111. if (pusher->m_lexical_names.contains(name)
  112. || pusher->m_function_names.contains(name)
  113. || pusher->m_forbidden_var_names.contains(name))
  114. throw_identifier_declared(name, declaration);
  115. pusher->m_var_names.set(name);
  116. if (pusher->m_is_top_level)
  117. break;
  118. VERIFY(pusher->m_parent_scope != nullptr);
  119. pusher = pusher->m_parent_scope;
  120. }
  121. VERIFY(pusher->m_is_top_level && pusher->m_node);
  122. pusher->m_node->add_var_scoped_declaration(declaration);
  123. });
  124. VERIFY(m_top_level_scope);
  125. m_top_level_scope->m_node->add_var_scoped_declaration(move(declaration));
  126. } else {
  127. if (m_is_top_level && m_parser.m_program_type == Program::Type::Script) {
  128. declaration->for_each_bound_name([&](auto const& name) {
  129. m_var_names.set(name);
  130. });
  131. m_node->add_var_scoped_declaration(move(declaration));
  132. } else {
  133. VERIFY(is<FunctionDeclaration>(*declaration));
  134. auto& function_declaration = static_cast<FunctionDeclaration const&>(*declaration);
  135. auto& function_name = function_declaration.name();
  136. if (m_var_names.contains(function_name) || m_lexical_names.contains(function_name))
  137. throw_identifier_declared(function_name, declaration);
  138. if (function_declaration.kind() != FunctionKind::Normal || m_parser.m_state.strict_mode) {
  139. if (m_function_names.contains(function_name))
  140. throw_identifier_declared(function_name, declaration);
  141. m_lexical_names.set(function_name);
  142. m_node->add_lexical_declaration(move(declaration));
  143. return;
  144. }
  145. m_function_names.set(function_name);
  146. if (!m_lexical_names.contains(function_name))
  147. m_functions_to_hoist.append(static_ptr_cast<FunctionDeclaration>(declaration));
  148. m_node->add_lexical_declaration(move(declaration));
  149. }
  150. }
  151. }
  152. ScopePusher const* last_function_scope() const
  153. {
  154. for (auto scope_ptr = this; scope_ptr; scope_ptr = scope_ptr->m_parent_scope) {
  155. if (scope_ptr->m_function_parameters.has_value())
  156. return scope_ptr;
  157. }
  158. return nullptr;
  159. }
  160. Vector<FunctionDeclaration::Parameter> const& function_parameters() const
  161. {
  162. return *m_function_parameters;
  163. }
  164. ScopePusher* parent_scope() { return m_parent_scope; }
  165. ScopePusher const* parent_scope() const { return m_parent_scope; }
  166. [[nodiscard]] bool has_declaration(FlyString const& name) const
  167. {
  168. return m_lexical_names.contains(name) || m_var_names.contains(name) || !m_functions_to_hoist.find_if([&name](auto& function) { return function->name() == name; }).is_end();
  169. }
  170. bool contains_direct_call_to_eval() const { return m_contains_direct_call_to_eval; }
  171. bool contains_access_to_arguments_object() const { return m_contains_access_to_arguments_object; }
  172. void set_contains_direct_call_to_eval() { m_contains_direct_call_to_eval = true; }
  173. void set_contains_access_to_arguments_object() { m_contains_access_to_arguments_object = true; }
  174. ~ScopePusher()
  175. {
  176. VERIFY(m_is_top_level || m_parent_scope);
  177. if (!m_contains_access_to_arguments_object) {
  178. for (auto& it : m_identifier_and_argument_index_associations) {
  179. for (auto& identifier : it.value) {
  180. if (!has_declaration(identifier.string()))
  181. identifier.set_lexically_bound_function_argument_index(it.key);
  182. }
  183. }
  184. }
  185. for (size_t i = 0; i < m_functions_to_hoist.size(); i++) {
  186. auto const& function_declaration = m_functions_to_hoist[i];
  187. if (m_lexical_names.contains(function_declaration.name()) || m_forbidden_var_names.contains(function_declaration.name()))
  188. continue;
  189. if (m_is_top_level)
  190. m_node->add_hoisted_function(move(m_functions_to_hoist[i]));
  191. else
  192. m_parent_scope->m_functions_to_hoist.append(move(m_functions_to_hoist[i]));
  193. }
  194. if (m_parent_scope && !m_function_parameters.has_value()) {
  195. m_parent_scope->m_contains_access_to_arguments_object |= m_contains_access_to_arguments_object;
  196. m_parent_scope->m_contains_direct_call_to_eval |= m_contains_direct_call_to_eval;
  197. }
  198. VERIFY(m_parser.m_state.current_scope_pusher == this);
  199. m_parser.m_state.current_scope_pusher = m_parent_scope;
  200. }
  201. void associate_identifier_with_argument_index(NonnullRefPtr<Identifier> identifier, size_t index)
  202. {
  203. m_identifier_and_argument_index_associations.ensure(index).append(move(identifier));
  204. }
  205. void set_contains_await_expression()
  206. {
  207. m_contains_await_expression = true;
  208. }
  209. bool contains_await_expression() const
  210. {
  211. return m_contains_await_expression;
  212. }
  213. private:
  214. void throw_identifier_declared(FlyString const& name, NonnullRefPtr<Declaration> const& declaration)
  215. {
  216. m_parser.syntax_error(String::formatted("Identifier '{}' already declared", name), declaration->source_range().start);
  217. }
  218. Parser& m_parser;
  219. ScopeNode* m_node { nullptr };
  220. bool m_is_top_level { false };
  221. ScopePusher* m_parent_scope { nullptr };
  222. ScopePusher* m_top_level_scope { nullptr };
  223. HashTable<FlyString> m_lexical_names;
  224. HashTable<FlyString> m_var_names;
  225. HashTable<FlyString> m_function_names;
  226. HashTable<FlyString> m_forbidden_lexical_names;
  227. HashTable<FlyString> m_forbidden_var_names;
  228. NonnullRefPtrVector<FunctionDeclaration> m_functions_to_hoist;
  229. Optional<Vector<FunctionDeclaration::Parameter>> m_function_parameters;
  230. HashMap<size_t, NonnullRefPtrVector<Identifier>> m_identifier_and_argument_index_associations;
  231. bool m_contains_access_to_arguments_object { false };
  232. bool m_contains_direct_call_to_eval { false };
  233. bool m_contains_await_expression { false };
  234. };
  235. class OperatorPrecedenceTable {
  236. public:
  237. constexpr OperatorPrecedenceTable()
  238. : m_token_precedence()
  239. {
  240. for (size_t i = 0; i < array_size(m_operator_precedence); ++i) {
  241. auto& op = m_operator_precedence[i];
  242. m_token_precedence[static_cast<size_t>(op.token)] = op.precedence;
  243. }
  244. }
  245. constexpr int get(TokenType token) const
  246. {
  247. int p = m_token_precedence[static_cast<size_t>(token)];
  248. if (p == 0) {
  249. warnln("Internal Error: No precedence for operator {}", Token::name(token));
  250. VERIFY_NOT_REACHED();
  251. return -1;
  252. }
  253. return p;
  254. }
  255. private:
  256. int m_token_precedence[cs_num_of_js_tokens];
  257. struct OperatorPrecedence {
  258. TokenType token;
  259. int precedence;
  260. };
  261. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  262. static constexpr const OperatorPrecedence m_operator_precedence[] = {
  263. { TokenType::Period, 20 },
  264. { TokenType::BracketOpen, 20 },
  265. { TokenType::ParenOpen, 20 },
  266. { TokenType::QuestionMarkPeriod, 20 },
  267. { TokenType::New, 19 },
  268. { TokenType::PlusPlus, 18 },
  269. { TokenType::MinusMinus, 18 },
  270. { TokenType::ExclamationMark, 17 },
  271. { TokenType::Tilde, 17 },
  272. { TokenType::Typeof, 17 },
  273. { TokenType::Void, 17 },
  274. { TokenType::Delete, 17 },
  275. { TokenType::Await, 17 },
  276. { TokenType::DoubleAsterisk, 16 },
  277. { TokenType::Asterisk, 15 },
  278. { TokenType::Slash, 15 },
  279. { TokenType::Percent, 15 },
  280. { TokenType::Plus, 14 },
  281. { TokenType::Minus, 14 },
  282. { TokenType::ShiftLeft, 13 },
  283. { TokenType::ShiftRight, 13 },
  284. { TokenType::UnsignedShiftRight, 13 },
  285. { TokenType::LessThan, 12 },
  286. { TokenType::LessThanEquals, 12 },
  287. { TokenType::GreaterThan, 12 },
  288. { TokenType::GreaterThanEquals, 12 },
  289. { TokenType::In, 12 },
  290. { TokenType::Instanceof, 12 },
  291. { TokenType::EqualsEquals, 11 },
  292. { TokenType::ExclamationMarkEquals, 11 },
  293. { TokenType::EqualsEqualsEquals, 11 },
  294. { TokenType::ExclamationMarkEqualsEquals, 11 },
  295. { TokenType::Ampersand, 10 },
  296. { TokenType::Caret, 9 },
  297. { TokenType::Pipe, 8 },
  298. { TokenType::DoubleQuestionMark, 7 },
  299. { TokenType::DoubleAmpersand, 6 },
  300. { TokenType::DoublePipe, 5 },
  301. { TokenType::QuestionMark, 4 },
  302. { TokenType::Equals, 3 },
  303. { TokenType::PlusEquals, 3 },
  304. { TokenType::MinusEquals, 3 },
  305. { TokenType::DoubleAsteriskEquals, 3 },
  306. { TokenType::AsteriskEquals, 3 },
  307. { TokenType::SlashEquals, 3 },
  308. { TokenType::PercentEquals, 3 },
  309. { TokenType::ShiftLeftEquals, 3 },
  310. { TokenType::ShiftRightEquals, 3 },
  311. { TokenType::UnsignedShiftRightEquals, 3 },
  312. { TokenType::AmpersandEquals, 3 },
  313. { TokenType::CaretEquals, 3 },
  314. { TokenType::PipeEquals, 3 },
  315. { TokenType::DoubleAmpersandEquals, 3 },
  316. { TokenType::DoublePipeEquals, 3 },
  317. { TokenType::DoubleQuestionMarkEquals, 3 },
  318. { TokenType::Yield, 2 },
  319. { TokenType::Comma, 1 },
  320. };
  321. };
  322. constexpr OperatorPrecedenceTable g_operator_precedence;
  323. Parser::ParserState::ParserState(Lexer l, Program::Type program_type)
  324. : lexer(move(l))
  325. {
  326. if (program_type == Program::Type::Module)
  327. lexer.disallow_html_comments();
  328. current_token = lexer.next();
  329. }
  330. Parser::Parser(Lexer lexer, Program::Type program_type)
  331. : m_state(move(lexer), program_type)
  332. , m_program_type(program_type)
  333. {
  334. }
  335. Associativity Parser::operator_associativity(TokenType type) const
  336. {
  337. switch (type) {
  338. case TokenType::Period:
  339. case TokenType::BracketOpen:
  340. case TokenType::ParenOpen:
  341. case TokenType::QuestionMarkPeriod:
  342. case TokenType::Asterisk:
  343. case TokenType::Slash:
  344. case TokenType::Percent:
  345. case TokenType::Plus:
  346. case TokenType::Minus:
  347. case TokenType::ShiftLeft:
  348. case TokenType::ShiftRight:
  349. case TokenType::UnsignedShiftRight:
  350. case TokenType::LessThan:
  351. case TokenType::LessThanEquals:
  352. case TokenType::GreaterThan:
  353. case TokenType::GreaterThanEquals:
  354. case TokenType::In:
  355. case TokenType::Instanceof:
  356. case TokenType::EqualsEquals:
  357. case TokenType::ExclamationMarkEquals:
  358. case TokenType::EqualsEqualsEquals:
  359. case TokenType::ExclamationMarkEqualsEquals:
  360. case TokenType::Typeof:
  361. case TokenType::Void:
  362. case TokenType::Delete:
  363. case TokenType::Await:
  364. case TokenType::Ampersand:
  365. case TokenType::Caret:
  366. case TokenType::Pipe:
  367. case TokenType::DoubleQuestionMark:
  368. case TokenType::DoubleAmpersand:
  369. case TokenType::DoublePipe:
  370. case TokenType::Comma:
  371. return Associativity::Left;
  372. default:
  373. return Associativity::Right;
  374. }
  375. }
  376. bool Parser::parse_directive(ScopeNode& body)
  377. {
  378. bool found_use_strict = false;
  379. while (!done() && match(TokenType::StringLiteral)) {
  380. // It cannot be a labelled function since we hit a string literal.
  381. auto statement = parse_statement(AllowLabelledFunction::No);
  382. body.append(statement);
  383. VERIFY(is<ExpressionStatement>(*statement));
  384. auto& expression = static_cast<ExpressionStatement const&>(*statement).expression();
  385. if (!is<StringLiteral>(expression))
  386. break;
  387. auto& string_literal = static_cast<StringLiteral const&>(expression);
  388. if (string_literal.is_use_strict_directive()) {
  389. found_use_strict = true;
  390. if (m_state.string_legacy_octal_escape_sequence_in_scope)
  391. syntax_error("Octal escape sequence in string literal not allowed in strict mode");
  392. break;
  393. }
  394. }
  395. m_state.string_legacy_octal_escape_sequence_in_scope = false;
  396. return found_use_strict;
  397. }
  398. NonnullRefPtr<Program> Parser::parse_program(bool starts_in_strict_mode)
  399. {
  400. auto rule_start = push_start();
  401. auto program = adopt_ref(*new Program({ m_filename, rule_start.position(), position() }, m_program_type));
  402. ScopePusher program_scope = ScopePusher::program_scope(*this, *program);
  403. if (m_program_type == Program::Type::Script)
  404. parse_script(program, starts_in_strict_mode);
  405. else
  406. parse_module(program);
  407. program->source_range().end = position();
  408. return program;
  409. }
  410. void Parser::parse_script(Program& program, bool starts_in_strict_mode)
  411. {
  412. bool strict_before = m_state.strict_mode;
  413. if (starts_in_strict_mode)
  414. m_state.strict_mode = true;
  415. bool has_use_strict = parse_directive(program);
  416. if (m_state.strict_mode || has_use_strict) {
  417. program.set_strict_mode();
  418. m_state.strict_mode = true;
  419. }
  420. parse_statement_list(program, AllowLabelledFunction::Yes);
  421. if (!done()) {
  422. expected("statement or declaration");
  423. consume();
  424. }
  425. m_state.strict_mode = strict_before;
  426. }
  427. void Parser::parse_module(Program& program)
  428. {
  429. TemporaryChange strict_mode_rollback(m_state.strict_mode, true);
  430. TemporaryChange await_expression_valid_rollback(m_state.await_expression_is_valid, true);
  431. // Since strict mode is already enabled we skip any directive parsing.
  432. while (!done()) {
  433. parse_statement_list(program, AllowLabelledFunction::Yes);
  434. if (done())
  435. break;
  436. if (match_export_or_import()) {
  437. VERIFY(m_state.current_token.type() == TokenType::Export || m_state.current_token.type() == TokenType::Import);
  438. if (m_state.current_token.type() == TokenType::Export)
  439. program.append_export(parse_export_statement(program));
  440. else
  441. program.append_import(parse_import_statement(program));
  442. } else {
  443. expected("statement or declaration");
  444. consume();
  445. }
  446. }
  447. VERIFY(m_state.current_scope_pusher);
  448. if (m_state.current_scope_pusher->contains_await_expression())
  449. program.set_has_top_level_await();
  450. for (auto& export_statement : program.exports()) {
  451. if (export_statement.has_statement())
  452. continue;
  453. for (auto& entry : export_statement.entries()) {
  454. if (entry.is_module_request())
  455. return;
  456. auto const& exported_name = entry.local_or_import_name;
  457. bool found = false;
  458. program.for_each_lexically_declared_name([&](auto const& name) {
  459. if (name == exported_name)
  460. found = true;
  461. });
  462. if (found)
  463. continue;
  464. program.for_each_var_declared_name([&](auto const& name) {
  465. if (name == exported_name)
  466. found = true;
  467. });
  468. if (!found)
  469. syntax_error(String::formatted("'{}' is not declared", exported_name));
  470. }
  471. }
  472. }
  473. NonnullRefPtr<Declaration> Parser::parse_declaration()
  474. {
  475. auto rule_start = push_start();
  476. if (m_state.current_token.type() == TokenType::Async && next_token().type() == TokenType::Function)
  477. return parse_function_node<FunctionDeclaration>();
  478. switch (m_state.current_token.type()) {
  479. case TokenType::Class:
  480. return parse_class_declaration();
  481. case TokenType::Function:
  482. return parse_function_node<FunctionDeclaration>();
  483. case TokenType::Let:
  484. case TokenType::Const:
  485. return parse_variable_declaration();
  486. default:
  487. expected("declaration");
  488. consume();
  489. return create_ast_node<ErrorDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() });
  490. }
  491. }
  492. NonnullRefPtr<Statement> Parser::parse_statement(AllowLabelledFunction allow_labelled_function)
  493. {
  494. auto rule_start = push_start();
  495. auto type = m_state.current_token.type();
  496. switch (type) {
  497. case TokenType::CurlyOpen:
  498. return parse_block_statement();
  499. case TokenType::Return:
  500. return parse_return_statement();
  501. case TokenType::Var: {
  502. auto declaration = parse_variable_declaration();
  503. m_state.current_scope_pusher->add_declaration(declaration);
  504. return declaration;
  505. }
  506. case TokenType::For:
  507. return parse_for_statement();
  508. case TokenType::If:
  509. return parse_if_statement();
  510. case TokenType::Throw:
  511. return parse_throw_statement();
  512. case TokenType::Try:
  513. return parse_try_statement();
  514. case TokenType::Break:
  515. return parse_break_statement();
  516. case TokenType::Continue:
  517. return parse_continue_statement();
  518. case TokenType::Switch:
  519. return parse_switch_statement();
  520. case TokenType::Do:
  521. return parse_do_while_statement();
  522. case TokenType::While:
  523. return parse_while_statement();
  524. case TokenType::With:
  525. if (m_state.strict_mode)
  526. syntax_error("'with' statement not allowed in strict mode");
  527. return parse_with_statement();
  528. case TokenType::Debugger:
  529. return parse_debugger_statement();
  530. case TokenType::Semicolon:
  531. consume();
  532. return create_ast_node<EmptyStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  533. case TokenType::Slash:
  534. case TokenType::SlashEquals:
  535. m_state.current_token = m_state.lexer.force_slash_as_regex();
  536. [[fallthrough]];
  537. default:
  538. if (match_invalid_escaped_keyword())
  539. syntax_error("Keyword must not contain escaped characters");
  540. if (match_identifier_name()) {
  541. auto result = try_parse_labelled_statement(allow_labelled_function);
  542. if (!result.is_null())
  543. return result.release_nonnull();
  544. }
  545. if (match_expression()) {
  546. if (match(TokenType::Async)) {
  547. auto lookahead_token = next_token();
  548. if (lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator())
  549. syntax_error("Async function declaration not allowed in single-statement context");
  550. } else if (match(TokenType::Function) || match(TokenType::Class)) {
  551. syntax_error(String::formatted("{} declaration not allowed in single-statement context", m_state.current_token.name()));
  552. } else if (match(TokenType::Let) && next_token().type() == TokenType::BracketOpen) {
  553. syntax_error(String::formatted("let followed by [ is not allowed in single-statement context"));
  554. }
  555. auto expr = parse_expression(0);
  556. consume_or_insert_semicolon();
  557. return create_ast_node<ExpressionStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expr));
  558. }
  559. expected("statement");
  560. consume();
  561. return create_ast_node<ErrorStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  562. }
  563. }
  564. bool Parser::match_invalid_escaped_keyword() const
  565. {
  566. if (m_state.current_token.type() != TokenType::EscapedKeyword)
  567. return false;
  568. auto token_value = m_state.current_token.value();
  569. if (token_value == "await"sv)
  570. return m_program_type == Program::Type::Module || m_state.await_expression_is_valid;
  571. if (token_value == "async"sv)
  572. return false;
  573. if (token_value == "yield"sv)
  574. return m_state.in_generator_function_context;
  575. if (m_state.strict_mode)
  576. return true;
  577. return token_value != "let"sv;
  578. }
  579. static constexpr AK::Array<StringView, 9> strict_reserved_words = { "implements", "interface", "let", "package", "private", "protected", "public", "static", "yield" };
  580. static bool is_strict_reserved_word(StringView str)
  581. {
  582. return any_of(strict_reserved_words, [&str](StringView word) {
  583. return word == str;
  584. });
  585. }
  586. static bool is_simple_parameter_list(Vector<FunctionNode::Parameter> const& parameters)
  587. {
  588. return all_of(parameters, [](FunctionNode::Parameter const& parameter) {
  589. return !parameter.is_rest && parameter.default_value.is_null() && parameter.binding.has<FlyString>();
  590. });
  591. }
  592. RefPtr<FunctionExpression> Parser::try_parse_arrow_function_expression(bool expect_parens, bool is_async)
  593. {
  594. if (is_async)
  595. VERIFY(match(TokenType::Async));
  596. if (!expect_parens && !is_async) {
  597. // NOTE: This is a fast path where we try to fail early in case this can't possibly
  598. // be a match. The idea is to avoid the expensive parser state save/load mechanism.
  599. // The logic is duplicated below in the "real" !expect_parens branch.
  600. if (!match_identifier() && !match(TokenType::Yield) && !match(TokenType::Await))
  601. return nullptr;
  602. auto token = next_token();
  603. if (token.trivia_contains_line_terminator())
  604. return nullptr;
  605. if (token.type() != TokenType::Arrow)
  606. return nullptr;
  607. }
  608. save_state();
  609. auto rule_start = (expect_parens && !is_async)
  610. // Someone has consumed the opening parenthesis for us! Start there.
  611. ? RulePosition { *this, m_rule_starts.last() }
  612. // We've not encountered one yet, so the rule start is actually here.
  613. : push_start();
  614. ArmedScopeGuard state_rollback_guard = [&] {
  615. load_state();
  616. };
  617. auto function_kind = FunctionKind::Normal;
  618. if (is_async) {
  619. consume(TokenType::Async);
  620. function_kind = FunctionKind::Async;
  621. if (m_state.current_token.trivia_contains_line_terminator())
  622. return nullptr;
  623. // Since we have async it can be followed by paren open in the expect_parens case
  624. // so we also consume that token.
  625. if (expect_parens) {
  626. VERIFY(match(TokenType::ParenOpen));
  627. consume(TokenType::ParenOpen);
  628. }
  629. }
  630. Vector<FunctionNode::Parameter> parameters;
  631. i32 function_length = -1;
  632. if (expect_parens) {
  633. // We have parens around the function parameters and can re-use the same parsing
  634. // logic used for regular functions: multiple parameters, default values, rest
  635. // parameter, maybe a trailing comma. If we have a new syntax error afterwards we
  636. // check if it's about a wrong token (something like duplicate parameter name must
  637. // not abort), know parsing failed and rollback the parser state.
  638. auto previous_syntax_errors = m_state.errors.size();
  639. TemporaryChange in_async_context(m_state.await_expression_is_valid, is_async || m_state.await_expression_is_valid);
  640. parameters = parse_formal_parameters(function_length, FunctionNodeParseOptions::IsArrowFunction | (is_async ? FunctionNodeParseOptions::IsAsyncFunction : 0));
  641. if (m_state.errors.size() > previous_syntax_errors && m_state.errors[previous_syntax_errors].message.starts_with("Unexpected token"))
  642. return nullptr;
  643. if (!match(TokenType::ParenClose))
  644. return nullptr;
  645. consume();
  646. } else {
  647. // No parens - this must be an identifier followed by arrow. That's it.
  648. if (!match_identifier() && !match(TokenType::Yield) && !match(TokenType::Await))
  649. return nullptr;
  650. auto token = consume_identifier_reference();
  651. if (m_state.strict_mode && token.value().is_one_of("arguments"sv, "eval"sv))
  652. syntax_error("BindingIdentifier may not be 'arguments' or 'eval' in strict mode");
  653. if (is_async && token.value() == "await"sv)
  654. syntax_error("'await' is a reserved identifier in async functions");
  655. parameters.append({ FlyString { token.value() }, {} });
  656. }
  657. // If there's a newline between the closing paren and arrow it's not a valid arrow function,
  658. // ASI should kick in instead (it'll then fail with "Unexpected token Arrow")
  659. if (m_state.current_token.trivia_contains_line_terminator())
  660. return nullptr;
  661. if (!match(TokenType::Arrow))
  662. return nullptr;
  663. consume();
  664. if (function_length == -1)
  665. function_length = parameters.size();
  666. auto old_labels_in_scope = move(m_state.labels_in_scope);
  667. ScopeGuard guard([&]() {
  668. m_state.labels_in_scope = move(old_labels_in_scope);
  669. });
  670. bool contains_direct_call_to_eval = false;
  671. auto function_body_result = [&]() -> RefPtr<FunctionBody> {
  672. TemporaryChange change(m_state.in_arrow_function_context, true);
  673. TemporaryChange async_context_change(m_state.await_expression_is_valid, is_async);
  674. TemporaryChange in_class_static_init_block_change(m_state.in_class_static_init_block, false);
  675. if (match(TokenType::CurlyOpen)) {
  676. // Parse a function body with statements
  677. consume(TokenType::CurlyOpen);
  678. auto body = parse_function_body(parameters, function_kind, contains_direct_call_to_eval);
  679. consume(TokenType::CurlyClose);
  680. return body;
  681. }
  682. if (match_expression()) {
  683. // Parse a function body which returns a single expression
  684. // FIXME: We synthesize a block with a return statement
  685. // for arrow function bodies which are a single expression.
  686. // Esprima generates a single "ArrowFunctionExpression"
  687. // with a "body" property.
  688. auto return_block = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  689. ScopePusher function_scope = ScopePusher::function_scope(*this, return_block, parameters);
  690. auto return_expression = parse_expression(2);
  691. return_block->append<ReturnStatement>({ m_filename, rule_start.position(), position() }, move(return_expression));
  692. if (m_state.strict_mode)
  693. return_block->set_strict_mode();
  694. contains_direct_call_to_eval = function_scope.contains_direct_call_to_eval();
  695. return return_block;
  696. }
  697. // Invalid arrow function body
  698. return nullptr;
  699. }();
  700. if (function_body_result.is_null())
  701. return nullptr;
  702. state_rollback_guard.disarm();
  703. discard_saved_state();
  704. auto body = function_body_result.release_nonnull();
  705. if (body->in_strict_mode()) {
  706. for (auto& parameter : parameters) {
  707. parameter.binding.visit(
  708. [&](FlyString const& name) {
  709. check_identifier_name_for_assignment_validity(name, true);
  710. },
  711. [&](auto const&) {});
  712. }
  713. }
  714. auto function_start_offset = rule_start.position().offset;
  715. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  716. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  717. return create_ast_node<FunctionExpression>(
  718. { m_state.current_token.filename(), rule_start.position(), position() }, "", move(source_text),
  719. move(body), move(parameters), function_length, function_kind, body->in_strict_mode(),
  720. /* might_need_arguments_object */ false, contains_direct_call_to_eval, /* is_arrow_function */ true);
  721. }
  722. RefPtr<LabelledStatement> Parser::try_parse_labelled_statement(AllowLabelledFunction allow_function)
  723. {
  724. {
  725. // NOTE: This is a fast path where we try to fail early to avoid the expensive save_state+load_state.
  726. if (next_token().type() != TokenType::Colon)
  727. return {};
  728. }
  729. save_state();
  730. auto rule_start = push_start();
  731. ArmedScopeGuard state_rollback_guard = [&] {
  732. load_state();
  733. };
  734. if (m_state.current_token.value() == "yield"sv && (m_state.strict_mode || m_state.in_generator_function_context)) {
  735. return {};
  736. }
  737. if (m_state.current_token.value() == "await"sv && (m_program_type == Program::Type::Module || m_state.await_expression_is_valid || m_state.in_class_static_init_block)) {
  738. return {};
  739. }
  740. auto identifier = [&] {
  741. if (m_state.current_token.value() == "await"sv) {
  742. return consume().value();
  743. }
  744. return consume_identifier_reference().value();
  745. }();
  746. if (!match(TokenType::Colon))
  747. return {};
  748. consume(TokenType::Colon);
  749. if (!match_statement())
  750. return {};
  751. state_rollback_guard.disarm();
  752. discard_saved_state();
  753. if (m_state.strict_mode && identifier == "let"sv) {
  754. syntax_error("Strict mode reserved word 'let' is not allowed in label", rule_start.position());
  755. return {};
  756. }
  757. if (match(TokenType::Function) && (allow_function == AllowLabelledFunction::No || m_state.strict_mode)) {
  758. syntax_error("Not allowed to declare a function here");
  759. return {};
  760. }
  761. if (m_state.labels_in_scope.contains(identifier))
  762. syntax_error(String::formatted("Label '{}' has already been declared", identifier));
  763. RefPtr<Statement> labelled_item;
  764. auto is_iteration_statement = false;
  765. if (match(TokenType::Function)) {
  766. m_state.labels_in_scope.set(identifier, {});
  767. auto function_declaration = parse_function_node<FunctionDeclaration>();
  768. VERIFY(m_state.current_scope_pusher);
  769. m_state.current_scope_pusher->add_declaration(function_declaration);
  770. if (function_declaration->kind() == FunctionKind::Generator)
  771. syntax_error("Generator functions cannot be defined in labelled statements");
  772. if (function_declaration->kind() == FunctionKind::Async)
  773. syntax_error("Async functions cannot be defined in labelled statements");
  774. labelled_item = move(function_declaration);
  775. } else {
  776. m_state.labels_in_scope.set(identifier, {});
  777. labelled_item = parse_statement(allow_function);
  778. // Extract the innermost statement from a potentially nested chain of LabelledStatements.
  779. auto statement = labelled_item;
  780. while (is<LabelledStatement>(*statement))
  781. statement = static_cast<LabelledStatement&>(*statement).labelled_item();
  782. if (is<IterationStatement>(*statement))
  783. is_iteration_statement = true;
  784. }
  785. if (!is_iteration_statement) {
  786. if (auto entry = m_state.labels_in_scope.find(identifier); entry != m_state.labels_in_scope.end() && entry->value.has_value())
  787. syntax_error("labelled continue statement cannot use non iterating statement", m_state.labels_in_scope.get(identifier).value());
  788. }
  789. m_state.labels_in_scope.remove(identifier);
  790. return create_ast_node<LabelledStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier, labelled_item.release_nonnull());
  791. }
  792. RefPtr<MetaProperty> Parser::try_parse_new_target_expression()
  793. {
  794. // Optimization which skips the save/load state.
  795. if (next_token().type() != TokenType::Period)
  796. return {};
  797. save_state();
  798. auto rule_start = push_start();
  799. ArmedScopeGuard state_rollback_guard = [&] {
  800. load_state();
  801. };
  802. consume(TokenType::New);
  803. consume(TokenType::Period);
  804. if (!match(TokenType::Identifier))
  805. return {};
  806. // The string 'target' cannot have escapes so we check original value.
  807. if (consume().original_value() != "target"sv)
  808. return {};
  809. state_rollback_guard.disarm();
  810. discard_saved_state();
  811. return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::NewTarget);
  812. }
  813. RefPtr<MetaProperty> Parser::try_parse_import_meta_expression()
  814. {
  815. // Optimization which skips the save/load state.
  816. if (next_token().type() != TokenType::Period)
  817. return {};
  818. save_state();
  819. auto rule_start = push_start();
  820. ArmedScopeGuard state_rollback_guard = [&] {
  821. load_state();
  822. };
  823. consume(TokenType::Import);
  824. consume(TokenType::Period);
  825. if (!match(TokenType::Identifier))
  826. return {};
  827. // The string 'meta' cannot have escapes so we check original value.
  828. if (consume().original_value() != "meta"sv)
  829. return {};
  830. state_rollback_guard.disarm();
  831. discard_saved_state();
  832. return create_ast_node<MetaProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, MetaProperty::Type::ImportMeta);
  833. }
  834. NonnullRefPtr<ImportCall> Parser::parse_import_call()
  835. {
  836. auto rule_start = push_start();
  837. // We use the extended definition:
  838. // ImportCall[Yield, Await]:
  839. // import(AssignmentExpression[+In, ?Yield, ?Await] ,opt)
  840. // import(AssignmentExpression[+In, ?Yield, ?Await] ,AssignmentExpression[+In, ?Yield, ?Await] ,opt)
  841. // From https://tc39.es/proposal-import-assertions/#sec-evaluate-import-call
  842. consume(TokenType::Import);
  843. consume(TokenType::ParenOpen);
  844. auto argument = parse_expression(2);
  845. RefPtr<Expression> options;
  846. if (match(TokenType::Comma)) {
  847. consume(TokenType::Comma);
  848. if (!match(TokenType::ParenClose)) {
  849. options = parse_expression(2);
  850. // Second optional comma
  851. if (match(TokenType::Comma))
  852. consume(TokenType::Comma);
  853. }
  854. }
  855. consume(TokenType::ParenClose);
  856. return create_ast_node<ImportCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), move(options));
  857. }
  858. NonnullRefPtr<ClassDeclaration> Parser::parse_class_declaration()
  859. {
  860. auto rule_start = push_start();
  861. return create_ast_node<ClassDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_class_expression(true));
  862. }
  863. NonnullRefPtr<ClassExpression> Parser::parse_class_expression(bool expect_class_name)
  864. {
  865. auto rule_start = push_start();
  866. // Classes are always in strict mode.
  867. TemporaryChange strict_mode_rollback(m_state.strict_mode, true);
  868. consume(TokenType::Class);
  869. NonnullRefPtrVector<ClassElement> elements;
  870. RefPtr<Expression> super_class;
  871. RefPtr<FunctionExpression> constructor;
  872. HashTable<FlyString> found_private_names;
  873. FlyString class_name = expect_class_name || match_identifier() || match(TokenType::Yield) || match(TokenType::Await)
  874. ? consume_identifier_reference().flystring_value()
  875. : "";
  876. check_identifier_name_for_assignment_validity(class_name, true);
  877. if (m_state.in_class_static_init_block && class_name == "await"sv)
  878. syntax_error("Identifier must not be a reserved word in modules ('await')");
  879. if (match(TokenType::Extends)) {
  880. consume();
  881. auto [expression, should_continue_parsing] = parse_primary_expression();
  882. // Basically a (much) simplified parse_secondary_expression().
  883. for (;;) {
  884. if (match(TokenType::TemplateLiteralStart)) {
  885. auto template_literal = parse_template_literal(true);
  886. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  887. continue;
  888. }
  889. if (match(TokenType::BracketOpen) || match(TokenType::Period) || match(TokenType::ParenOpen)) {
  890. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  891. expression = parse_secondary_expression(move(expression), precedence).expression;
  892. continue;
  893. }
  894. break;
  895. }
  896. super_class = move(expression);
  897. (void)should_continue_parsing;
  898. }
  899. consume(TokenType::CurlyOpen);
  900. HashTable<StringView> referenced_private_names;
  901. HashTable<StringView>* outer_referenced_private_names = m_state.referenced_private_names;
  902. m_state.referenced_private_names = &referenced_private_names;
  903. ScopeGuard restore_private_name_table = [&] {
  904. m_state.referenced_private_names = outer_referenced_private_names;
  905. };
  906. while (!done() && !match(TokenType::CurlyClose)) {
  907. RefPtr<Expression> property_key;
  908. bool is_static = false;
  909. bool is_constructor = false;
  910. bool is_generator = false;
  911. bool is_async = false;
  912. auto method_kind = ClassMethod::Kind::Method;
  913. if (match(TokenType::Semicolon)) {
  914. consume();
  915. continue;
  916. }
  917. auto function_start = position();
  918. if (match(TokenType::Async)) {
  919. auto lookahead_token = next_token();
  920. // If async is followed by a Semicolon or CurlyClose it is a field (CurlyClose indicates end of class)
  921. // Otherwise if it is followed by a ParenOpen it is a function named async
  922. if (lookahead_token.type() != TokenType::Semicolon && lookahead_token.type() != TokenType::CurlyClose && lookahead_token.type() != TokenType::ParenOpen
  923. && !lookahead_token.trivia_contains_line_terminator()) {
  924. consume();
  925. is_async = true;
  926. }
  927. }
  928. if (match(TokenType::Asterisk)) {
  929. consume();
  930. is_generator = true;
  931. }
  932. StringView name;
  933. if (match_property_key() || match(TokenType::PrivateIdentifier)) {
  934. if (!is_generator && !is_async && m_state.current_token.original_value() == "static"sv) {
  935. if (match(TokenType::Identifier)) {
  936. consume();
  937. is_static = true;
  938. function_start = position();
  939. if (match(TokenType::Async)) {
  940. consume();
  941. is_async = true;
  942. }
  943. if (match(TokenType::Asterisk)) {
  944. consume();
  945. is_generator = true;
  946. }
  947. }
  948. }
  949. if (match(TokenType::Identifier)) {
  950. auto identifier_name = m_state.current_token.original_value();
  951. if (identifier_name == "get"sv) {
  952. method_kind = ClassMethod::Kind::Getter;
  953. consume();
  954. } else if (identifier_name == "set"sv) {
  955. method_kind = ClassMethod::Kind::Setter;
  956. consume();
  957. }
  958. }
  959. if (match_property_key() || match(TokenType::PrivateIdentifier)) {
  960. switch (m_state.current_token.type()) {
  961. case TokenType::Identifier:
  962. name = consume().value();
  963. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  964. break;
  965. case TokenType::PrivateIdentifier:
  966. name = consume().value();
  967. if (name == "#constructor")
  968. syntax_error("Private property with name '#constructor' is not allowed");
  969. if (method_kind != ClassMethod::Kind::Method) {
  970. // It is a Syntax Error if PrivateBoundIdentifiers of ClassElementList contains any duplicate entries,
  971. // unless the name is used once for a getter and once for a setter and in no other entries,
  972. // and the getter and setter are either both static or both non-static.
  973. for (auto& element : elements) {
  974. auto private_name = element.private_bound_identifier();
  975. if (!private_name.has_value() || private_name.value() != name)
  976. continue;
  977. if (element.class_element_kind() != ClassElement::ElementKind::Method
  978. || element.is_static() != is_static) {
  979. syntax_error(String::formatted("Duplicate private field or method named '{}'", name));
  980. break;
  981. }
  982. VERIFY(is<ClassMethod>(element));
  983. auto& class_method_element = static_cast<ClassMethod const&>(element);
  984. if (class_method_element.kind() == ClassMethod::Kind::Method || class_method_element.kind() == method_kind) {
  985. syntax_error(String::formatted("Duplicate private field or method named '{}'", name));
  986. break;
  987. }
  988. }
  989. found_private_names.set(name);
  990. } else if (found_private_names.set(name) != AK::HashSetResult::InsertedNewEntry) {
  991. syntax_error(String::formatted("Duplicate private field or method named '{}'", name));
  992. }
  993. property_key = create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  994. break;
  995. case TokenType::StringLiteral: {
  996. auto string_literal = parse_string_literal(consume());
  997. name = string_literal->value();
  998. property_key = move(string_literal);
  999. break;
  1000. }
  1001. default:
  1002. property_key = parse_property_key();
  1003. break;
  1004. }
  1005. // https://tc39.es/ecma262/#sec-class-definitions-static-semantics-early-errors
  1006. // ClassElement : static MethodDefinition
  1007. // It is a Syntax Error if PropName of MethodDefinition is "prototype".
  1008. if (is_static && name == "prototype"sv)
  1009. syntax_error("Classes may not have a static property named 'prototype'");
  1010. } else if ((match(TokenType::ParenOpen) || match(TokenType::Equals) || match(TokenType::Semicolon) || match(TokenType::CurlyClose)) && (is_static || is_async || method_kind != ClassMethod::Kind::Method)) {
  1011. switch (method_kind) {
  1012. case ClassMethod::Kind::Method:
  1013. if (is_async) {
  1014. name = "async";
  1015. is_async = false;
  1016. } else {
  1017. VERIFY(is_static);
  1018. name = "static";
  1019. is_static = false;
  1020. }
  1021. break;
  1022. case ClassMethod::Kind::Getter:
  1023. name = "get";
  1024. method_kind = ClassMethod::Kind::Method;
  1025. break;
  1026. case ClassMethod::Kind::Setter:
  1027. name = "set";
  1028. method_kind = ClassMethod::Kind::Method;
  1029. break;
  1030. }
  1031. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, name);
  1032. } else if (match(TokenType::CurlyOpen) && is_static) {
  1033. auto static_start = push_start();
  1034. consume(TokenType::CurlyOpen);
  1035. auto static_init_block = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  1036. TemporaryChange break_context_rollback(m_state.in_break_context, false);
  1037. TemporaryChange continue_context_rollback(m_state.in_continue_context, false);
  1038. TemporaryChange function_context_rollback(m_state.in_function_context, false);
  1039. TemporaryChange generator_function_context_rollback(m_state.in_generator_function_context, false);
  1040. TemporaryChange async_function_context_rollback(m_state.await_expression_is_valid, false);
  1041. TemporaryChange class_field_initializer_rollback(m_state.in_class_field_initializer, true);
  1042. TemporaryChange class_static_init_block_rollback(m_state.in_class_static_init_block, true);
  1043. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, true);
  1044. ScopePusher static_init_scope = ScopePusher::static_init_block_scope(*this, *static_init_block);
  1045. parse_statement_list(static_init_block);
  1046. consume(TokenType::CurlyClose);
  1047. elements.append(create_ast_node<StaticInitializer>({ m_state.current_token.filename(), static_start.position(), position() }, move(static_init_block), static_init_scope.contains_direct_call_to_eval()));
  1048. continue;
  1049. } else {
  1050. expected("property key");
  1051. }
  1052. // Constructor may be a StringLiteral or an Identifier.
  1053. if (!is_static && name == "constructor"sv) {
  1054. if (method_kind != ClassMethod::Kind::Method)
  1055. syntax_error("Class constructor may not be an accessor");
  1056. if (!constructor.is_null())
  1057. syntax_error("Classes may not have more than one constructor");
  1058. if (is_generator)
  1059. syntax_error("Class constructor may not be a generator");
  1060. if (is_async)
  1061. syntax_error("Class constructor may not be async");
  1062. is_constructor = true;
  1063. }
  1064. }
  1065. if (match(TokenType::ParenOpen)) {
  1066. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  1067. if (!super_class.is_null() && !is_static && is_constructor)
  1068. parse_options |= FunctionNodeParseOptions::AllowSuperConstructorCall;
  1069. if (method_kind == ClassMethod::Kind::Getter)
  1070. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  1071. if (method_kind == ClassMethod::Kind::Setter)
  1072. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  1073. if (is_generator)
  1074. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  1075. if (is_async)
  1076. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  1077. auto function = parse_function_node<FunctionExpression>(parse_options, function_start);
  1078. if (is_constructor) {
  1079. constructor = move(function);
  1080. } else if (!property_key.is_null()) {
  1081. elements.append(create_ast_node<ClassMethod>({ m_state.current_token.filename(), rule_start.position(), position() }, property_key.release_nonnull(), move(function), method_kind, is_static));
  1082. } else {
  1083. syntax_error("No key for class method");
  1084. }
  1085. } else if (is_generator || is_async) {
  1086. expected("ParenOpen");
  1087. consume();
  1088. } else if (property_key.is_null()) {
  1089. expected("property key");
  1090. consume();
  1091. } else {
  1092. if (name == "constructor"sv)
  1093. syntax_error("Class cannot have field named 'constructor'");
  1094. RefPtr<Expression> initializer;
  1095. bool contains_direct_call_to_eval = false;
  1096. if (match(TokenType::Equals)) {
  1097. consume();
  1098. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, true);
  1099. TemporaryChange field_initializer_rollback(m_state.in_class_field_initializer, true);
  1100. auto class_field_scope = ScopePusher::class_field_scope(*this);
  1101. initializer = parse_expression(2);
  1102. contains_direct_call_to_eval = class_field_scope.contains_direct_call_to_eval();
  1103. }
  1104. elements.append(create_ast_node<ClassField>({ m_state.current_token.filename(), rule_start.position(), position() }, property_key.release_nonnull(), move(initializer), contains_direct_call_to_eval, is_static));
  1105. consume_or_insert_semicolon();
  1106. }
  1107. }
  1108. consume(TokenType::CurlyClose);
  1109. if (constructor.is_null()) {
  1110. auto constructor_body = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  1111. if (!super_class.is_null()) {
  1112. // Set constructor to the result of parsing the source text
  1113. // constructor(... args){ super (...args);}
  1114. auto super_call = create_ast_node<SuperCall>(
  1115. { m_state.current_token.filename(), rule_start.position(), position() },
  1116. Vector { CallExpression::Argument { create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, "args"), true } });
  1117. // NOTE: While the JS approximation above doesn't do `return super(...args)`, the
  1118. // abstract closure is expected to capture and return the result, so we do need a
  1119. // return statement here to create the correct completion.
  1120. constructor_body->append(create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(super_call)));
  1121. constructor = create_ast_node<FunctionExpression>(
  1122. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, "",
  1123. move(constructor_body), Vector { FunctionNode::Parameter { FlyString { "args" }, nullptr, true } }, 0, FunctionKind::Normal,
  1124. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1125. } else {
  1126. constructor = create_ast_node<FunctionExpression>(
  1127. { m_state.current_token.filename(), rule_start.position(), position() }, class_name, "",
  1128. move(constructor_body), Vector<FunctionNode::Parameter> {}, 0, FunctionKind::Normal,
  1129. /* is_strict_mode */ true, /* might_need_arguments_object */ false, /* contains_direct_call_to_eval */ false);
  1130. }
  1131. }
  1132. // We could be in a subclass defined within the main class so must move all non declared private names to outer.
  1133. for (auto& private_name : referenced_private_names) {
  1134. if (found_private_names.contains(private_name))
  1135. continue;
  1136. if (outer_referenced_private_names)
  1137. outer_referenced_private_names->set(private_name);
  1138. else // FIXME: Make these error appear in the appropriate places.
  1139. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", private_name));
  1140. }
  1141. auto function_start_offset = rule_start.position().offset;
  1142. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  1143. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  1144. return create_ast_node<ClassExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(class_name), move(source_text), move(constructor), move(super_class), move(elements));
  1145. }
  1146. Parser::PrimaryExpressionParseResult Parser::parse_primary_expression()
  1147. {
  1148. auto rule_start = push_start();
  1149. if (match_unary_prefixed_expression())
  1150. return { parse_unary_prefixed_expression() };
  1151. auto try_arrow_function_parse_or_fail = [this](Position const& position, bool expect_paren, bool is_async = false) -> RefPtr<FunctionExpression> {
  1152. if (try_parse_arrow_function_expression_failed_at_position(position))
  1153. return nullptr;
  1154. auto arrow_function = try_parse_arrow_function_expression(expect_paren, is_async);
  1155. if (arrow_function)
  1156. return arrow_function;
  1157. set_try_parse_arrow_function_expression_failed_at_position(position, true);
  1158. return nullptr;
  1159. };
  1160. switch (m_state.current_token.type()) {
  1161. case TokenType::ParenOpen: {
  1162. auto paren_position = position();
  1163. consume(TokenType::ParenOpen);
  1164. if ((match(TokenType::ParenClose) || match_identifier() || match(TokenType::TripleDot) || match(TokenType::CurlyOpen) || match(TokenType::BracketOpen))) {
  1165. if (auto arrow_function_result = try_arrow_function_parse_or_fail(paren_position, true))
  1166. return { arrow_function_result.release_nonnull(), false };
  1167. }
  1168. auto expression = parse_expression(0);
  1169. consume(TokenType::ParenClose);
  1170. if (is<FunctionExpression>(*expression)) {
  1171. auto& function = static_cast<FunctionExpression&>(*expression);
  1172. if (function.kind() == FunctionKind::Generator && function.name() == "yield"sv)
  1173. syntax_error("function is not allowed to be called 'yield' in this context", function.source_range().start);
  1174. if (function.kind() == FunctionKind::Async && function.name() == "await"sv)
  1175. syntax_error("function is not allowed to be called 'await' in this context", function.source_range().start);
  1176. }
  1177. return { move(expression) };
  1178. }
  1179. case TokenType::This:
  1180. consume();
  1181. return { create_ast_node<ThisExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1182. case TokenType::Class:
  1183. return { parse_class_expression(false) };
  1184. case TokenType::Super:
  1185. consume();
  1186. if (!m_state.allow_super_property_lookup)
  1187. syntax_error("'super' keyword unexpected here");
  1188. return { create_ast_node<SuperExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1189. case TokenType::EscapedKeyword:
  1190. if (match_invalid_escaped_keyword())
  1191. syntax_error("Keyword must not contain escaped characters");
  1192. [[fallthrough]];
  1193. case TokenType::Identifier: {
  1194. read_as_identifier:;
  1195. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false))
  1196. return { arrow_function_result.release_nonnull(), false };
  1197. auto string = m_state.current_token.value();
  1198. // This could be 'eval' or 'arguments' and thus needs a custom check (`eval[1] = true`)
  1199. if (m_state.strict_mode && (string == "let" || is_strict_reserved_word(string)))
  1200. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", string));
  1201. return { parse_identifier() };
  1202. }
  1203. case TokenType::NumericLiteral:
  1204. return { create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume_and_validate_numeric_literal().double_value()) };
  1205. case TokenType::BigIntLiteral:
  1206. return { create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1207. case TokenType::BoolLiteral:
  1208. return { create_ast_node<BooleanLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().bool_value()) };
  1209. case TokenType::StringLiteral:
  1210. return { parse_string_literal(consume()) };
  1211. case TokenType::NullLiteral:
  1212. consume();
  1213. return { create_ast_node<NullLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1214. case TokenType::CurlyOpen:
  1215. return { parse_object_expression() };
  1216. case TokenType::Async: {
  1217. auto lookahead_token = next_token();
  1218. // No valid async function (arrow or not) can have a line terminator after the async since asi would kick in.
  1219. if (lookahead_token.trivia_contains_line_terminator())
  1220. goto read_as_identifier;
  1221. if (lookahead_token.type() == TokenType::Function)
  1222. return { parse_function_node<FunctionExpression>() };
  1223. if (lookahead_token.type() == TokenType::ParenOpen) {
  1224. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), true, true))
  1225. return { arrow_function_result.release_nonnull(), false };
  1226. } else if (lookahead_token.is_identifier_name()) {
  1227. if (auto arrow_function_result = try_arrow_function_parse_or_fail(position(), false, true))
  1228. return { arrow_function_result.release_nonnull(), false };
  1229. }
  1230. goto read_as_identifier;
  1231. }
  1232. case TokenType::Function:
  1233. return { parse_function_node<FunctionExpression>() };
  1234. case TokenType::BracketOpen:
  1235. return { parse_array_expression() };
  1236. case TokenType::RegexLiteral:
  1237. return { parse_regexp_literal() };
  1238. case TokenType::TemplateLiteralStart:
  1239. return { parse_template_literal(false) };
  1240. case TokenType::New: {
  1241. auto new_start = position();
  1242. auto new_target_result = try_parse_new_target_expression();
  1243. if (!new_target_result.is_null()) {
  1244. if (!m_state.in_function_context && !m_state.in_class_static_init_block)
  1245. syntax_error("'new.target' not allowed outside of a function", new_start);
  1246. return { new_target_result.release_nonnull() };
  1247. }
  1248. return { parse_new_expression() };
  1249. }
  1250. case TokenType::Import: {
  1251. auto lookahead_token = next_token();
  1252. if (lookahead_token.type() == TokenType::ParenOpen)
  1253. return { parse_import_call() };
  1254. if (lookahead_token.type() == TokenType::Period) {
  1255. if (auto import_meta = try_parse_import_meta_expression()) {
  1256. if (m_program_type != Program::Type::Module)
  1257. syntax_error("import.meta is only allowed in modules");
  1258. return { import_meta.release_nonnull() };
  1259. }
  1260. } else {
  1261. consume();
  1262. expected("import.meta or import call");
  1263. }
  1264. break;
  1265. }
  1266. case TokenType::Yield:
  1267. if (!m_state.in_generator_function_context)
  1268. goto read_as_identifier;
  1269. return { parse_yield_expression(), false };
  1270. case TokenType::Await:
  1271. if (!m_state.await_expression_is_valid)
  1272. goto read_as_identifier;
  1273. return { parse_await_expression() };
  1274. case TokenType::PrivateIdentifier:
  1275. if (next_token().type() != TokenType::In)
  1276. syntax_error("Cannot have a private identifier in expression if not followed by 'in'");
  1277. if (!is_private_identifier_valid())
  1278. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1279. return { create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()) };
  1280. default:
  1281. if (match_identifier_name())
  1282. goto read_as_identifier;
  1283. break;
  1284. }
  1285. expected("primary expression");
  1286. consume();
  1287. return { create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }) };
  1288. }
  1289. NonnullRefPtr<RegExpLiteral> Parser::parse_regexp_literal()
  1290. {
  1291. auto rule_start = push_start();
  1292. auto pattern = consume().value();
  1293. // Remove leading and trailing slash.
  1294. pattern = pattern.substring_view(1, pattern.length() - 2);
  1295. auto flags = String::empty();
  1296. auto parsed_flags = RegExpObject::default_flags;
  1297. if (match(TokenType::RegexFlags)) {
  1298. auto flags_start = position();
  1299. flags = consume().value();
  1300. auto parsed_flags_or_error = regex_flags_from_string(flags);
  1301. if (parsed_flags_or_error.is_error())
  1302. syntax_error(parsed_flags_or_error.release_error(), flags_start);
  1303. else
  1304. parsed_flags = parsed_flags_or_error.release_value();
  1305. }
  1306. auto parsed_pattern = parse_regex_pattern(pattern, parsed_flags.has_flag_set(ECMAScriptFlags::Unicode));
  1307. auto parsed_regex = Regex<ECMA262>::parse_pattern(parsed_pattern, parsed_flags);
  1308. if (parsed_regex.error != regex::Error::NoError)
  1309. syntax_error(String::formatted("RegExp compile error: {}", Regex<ECMA262>(parsed_regex, parsed_pattern, parsed_flags).error_string()), rule_start.position());
  1310. SourceRange range { m_state.current_token.filename(), rule_start.position(), position() };
  1311. return create_ast_node<RegExpLiteral>(move(range), move(parsed_regex), move(parsed_pattern), move(parsed_flags), pattern.to_string(), move(flags));
  1312. }
  1313. NonnullRefPtr<Expression> Parser::parse_unary_prefixed_expression()
  1314. {
  1315. auto rule_start = push_start();
  1316. auto precedence = g_operator_precedence.get(m_state.current_token.type());
  1317. auto associativity = operator_associativity(m_state.current_token.type());
  1318. switch (m_state.current_token.type()) {
  1319. case TokenType::PlusPlus: {
  1320. consume();
  1321. auto rhs_start = position();
  1322. auto rhs = parse_expression(precedence, associativity);
  1323. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1324. // other engines throw ReferenceError for ++foo()
  1325. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1326. syntax_error(String::formatted("Right-hand side of prefix increment operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1327. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1328. auto& identifier = static_cast<Identifier&>(*rhs);
  1329. auto& name = identifier.string();
  1330. check_identifier_name_for_assignment_validity(name);
  1331. }
  1332. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(rhs), true);
  1333. }
  1334. case TokenType::MinusMinus: {
  1335. consume();
  1336. auto rhs_start = position();
  1337. auto rhs = parse_expression(precedence, associativity);
  1338. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1339. // other engines throw ReferenceError for --foo()
  1340. if (!is<Identifier>(*rhs) && !is<MemberExpression>(*rhs))
  1341. syntax_error(String::formatted("Right-hand side of prefix decrement operator must be identifier or member expression, got {}", rhs->class_name()), rhs_start);
  1342. if (m_state.strict_mode && is<Identifier>(*rhs)) {
  1343. auto& identifier = static_cast<Identifier&>(*rhs);
  1344. auto& name = identifier.string();
  1345. check_identifier_name_for_assignment_validity(name);
  1346. }
  1347. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(rhs), true);
  1348. }
  1349. case TokenType::ExclamationMark:
  1350. consume();
  1351. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Not, parse_expression(precedence, associativity));
  1352. case TokenType::Tilde:
  1353. consume();
  1354. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::BitwiseNot, parse_expression(precedence, associativity));
  1355. case TokenType::Plus:
  1356. consume();
  1357. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Plus, parse_expression(precedence, associativity));
  1358. case TokenType::Minus:
  1359. consume();
  1360. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Minus, parse_expression(precedence, associativity));
  1361. case TokenType::Typeof:
  1362. consume();
  1363. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Typeof, parse_expression(precedence, associativity));
  1364. case TokenType::Void:
  1365. consume();
  1366. // FIXME: This check is really hiding the fact that we don't deal with different expressions correctly.
  1367. if (match(TokenType::Yield) && m_state.in_generator_function_context)
  1368. syntax_error("'yield' is not an identifier in generator function context");
  1369. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Void, parse_expression(precedence, associativity));
  1370. case TokenType::Delete: {
  1371. consume();
  1372. auto rhs_start = position();
  1373. auto rhs = parse_expression(precedence, associativity);
  1374. if (is<Identifier>(*rhs) && m_state.strict_mode) {
  1375. syntax_error("Delete of an unqualified identifier in strict mode.", rhs_start);
  1376. }
  1377. if (is<MemberExpression>(*rhs)) {
  1378. auto& member_expression = static_cast<MemberExpression const&>(*rhs);
  1379. if (member_expression.ends_in_private_name())
  1380. syntax_error("Private fields cannot be deleted");
  1381. }
  1382. return create_ast_node<UnaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UnaryOp::Delete, move(rhs));
  1383. }
  1384. default:
  1385. expected("primary expression");
  1386. consume();
  1387. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1388. }
  1389. }
  1390. NonnullRefPtr<Expression> Parser::parse_property_key()
  1391. {
  1392. auto rule_start = push_start();
  1393. if (match(TokenType::StringLiteral)) {
  1394. return parse_string_literal(consume());
  1395. } else if (match(TokenType::NumericLiteral)) {
  1396. return create_ast_node<NumericLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().double_value());
  1397. } else if (match(TokenType::BigIntLiteral)) {
  1398. return create_ast_node<BigIntLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1399. } else if (match(TokenType::BracketOpen)) {
  1400. consume(TokenType::BracketOpen);
  1401. auto result = parse_expression(2);
  1402. consume(TokenType::BracketClose);
  1403. return result;
  1404. } else {
  1405. if (!match_identifier_name())
  1406. expected("IdentifierName");
  1407. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value());
  1408. }
  1409. }
  1410. NonnullRefPtr<ObjectExpression> Parser::parse_object_expression()
  1411. {
  1412. auto rule_start = push_start();
  1413. consume(TokenType::CurlyOpen);
  1414. NonnullRefPtrVector<ObjectProperty> properties;
  1415. ObjectProperty::Type property_type;
  1416. Optional<SourceRange> invalid_object_literal_property_range;
  1417. auto skip_to_next_property = [&] {
  1418. while (!done() && !match(TokenType::Comma) && !match(TokenType::CurlyOpen))
  1419. consume();
  1420. };
  1421. // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any duplicate
  1422. // entries for "__proto__" and at least two of those entries were obtained from productions of
  1423. // the form PropertyDefinition : PropertyKey : AssignmentExpression .
  1424. bool has_direct_proto_property = false;
  1425. while (!done() && !match(TokenType::CurlyClose)) {
  1426. property_type = ObjectProperty::Type::KeyValue;
  1427. RefPtr<Expression> property_key;
  1428. RefPtr<Expression> property_value;
  1429. FunctionKind function_kind { FunctionKind::Normal };
  1430. if (match(TokenType::TripleDot)) {
  1431. consume();
  1432. property_key = parse_expression(4);
  1433. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, nullptr, ObjectProperty::Type::Spread, false));
  1434. if (!match(TokenType::Comma))
  1435. break;
  1436. consume(TokenType::Comma);
  1437. continue;
  1438. }
  1439. auto type = m_state.current_token.type();
  1440. auto function_start = position();
  1441. if (match(TokenType::Async)) {
  1442. auto lookahead_token = next_token();
  1443. if (lookahead_token.type() != TokenType::ParenOpen && lookahead_token.type() != TokenType::Colon
  1444. && lookahead_token.type() != TokenType::Comma && lookahead_token.type() != TokenType::CurlyClose
  1445. && lookahead_token.type() != TokenType::Async
  1446. && !lookahead_token.trivia_contains_line_terminator()) {
  1447. consume(TokenType::Async);
  1448. function_kind = FunctionKind::Async;
  1449. }
  1450. }
  1451. if (match(TokenType::Asterisk)) {
  1452. consume();
  1453. property_type = ObjectProperty::Type::KeyValue;
  1454. property_key = parse_property_key();
  1455. VERIFY(function_kind == FunctionKind::Normal || function_kind == FunctionKind::Async);
  1456. function_kind = function_kind == FunctionKind::Normal ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  1457. } else if (match_identifier()) {
  1458. auto identifier = consume();
  1459. if (identifier.original_value() == "get"sv && match_property_key()) {
  1460. property_type = ObjectProperty::Type::Getter;
  1461. property_key = parse_property_key();
  1462. } else if (identifier.original_value() == "set"sv && match_property_key()) {
  1463. property_type = ObjectProperty::Type::Setter;
  1464. property_key = parse_property_key();
  1465. } else {
  1466. property_key = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.value());
  1467. property_value = create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, identifier.flystring_value());
  1468. }
  1469. } else {
  1470. property_key = parse_property_key();
  1471. }
  1472. bool is_proto = (type == TokenType::StringLiteral || type == TokenType::Identifier) && is<StringLiteral>(*property_key) && static_cast<StringLiteral const&>(*property_key).value() == "__proto__";
  1473. if (property_type == ObjectProperty::Type::Getter || property_type == ObjectProperty::Type::Setter) {
  1474. if (!match(TokenType::ParenOpen)) {
  1475. expected("'(' for object getter or setter property");
  1476. skip_to_next_property();
  1477. continue;
  1478. }
  1479. }
  1480. if (match(TokenType::Equals)) {
  1481. // Not a valid object literal, but a valid assignment target
  1482. consume();
  1483. // Parse the expression and throw it away
  1484. auto expression = parse_expression(2);
  1485. if (!invalid_object_literal_property_range.has_value())
  1486. invalid_object_literal_property_range = expression->source_range();
  1487. } else if (match(TokenType::ParenOpen)) {
  1488. VERIFY(property_key);
  1489. u8 parse_options = FunctionNodeParseOptions::AllowSuperPropertyLookup;
  1490. if (property_type == ObjectProperty::Type::Getter)
  1491. parse_options |= FunctionNodeParseOptions::IsGetterFunction;
  1492. if (property_type == ObjectProperty::Type::Setter)
  1493. parse_options |= FunctionNodeParseOptions::IsSetterFunction;
  1494. if (function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator)
  1495. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  1496. if (function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator)
  1497. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  1498. auto function = parse_function_node<FunctionExpression>(parse_options, function_start);
  1499. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, function, property_type, true));
  1500. } else if (match(TokenType::Colon)) {
  1501. if (!property_key) {
  1502. expected("a property name");
  1503. skip_to_next_property();
  1504. continue;
  1505. }
  1506. consume();
  1507. if (is_proto) {
  1508. if (has_direct_proto_property)
  1509. syntax_error("Property name '__proto__' must not appear more than once in object literal");
  1510. has_direct_proto_property = true;
  1511. }
  1512. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, parse_expression(2), property_type, false));
  1513. } else if (property_key && property_value) {
  1514. if (m_state.strict_mode && is<StringLiteral>(*property_key)) {
  1515. auto& string_literal = static_cast<StringLiteral const&>(*property_key);
  1516. if (is_strict_reserved_word(string_literal.value()))
  1517. syntax_error(String::formatted("'{}' is a reserved keyword", string_literal.value()));
  1518. }
  1519. properties.append(create_ast_node<ObjectProperty>({ m_state.current_token.filename(), rule_start.position(), position() }, *property_key, *property_value, property_type, false));
  1520. } else {
  1521. expected("a property");
  1522. skip_to_next_property();
  1523. continue;
  1524. }
  1525. if (!match(TokenType::Comma))
  1526. break;
  1527. consume(TokenType::Comma);
  1528. }
  1529. consume(TokenType::CurlyClose);
  1530. return create_ast_node<ObjectExpression>(
  1531. { m_state.current_token.filename(), rule_start.position(), position() },
  1532. move(properties),
  1533. move(invalid_object_literal_property_range));
  1534. }
  1535. NonnullRefPtr<ArrayExpression> Parser::parse_array_expression()
  1536. {
  1537. auto rule_start = push_start();
  1538. consume(TokenType::BracketOpen);
  1539. Vector<RefPtr<Expression>> elements;
  1540. while (match_expression() || match(TokenType::TripleDot) || match(TokenType::Comma)) {
  1541. RefPtr<Expression> expression;
  1542. if (match(TokenType::TripleDot)) {
  1543. consume(TokenType::TripleDot);
  1544. expression = create_ast_node<SpreadExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, parse_expression(2));
  1545. } else if (match_expression()) {
  1546. expression = parse_expression(2);
  1547. }
  1548. elements.append(expression);
  1549. if (!match(TokenType::Comma))
  1550. break;
  1551. consume(TokenType::Comma);
  1552. }
  1553. consume(TokenType::BracketClose);
  1554. return create_ast_node<ArrayExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(elements));
  1555. }
  1556. NonnullRefPtr<StringLiteral> Parser::parse_string_literal(const Token& token, bool in_template_literal)
  1557. {
  1558. auto rule_start = push_start();
  1559. auto status = Token::StringValueStatus::Ok;
  1560. auto string = token.string_value(status);
  1561. if (status != Token::StringValueStatus::Ok) {
  1562. String message;
  1563. if (status == Token::StringValueStatus::LegacyOctalEscapeSequence) {
  1564. m_state.string_legacy_octal_escape_sequence_in_scope = true;
  1565. if (in_template_literal)
  1566. message = "Octal escape sequence not allowed in template literal";
  1567. else if (m_state.strict_mode)
  1568. message = "Octal escape sequence in string literal not allowed in strict mode";
  1569. } else if (status == Token::StringValueStatus::MalformedHexEscape || status == Token::StringValueStatus::MalformedUnicodeEscape) {
  1570. auto type = status == Token::StringValueStatus::MalformedUnicodeEscape ? "unicode" : "hexadecimal";
  1571. message = String::formatted("Malformed {} escape sequence", type);
  1572. } else if (status == Token::StringValueStatus::UnicodeEscapeOverflow) {
  1573. message = "Unicode code_point must not be greater than 0x10ffff in escape sequence";
  1574. } else {
  1575. VERIFY_NOT_REACHED();
  1576. }
  1577. if (!message.is_empty())
  1578. syntax_error(message, Position { token.line_number(), token.line_column() });
  1579. }
  1580. auto is_use_strict_directive = !in_template_literal && (token.value() == "'use strict'" || token.value() == "\"use strict\"");
  1581. return create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, string, is_use_strict_directive);
  1582. }
  1583. NonnullRefPtr<TemplateLiteral> Parser::parse_template_literal(bool is_tagged)
  1584. {
  1585. auto rule_start = push_start();
  1586. consume(TokenType::TemplateLiteralStart);
  1587. NonnullRefPtrVector<Expression> expressions;
  1588. NonnullRefPtrVector<Expression> raw_strings;
  1589. auto append_empty_string = [this, &rule_start, &expressions, &raw_strings, is_tagged]() {
  1590. auto string_literal = create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, "");
  1591. expressions.append(string_literal);
  1592. if (is_tagged)
  1593. raw_strings.append(string_literal);
  1594. };
  1595. if (!match(TokenType::TemplateLiteralString))
  1596. append_empty_string();
  1597. while (!done() && !match(TokenType::TemplateLiteralEnd) && !match(TokenType::UnterminatedTemplateLiteral)) {
  1598. if (match(TokenType::TemplateLiteralString)) {
  1599. auto token = consume();
  1600. expressions.append(parse_string_literal(token, true));
  1601. if (is_tagged)
  1602. raw_strings.append(create_ast_node<StringLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, token.raw_template_value()));
  1603. } else if (match(TokenType::TemplateLiteralExprStart)) {
  1604. consume(TokenType::TemplateLiteralExprStart);
  1605. if (match(TokenType::TemplateLiteralExprEnd)) {
  1606. syntax_error("Empty template literal expression block");
  1607. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1608. }
  1609. expressions.append(parse_expression(0));
  1610. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1611. syntax_error("Unterminated template literal");
  1612. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1613. }
  1614. consume(TokenType::TemplateLiteralExprEnd);
  1615. if (!match(TokenType::TemplateLiteralString))
  1616. append_empty_string();
  1617. } else {
  1618. expected("Template literal string or expression");
  1619. break;
  1620. }
  1621. }
  1622. if (match(TokenType::UnterminatedTemplateLiteral)) {
  1623. syntax_error("Unterminated template literal");
  1624. } else {
  1625. consume(TokenType::TemplateLiteralEnd);
  1626. }
  1627. if (is_tagged)
  1628. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions, raw_strings);
  1629. return create_ast_node<TemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, expressions);
  1630. }
  1631. NonnullRefPtr<Expression> Parser::parse_expression(int min_precedence, Associativity associativity, ForbiddenTokens forbidden)
  1632. {
  1633. auto rule_start = push_start();
  1634. auto [expression, should_continue_parsing] = parse_primary_expression();
  1635. auto check_for_invalid_object_property = [&](auto& expression) {
  1636. if (is<ObjectExpression>(*expression)) {
  1637. if (auto range = static_cast<ObjectExpression&>(*expression).invalid_property_range(); range.has_value())
  1638. syntax_error("Invalid property in object literal", range->start);
  1639. }
  1640. };
  1641. if (is<Identifier>(*expression) && m_state.current_scope_pusher) {
  1642. auto identifier_instance = static_ptr_cast<Identifier>(expression);
  1643. auto function_scope = m_state.current_scope_pusher->last_function_scope();
  1644. auto function_parent_scope = function_scope ? function_scope->parent_scope() : nullptr;
  1645. bool has_not_been_declared_as_variable = true;
  1646. for (auto scope = m_state.current_scope_pusher; scope != function_parent_scope; scope = scope->parent_scope()) {
  1647. if (scope->has_declaration(identifier_instance->string())) {
  1648. has_not_been_declared_as_variable = false;
  1649. break;
  1650. }
  1651. }
  1652. if (has_not_been_declared_as_variable) {
  1653. if (identifier_instance->string() == "arguments"sv)
  1654. m_state.current_scope_pusher->set_contains_access_to_arguments_object();
  1655. }
  1656. }
  1657. while (match(TokenType::TemplateLiteralStart)) {
  1658. auto template_literal = parse_template_literal(true);
  1659. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1660. }
  1661. if (should_continue_parsing) {
  1662. while (match_secondary_expression(forbidden)) {
  1663. int new_precedence = g_operator_precedence.get(m_state.current_token.type());
  1664. if (new_precedence < min_precedence)
  1665. break;
  1666. if (new_precedence == min_precedence && associativity == Associativity::Left)
  1667. break;
  1668. check_for_invalid_object_property(expression);
  1669. Associativity new_associativity = operator_associativity(m_state.current_token.type());
  1670. auto result = parse_secondary_expression(move(expression), new_precedence, new_associativity, forbidden);
  1671. expression = result.expression;
  1672. forbidden = forbidden.merge(result.forbidden);
  1673. while (match(TokenType::TemplateLiteralStart) && !is<UpdateExpression>(*expression)) {
  1674. auto template_literal = parse_template_literal(true);
  1675. expression = create_ast_node<TaggedTemplateLiteral>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(template_literal));
  1676. }
  1677. }
  1678. }
  1679. if (is<SuperExpression>(*expression))
  1680. syntax_error("'super' keyword unexpected here");
  1681. check_for_invalid_object_property(expression);
  1682. if (is<CallExpression>(*expression) && m_state.current_scope_pusher) {
  1683. auto& callee = static_ptr_cast<CallExpression>(expression)->callee();
  1684. if (is<Identifier>(callee)) {
  1685. auto& identifier_instance = static_cast<Identifier const&>(callee);
  1686. if (identifier_instance.string() == "eval"sv) {
  1687. bool has_not_been_declared_as_variable = true;
  1688. for (auto scope = m_state.current_scope_pusher; scope; scope = scope->parent_scope()) {
  1689. if (scope->has_declaration(identifier_instance.string())) {
  1690. has_not_been_declared_as_variable = false;
  1691. break;
  1692. }
  1693. }
  1694. if (has_not_been_declared_as_variable)
  1695. m_state.current_scope_pusher->set_contains_direct_call_to_eval();
  1696. }
  1697. }
  1698. }
  1699. if (match(TokenType::Comma) && min_precedence <= 1) {
  1700. NonnullRefPtrVector<Expression> expressions;
  1701. expressions.append(expression);
  1702. while (match(TokenType::Comma)) {
  1703. consume();
  1704. expressions.append(parse_expression(2));
  1705. }
  1706. expression = create_ast_node<SequenceExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expressions));
  1707. }
  1708. return expression;
  1709. }
  1710. Parser::ExpressionResult Parser::parse_secondary_expression(NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity, ForbiddenTokens forbidden)
  1711. {
  1712. auto rule_start = push_start();
  1713. switch (m_state.current_token.type()) {
  1714. case TokenType::Plus:
  1715. consume();
  1716. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Addition, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1717. case TokenType::PlusEquals:
  1718. return parse_assignment_expression(AssignmentOp::AdditionAssignment, move(lhs), min_precedence, associativity, forbidden);
  1719. case TokenType::Minus:
  1720. consume();
  1721. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Subtraction, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1722. case TokenType::MinusEquals:
  1723. return parse_assignment_expression(AssignmentOp::SubtractionAssignment, move(lhs), min_precedence, associativity, forbidden);
  1724. case TokenType::Asterisk:
  1725. consume();
  1726. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Multiplication, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1727. case TokenType::AsteriskEquals:
  1728. return parse_assignment_expression(AssignmentOp::MultiplicationAssignment, move(lhs), min_precedence, associativity, forbidden);
  1729. case TokenType::Slash:
  1730. consume();
  1731. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Division, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1732. case TokenType::SlashEquals:
  1733. return parse_assignment_expression(AssignmentOp::DivisionAssignment, move(lhs), min_precedence, associativity, forbidden);
  1734. case TokenType::Percent:
  1735. consume();
  1736. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Modulo, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1737. case TokenType::PercentEquals:
  1738. return parse_assignment_expression(AssignmentOp::ModuloAssignment, move(lhs), min_precedence, associativity, forbidden);
  1739. case TokenType::DoubleAsterisk:
  1740. consume();
  1741. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::Exponentiation, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1742. case TokenType::DoubleAsteriskEquals:
  1743. return parse_assignment_expression(AssignmentOp::ExponentiationAssignment, move(lhs), min_precedence, associativity, forbidden);
  1744. case TokenType::GreaterThan:
  1745. consume();
  1746. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThan, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1747. case TokenType::GreaterThanEquals:
  1748. consume();
  1749. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::GreaterThanEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1750. case TokenType::LessThan:
  1751. consume();
  1752. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThan, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1753. case TokenType::LessThanEquals:
  1754. consume();
  1755. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LessThanEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1756. case TokenType::EqualsEqualsEquals:
  1757. consume();
  1758. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1759. case TokenType::ExclamationMarkEqualsEquals:
  1760. consume();
  1761. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::StrictlyInequals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1762. case TokenType::EqualsEquals:
  1763. consume();
  1764. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyEquals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1765. case TokenType::ExclamationMarkEquals:
  1766. consume();
  1767. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LooselyInequals, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1768. case TokenType::In:
  1769. consume();
  1770. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::In, move(lhs), parse_expression(min_precedence, associativity));
  1771. case TokenType::Instanceof:
  1772. consume();
  1773. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::InstanceOf, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1774. case TokenType::Ampersand:
  1775. consume();
  1776. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseAnd, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1777. case TokenType::AmpersandEquals:
  1778. return parse_assignment_expression(AssignmentOp::BitwiseAndAssignment, move(lhs), min_precedence, associativity, forbidden);
  1779. case TokenType::Pipe:
  1780. consume();
  1781. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseOr, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1782. case TokenType::PipeEquals:
  1783. return parse_assignment_expression(AssignmentOp::BitwiseOrAssignment, move(lhs), min_precedence, associativity, forbidden);
  1784. case TokenType::Caret:
  1785. consume();
  1786. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::BitwiseXor, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1787. case TokenType::CaretEquals:
  1788. return parse_assignment_expression(AssignmentOp::BitwiseXorAssignment, move(lhs), min_precedence, associativity, forbidden);
  1789. case TokenType::ShiftLeft:
  1790. consume();
  1791. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::LeftShift, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1792. case TokenType::ShiftLeftEquals:
  1793. return parse_assignment_expression(AssignmentOp::LeftShiftAssignment, move(lhs), min_precedence, associativity, forbidden);
  1794. case TokenType::ShiftRight:
  1795. consume();
  1796. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::RightShift, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1797. case TokenType::ShiftRightEquals:
  1798. return parse_assignment_expression(AssignmentOp::RightShiftAssignment, move(lhs), min_precedence, associativity, forbidden);
  1799. case TokenType::UnsignedShiftRight:
  1800. consume();
  1801. return create_ast_node<BinaryExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, BinaryOp::UnsignedRightShift, move(lhs), parse_expression(min_precedence, associativity, forbidden));
  1802. case TokenType::UnsignedShiftRightEquals:
  1803. return parse_assignment_expression(AssignmentOp::UnsignedRightShiftAssignment, move(lhs), min_precedence, associativity, forbidden);
  1804. case TokenType::ParenOpen:
  1805. return parse_call_expression(move(lhs));
  1806. case TokenType::Equals:
  1807. return parse_assignment_expression(AssignmentOp::Assignment, move(lhs), min_precedence, associativity, forbidden);
  1808. case TokenType::Period:
  1809. consume();
  1810. if (match(TokenType::PrivateIdentifier)) {
  1811. if (!is_private_identifier_valid())
  1812. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  1813. else if (is<SuperExpression>(*lhs))
  1814. syntax_error(String::formatted("Cannot access private field or method '{}' on super", m_state.current_token.value()));
  1815. return create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().value()));
  1816. } else if (!match_identifier_name()) {
  1817. expected("IdentifierName");
  1818. }
  1819. return create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), create_ast_node<Identifier>({ m_state.current_token.filename(), rule_start.position(), position() }, consume().flystring_value()));
  1820. case TokenType::BracketOpen: {
  1821. consume(TokenType::BracketOpen);
  1822. auto expression = create_ast_node<MemberExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), parse_expression(0), true);
  1823. consume(TokenType::BracketClose);
  1824. return expression;
  1825. }
  1826. case TokenType::PlusPlus:
  1827. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1828. // other engines throw ReferenceError for foo()++
  1829. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1830. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1831. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1832. auto& identifier = static_cast<Identifier&>(*lhs);
  1833. auto& name = identifier.string();
  1834. check_identifier_name_for_assignment_validity(name);
  1835. }
  1836. consume();
  1837. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Increment, move(lhs));
  1838. case TokenType::MinusMinus:
  1839. // FIXME: Apparently for functions this should also not be enforced on a parser level,
  1840. // other engines throw ReferenceError for foo()--
  1841. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs))
  1842. syntax_error(String::formatted("Left-hand side of postfix increment operator must be identifier or member expression, got {}", lhs->class_name()));
  1843. if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1844. auto& identifier = static_cast<Identifier&>(*lhs);
  1845. auto& name = identifier.string();
  1846. check_identifier_name_for_assignment_validity(name);
  1847. }
  1848. consume();
  1849. return create_ast_node<UpdateExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, UpdateOp::Decrement, move(lhs));
  1850. case TokenType::DoubleAmpersand: {
  1851. consume();
  1852. auto expression = create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::And, move(lhs), parse_expression(min_precedence, associativity, forbidden.forbid({ TokenType::DoubleQuestionMark })));
  1853. return { expression, { TokenType::DoubleQuestionMark } };
  1854. }
  1855. case TokenType::DoubleAmpersandEquals:
  1856. return parse_assignment_expression(AssignmentOp::AndAssignment, move(lhs), min_precedence, associativity, forbidden);
  1857. case TokenType::DoublePipe: {
  1858. consume();
  1859. auto expression = create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::Or, move(lhs), parse_expression(min_precedence, associativity, forbidden.forbid({ TokenType::DoubleQuestionMark })));
  1860. return { expression, { TokenType::DoubleQuestionMark } };
  1861. }
  1862. case TokenType::DoublePipeEquals:
  1863. return parse_assignment_expression(AssignmentOp::OrAssignment, move(lhs), min_precedence, associativity, forbidden);
  1864. case TokenType::DoubleQuestionMark: {
  1865. consume();
  1866. auto expression = create_ast_node<LogicalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, LogicalOp::NullishCoalescing, move(lhs), parse_expression(min_precedence, associativity, forbidden.forbid({ TokenType::DoubleAmpersand, TokenType::DoublePipe })));
  1867. return { expression, { TokenType::DoubleAmpersand, TokenType::DoublePipe } };
  1868. }
  1869. case TokenType::DoubleQuestionMarkEquals:
  1870. return parse_assignment_expression(AssignmentOp::NullishAssignment, move(lhs), min_precedence, associativity, forbidden);
  1871. case TokenType::QuestionMark:
  1872. return parse_conditional_expression(move(lhs), forbidden);
  1873. case TokenType::QuestionMarkPeriod:
  1874. // FIXME: This should allow `(new Foo)?.bar', but as our parser strips parenthesis,
  1875. // we can't really tell if `lhs' was parenthesized at this point.
  1876. if (is<NewExpression>(lhs.ptr())) {
  1877. syntax_error("'new' cannot be used with optional chaining", position());
  1878. consume();
  1879. return lhs;
  1880. }
  1881. return parse_optional_chain(move(lhs));
  1882. default:
  1883. expected("secondary expression");
  1884. consume();
  1885. return create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() });
  1886. }
  1887. }
  1888. bool Parser::is_private_identifier_valid() const
  1889. {
  1890. VERIFY(match(TokenType::PrivateIdentifier));
  1891. if (!m_state.referenced_private_names)
  1892. return false;
  1893. // We might not have hit the declaration yet so class will check this in the end
  1894. m_state.referenced_private_names->set(m_state.current_token.value());
  1895. return true;
  1896. }
  1897. RefPtr<BindingPattern> Parser::synthesize_binding_pattern(Expression const& expression)
  1898. {
  1899. VERIFY(is<ArrayExpression>(expression) || is<ObjectExpression>(expression));
  1900. // Clear any syntax error that has occurred in the range that 'expression' spans.
  1901. m_state.errors.remove_all_matching([range = expression.source_range()](auto const& error) {
  1902. return error.position.has_value() && range.contains(*error.position);
  1903. });
  1904. // Make a parser and parse the source for this expression as a binding pattern.
  1905. // NOTE: There's currently a fundamental problem that we pass the *next* (a.k.a. `current_token`)
  1906. // token's position to most nodes' SourceRange when using `rule_start.position(), position()`.
  1907. // This means that `source` will contain the subsequent token's trivia, if any (which is fine).
  1908. auto source_start_offset = expression.source_range().start.offset;
  1909. auto source_end_offset = expression.source_range().end.offset;
  1910. auto source = m_state.lexer.source().substring_view(source_start_offset, source_end_offset - source_start_offset);
  1911. Lexer lexer { source, m_state.lexer.filename(), expression.source_range().start.line, expression.source_range().start.column };
  1912. Parser parser { lexer };
  1913. parser.m_state.strict_mode = m_state.strict_mode;
  1914. parser.m_state.allow_super_property_lookup = m_state.allow_super_property_lookup;
  1915. parser.m_state.allow_super_constructor_call = m_state.allow_super_constructor_call;
  1916. parser.m_state.in_function_context = m_state.in_function_context;
  1917. parser.m_state.in_formal_parameter_context = m_state.in_formal_parameter_context;
  1918. parser.m_state.in_generator_function_context = m_state.in_generator_function_context;
  1919. parser.m_state.await_expression_is_valid = m_state.await_expression_is_valid;
  1920. parser.m_state.in_arrow_function_context = m_state.in_arrow_function_context;
  1921. parser.m_state.in_break_context = m_state.in_break_context;
  1922. parser.m_state.in_continue_context = m_state.in_continue_context;
  1923. parser.m_state.string_legacy_octal_escape_sequence_in_scope = m_state.string_legacy_octal_escape_sequence_in_scope;
  1924. parser.m_state.in_class_field_initializer = m_state.in_class_field_initializer;
  1925. parser.m_state.in_class_static_init_block = m_state.in_class_static_init_block;
  1926. parser.m_state.referenced_private_names = m_state.referenced_private_names;
  1927. auto result = parser.parse_binding_pattern(AllowDuplicates::Yes, AllowMemberExpressions::Yes);
  1928. if (parser.has_errors())
  1929. m_state.errors.extend(parser.errors());
  1930. return result;
  1931. }
  1932. NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(AssignmentOp assignment_op, NonnullRefPtr<Expression> lhs, int min_precedence, Associativity associativity, ForbiddenTokens forbidden)
  1933. {
  1934. auto rule_start = push_start();
  1935. VERIFY(match(TokenType::Equals)
  1936. || match(TokenType::PlusEquals)
  1937. || match(TokenType::MinusEquals)
  1938. || match(TokenType::AsteriskEquals)
  1939. || match(TokenType::SlashEquals)
  1940. || match(TokenType::PercentEquals)
  1941. || match(TokenType::DoubleAsteriskEquals)
  1942. || match(TokenType::AmpersandEquals)
  1943. || match(TokenType::PipeEquals)
  1944. || match(TokenType::CaretEquals)
  1945. || match(TokenType::ShiftLeftEquals)
  1946. || match(TokenType::ShiftRightEquals)
  1947. || match(TokenType::UnsignedShiftRightEquals)
  1948. || match(TokenType::DoubleAmpersandEquals)
  1949. || match(TokenType::DoublePipeEquals)
  1950. || match(TokenType::DoubleQuestionMarkEquals));
  1951. consume();
  1952. if (assignment_op == AssignmentOp::Assignment) {
  1953. if (is<ArrayExpression>(*lhs) || is<ObjectExpression>(*lhs)) {
  1954. auto binding_pattern = synthesize_binding_pattern(*lhs);
  1955. if (binding_pattern) {
  1956. auto rhs = parse_expression(min_precedence, associativity);
  1957. return create_ast_node<AssignmentExpression>(
  1958. { m_state.current_token.filename(), rule_start.position(), position() },
  1959. assignment_op,
  1960. binding_pattern.release_nonnull(),
  1961. move(rhs));
  1962. }
  1963. }
  1964. }
  1965. if (!is<Identifier>(*lhs) && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  1966. syntax_error("Invalid left-hand side in assignment");
  1967. } else if (m_state.strict_mode && is<Identifier>(*lhs)) {
  1968. auto const& name = static_cast<Identifier const&>(*lhs).string();
  1969. check_identifier_name_for_assignment_validity(name);
  1970. } else if (m_state.strict_mode && is<CallExpression>(*lhs)) {
  1971. syntax_error("Cannot assign to function call");
  1972. }
  1973. auto rhs = parse_expression(min_precedence, associativity, forbidden);
  1974. return create_ast_node<AssignmentExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, assignment_op, move(lhs), move(rhs));
  1975. }
  1976. NonnullRefPtr<Identifier> Parser::parse_identifier()
  1977. {
  1978. auto identifier_start = position();
  1979. auto token = consume_identifier();
  1980. if (m_state.in_class_field_initializer && token.value() == "arguments"sv)
  1981. syntax_error("'arguments' is not allowed in class field initializer");
  1982. return create_ast_node<Identifier>(
  1983. { m_state.current_token.filename(), identifier_start, position() },
  1984. token.flystring_value());
  1985. }
  1986. Vector<CallExpression::Argument> Parser::parse_arguments()
  1987. {
  1988. Vector<CallExpression::Argument> arguments;
  1989. consume(TokenType::ParenOpen);
  1990. while (match_expression() || match(TokenType::TripleDot)) {
  1991. if (match(TokenType::TripleDot)) {
  1992. consume();
  1993. arguments.append({ parse_expression(2), true });
  1994. } else {
  1995. arguments.append({ parse_expression(2), false });
  1996. }
  1997. if (!match(TokenType::Comma))
  1998. break;
  1999. consume();
  2000. }
  2001. consume(TokenType::ParenClose);
  2002. return arguments;
  2003. }
  2004. NonnullRefPtr<Expression> Parser::parse_call_expression(NonnullRefPtr<Expression> lhs)
  2005. {
  2006. auto rule_start = push_start();
  2007. if (!m_state.allow_super_constructor_call && is<SuperExpression>(*lhs))
  2008. syntax_error("'super' keyword unexpected here");
  2009. auto arguments = parse_arguments();
  2010. if (is<SuperExpression>(*lhs))
  2011. return create_ast_node<SuperCall>({ m_state.current_token.filename(), rule_start.position(), position() }, move(arguments));
  2012. return create_ast_node<CallExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(lhs), move(arguments));
  2013. }
  2014. NonnullRefPtr<NewExpression> Parser::parse_new_expression()
  2015. {
  2016. auto rule_start = push_start();
  2017. consume(TokenType::New);
  2018. auto callee = parse_expression(g_operator_precedence.get(TokenType::New), Associativity::Right, { TokenType::ParenOpen, TokenType::QuestionMarkPeriod });
  2019. if (is<ImportCall>(*callee))
  2020. syntax_error("Cannot call new on dynamic import", callee->source_range().start);
  2021. Vector<CallExpression::Argument> arguments;
  2022. if (match(TokenType::ParenOpen)) {
  2023. consume(TokenType::ParenOpen);
  2024. while (match_expression() || match(TokenType::TripleDot)) {
  2025. if (match(TokenType::TripleDot)) {
  2026. consume();
  2027. arguments.append({ parse_expression(2), true });
  2028. } else {
  2029. arguments.append({ parse_expression(2), false });
  2030. }
  2031. if (!match(TokenType::Comma))
  2032. break;
  2033. consume();
  2034. }
  2035. consume(TokenType::ParenClose);
  2036. }
  2037. return create_ast_node<NewExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(callee), move(arguments));
  2038. }
  2039. NonnullRefPtr<YieldExpression> Parser::parse_yield_expression()
  2040. {
  2041. auto rule_start = push_start();
  2042. if (m_state.in_formal_parameter_context)
  2043. syntax_error("'Yield' expression is not allowed in formal parameters of generator function");
  2044. consume(TokenType::Yield);
  2045. RefPtr<Expression> argument;
  2046. bool yield_from = false;
  2047. if (!m_state.current_token.trivia_contains_line_terminator()) {
  2048. if (match(TokenType::Asterisk)) {
  2049. consume();
  2050. yield_from = true;
  2051. }
  2052. if (yield_from || match_expression() || match(TokenType::Class))
  2053. argument = parse_expression(2);
  2054. }
  2055. return create_ast_node<YieldExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument), yield_from);
  2056. }
  2057. NonnullRefPtr<AwaitExpression> Parser::parse_await_expression()
  2058. {
  2059. auto rule_start = push_start();
  2060. if (m_state.in_formal_parameter_context)
  2061. syntax_error("'Await' expression is not allowed in formal parameters of an async function");
  2062. consume(TokenType::Await);
  2063. auto precedence = g_operator_precedence.get(TokenType::Await);
  2064. auto associativity = operator_associativity(TokenType::Await);
  2065. auto argument = parse_expression(precedence, associativity);
  2066. m_state.current_scope_pusher->set_contains_await_expression();
  2067. return create_ast_node<AwaitExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(argument));
  2068. }
  2069. NonnullRefPtr<ReturnStatement> Parser::parse_return_statement()
  2070. {
  2071. auto rule_start = push_start();
  2072. if (!m_state.in_function_context && !m_state.in_arrow_function_context)
  2073. syntax_error("'return' not allowed outside of a function");
  2074. consume(TokenType::Return);
  2075. // Automatic semicolon insertion: terminate statement when return is followed by newline
  2076. if (m_state.current_token.trivia_contains_line_terminator())
  2077. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2078. if (match_expression()) {
  2079. auto expression = parse_expression(0);
  2080. consume_or_insert_semicolon();
  2081. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2082. }
  2083. consume_or_insert_semicolon();
  2084. return create_ast_node<ReturnStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, nullptr);
  2085. }
  2086. void Parser::parse_statement_list(ScopeNode& output_node, AllowLabelledFunction allow_labelled_functions)
  2087. {
  2088. while (!done()) {
  2089. if (match_declaration()) {
  2090. auto declaration = parse_declaration();
  2091. VERIFY(m_state.current_scope_pusher);
  2092. m_state.current_scope_pusher->add_declaration(declaration);
  2093. output_node.append(move(declaration));
  2094. } else if (match_statement()) {
  2095. output_node.append(parse_statement(allow_labelled_functions));
  2096. } else {
  2097. break;
  2098. }
  2099. }
  2100. }
  2101. // FunctionBody, https://tc39.es/ecma262/#prod-FunctionBody
  2102. NonnullRefPtr<FunctionBody> Parser::parse_function_body(Vector<FunctionDeclaration::Parameter> const& parameters, FunctionKind function_kind, bool& contains_direct_call_to_eval)
  2103. {
  2104. auto rule_start = push_start();
  2105. auto function_body = create_ast_node<FunctionBody>({ m_state.current_token.filename(), rule_start.position(), position() });
  2106. ScopePusher function_scope = ScopePusher::function_scope(*this, function_body, parameters); // FIXME <-
  2107. auto has_use_strict = parse_directive(function_body);
  2108. bool previous_strict_mode = m_state.strict_mode;
  2109. if (has_use_strict) {
  2110. m_state.strict_mode = true;
  2111. function_body->set_strict_mode();
  2112. if (!is_simple_parameter_list(parameters))
  2113. syntax_error("Illegal 'use strict' directive in function with non-simple parameter list");
  2114. } else if (previous_strict_mode) {
  2115. function_body->set_strict_mode();
  2116. }
  2117. parse_statement_list(function_body);
  2118. // If we're parsing the function body standalone, e.g. via CreateDynamicFunction, we must have reached EOF here.
  2119. // Otherwise, we need a closing curly bracket (which is consumed elsewhere). If we get neither, it's an error.
  2120. if (!match(TokenType::Eof) && !match(TokenType::CurlyClose))
  2121. expected(Token::name(TokenType::CurlyClose));
  2122. // If the function contains 'use strict' we need to check the parameters (again).
  2123. if (function_body->in_strict_mode() || function_kind != FunctionKind::Normal) {
  2124. Vector<StringView> parameter_names;
  2125. for (auto& parameter : parameters) {
  2126. parameter.binding.visit(
  2127. [&](FlyString const& parameter_name) {
  2128. check_identifier_name_for_assignment_validity(parameter_name, function_body->in_strict_mode());
  2129. if (function_kind == FunctionKind::Generator && parameter_name == "yield"sv)
  2130. syntax_error("Parameter name 'yield' not allowed in this context");
  2131. if (function_kind == FunctionKind::Async && parameter_name == "await"sv)
  2132. syntax_error("Parameter name 'await' not allowed in this context");
  2133. for (auto& previous_name : parameter_names) {
  2134. if (previous_name == parameter_name) {
  2135. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name));
  2136. }
  2137. }
  2138. parameter_names.append(parameter_name);
  2139. },
  2140. [&](NonnullRefPtr<BindingPattern> const& binding) {
  2141. binding->for_each_bound_name([&](auto& bound_name) {
  2142. if (function_kind == FunctionKind::Generator && bound_name == "yield"sv)
  2143. syntax_error("Parameter name 'yield' not allowed in this context");
  2144. if (function_kind == FunctionKind::Async && bound_name == "await"sv)
  2145. syntax_error("Parameter name 'await' not allowed in this context");
  2146. for (auto& previous_name : parameter_names) {
  2147. if (previous_name == bound_name) {
  2148. syntax_error(String::formatted("Duplicate parameter '{}' not allowed in strict mode", bound_name));
  2149. break;
  2150. }
  2151. }
  2152. parameter_names.append(bound_name);
  2153. });
  2154. });
  2155. }
  2156. }
  2157. m_state.strict_mode = previous_strict_mode;
  2158. contains_direct_call_to_eval = function_scope.contains_direct_call_to_eval();
  2159. return function_body;
  2160. }
  2161. NonnullRefPtr<BlockStatement> Parser::parse_block_statement()
  2162. {
  2163. auto rule_start = push_start();
  2164. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2165. ScopePusher block_scope = ScopePusher::block_scope(*this, block);
  2166. consume(TokenType::CurlyOpen);
  2167. parse_statement_list(block);
  2168. consume(TokenType::CurlyClose);
  2169. return block;
  2170. }
  2171. template<typename FunctionNodeType>
  2172. NonnullRefPtr<FunctionNodeType> Parser::parse_function_node(u8 parse_options, Optional<Position> const& function_start)
  2173. {
  2174. auto rule_start = function_start.has_value()
  2175. ? RulePosition { *this, *function_start }
  2176. : push_start();
  2177. VERIFY(!(parse_options & FunctionNodeParseOptions::IsGetterFunction && parse_options & FunctionNodeParseOptions::IsSetterFunction));
  2178. TemporaryChange super_property_access_rollback(m_state.allow_super_property_lookup, !!(parse_options & FunctionNodeParseOptions::AllowSuperPropertyLookup));
  2179. TemporaryChange super_constructor_call_rollback(m_state.allow_super_constructor_call, !!(parse_options & FunctionNodeParseOptions::AllowSuperConstructorCall));
  2180. TemporaryChange break_context_rollback(m_state.in_break_context, false);
  2181. TemporaryChange continue_context_rollback(m_state.in_continue_context, false);
  2182. TemporaryChange class_field_initializer_rollback(m_state.in_class_field_initializer, false);
  2183. TemporaryChange might_need_arguments_object_rollback(m_state.function_might_need_arguments_object, false);
  2184. constexpr auto is_function_expression = IsSame<FunctionNodeType, FunctionExpression>;
  2185. FunctionKind function_kind;
  2186. if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0 && (parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2187. function_kind = FunctionKind::AsyncGenerator;
  2188. else if ((parse_options & FunctionNodeParseOptions::IsGeneratorFunction) != 0)
  2189. function_kind = FunctionKind::Generator;
  2190. else if ((parse_options & FunctionNodeParseOptions::IsAsyncFunction) != 0)
  2191. function_kind = FunctionKind::Async;
  2192. else
  2193. function_kind = FunctionKind::Normal;
  2194. FlyString name;
  2195. if (parse_options & FunctionNodeParseOptions::CheckForFunctionAndName) {
  2196. if (function_kind == FunctionKind::Normal && match(TokenType::Async) && !next_token().trivia_contains_line_terminator()) {
  2197. function_kind = FunctionKind::Async;
  2198. consume(TokenType::Async);
  2199. parse_options |= FunctionNodeParseOptions::IsAsyncFunction;
  2200. }
  2201. consume(TokenType::Function);
  2202. if (match(TokenType::Asterisk)) {
  2203. function_kind = function_kind == FunctionKind::Normal ? FunctionKind::Generator : FunctionKind::AsyncGenerator;
  2204. consume(TokenType::Asterisk);
  2205. parse_options |= FunctionNodeParseOptions::IsGeneratorFunction;
  2206. }
  2207. if (FunctionNodeType::must_have_name() || match_identifier())
  2208. name = consume_identifier().flystring_value();
  2209. else if (is_function_expression && (match(TokenType::Yield) || match(TokenType::Await)))
  2210. name = consume().flystring_value();
  2211. check_identifier_name_for_assignment_validity(name);
  2212. if (function_kind == FunctionKind::AsyncGenerator && (name == "await"sv || name == "yield"sv))
  2213. syntax_error(String::formatted("async generator function is not allowed to be called '{}'", name));
  2214. if (m_state.in_class_static_init_block && name == "await"sv)
  2215. syntax_error("'await' is a reserved word");
  2216. }
  2217. TemporaryChange class_static_initializer_rollback(m_state.in_class_static_init_block, false);
  2218. TemporaryChange generator_change(m_state.in_generator_function_context, function_kind == FunctionKind::Generator || function_kind == FunctionKind::AsyncGenerator);
  2219. TemporaryChange async_change(m_state.await_expression_is_valid, function_kind == FunctionKind::Async || function_kind == FunctionKind::AsyncGenerator);
  2220. consume(TokenType::ParenOpen);
  2221. i32 function_length = -1;
  2222. auto parameters = parse_formal_parameters(function_length, parse_options);
  2223. consume(TokenType::ParenClose);
  2224. if (function_length == -1)
  2225. function_length = parameters.size();
  2226. TemporaryChange function_context_rollback(m_state.in_function_context, true);
  2227. auto old_labels_in_scope = move(m_state.labels_in_scope);
  2228. ScopeGuard guard([&]() {
  2229. m_state.labels_in_scope = move(old_labels_in_scope);
  2230. });
  2231. consume(TokenType::CurlyOpen);
  2232. bool contains_direct_call_to_eval = false;
  2233. auto body = parse_function_body(parameters, function_kind, contains_direct_call_to_eval);
  2234. consume(TokenType::CurlyClose);
  2235. auto has_strict_directive = body->in_strict_mode();
  2236. if (has_strict_directive)
  2237. check_identifier_name_for_assignment_validity(name, true);
  2238. auto function_start_offset = rule_start.position().offset;
  2239. auto function_end_offset = position().offset - m_state.current_token.trivia().length();
  2240. auto source_text = String { m_state.lexer.source().substring_view(function_start_offset, function_end_offset - function_start_offset) };
  2241. return create_ast_node<FunctionNodeType>(
  2242. { m_state.current_token.filename(), rule_start.position(), position() },
  2243. name, move(source_text), move(body), move(parameters), function_length,
  2244. function_kind, has_strict_directive, m_state.function_might_need_arguments_object,
  2245. contains_direct_call_to_eval);
  2246. }
  2247. Vector<FunctionNode::Parameter> Parser::parse_formal_parameters(int& function_length, u8 parse_options)
  2248. {
  2249. auto rule_start = push_start();
  2250. bool has_default_parameter = false;
  2251. bool has_rest_parameter = false;
  2252. TemporaryChange formal_parameter_context_change { m_state.in_formal_parameter_context, true };
  2253. Vector<FunctionNode::Parameter> parameters;
  2254. auto consume_identifier_or_binding_pattern = [&]() -> Variant<FlyString, NonnullRefPtr<BindingPattern>> {
  2255. if (auto pattern = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No))
  2256. return pattern.release_nonnull();
  2257. auto token = consume_identifier();
  2258. auto parameter_name = token.flystring_value();
  2259. check_identifier_name_for_assignment_validity(parameter_name);
  2260. for (auto& parameter : parameters) {
  2261. bool has_same_name = parameter.binding.visit(
  2262. [&](FlyString const& name) {
  2263. return name == parameter_name;
  2264. },
  2265. [&](NonnullRefPtr<BindingPattern> const& bindings) {
  2266. bool found_duplicate = false;
  2267. bindings->for_each_bound_name([&](auto& bound_name) {
  2268. if (bound_name == parameter_name)
  2269. found_duplicate = true;
  2270. });
  2271. return found_duplicate;
  2272. });
  2273. if (!has_same_name)
  2274. continue;
  2275. String message;
  2276. if (parse_options & FunctionNodeParseOptions::IsArrowFunction)
  2277. message = String::formatted("Duplicate parameter '{}' not allowed in arrow function", parameter_name);
  2278. else if (m_state.strict_mode)
  2279. message = String::formatted("Duplicate parameter '{}' not allowed in strict mode", parameter_name);
  2280. else if (has_default_parameter || match(TokenType::Equals))
  2281. message = String::formatted("Duplicate parameter '{}' not allowed in function with default parameter", parameter_name);
  2282. else if (has_rest_parameter)
  2283. message = String::formatted("Duplicate parameter '{}' not allowed in function with rest parameter", parameter_name);
  2284. if (!message.is_empty())
  2285. syntax_error(message, Position { token.line_number(), token.line_column() });
  2286. break;
  2287. }
  2288. return FlyString { token.value() };
  2289. };
  2290. while (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen) || match_identifier() || match(TokenType::TripleDot)) {
  2291. if (parse_options & FunctionNodeParseOptions::IsGetterFunction)
  2292. syntax_error("Getter function must have no arguments");
  2293. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && (parameters.size() >= 1 || match(TokenType::TripleDot)))
  2294. syntax_error("Setter function must have one argument");
  2295. auto is_rest = false;
  2296. if (match(TokenType::TripleDot)) {
  2297. consume();
  2298. has_rest_parameter = true;
  2299. function_length = parameters.size();
  2300. is_rest = true;
  2301. }
  2302. auto parameter = consume_identifier_or_binding_pattern();
  2303. RefPtr<Expression> default_value;
  2304. if (match(TokenType::Equals)) {
  2305. consume();
  2306. if (is_rest)
  2307. syntax_error("Rest parameter may not have a default initializer");
  2308. TemporaryChange change(m_state.in_function_context, true);
  2309. has_default_parameter = true;
  2310. function_length = parameters.size();
  2311. default_value = parse_expression(2);
  2312. bool is_generator = parse_options & FunctionNodeParseOptions::IsGeneratorFunction;
  2313. if ((is_generator || m_state.strict_mode) && default_value && default_value->fast_is<Identifier>() && static_cast<Identifier&>(*default_value).string() == "yield"sv)
  2314. syntax_error("Generator function parameter initializer cannot contain a reference to an identifier named \"yield\"");
  2315. }
  2316. parameters.append({ move(parameter), default_value, is_rest });
  2317. if (!match(TokenType::Comma) || is_rest)
  2318. break;
  2319. consume(TokenType::Comma);
  2320. }
  2321. if (parse_options & FunctionNodeParseOptions::IsSetterFunction && parameters.is_empty())
  2322. syntax_error("Setter function must have one argument");
  2323. // If we're parsing the parameters standalone, e.g. via CreateDynamicFunction, we must have reached EOF here.
  2324. // Otherwise, we need a closing parenthesis (which is consumed elsewhere). If we get neither, it's an error.
  2325. if (!match(TokenType::Eof) && !match(TokenType::ParenClose))
  2326. expected(Token::name(TokenType::ParenClose));
  2327. return parameters;
  2328. }
  2329. static AK::Array<FlyString, 36> s_reserved_words = { "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with" };
  2330. RefPtr<BindingPattern> Parser::parse_binding_pattern(Parser::AllowDuplicates allow_duplicates, Parser::AllowMemberExpressions allow_member_expressions)
  2331. {
  2332. auto rule_start = push_start();
  2333. TokenType closing_token;
  2334. bool is_object = true;
  2335. if (match(TokenType::BracketOpen)) {
  2336. consume();
  2337. closing_token = TokenType::BracketClose;
  2338. is_object = false;
  2339. } else if (match(TokenType::CurlyOpen)) {
  2340. consume();
  2341. closing_token = TokenType::CurlyClose;
  2342. } else {
  2343. return {};
  2344. }
  2345. Vector<BindingPattern::BindingEntry> entries;
  2346. while (!match(closing_token)) {
  2347. if (!is_object && match(TokenType::Comma)) {
  2348. consume();
  2349. entries.append(BindingPattern::BindingEntry {});
  2350. continue;
  2351. }
  2352. auto is_rest = false;
  2353. if (match(TokenType::TripleDot)) {
  2354. consume();
  2355. is_rest = true;
  2356. }
  2357. decltype(BindingPattern::BindingEntry::name) name = Empty {};
  2358. decltype(BindingPattern::BindingEntry::alias) alias = Empty {};
  2359. RefPtr<Expression> initializer = {};
  2360. if (is_object) {
  2361. bool needs_alias = false;
  2362. if (allow_member_expressions == AllowMemberExpressions::Yes && is_rest) {
  2363. auto expression_position = position();
  2364. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2365. if (is<MemberExpression>(*expression))
  2366. alias = static_ptr_cast<MemberExpression>(expression);
  2367. else if (is<Identifier>(*expression))
  2368. name = static_ptr_cast<Identifier>(expression);
  2369. else
  2370. syntax_error("Invalid destructuring assignment target", expression_position);
  2371. } else if (match_identifier_name() || match(TokenType::StringLiteral) || match(TokenType::NumericLiteral)) {
  2372. if (match(TokenType::StringLiteral) || match(TokenType::NumericLiteral))
  2373. needs_alias = true;
  2374. if (match(TokenType::StringLiteral)) {
  2375. auto token = consume(TokenType::StringLiteral);
  2376. auto string_literal = parse_string_literal(token);
  2377. name = create_ast_node<Identifier>(
  2378. { m_state.current_token.filename(), rule_start.position(), position() },
  2379. string_literal->value());
  2380. } else {
  2381. name = create_ast_node<Identifier>(
  2382. { m_state.current_token.filename(), rule_start.position(), position() },
  2383. consume().flystring_value());
  2384. }
  2385. } else if (match(TokenType::BracketOpen)) {
  2386. consume();
  2387. auto expression = parse_expression(0);
  2388. name = move(expression);
  2389. consume(TokenType::BracketClose);
  2390. } else {
  2391. expected("identifier or computed property name");
  2392. return {};
  2393. }
  2394. if (!is_rest && match(TokenType::Colon)) {
  2395. consume();
  2396. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2397. auto expression_position = position();
  2398. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2399. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2400. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2401. alias = synthesized_binding_pattern.release_nonnull();
  2402. else
  2403. syntax_error("Invalid destructuring assignment target", expression_position);
  2404. } else if (is<MemberExpression>(*expression)) {
  2405. alias = static_ptr_cast<MemberExpression>(expression);
  2406. } else if (is<Identifier>(*expression)) {
  2407. alias = static_ptr_cast<Identifier>(expression);
  2408. } else {
  2409. syntax_error("Invalid destructuring assignment target", expression_position);
  2410. }
  2411. } else if (match(TokenType::CurlyOpen) || match(TokenType::BracketOpen)) {
  2412. auto binding_pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2413. if (!binding_pattern)
  2414. return {};
  2415. alias = binding_pattern.release_nonnull();
  2416. } else if (match_identifier_name()) {
  2417. alias = create_ast_node<Identifier>(
  2418. { m_state.current_token.filename(), rule_start.position(), position() },
  2419. consume().flystring_value());
  2420. } else {
  2421. expected("identifier or binding pattern");
  2422. return {};
  2423. }
  2424. } else if (needs_alias) {
  2425. expected("alias for string or numeric literal name");
  2426. return {};
  2427. }
  2428. } else {
  2429. if (allow_member_expressions == AllowMemberExpressions::Yes) {
  2430. auto expression_position = position();
  2431. auto expression = parse_expression(2, Associativity::Right, { TokenType::Equals });
  2432. if (is<ArrayExpression>(*expression) || is<ObjectExpression>(*expression)) {
  2433. if (auto synthesized_binding_pattern = synthesize_binding_pattern(*expression))
  2434. alias = synthesized_binding_pattern.release_nonnull();
  2435. else
  2436. syntax_error("Invalid destructuring assignment target", expression_position);
  2437. } else if (is<MemberExpression>(*expression)) {
  2438. alias = static_ptr_cast<MemberExpression>(expression);
  2439. } else if (is<Identifier>(*expression)) {
  2440. alias = static_ptr_cast<Identifier>(expression);
  2441. } else {
  2442. syntax_error("Invalid destructuring assignment target", expression_position);
  2443. }
  2444. } else if (match(TokenType::BracketOpen) || match(TokenType::CurlyOpen)) {
  2445. auto pattern = parse_binding_pattern(allow_duplicates, allow_member_expressions);
  2446. if (!pattern) {
  2447. expected("binding pattern");
  2448. return {};
  2449. }
  2450. alias = pattern.release_nonnull();
  2451. } else if (match_identifier_name()) {
  2452. // BindingElement must always have an Empty name field
  2453. auto identifier_name = consume_identifier().flystring_value();
  2454. alias = create_ast_node<Identifier>(
  2455. { m_state.current_token.filename(), rule_start.position(), position() },
  2456. identifier_name);
  2457. } else {
  2458. expected("identifier or binding pattern");
  2459. return {};
  2460. }
  2461. }
  2462. if (match(TokenType::Equals)) {
  2463. if (is_rest) {
  2464. syntax_error("Unexpected initializer after rest element");
  2465. return {};
  2466. }
  2467. consume();
  2468. initializer = parse_expression(2);
  2469. if (!initializer) {
  2470. expected("initialization expression");
  2471. return {};
  2472. }
  2473. }
  2474. entries.append(BindingPattern::BindingEntry { move(name), move(alias), move(initializer), is_rest });
  2475. if (match(TokenType::Comma)) {
  2476. if (is_rest) {
  2477. syntax_error("Rest element may not be followed by a comma");
  2478. return {};
  2479. }
  2480. consume();
  2481. } else if (is_object && !match(TokenType::CurlyClose)) {
  2482. consume(TokenType::Comma);
  2483. }
  2484. }
  2485. while (!is_object && match(TokenType::Comma))
  2486. consume();
  2487. consume(closing_token);
  2488. auto kind = is_object ? BindingPattern::Kind::Object : BindingPattern::Kind::Array;
  2489. auto pattern = adopt_ref(*new BindingPattern);
  2490. pattern->entries = move(entries);
  2491. pattern->kind = kind;
  2492. Vector<StringView> bound_names;
  2493. pattern->for_each_bound_name([&](auto& name) {
  2494. if (allow_duplicates == AllowDuplicates::No) {
  2495. if (bound_names.contains_slow(name))
  2496. syntax_error("Duplicate parameter names in bindings");
  2497. bound_names.append(name);
  2498. }
  2499. check_identifier_name_for_assignment_validity(name);
  2500. });
  2501. return pattern;
  2502. }
  2503. NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(bool for_loop_variable_declaration)
  2504. {
  2505. auto rule_start = push_start();
  2506. DeclarationKind declaration_kind;
  2507. switch (m_state.current_token.type()) {
  2508. case TokenType::Var:
  2509. declaration_kind = DeclarationKind::Var;
  2510. break;
  2511. case TokenType::Let:
  2512. declaration_kind = DeclarationKind::Let;
  2513. break;
  2514. case TokenType::Const:
  2515. declaration_kind = DeclarationKind::Const;
  2516. break;
  2517. default:
  2518. VERIFY_NOT_REACHED();
  2519. }
  2520. consume();
  2521. NonnullRefPtrVector<VariableDeclarator> declarations;
  2522. for (;;) {
  2523. Variant<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>, Empty> target {};
  2524. if (match_identifier()) {
  2525. auto identifier_start = push_start();
  2526. auto name = consume_identifier().flystring_value();
  2527. target = create_ast_node<Identifier>(
  2528. { m_state.current_token.filename(), rule_start.position(), position() },
  2529. name);
  2530. check_identifier_name_for_assignment_validity(name);
  2531. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const) && name == "let"sv)
  2532. syntax_error("Lexical binding may not be called 'let'");
  2533. } else if (auto pattern = parse_binding_pattern(declaration_kind != DeclarationKind::Var ? AllowDuplicates::No : AllowDuplicates::Yes, AllowMemberExpressions::No)) {
  2534. target = pattern.release_nonnull();
  2535. if ((declaration_kind == DeclarationKind::Let || declaration_kind == DeclarationKind::Const)) {
  2536. target.get<NonnullRefPtr<BindingPattern>>()->for_each_bound_name([this](auto& name) {
  2537. if (name == "let"sv)
  2538. syntax_error("Lexical binding may not be called 'let'");
  2539. });
  2540. }
  2541. } else if (!m_state.in_generator_function_context && match(TokenType::Yield)) {
  2542. if (m_state.strict_mode)
  2543. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  2544. target = create_ast_node<Identifier>(
  2545. { m_state.current_token.filename(), rule_start.position(), position() },
  2546. consume().flystring_value());
  2547. } else if (!m_state.await_expression_is_valid && match(TokenType::Async)) {
  2548. if (m_program_type == Program::Type::Module)
  2549. syntax_error("Identifier must not be a reserved word in modules ('async')");
  2550. target = create_ast_node<Identifier>(
  2551. { m_state.current_token.filename(), rule_start.position(), position() },
  2552. consume().flystring_value());
  2553. }
  2554. if (target.has<Empty>()) {
  2555. expected("identifier or a binding pattern");
  2556. if (match(TokenType::Comma)) {
  2557. consume();
  2558. continue;
  2559. }
  2560. break;
  2561. }
  2562. RefPtr<Expression> init;
  2563. if (match(TokenType::Equals)) {
  2564. consume();
  2565. // In a for loop 'in' can be ambiguous so we do not allow it
  2566. // 14.7.4 The for Statement, https://tc39.es/ecma262/#prod-ForStatement and 14.7.5 The for-in, for-of, and for-await-of Statements, https://tc39.es/ecma262/#prod-ForInOfStatement
  2567. if (for_loop_variable_declaration)
  2568. init = parse_expression(2, Associativity::Right, { TokenType::In });
  2569. else
  2570. init = parse_expression(2);
  2571. } else if (!for_loop_variable_declaration && declaration_kind == DeclarationKind::Const) {
  2572. syntax_error("Missing initializer in 'const' variable declaration");
  2573. } else if (!for_loop_variable_declaration && target.has<NonnullRefPtr<BindingPattern>>()) {
  2574. syntax_error("Missing initializer in destructuring assignment");
  2575. }
  2576. declarations.append(create_ast_node<VariableDeclarator>(
  2577. { m_state.current_token.filename(), rule_start.position(), position() },
  2578. move(target).downcast<NonnullRefPtr<Identifier>, NonnullRefPtr<BindingPattern>>(),
  2579. move(init)));
  2580. if (match(TokenType::Comma)) {
  2581. consume();
  2582. continue;
  2583. }
  2584. break;
  2585. }
  2586. if (!for_loop_variable_declaration)
  2587. consume_or_insert_semicolon();
  2588. auto declaration = create_ast_node<VariableDeclaration>({ m_state.current_token.filename(), rule_start.position(), position() }, declaration_kind, move(declarations));
  2589. return declaration;
  2590. }
  2591. NonnullRefPtr<ThrowStatement> Parser::parse_throw_statement()
  2592. {
  2593. auto rule_start = push_start();
  2594. consume(TokenType::Throw);
  2595. // Automatic semicolon insertion: terminate statement when throw is followed by newline
  2596. if (m_state.current_token.trivia_contains_line_terminator()) {
  2597. syntax_error("No line break is allowed between 'throw' and its expression");
  2598. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, create_ast_node<ErrorExpression>({ m_state.current_token.filename(), rule_start.position(), position() }));
  2599. }
  2600. auto expression = parse_expression(0);
  2601. consume_or_insert_semicolon();
  2602. return create_ast_node<ThrowStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression));
  2603. }
  2604. NonnullRefPtr<BreakStatement> Parser::parse_break_statement()
  2605. {
  2606. auto rule_start = push_start();
  2607. consume(TokenType::Break);
  2608. FlyString target_label;
  2609. if (match(TokenType::Semicolon)) {
  2610. consume();
  2611. } else {
  2612. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2613. target_label = consume().value();
  2614. auto label = m_state.labels_in_scope.find(target_label);
  2615. if (label == m_state.labels_in_scope.end())
  2616. syntax_error(String::formatted("Label '{}' not found", target_label));
  2617. }
  2618. consume_or_insert_semicolon();
  2619. }
  2620. if (target_label.is_null() && !m_state.in_break_context)
  2621. syntax_error("Unlabeled 'break' not allowed outside of a loop or switch statement");
  2622. return create_ast_node<BreakStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2623. }
  2624. NonnullRefPtr<ContinueStatement> Parser::parse_continue_statement()
  2625. {
  2626. auto rule_start = push_start();
  2627. if (!m_state.in_continue_context)
  2628. syntax_error("'continue' not allow outside of a loop");
  2629. consume(TokenType::Continue);
  2630. FlyString target_label;
  2631. if (match(TokenType::Semicolon)) {
  2632. consume();
  2633. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2634. }
  2635. if (!m_state.current_token.trivia_contains_line_terminator() && match_identifier()) {
  2636. auto label_position = position();
  2637. target_label = consume().value();
  2638. auto label = m_state.labels_in_scope.find(target_label);
  2639. if (label == m_state.labels_in_scope.end())
  2640. syntax_error(String::formatted("Label '{}' not found or invalid", target_label));
  2641. else
  2642. label->value = label_position;
  2643. }
  2644. consume_or_insert_semicolon();
  2645. return create_ast_node<ContinueStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, target_label);
  2646. }
  2647. NonnullRefPtr<ConditionalExpression> Parser::parse_conditional_expression(NonnullRefPtr<Expression> test, ForbiddenTokens forbidden)
  2648. {
  2649. auto rule_start = push_start();
  2650. consume(TokenType::QuestionMark);
  2651. auto consequent = parse_expression(2);
  2652. consume(TokenType::Colon);
  2653. auto alternate = parse_expression(2, Associativity::Right, forbidden);
  2654. return create_ast_node<ConditionalExpression>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(consequent), move(alternate));
  2655. }
  2656. NonnullRefPtr<OptionalChain> Parser::parse_optional_chain(NonnullRefPtr<Expression> base)
  2657. {
  2658. auto rule_start = push_start();
  2659. Vector<OptionalChain::Reference> chain;
  2660. do {
  2661. if (match(TokenType::QuestionMarkPeriod)) {
  2662. consume(TokenType::QuestionMarkPeriod);
  2663. switch (m_state.current_token.type()) {
  2664. case TokenType::ParenOpen:
  2665. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::Optional });
  2666. break;
  2667. case TokenType::BracketOpen:
  2668. consume();
  2669. chain.append(OptionalChain::ComputedReference { parse_expression(0), OptionalChain::Mode::Optional });
  2670. consume(TokenType::BracketClose);
  2671. break;
  2672. case TokenType::PrivateIdentifier: {
  2673. if (!is_private_identifier_valid())
  2674. syntax_error(String::formatted("Reference to undeclared private field or method '{}'", m_state.current_token.value()));
  2675. auto start = position();
  2676. auto private_identifier = consume();
  2677. chain.append(OptionalChain::PrivateMemberReference {
  2678. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2679. OptionalChain::Mode::Optional });
  2680. break;
  2681. }
  2682. case TokenType::TemplateLiteralStart:
  2683. // 13.3.1.1 - Static Semantics: Early Errors
  2684. // OptionalChain :
  2685. // ?. TemplateLiteral
  2686. // OptionalChain TemplateLiteral
  2687. // This is a hard error.
  2688. syntax_error("Invalid tagged template literal after ?.", position());
  2689. break;
  2690. default:
  2691. if (match_identifier_name()) {
  2692. auto start = position();
  2693. auto identifier = consume();
  2694. chain.append(OptionalChain::MemberReference {
  2695. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.flystring_value()),
  2696. OptionalChain::Mode::Optional,
  2697. });
  2698. } else {
  2699. syntax_error("Invalid optional chain reference after ?.", position());
  2700. }
  2701. break;
  2702. }
  2703. } else if (match(TokenType::ParenOpen)) {
  2704. chain.append(OptionalChain::Call { parse_arguments(), OptionalChain::Mode::NotOptional });
  2705. } else if (match(TokenType::Period)) {
  2706. consume();
  2707. if (match(TokenType::PrivateIdentifier)) {
  2708. auto start = position();
  2709. auto private_identifier = consume();
  2710. chain.append(OptionalChain::PrivateMemberReference {
  2711. create_ast_node<PrivateIdentifier>({ m_state.current_token.filename(), start, position() }, private_identifier.value()),
  2712. OptionalChain::Mode::NotOptional,
  2713. });
  2714. } else if (match_identifier_name()) {
  2715. auto start = position();
  2716. auto identifier = consume();
  2717. chain.append(OptionalChain::MemberReference {
  2718. create_ast_node<Identifier>({ m_state.current_token.filename(), start, position() }, identifier.flystring_value()),
  2719. OptionalChain::Mode::NotOptional,
  2720. });
  2721. } else {
  2722. expected("an identifier");
  2723. break;
  2724. }
  2725. } else if (match(TokenType::TemplateLiteralStart)) {
  2726. // 13.3.1.1 - Static Semantics: Early Errors
  2727. // OptionalChain :
  2728. // ?. TemplateLiteral
  2729. // OptionalChain TemplateLiteral
  2730. syntax_error("Invalid tagged template literal after optional chain", position());
  2731. break;
  2732. } else if (match(TokenType::BracketOpen)) {
  2733. consume();
  2734. chain.append(OptionalChain::ComputedReference { parse_expression(2), OptionalChain::Mode::NotOptional });
  2735. consume(TokenType::BracketClose);
  2736. } else {
  2737. break;
  2738. }
  2739. } while (!done());
  2740. return create_ast_node<OptionalChain>(
  2741. { m_state.current_token.filename(), rule_start.position(), position() },
  2742. move(base),
  2743. move(chain));
  2744. }
  2745. NonnullRefPtr<TryStatement> Parser::parse_try_statement()
  2746. {
  2747. auto rule_start = push_start();
  2748. consume(TokenType::Try);
  2749. auto block = parse_block_statement();
  2750. RefPtr<CatchClause> handler;
  2751. if (match(TokenType::Catch))
  2752. handler = parse_catch_clause();
  2753. RefPtr<BlockStatement> finalizer;
  2754. if (match(TokenType::Finally)) {
  2755. consume();
  2756. finalizer = parse_block_statement();
  2757. }
  2758. if (!handler && !finalizer)
  2759. syntax_error("try statement must have a 'catch' or 'finally' clause");
  2760. return create_ast_node<TryStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(block), move(handler), move(finalizer));
  2761. }
  2762. NonnullRefPtr<DoWhileStatement> Parser::parse_do_while_statement()
  2763. {
  2764. auto rule_start = push_start();
  2765. consume(TokenType::Do);
  2766. auto body = [&]() -> NonnullRefPtr<Statement> {
  2767. TemporaryChange break_change(m_state.in_break_context, true);
  2768. TemporaryChange continue_change(m_state.in_continue_context, true);
  2769. return parse_statement();
  2770. }();
  2771. consume(TokenType::While);
  2772. consume(TokenType::ParenOpen);
  2773. auto test = parse_expression(0);
  2774. consume(TokenType::ParenClose);
  2775. // Since ES 2015 a missing semicolon is inserted here, despite the regular ASI rules not applying
  2776. if (match(TokenType::Semicolon))
  2777. consume();
  2778. return create_ast_node<DoWhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2779. }
  2780. NonnullRefPtr<WhileStatement> Parser::parse_while_statement()
  2781. {
  2782. auto rule_start = push_start();
  2783. consume(TokenType::While);
  2784. consume(TokenType::ParenOpen);
  2785. auto test = parse_expression(0);
  2786. consume(TokenType::ParenClose);
  2787. TemporaryChange break_change(m_state.in_break_context, true);
  2788. TemporaryChange continue_change(m_state.in_continue_context, true);
  2789. auto body = parse_statement();
  2790. return create_ast_node<WhileStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test), move(body));
  2791. }
  2792. NonnullRefPtr<SwitchStatement> Parser::parse_switch_statement()
  2793. {
  2794. auto rule_start = push_start();
  2795. consume(TokenType::Switch);
  2796. consume(TokenType::ParenOpen);
  2797. auto determinant = parse_expression(0);
  2798. consume(TokenType::ParenClose);
  2799. consume(TokenType::CurlyOpen);
  2800. NonnullRefPtrVector<SwitchCase> cases;
  2801. auto switch_statement = create_ast_node<SwitchStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(determinant));
  2802. ScopePusher switch_scope = ScopePusher::block_scope(*this, switch_statement);
  2803. auto has_default = false;
  2804. while (match(TokenType::Case) || match(TokenType::Default)) {
  2805. if (match(TokenType::Default)) {
  2806. if (has_default)
  2807. syntax_error("Multiple 'default' clauses in switch statement");
  2808. has_default = true;
  2809. }
  2810. switch_statement->add_case(parse_switch_case());
  2811. }
  2812. consume(TokenType::CurlyClose);
  2813. return switch_statement;
  2814. }
  2815. NonnullRefPtr<WithStatement> Parser::parse_with_statement()
  2816. {
  2817. auto rule_start = push_start();
  2818. consume(TokenType::With);
  2819. consume(TokenType::ParenOpen);
  2820. auto object = parse_expression(0);
  2821. consume(TokenType::ParenClose);
  2822. auto body = parse_statement();
  2823. return create_ast_node<WithStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(object), move(body));
  2824. }
  2825. NonnullRefPtr<SwitchCase> Parser::parse_switch_case()
  2826. {
  2827. auto rule_start = push_start();
  2828. RefPtr<Expression> test;
  2829. if (consume().type() == TokenType::Case) {
  2830. test = parse_expression(0);
  2831. }
  2832. consume(TokenType::Colon);
  2833. NonnullRefPtrVector<Statement> consequent;
  2834. TemporaryChange break_change(m_state.in_break_context, true);
  2835. auto switch_case = create_ast_node<SwitchCase>({ m_state.current_token.filename(), rule_start.position(), position() }, move(test));
  2836. parse_statement_list(switch_case);
  2837. return switch_case;
  2838. }
  2839. NonnullRefPtr<CatchClause> Parser::parse_catch_clause()
  2840. {
  2841. auto rule_start = push_start();
  2842. consume(TokenType::Catch);
  2843. FlyString parameter;
  2844. RefPtr<BindingPattern> pattern_parameter;
  2845. auto should_expect_parameter = false;
  2846. if (match(TokenType::ParenOpen)) {
  2847. should_expect_parameter = true;
  2848. consume();
  2849. if (match_identifier_name()
  2850. && (!match(TokenType::Yield) || !m_state.in_generator_function_context)
  2851. && (!match(TokenType::Async) || !m_state.await_expression_is_valid)
  2852. && (!match(TokenType::Await) || !m_state.in_class_static_init_block))
  2853. parameter = consume().value();
  2854. else
  2855. pattern_parameter = parse_binding_pattern(AllowDuplicates::No, AllowMemberExpressions::No);
  2856. consume(TokenType::ParenClose);
  2857. }
  2858. if (should_expect_parameter && parameter.is_empty() && !pattern_parameter)
  2859. expected("an identifier or a binding pattern");
  2860. HashTable<FlyString> bound_names;
  2861. if (pattern_parameter) {
  2862. pattern_parameter->for_each_bound_name(
  2863. [&](auto& name) {
  2864. check_identifier_name_for_assignment_validity(name);
  2865. bound_names.set(name);
  2866. });
  2867. }
  2868. if (!parameter.is_empty()) {
  2869. check_identifier_name_for_assignment_validity(parameter);
  2870. bound_names.set(parameter);
  2871. }
  2872. ScopePusher catch_scope = ScopePusher::catch_scope(*this, pattern_parameter, parameter);
  2873. auto body = parse_block_statement();
  2874. body->for_each_lexically_declared_name([&](auto const& name) {
  2875. if (bound_names.contains(name))
  2876. syntax_error(String::formatted("Identifier '{}' already declared as catch parameter", name));
  2877. });
  2878. if (pattern_parameter) {
  2879. return create_ast_node<CatchClause>(
  2880. { m_state.current_token.filename(), rule_start.position(), position() },
  2881. pattern_parameter.release_nonnull(),
  2882. move(body));
  2883. }
  2884. return create_ast_node<CatchClause>(
  2885. { m_state.current_token.filename(), rule_start.position(), position() },
  2886. move(parameter),
  2887. move(body));
  2888. }
  2889. NonnullRefPtr<IfStatement> Parser::parse_if_statement()
  2890. {
  2891. auto rule_start = push_start();
  2892. auto parse_function_declaration_as_block_statement = [&] {
  2893. // https://tc39.es/ecma262/#sec-functiondeclarations-in-ifstatement-statement-clauses
  2894. // Code matching this production is processed as if each matching occurrence of
  2895. // FunctionDeclaration[?Yield, ?Await, ~Default] was the sole StatementListItem
  2896. // of a BlockStatement occupying that position in the source code.
  2897. VERIFY(match(TokenType::Function));
  2898. auto block = create_ast_node<BlockStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  2899. ScopePusher block_scope = ScopePusher::block_scope(*this, *block);
  2900. auto declaration = parse_declaration();
  2901. VERIFY(m_state.current_scope_pusher);
  2902. block_scope.add_declaration(declaration);
  2903. VERIFY(is<FunctionDeclaration>(*declaration));
  2904. auto& function_declaration = static_cast<FunctionDeclaration const&>(*declaration);
  2905. if (function_declaration.kind() == FunctionKind::Generator)
  2906. syntax_error("Generator functions can only be declared in top-level or within a block");
  2907. if (function_declaration.kind() == FunctionKind::Async)
  2908. syntax_error("Async functions can only be declared in top-level or within a block");
  2909. block->append(move(declaration));
  2910. return block;
  2911. };
  2912. consume(TokenType::If);
  2913. consume(TokenType::ParenOpen);
  2914. auto predicate = parse_expression(0);
  2915. consume(TokenType::ParenClose);
  2916. RefPtr<Statement> consequent;
  2917. if (!m_state.strict_mode && match(TokenType::Function))
  2918. consequent = parse_function_declaration_as_block_statement();
  2919. else
  2920. consequent = parse_statement();
  2921. RefPtr<Statement> alternate;
  2922. if (match(TokenType::Else)) {
  2923. consume();
  2924. if (!m_state.strict_mode && match(TokenType::Function))
  2925. alternate = parse_function_declaration_as_block_statement();
  2926. else
  2927. alternate = parse_statement();
  2928. }
  2929. return create_ast_node<IfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(predicate), move(*consequent), move(alternate));
  2930. }
  2931. NonnullRefPtr<Statement> Parser::parse_for_statement()
  2932. {
  2933. auto rule_start = push_start();
  2934. auto is_await_loop = IsForAwaitLoop::No;
  2935. auto match_of = [&](Token const& token) {
  2936. return token.type() == TokenType::Identifier && token.original_value() == "of"sv;
  2937. };
  2938. auto match_for_in_of = [&]() {
  2939. bool is_of = match_of(m_state.current_token);
  2940. if (is_await_loop == IsForAwaitLoop::Yes) {
  2941. if (!is_of)
  2942. syntax_error("for await loop is only valid with 'of'");
  2943. else if (!m_state.await_expression_is_valid)
  2944. syntax_error("for await loop is only valid in async function or generator");
  2945. return true;
  2946. }
  2947. return match(TokenType::In) || is_of;
  2948. };
  2949. consume(TokenType::For);
  2950. if (match(TokenType::Await)) {
  2951. consume();
  2952. if (!m_state.await_expression_is_valid)
  2953. syntax_error("for-await-of is only allowed in async function context");
  2954. is_await_loop = IsForAwaitLoop::Yes;
  2955. }
  2956. consume(TokenType::ParenOpen);
  2957. Optional<ScopePusher> scope_pusher;
  2958. RefPtr<ASTNode> init;
  2959. if (!match(TokenType::Semicolon)) {
  2960. if (match_variable_declaration()) {
  2961. auto declaration = parse_variable_declaration(true);
  2962. if (declaration->declaration_kind() == DeclarationKind::Var) {
  2963. m_state.current_scope_pusher->add_declaration(declaration);
  2964. } else {
  2965. // This does not follow the normal declaration structure so we need additional checks.
  2966. HashTable<FlyString> bound_names;
  2967. declaration->for_each_bound_name([&](auto const& name) {
  2968. if (bound_names.set(name) != AK::HashSetResult::InsertedNewEntry)
  2969. syntax_error(String::formatted("Identifier '{}' already declared in for loop initializer", name), declaration->source_range().start);
  2970. });
  2971. }
  2972. init = move(declaration);
  2973. if (match_for_in_of())
  2974. return parse_for_in_of_statement(*init, is_await_loop);
  2975. if (static_cast<VariableDeclaration&>(*init).declaration_kind() == DeclarationKind::Const) {
  2976. for (auto& variable : static_cast<VariableDeclaration&>(*init).declarations()) {
  2977. if (!variable.init())
  2978. syntax_error("Missing initializer in 'const' variable declaration");
  2979. }
  2980. }
  2981. } else if (match_expression()) {
  2982. auto lookahead_token = next_token();
  2983. bool starts_with_async_of = match(TokenType::Async) && match_of(lookahead_token);
  2984. init = parse_expression(0, Associativity::Right, { TokenType::In });
  2985. if (match_for_in_of()) {
  2986. if (is_await_loop != IsForAwaitLoop::Yes
  2987. && starts_with_async_of && match_of(m_state.current_token))
  2988. syntax_error("for-of loop may not start with async of");
  2989. return parse_for_in_of_statement(*init, is_await_loop);
  2990. }
  2991. } else {
  2992. syntax_error("Unexpected token in for loop");
  2993. }
  2994. }
  2995. consume(TokenType::Semicolon);
  2996. RefPtr<Expression> test;
  2997. if (!match(TokenType::Semicolon))
  2998. test = parse_expression(0);
  2999. consume(TokenType::Semicolon);
  3000. RefPtr<Expression> update;
  3001. if (!match(TokenType::ParenClose))
  3002. update = parse_expression(0);
  3003. consume(TokenType::ParenClose);
  3004. TemporaryChange break_change(m_state.in_break_context, true);
  3005. TemporaryChange continue_change(m_state.in_continue_context, true);
  3006. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, init);
  3007. auto body = parse_statement();
  3008. return create_ast_node<ForStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(init), move(test), move(update), move(body));
  3009. }
  3010. NonnullRefPtr<Statement> Parser::parse_for_in_of_statement(NonnullRefPtr<ASTNode> lhs, IsForAwaitLoop is_for_await_loop)
  3011. {
  3012. Variant<NonnullRefPtr<ASTNode>, NonnullRefPtr<BindingPattern>> for_declaration = lhs;
  3013. auto rule_start = push_start();
  3014. auto has_annexB_for_in_init_extension = false;
  3015. if (is<VariableDeclaration>(*lhs)) {
  3016. auto& declaration = static_cast<VariableDeclaration&>(*lhs);
  3017. if (declaration.declarations().size() > 1) {
  3018. syntax_error("Multiple declarations not allowed in for..in/of");
  3019. } else if (declaration.declarations().size() < 1) {
  3020. syntax_error("Need exactly one variable declaration in for..in/of");
  3021. } else {
  3022. // AnnexB extension B.3.5 Initializers in ForIn Statement Heads, https://tc39.es/ecma262/#sec-initializers-in-forin-statement-heads
  3023. auto& variable = declaration.declarations().first();
  3024. if (variable.init()) {
  3025. if (m_state.strict_mode || declaration.declaration_kind() != DeclarationKind::Var || !variable.target().has<NonnullRefPtr<Identifier>>())
  3026. syntax_error("Variable initializer not allowed in for..in/of");
  3027. else
  3028. has_annexB_for_in_init_extension = true;
  3029. }
  3030. }
  3031. } else if (!lhs->is_identifier() && !is<MemberExpression>(*lhs) && !is<CallExpression>(*lhs)) {
  3032. bool valid = false;
  3033. if (is<ObjectExpression>(*lhs) || is<ArrayExpression>(*lhs)) {
  3034. auto synthesized_binding_pattern = synthesize_binding_pattern(static_cast<Expression const&>(*lhs));
  3035. if (synthesized_binding_pattern) {
  3036. for_declaration = synthesized_binding_pattern.release_nonnull();
  3037. valid = true;
  3038. }
  3039. }
  3040. if (!valid)
  3041. syntax_error(String::formatted("Invalid left-hand side in for-loop ('{}')", lhs->class_name()));
  3042. }
  3043. auto in_or_of = consume();
  3044. auto is_in = in_or_of.type() == TokenType::In;
  3045. if (!is_in) {
  3046. if (is<MemberExpression>(*lhs)) {
  3047. auto& member = static_cast<MemberExpression const&>(*lhs);
  3048. if (member.object().is_identifier() && static_cast<Identifier const&>(member.object()).string() == "let"sv)
  3049. syntax_error("For of statement may not start with let.");
  3050. }
  3051. if (has_annexB_for_in_init_extension)
  3052. syntax_error("Variable initializer not allowed in for..of", rule_start.position());
  3053. }
  3054. auto rhs = parse_expression(is_in ? 0 : 2);
  3055. consume(TokenType::ParenClose);
  3056. TemporaryChange break_change(m_state.in_break_context, true);
  3057. TemporaryChange continue_change(m_state.in_continue_context, true);
  3058. ScopePusher for_loop_scope = ScopePusher::for_loop_scope(*this, lhs);
  3059. auto body = parse_statement();
  3060. if (is_in)
  3061. return create_ast_node<ForInStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3062. if (is_for_await_loop == IsForAwaitLoop::Yes)
  3063. return create_ast_node<ForAwaitOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3064. return create_ast_node<ForOfStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(for_declaration), move(rhs), move(body));
  3065. }
  3066. NonnullRefPtr<DebuggerStatement> Parser::parse_debugger_statement()
  3067. {
  3068. auto rule_start = push_start();
  3069. consume(TokenType::Debugger);
  3070. consume_or_insert_semicolon();
  3071. return create_ast_node<DebuggerStatement>({ m_state.current_token.filename(), rule_start.position(), position() });
  3072. }
  3073. bool Parser::match(TokenType type) const
  3074. {
  3075. return m_state.current_token.type() == type;
  3076. }
  3077. bool Parser::match_expression() const
  3078. {
  3079. auto type = m_state.current_token.type();
  3080. if (type == TokenType::Import) {
  3081. auto lookahead_token = next_token();
  3082. return lookahead_token.type() == TokenType::Period || lookahead_token.type() == TokenType::ParenOpen;
  3083. }
  3084. return type == TokenType::BoolLiteral
  3085. || type == TokenType::NumericLiteral
  3086. || type == TokenType::BigIntLiteral
  3087. || type == TokenType::StringLiteral
  3088. || type == TokenType::TemplateLiteralStart
  3089. || type == TokenType::NullLiteral
  3090. || match_identifier()
  3091. || type == TokenType::PrivateIdentifier
  3092. || type == TokenType::Await
  3093. || type == TokenType::New
  3094. || type == TokenType::Class
  3095. || type == TokenType::CurlyOpen
  3096. || type == TokenType::BracketOpen
  3097. || type == TokenType::ParenOpen
  3098. || type == TokenType::Function
  3099. || type == TokenType::Async
  3100. || type == TokenType::This
  3101. || type == TokenType::Super
  3102. || type == TokenType::RegexLiteral
  3103. || type == TokenType::Slash // Wrongly recognized regex by lexer
  3104. || type == TokenType::SlashEquals // Wrongly recognized regex by lexer (/=a/ is a valid regex)
  3105. || type == TokenType::Yield
  3106. || match_unary_prefixed_expression();
  3107. }
  3108. bool Parser::match_unary_prefixed_expression() const
  3109. {
  3110. auto type = m_state.current_token.type();
  3111. return type == TokenType::PlusPlus
  3112. || type == TokenType::MinusMinus
  3113. || type == TokenType::ExclamationMark
  3114. || type == TokenType::Tilde
  3115. || type == TokenType::Plus
  3116. || type == TokenType::Minus
  3117. || type == TokenType::Typeof
  3118. || type == TokenType::Void
  3119. || type == TokenType::Delete;
  3120. }
  3121. bool Parser::match_secondary_expression(ForbiddenTokens forbidden) const
  3122. {
  3123. auto type = m_state.current_token.type();
  3124. if (!forbidden.allows(type))
  3125. return false;
  3126. return type == TokenType::Plus
  3127. || type == TokenType::PlusEquals
  3128. || type == TokenType::Minus
  3129. || type == TokenType::MinusEquals
  3130. || type == TokenType::Asterisk
  3131. || type == TokenType::AsteriskEquals
  3132. || type == TokenType::Slash
  3133. || type == TokenType::SlashEquals
  3134. || type == TokenType::Percent
  3135. || type == TokenType::PercentEquals
  3136. || type == TokenType::DoubleAsterisk
  3137. || type == TokenType::DoubleAsteriskEquals
  3138. || type == TokenType::Equals
  3139. || type == TokenType::EqualsEqualsEquals
  3140. || type == TokenType::ExclamationMarkEqualsEquals
  3141. || type == TokenType::EqualsEquals
  3142. || type == TokenType::ExclamationMarkEquals
  3143. || type == TokenType::GreaterThan
  3144. || type == TokenType::GreaterThanEquals
  3145. || type == TokenType::LessThan
  3146. || type == TokenType::LessThanEquals
  3147. || type == TokenType::ParenOpen
  3148. || type == TokenType::Period
  3149. || type == TokenType::BracketOpen
  3150. || (type == TokenType::PlusPlus && !m_state.current_token.trivia_contains_line_terminator())
  3151. || (type == TokenType::MinusMinus && !m_state.current_token.trivia_contains_line_terminator())
  3152. || type == TokenType::In
  3153. || type == TokenType::Instanceof
  3154. || type == TokenType::QuestionMark
  3155. || type == TokenType::Ampersand
  3156. || type == TokenType::AmpersandEquals
  3157. || type == TokenType::Pipe
  3158. || type == TokenType::PipeEquals
  3159. || type == TokenType::Caret
  3160. || type == TokenType::CaretEquals
  3161. || type == TokenType::ShiftLeft
  3162. || type == TokenType::ShiftLeftEquals
  3163. || type == TokenType::ShiftRight
  3164. || type == TokenType::ShiftRightEquals
  3165. || type == TokenType::UnsignedShiftRight
  3166. || type == TokenType::UnsignedShiftRightEquals
  3167. || type == TokenType::DoubleAmpersand
  3168. || type == TokenType::DoubleAmpersandEquals
  3169. || type == TokenType::DoublePipe
  3170. || type == TokenType::DoublePipeEquals
  3171. || type == TokenType::DoubleQuestionMark
  3172. || type == TokenType::DoubleQuestionMarkEquals
  3173. || type == TokenType::QuestionMarkPeriod;
  3174. }
  3175. bool Parser::match_statement() const
  3176. {
  3177. auto type = m_state.current_token.type();
  3178. return match_expression()
  3179. || type == TokenType::Return
  3180. || type == TokenType::Yield
  3181. || type == TokenType::Do
  3182. || type == TokenType::If
  3183. || type == TokenType::Throw
  3184. || type == TokenType::Try
  3185. || type == TokenType::While
  3186. || type == TokenType::With
  3187. || type == TokenType::For
  3188. || type == TokenType::CurlyOpen
  3189. || type == TokenType::Switch
  3190. || type == TokenType::Break
  3191. || type == TokenType::Continue
  3192. || type == TokenType::Var
  3193. || type == TokenType::Debugger
  3194. || type == TokenType::Semicolon;
  3195. }
  3196. bool Parser::match_export_or_import() const
  3197. {
  3198. auto type = m_state.current_token.type();
  3199. return type == TokenType::Export
  3200. || type == TokenType::Import;
  3201. }
  3202. bool Parser::match_declaration() const
  3203. {
  3204. auto type = m_state.current_token.type();
  3205. if (type == TokenType::Let && !m_state.strict_mode) {
  3206. return try_match_let_declaration();
  3207. }
  3208. if (type == TokenType::Async) {
  3209. auto lookahead_token = next_token();
  3210. return lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator();
  3211. }
  3212. return type == TokenType::Function
  3213. || type == TokenType::Class
  3214. || type == TokenType::Const
  3215. || type == TokenType::Let;
  3216. }
  3217. Token Parser::next_token(size_t steps) const
  3218. {
  3219. Lexer lookahead_lexer = m_state.lexer;
  3220. Token lookahead_token;
  3221. while (steps > 0) {
  3222. lookahead_token = lookahead_lexer.next();
  3223. steps--;
  3224. }
  3225. return lookahead_token;
  3226. }
  3227. bool Parser::try_match_let_declaration() const
  3228. {
  3229. VERIFY(m_state.current_token.type() == TokenType::Let);
  3230. auto token_after = next_token();
  3231. if (token_after.is_identifier_name() && token_after.value() != "in"sv)
  3232. return true;
  3233. if (token_after.type() == TokenType::CurlyOpen || token_after.type() == TokenType::BracketOpen)
  3234. return true;
  3235. return false;
  3236. }
  3237. bool Parser::match_variable_declaration() const
  3238. {
  3239. auto type = m_state.current_token.type();
  3240. if (type == TokenType::Let && !m_state.strict_mode) {
  3241. return try_match_let_declaration();
  3242. }
  3243. return type == TokenType::Var
  3244. || type == TokenType::Let
  3245. || type == TokenType::Const;
  3246. }
  3247. bool Parser::match_identifier() const
  3248. {
  3249. if (m_state.current_token.type() == TokenType::EscapedKeyword) {
  3250. if (m_state.current_token.value() == "let"sv)
  3251. return !m_state.strict_mode;
  3252. if (m_state.current_token.value() == "yield"sv)
  3253. return !m_state.strict_mode && !m_state.in_generator_function_context;
  3254. if (m_state.current_token.value() == "await"sv)
  3255. return m_program_type != Program::Type::Module && !m_state.await_expression_is_valid && !m_state.in_class_static_init_block;
  3256. return true;
  3257. }
  3258. return m_state.current_token.type() == TokenType::Identifier
  3259. || m_state.current_token.type() == TokenType::Async
  3260. || (m_state.current_token.type() == TokenType::Let && !m_state.strict_mode)
  3261. || (m_state.current_token.type() == TokenType::Await && m_program_type != Program::Type::Module && !m_state.await_expression_is_valid && !m_state.in_class_static_init_block)
  3262. || (m_state.current_token.type() == TokenType::Yield && !m_state.in_generator_function_context && !m_state.strict_mode); // See note in Parser::parse_identifier().
  3263. }
  3264. bool Parser::match_identifier_name() const
  3265. {
  3266. return m_state.current_token.is_identifier_name();
  3267. }
  3268. bool Parser::match_property_key() const
  3269. {
  3270. auto type = m_state.current_token.type();
  3271. return match_identifier_name()
  3272. || type == TokenType::BracketOpen
  3273. || type == TokenType::StringLiteral
  3274. || type == TokenType::NumericLiteral
  3275. || type == TokenType::BigIntLiteral;
  3276. }
  3277. bool Parser::done() const
  3278. {
  3279. return match(TokenType::Eof);
  3280. }
  3281. Token Parser::consume()
  3282. {
  3283. auto old_token = m_state.current_token;
  3284. m_state.current_token = m_state.lexer.next();
  3285. // NOTE: This is the bare minimum needed to decide whether we might need an arguments object
  3286. // in a function expression or declaration. ("might" because the AST implements some further
  3287. // conditions from the spec that rule out the need for allocating one)
  3288. if (old_token.type() == TokenType::Identifier && old_token.value().is_one_of("arguments"sv, "eval"sv))
  3289. m_state.function_might_need_arguments_object = true;
  3290. return old_token;
  3291. }
  3292. void Parser::consume_or_insert_semicolon()
  3293. {
  3294. // Semicolon was found and will be consumed
  3295. if (match(TokenType::Semicolon)) {
  3296. consume();
  3297. return;
  3298. }
  3299. // Insert semicolon if...
  3300. // ...token is preceded by one or more newlines
  3301. if (m_state.current_token.trivia_contains_line_terminator())
  3302. return;
  3303. // ...token is a closing curly brace
  3304. if (match(TokenType::CurlyClose))
  3305. return;
  3306. // ...token is eof
  3307. if (match(TokenType::Eof))
  3308. return;
  3309. // No rule for semicolon insertion applies -> syntax error
  3310. expected("Semicolon");
  3311. }
  3312. Token Parser::consume_identifier()
  3313. {
  3314. if (match(TokenType::Identifier))
  3315. return consume(TokenType::Identifier);
  3316. if (match(TokenType::EscapedKeyword))
  3317. return consume(TokenType::EscapedKeyword);
  3318. // Note that 'let' is not a reserved keyword, but our lexer considers it such
  3319. // As it's pretty nice to have that (for syntax highlighting and such), we'll
  3320. // special-case it here instead.
  3321. if (match(TokenType::Let)) {
  3322. if (m_state.strict_mode)
  3323. syntax_error("'let' is not allowed as an identifier in strict mode");
  3324. return consume();
  3325. }
  3326. if (match(TokenType::Yield)) {
  3327. if (m_state.strict_mode || m_state.in_generator_function_context)
  3328. syntax_error("Identifier must not be a reserved word in strict mode ('yield')");
  3329. return consume();
  3330. }
  3331. if (match(TokenType::Await)) {
  3332. if (m_program_type == Program::Type::Module || m_state.await_expression_is_valid || m_state.in_class_static_init_block)
  3333. syntax_error("Identifier must not be a reserved word in modules ('await')");
  3334. return consume();
  3335. }
  3336. if (match(TokenType::Async))
  3337. return consume();
  3338. expected("Identifier");
  3339. return consume();
  3340. }
  3341. // https://tc39.es/ecma262/#prod-IdentifierReference
  3342. Token Parser::consume_identifier_reference()
  3343. {
  3344. if (match(TokenType::Identifier))
  3345. return consume(TokenType::Identifier);
  3346. if (match(TokenType::EscapedKeyword)) {
  3347. auto name = m_state.current_token.value();
  3348. if (m_state.strict_mode && (name == "let"sv || name == "yield"sv))
  3349. syntax_error(String::formatted("'{}' is not allowed as an identifier in strict mode", name));
  3350. if (m_program_type == Program::Type::Module && name == "await"sv)
  3351. syntax_error("'await' is not allowed as an identifier in module");
  3352. return consume();
  3353. }
  3354. // See note in Parser::parse_identifier().
  3355. if (match(TokenType::Let)) {
  3356. if (m_state.strict_mode)
  3357. syntax_error("'let' is not allowed as an identifier in strict mode");
  3358. return consume();
  3359. }
  3360. if (match(TokenType::Yield)) {
  3361. if (m_state.strict_mode)
  3362. syntax_error("Identifier reference may not be 'yield' in strict mode");
  3363. return consume();
  3364. }
  3365. if (match(TokenType::Await)) {
  3366. if (m_program_type == Program::Type::Module)
  3367. syntax_error("'await' is not allowed as an identifier in module");
  3368. return consume();
  3369. }
  3370. if (match(TokenType::Async))
  3371. return consume();
  3372. expected(Token::name(TokenType::Identifier));
  3373. return consume();
  3374. }
  3375. Token Parser::consume(TokenType expected_type)
  3376. {
  3377. if (!match(expected_type)) {
  3378. expected(Token::name(expected_type));
  3379. }
  3380. auto token = consume();
  3381. if (expected_type == TokenType::Identifier) {
  3382. if (m_state.strict_mode && is_strict_reserved_word(token.value()))
  3383. syntax_error(String::formatted("Identifier must not be a reserved word in strict mode ('{}')", token.value()));
  3384. }
  3385. return token;
  3386. }
  3387. Token Parser::consume_and_validate_numeric_literal()
  3388. {
  3389. auto is_unprefixed_octal_number = [](StringView value) {
  3390. return value.length() > 1 && value[0] == '0' && is_ascii_digit(value[1]);
  3391. };
  3392. auto literal_start = position();
  3393. auto token = consume(TokenType::NumericLiteral);
  3394. if (m_state.strict_mode && is_unprefixed_octal_number(token.value()))
  3395. syntax_error("Unprefixed octal number not allowed in strict mode", literal_start);
  3396. if (match_identifier_name() && m_state.current_token.trivia().is_empty())
  3397. syntax_error("Numeric literal must not be immediately followed by identifier");
  3398. return token;
  3399. }
  3400. void Parser::expected(const char* what)
  3401. {
  3402. auto message = m_state.current_token.message();
  3403. if (message.is_empty())
  3404. message = String::formatted("Unexpected token {}. Expected {}", m_state.current_token.name(), what);
  3405. syntax_error(message);
  3406. }
  3407. Position Parser::position() const
  3408. {
  3409. return {
  3410. m_state.current_token.line_number(),
  3411. m_state.current_token.line_column(),
  3412. m_state.current_token.offset(),
  3413. };
  3414. }
  3415. bool Parser::try_parse_arrow_function_expression_failed_at_position(const Position& position) const
  3416. {
  3417. auto it = m_token_memoizations.find(position);
  3418. if (it == m_token_memoizations.end())
  3419. return false;
  3420. return (*it).value.try_parse_arrow_function_expression_failed;
  3421. }
  3422. void Parser::set_try_parse_arrow_function_expression_failed_at_position(const Position& position, bool failed)
  3423. {
  3424. m_token_memoizations.set(position, { failed });
  3425. }
  3426. void Parser::syntax_error(const String& message, Optional<Position> position)
  3427. {
  3428. if (!position.has_value())
  3429. position = this->position();
  3430. m_state.errors.append({ message, position });
  3431. }
  3432. void Parser::save_state()
  3433. {
  3434. m_saved_state.append(m_state);
  3435. }
  3436. void Parser::load_state()
  3437. {
  3438. VERIFY(!m_saved_state.is_empty());
  3439. m_state = m_saved_state.take_last();
  3440. }
  3441. void Parser::discard_saved_state()
  3442. {
  3443. m_saved_state.take_last();
  3444. }
  3445. void Parser::check_identifier_name_for_assignment_validity(FlyString const& name, bool force_strict)
  3446. {
  3447. // FIXME: this is now called from multiple places maybe the error message should be dynamic?
  3448. if (any_of(s_reserved_words, [&](auto& value) { return name == value; })) {
  3449. syntax_error("Binding pattern target may not be a reserved word");
  3450. } else if (m_state.strict_mode || force_strict) {
  3451. if (name.is_one_of("arguments"sv, "eval"sv))
  3452. syntax_error("Binding pattern target may not be called 'arguments' or 'eval' in strict mode");
  3453. else if (is_strict_reserved_word(name))
  3454. syntax_error(String::formatted("Binding pattern target may not be called '{}' in strict mode", name));
  3455. }
  3456. }
  3457. bool Parser::match_assert_clause() const
  3458. {
  3459. return !m_state.current_token.trivia_contains_line_terminator() && m_state.current_token.original_value() == "assert"sv;
  3460. }
  3461. FlyString Parser::consume_string_value()
  3462. {
  3463. VERIFY(match(TokenType::StringLiteral));
  3464. auto string_token = consume();
  3465. FlyString value = parse_string_literal(string_token, false)->value();
  3466. // This also checks IsStringWellFormedUnicode which makes sure there is no unpaired surrogate
  3467. // Surrogates are at least 3 bytes
  3468. if (value.length() < 3)
  3469. return value;
  3470. Utf8View view { value.view().substring_view(value.length() - 3) };
  3471. VERIFY(view.length() <= 3);
  3472. auto codepoint = *view.begin();
  3473. if (Utf16View::is_high_surrogate(codepoint)) {
  3474. syntax_error("StringValue ending with unpaired high surrogate");
  3475. VERIFY(view.length() == 1);
  3476. }
  3477. return value;
  3478. }
  3479. // AssertClause, https://tc39.es/proposal-import-assertions/#prod-AssertClause
  3480. ModuleRequest Parser::parse_module_request()
  3481. {
  3482. // Does not include the 'from' since that is not always required.
  3483. if (!match(TokenType::StringLiteral)) {
  3484. expected("ModuleSpecifier (string)");
  3485. return ModuleRequest { "!!invalid!!" };
  3486. }
  3487. ModuleRequest request { consume_string_value() };
  3488. if (!match_assert_clause())
  3489. return request;
  3490. VERIFY(m_state.current_token.original_value() == "assert"sv);
  3491. consume(TokenType::Identifier);
  3492. consume(TokenType::CurlyOpen);
  3493. while (!done() && !match(TokenType::CurlyClose)) {
  3494. String key;
  3495. if (match(TokenType::StringLiteral)) {
  3496. key = parse_string_literal(m_state.current_token)->value().to_string();
  3497. consume();
  3498. } else if (match_identifier_name()) {
  3499. key = consume().value();
  3500. } else {
  3501. expected("IdentifierName or StringValue as AssertionKey");
  3502. consume();
  3503. }
  3504. consume(TokenType::Colon);
  3505. if (match(TokenType::StringLiteral)) {
  3506. for (auto& entries : request.assertions) {
  3507. if (entries.key == key)
  3508. syntax_error(String::formatted("Duplicate assertion clauses with name: {}", key));
  3509. }
  3510. request.add_assertion(move(key), parse_string_literal(m_state.current_token)->value().to_string());
  3511. }
  3512. consume(TokenType::StringLiteral);
  3513. if (match(TokenType::Comma))
  3514. consume(TokenType::Comma);
  3515. else
  3516. break;
  3517. }
  3518. consume(TokenType::CurlyClose);
  3519. return request;
  3520. }
  3521. static FlyString default_string_value = "default";
  3522. NonnullRefPtr<ImportStatement> Parser::parse_import_statement(Program& program)
  3523. {
  3524. // We use the extended syntax which adds:
  3525. // ImportDeclaration:
  3526. // import ImportClause FromClause [no LineTerminator here] AssertClause;
  3527. // import ModuleSpecifier [no LineTerminator here] AssertClause;
  3528. // From: https://tc39.es/proposal-import-assertions/#prod-ImportDeclaration
  3529. auto rule_start = push_start();
  3530. if (program.type() != Program::Type::Module)
  3531. syntax_error("Cannot use import statement outside a module");
  3532. consume(TokenType::Import);
  3533. if (match(TokenType::StringLiteral)) {
  3534. // import ModuleSpecifier ;
  3535. auto module_request = parse_module_request();
  3536. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(module_request));
  3537. }
  3538. auto match_imported_binding = [&] {
  3539. return match_identifier() || match(TokenType::Yield) || match(TokenType::Await);
  3540. };
  3541. auto match_as = [&] {
  3542. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3543. };
  3544. bool continue_parsing = true;
  3545. struct ImportWithLocation {
  3546. ImportStatement::ImportEntry entry;
  3547. Position position;
  3548. };
  3549. Vector<ImportWithLocation> entries_with_location;
  3550. // import ImportClause FromClause ;
  3551. // ImportClause :
  3552. // ImportedDefaultBinding
  3553. // NameSpaceImport
  3554. // NamedImports
  3555. // ImportedDefaultBinding , NameSpaceImport
  3556. // ImportedDefaultBinding , NamedImports
  3557. if (match_imported_binding()) {
  3558. // ImportedDefaultBinding : ImportedBinding
  3559. auto id_position = position();
  3560. auto bound_name = consume().value();
  3561. entries_with_location.append({ { default_string_value, bound_name }, id_position });
  3562. if (match(TokenType::Comma)) {
  3563. consume(TokenType::Comma);
  3564. } else {
  3565. continue_parsing = false;
  3566. }
  3567. }
  3568. if (!continue_parsing) {
  3569. // skip the rest
  3570. } else if (match(TokenType::Asterisk)) {
  3571. // NameSpaceImport : * as ImportedBinding
  3572. consume(TokenType::Asterisk);
  3573. if (!match_as())
  3574. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3575. consume(TokenType::Identifier);
  3576. if (match_imported_binding()) {
  3577. auto namespace_position = position();
  3578. auto namespace_name = consume().value();
  3579. entries_with_location.append({ ImportStatement::ImportEntry({}, namespace_name, true), namespace_position });
  3580. } else {
  3581. syntax_error(String::formatted("Unexpected token: {}", m_state.current_token.name()));
  3582. }
  3583. } else if (match(TokenType::CurlyOpen)) {
  3584. // NamedImports :
  3585. // { ImportSpecifier ,_opt } (repeated any amount of times)
  3586. consume(TokenType::CurlyOpen);
  3587. while (!done() && !match(TokenType::CurlyClose)) {
  3588. if (match_identifier_name()) {
  3589. // ImportSpecifier : ImportedBinding
  3590. auto require_as = !match_imported_binding();
  3591. auto name_position = position();
  3592. auto name = consume().flystring_value();
  3593. if (match_as()) {
  3594. consume(TokenType::Identifier);
  3595. auto alias_position = position();
  3596. auto alias = consume_identifier().flystring_value();
  3597. check_identifier_name_for_assignment_validity(alias);
  3598. entries_with_location.append({ { name, alias }, alias_position });
  3599. } else if (require_as) {
  3600. syntax_error(String::formatted("Unexpected reserved word '{}'", name));
  3601. } else {
  3602. check_identifier_name_for_assignment_validity(name);
  3603. entries_with_location.append({ { name, name }, name_position });
  3604. }
  3605. } else if (match(TokenType::StringLiteral)) {
  3606. // ImportSpecifier : ModuleExportName as ImportedBinding
  3607. auto name = consume_string_value();
  3608. if (!match_as())
  3609. expected("as");
  3610. consume(TokenType::Identifier);
  3611. auto alias_position = position();
  3612. auto alias = consume_identifier().flystring_value();
  3613. check_identifier_name_for_assignment_validity(alias);
  3614. entries_with_location.append({ { move(name), alias }, alias_position });
  3615. } else {
  3616. expected("identifier");
  3617. break;
  3618. }
  3619. if (!match(TokenType::Comma))
  3620. break;
  3621. consume(TokenType::Comma);
  3622. }
  3623. consume(TokenType::CurlyClose);
  3624. } else {
  3625. expected("import clauses");
  3626. }
  3627. auto from_statement = consume(TokenType::Identifier).original_value();
  3628. if (from_statement != "from"sv)
  3629. syntax_error(String::formatted("Expected 'from' got {}", from_statement));
  3630. auto module_request = parse_module_request();
  3631. Vector<ImportStatement::ImportEntry> entries;
  3632. entries.ensure_capacity(entries_with_location.size());
  3633. for (auto& entry : entries_with_location) {
  3634. for (auto& import_statement : program.imports()) {
  3635. if (import_statement.has_bound_name(entry.entry.local_name))
  3636. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3637. }
  3638. for (auto& new_entry : entries) {
  3639. if (new_entry.local_name == entry.entry.local_name)
  3640. syntax_error(String::formatted("Identifier '{}' already declared", entry.entry.local_name), entry.position);
  3641. }
  3642. entries.append(move(entry.entry));
  3643. }
  3644. return create_ast_node<ImportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(module_request), move(entries));
  3645. }
  3646. NonnullRefPtr<ExportStatement> Parser::parse_export_statement(Program& program)
  3647. {
  3648. using ExportEntry = ExportStatement::ExportEntry;
  3649. // We use the extended syntax which adds:
  3650. // ExportDeclaration:
  3651. // export ExportFromClause FromClause [no LineTerminator here] AssertClause ;
  3652. // From: https://tc39.es/proposal-import-assertions/#prod-ExportDeclaration
  3653. auto rule_start = push_start();
  3654. if (program.type() != Program::Type::Module)
  3655. syntax_error("Cannot use export statement outside a module");
  3656. auto match_as = [&] {
  3657. return match(TokenType::Identifier) && m_state.current_token.original_value() == "as"sv;
  3658. };
  3659. auto match_from = [&] {
  3660. return match(TokenType::Identifier) && m_state.current_token.original_value() == "from"sv;
  3661. };
  3662. auto match_default = [&] {
  3663. return match(TokenType::Default) && m_state.current_token.original_value() == "default"sv;
  3664. };
  3665. consume(TokenType::Export);
  3666. struct EntryAndLocation {
  3667. ExportEntry entry;
  3668. Position position;
  3669. };
  3670. Vector<EntryAndLocation> entries_with_location;
  3671. RefPtr<ASTNode> expression = {};
  3672. bool is_default = false;
  3673. ModuleRequest from_specifier;
  3674. if (match_default()) {
  3675. is_default = true;
  3676. auto default_position = position();
  3677. consume(TokenType::Default);
  3678. FlyString local_name;
  3679. auto lookahead_token = next_token();
  3680. // Note: For some reason the spec here has declaration which can have no name
  3681. // and the rest of the parser is just not setup for that. With these
  3682. // hacks below we get through most things but we should probably figure
  3683. // out a better solution. I have attempted to explain why/what these "hacks" do below.
  3684. // The summary is treat named declarations just as declarations and hack around unnamed
  3685. // declarations with expression see also SourceTextModule::initialize_environment.
  3686. // As far as I'm aware the only problem (which is a tricky one) is:
  3687. // `export default function() {}()`
  3688. // Since we parse this as an expression you are immediately allowed to call it
  3689. // which is incorrect and this should give a SyntaxError.
  3690. auto match_function_declaration = [&] {
  3691. // Hack part 1.
  3692. // Match a function declaration with a name, since we have async and generator
  3693. // and asyncgenerator variants this is quite complicated.
  3694. auto current_type = m_state.current_token.type();
  3695. Lexer lookahead_lexer = m_state.lexer;
  3696. lookahead_lexer.next();
  3697. if (current_type == TokenType::Function) {
  3698. if (lookahead_token.type() == TokenType::Asterisk)
  3699. return lookahead_lexer.next().type() != TokenType::ParenOpen; // function * <name>
  3700. else
  3701. return lookahead_token.type() != TokenType::ParenOpen; // function <name>
  3702. }
  3703. if (current_type == TokenType::Async) {
  3704. if (lookahead_token.type() != TokenType::Function)
  3705. return false;
  3706. if (lookahead_token.trivia_contains_line_terminator())
  3707. return false;
  3708. auto lookahead_two_token = lookahead_lexer.next();
  3709. if (lookahead_two_token.type() == TokenType::Asterisk)
  3710. return lookahead_lexer.next().type() != TokenType::ParenOpen; // async function * <name>
  3711. else
  3712. return lookahead_two_token.type() != TokenType::ParenOpen; // async function <name>
  3713. }
  3714. return false;
  3715. };
  3716. if (match_function_declaration()) {
  3717. auto function_declaration = parse_function_node<FunctionDeclaration>();
  3718. m_state.current_scope_pusher->add_declaration(function_declaration);
  3719. local_name = function_declaration->name();
  3720. expression = move(function_declaration);
  3721. } else if (match(TokenType::Class) && lookahead_token.type() != TokenType::CurlyOpen && lookahead_token.type() != TokenType::Extends) {
  3722. // Hack part 2.
  3723. // Attempt to detect classes with names only as those are declarations,
  3724. // this actually seems to cover all cases already.
  3725. auto class_expression = parse_class_declaration();
  3726. m_state.current_scope_pusher->add_declaration(class_expression);
  3727. local_name = class_expression->name();
  3728. expression = move(class_expression);
  3729. } else if (match_expression()) {
  3730. // Hack part 3.
  3731. // Even though the unnamed declarations look like expression we should
  3732. // not treat them as such and thus not consume a semicolon after them.
  3733. bool special_case_declaration_without_name = match(TokenType::Class) || match(TokenType::Function) || (match(TokenType::Async) && lookahead_token.type() == TokenType::Function && !lookahead_token.trivia_contains_line_terminator());
  3734. expression = parse_expression(2);
  3735. if (!special_case_declaration_without_name)
  3736. consume_or_insert_semicolon();
  3737. if (is<ClassExpression>(*expression)) {
  3738. auto const& class_expression = static_cast<ClassExpression&>(*expression);
  3739. if (class_expression.has_name())
  3740. local_name = class_expression.name();
  3741. }
  3742. } else {
  3743. expected("Declaration or assignment expression");
  3744. local_name = "!!invalid!!";
  3745. }
  3746. if (local_name.is_null()) {
  3747. local_name = ExportStatement::local_name_for_default;
  3748. }
  3749. entries_with_location.append({ ExportEntry::named_export(default_string_value, move(local_name)), default_position });
  3750. } else {
  3751. enum FromSpecifier {
  3752. NotAllowed,
  3753. Optional,
  3754. Required
  3755. } check_for_from { NotAllowed };
  3756. if (match(TokenType::Asterisk)) {
  3757. auto asterisk_position = position();
  3758. consume(TokenType::Asterisk);
  3759. if (match_as()) {
  3760. consume(TokenType::Identifier);
  3761. if (match_identifier_name()) {
  3762. auto namespace_position = position();
  3763. auto exported_name = consume().value();
  3764. entries_with_location.append({ ExportEntry::all_module_request(exported_name), namespace_position });
  3765. } else {
  3766. expected("identifier");
  3767. }
  3768. } else {
  3769. entries_with_location.append({ ExportEntry::all_but_default_entry(), asterisk_position });
  3770. }
  3771. check_for_from = Required;
  3772. } else if (match_declaration()) {
  3773. auto decl_position = position();
  3774. auto declaration = parse_declaration();
  3775. m_state.current_scope_pusher->add_declaration(declaration);
  3776. if (is<FunctionDeclaration>(*declaration)) {
  3777. auto& func = static_cast<FunctionDeclaration&>(*declaration);
  3778. entries_with_location.append({ ExportEntry::named_export(func.name(), func.name()), func.source_range().start });
  3779. } else if (is<ClassDeclaration>(*declaration)) {
  3780. auto& class_declaration = static_cast<ClassDeclaration&>(*declaration);
  3781. entries_with_location.append({ ExportEntry::named_export(class_declaration.name(), class_declaration.name()), class_declaration.source_range().start });
  3782. } else {
  3783. VERIFY(is<VariableDeclaration>(*declaration));
  3784. auto& variables = static_cast<VariableDeclaration&>(*declaration);
  3785. VERIFY(variables.is_lexical_declaration());
  3786. for (auto& decl : variables.declarations()) {
  3787. decl.target().visit(
  3788. [&](NonnullRefPtr<Identifier> const& identifier) {
  3789. entries_with_location.append({ ExportEntry::named_export(identifier->string(), identifier->string()), identifier->source_range().start });
  3790. },
  3791. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3792. binding->for_each_bound_name([&](auto& name) {
  3793. entries_with_location.append({ ExportEntry::named_export(name, name), decl_position });
  3794. });
  3795. });
  3796. }
  3797. }
  3798. expression = declaration;
  3799. } else if (match(TokenType::Var)) {
  3800. auto variable_position = position();
  3801. auto variable_declaration = parse_variable_declaration();
  3802. m_state.current_scope_pusher->add_declaration(variable_declaration);
  3803. for (auto& decl : variable_declaration->declarations()) {
  3804. decl.target().visit(
  3805. [&](NonnullRefPtr<Identifier> const& identifier) {
  3806. entries_with_location.append({ ExportEntry::named_export(identifier->string(), identifier->string()), identifier->source_range().start });
  3807. },
  3808. [&](NonnullRefPtr<BindingPattern> const& binding) {
  3809. binding->for_each_bound_name([&](auto& name) {
  3810. entries_with_location.append({ ExportEntry::named_export(name, name), variable_position });
  3811. });
  3812. });
  3813. }
  3814. expression = variable_declaration;
  3815. } else if (match(TokenType::CurlyOpen)) {
  3816. consume(TokenType::CurlyOpen);
  3817. check_for_from = Optional;
  3818. auto parse_export_specifier = [&](bool lhs) -> FlyString {
  3819. if (match_identifier_name()) {
  3820. return consume().value();
  3821. }
  3822. if (match(TokenType::StringLiteral)) {
  3823. // It is a Syntax Error if ReferencedBindings of NamedExports contains any StringLiterals.
  3824. // Only for export { "a" as "b" }; // <-- no from
  3825. if (lhs)
  3826. check_for_from = Required;
  3827. return consume_string_value();
  3828. }
  3829. expected("ExportSpecifier (string or identifier)");
  3830. return {};
  3831. };
  3832. while (!done() && !match(TokenType::CurlyClose)) {
  3833. auto identifier_position = position();
  3834. auto identifier = parse_export_specifier(true);
  3835. if (match_as()) {
  3836. consume(TokenType::Identifier);
  3837. auto export_name = parse_export_specifier(false);
  3838. entries_with_location.append({ ExportEntry::named_export(move(export_name), move(identifier)), identifier_position });
  3839. } else {
  3840. entries_with_location.append({ ExportEntry::named_export(identifier, identifier), identifier_position });
  3841. }
  3842. if (!match(TokenType::Comma))
  3843. break;
  3844. consume(TokenType::Comma);
  3845. }
  3846. consume(TokenType::CurlyClose);
  3847. } else {
  3848. syntax_error("Unexpected token 'export'", rule_start.position());
  3849. }
  3850. if (check_for_from != NotAllowed && match_from()) {
  3851. consume(TokenType::Identifier);
  3852. from_specifier = parse_module_request();
  3853. } else if (check_for_from == Required) {
  3854. expected("from");
  3855. }
  3856. if (check_for_from != NotAllowed)
  3857. consume_or_insert_semicolon();
  3858. }
  3859. Vector<ExportStatement::ExportEntry> entries;
  3860. entries.ensure_capacity(entries_with_location.size());
  3861. for (auto& entry : entries_with_location) {
  3862. for (auto& export_statement : program.exports()) {
  3863. if (export_statement.has_export(entry.entry.export_name))
  3864. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3865. }
  3866. for (auto& new_entry : entries) {
  3867. if (new_entry.export_name == entry.entry.export_name)
  3868. syntax_error(String::formatted("Duplicate export with name: '{}'", entry.entry.export_name), entry.position);
  3869. }
  3870. entries.append(move(entry.entry));
  3871. }
  3872. return create_ast_node<ExportStatement>({ m_state.current_token.filename(), rule_start.position(), position() }, move(expression), move(entries), is_default, move(from_specifier));
  3873. }
  3874. Parser::ForbiddenTokens::ForbiddenTokens(std::initializer_list<TokenType> const& forbidden)
  3875. {
  3876. forbid_tokens(forbidden);
  3877. }
  3878. void Parser::ForbiddenTokens::forbid_tokens(std::initializer_list<TokenType> const& forbidden)
  3879. {
  3880. for (auto token : forbidden) {
  3881. switch (token) {
  3882. case TokenType::In:
  3883. m_forbid_in_token = true;
  3884. break;
  3885. case TokenType::DoubleAmpersand:
  3886. case TokenType::DoublePipe:
  3887. m_forbid_logical_tokens = true;
  3888. break;
  3889. case TokenType::DoubleQuestionMark:
  3890. m_forbid_coalesce_token = true;
  3891. break;
  3892. case TokenType::QuestionMarkPeriod:
  3893. m_forbid_question_mark_period = true;
  3894. break;
  3895. case TokenType::ParenOpen:
  3896. m_forbid_paren_open = true;
  3897. break;
  3898. case TokenType::Equals:
  3899. m_forbid_equals = true;
  3900. break;
  3901. default:
  3902. VERIFY_NOT_REACHED();
  3903. }
  3904. }
  3905. }
  3906. bool Parser::ForbiddenTokens::allows(TokenType token) const
  3907. {
  3908. switch (token) {
  3909. case TokenType::In:
  3910. return !m_forbid_in_token;
  3911. case TokenType::DoubleAmpersand:
  3912. case TokenType::DoublePipe:
  3913. return !m_forbid_logical_tokens;
  3914. case TokenType::DoubleQuestionMark:
  3915. return !m_forbid_coalesce_token;
  3916. case TokenType::QuestionMarkPeriod:
  3917. return !m_forbid_question_mark_period;
  3918. case TokenType::ParenOpen:
  3919. return !m_forbid_paren_open;
  3920. case TokenType::Equals:
  3921. return !m_forbid_equals;
  3922. default:
  3923. return true;
  3924. }
  3925. }
  3926. Parser::ForbiddenTokens Parser::ForbiddenTokens::merge(ForbiddenTokens other) const
  3927. {
  3928. ForbiddenTokens result = *this;
  3929. result.m_forbid_in_token |= other.m_forbid_in_token;
  3930. result.m_forbid_logical_tokens |= other.m_forbid_logical_tokens;
  3931. result.m_forbid_coalesce_token |= other.m_forbid_coalesce_token;
  3932. result.m_forbid_paren_open |= other.m_forbid_paren_open;
  3933. result.m_forbid_question_mark_period |= other.m_forbid_question_mark_period;
  3934. result.m_forbid_equals |= other.m_forbid_equals;
  3935. return result;
  3936. }
  3937. Parser::ForbiddenTokens Parser::ForbiddenTokens::forbid(std::initializer_list<TokenType> const& forbidden) const
  3938. {
  3939. ForbiddenTokens result = *this;
  3940. result.forbid_tokens(forbidden);
  3941. return result;
  3942. }
  3943. }