Parser.cpp 199 KB

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