Parser.cpp 185 KB

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