Parser.cpp 185 KB

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