Parser.cpp 186 KB

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