Parser.cpp 164 KB

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