Parser.cpp 175 KB

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