Parser.cpp 221 KB

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