Parser.cpp 204 KB

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