index.js 411 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. const beforeExpr = true;
  4. const startsExpr = true;
  5. const isLoop = true;
  6. const isAssign = true;
  7. const prefix = true;
  8. const postfix = true;
  9. class TokenType {
  10. constructor(label, conf = {}) {
  11. this.label = void 0;
  12. this.keyword = void 0;
  13. this.beforeExpr = void 0;
  14. this.startsExpr = void 0;
  15. this.rightAssociative = void 0;
  16. this.isLoop = void 0;
  17. this.isAssign = void 0;
  18. this.prefix = void 0;
  19. this.postfix = void 0;
  20. this.binop = void 0;
  21. this.updateContext = void 0;
  22. this.label = label;
  23. this.keyword = conf.keyword;
  24. this.beforeExpr = !!conf.beforeExpr;
  25. this.startsExpr = !!conf.startsExpr;
  26. this.rightAssociative = !!conf.rightAssociative;
  27. this.isLoop = !!conf.isLoop;
  28. this.isAssign = !!conf.isAssign;
  29. this.prefix = !!conf.prefix;
  30. this.postfix = !!conf.postfix;
  31. this.binop = conf.binop != null ? conf.binop : null;
  32. this.updateContext = null;
  33. }
  34. }
  35. const keywords = new Map();
  36. function createKeyword(name, options = {}) {
  37. options.keyword = name;
  38. const token = new TokenType(name, options);
  39. keywords.set(name, token);
  40. return token;
  41. }
  42. function createBinop(name, binop) {
  43. return new TokenType(name, {
  44. beforeExpr,
  45. binop
  46. });
  47. }
  48. const types = {
  49. num: new TokenType("num", {
  50. startsExpr
  51. }),
  52. bigint: new TokenType("bigint", {
  53. startsExpr
  54. }),
  55. decimal: new TokenType("decimal", {
  56. startsExpr
  57. }),
  58. regexp: new TokenType("regexp", {
  59. startsExpr
  60. }),
  61. string: new TokenType("string", {
  62. startsExpr
  63. }),
  64. name: new TokenType("name", {
  65. startsExpr
  66. }),
  67. eof: new TokenType("eof"),
  68. bracketL: new TokenType("[", {
  69. beforeExpr,
  70. startsExpr
  71. }),
  72. bracketHashL: new TokenType("#[", {
  73. beforeExpr,
  74. startsExpr
  75. }),
  76. bracketBarL: new TokenType("[|", {
  77. beforeExpr,
  78. startsExpr
  79. }),
  80. bracketR: new TokenType("]"),
  81. bracketBarR: new TokenType("|]"),
  82. braceL: new TokenType("{", {
  83. beforeExpr,
  84. startsExpr
  85. }),
  86. braceBarL: new TokenType("{|", {
  87. beforeExpr,
  88. startsExpr
  89. }),
  90. braceHashL: new TokenType("#{", {
  91. beforeExpr,
  92. startsExpr
  93. }),
  94. braceR: new TokenType("}"),
  95. braceBarR: new TokenType("|}"),
  96. parenL: new TokenType("(", {
  97. beforeExpr,
  98. startsExpr
  99. }),
  100. parenR: new TokenType(")"),
  101. comma: new TokenType(",", {
  102. beforeExpr
  103. }),
  104. semi: new TokenType(";", {
  105. beforeExpr
  106. }),
  107. colon: new TokenType(":", {
  108. beforeExpr
  109. }),
  110. doubleColon: new TokenType("::", {
  111. beforeExpr
  112. }),
  113. dot: new TokenType("."),
  114. question: new TokenType("?", {
  115. beforeExpr
  116. }),
  117. questionDot: new TokenType("?."),
  118. arrow: new TokenType("=>", {
  119. beforeExpr
  120. }),
  121. template: new TokenType("template"),
  122. ellipsis: new TokenType("...", {
  123. beforeExpr
  124. }),
  125. backQuote: new TokenType("`", {
  126. startsExpr
  127. }),
  128. dollarBraceL: new TokenType("${", {
  129. beforeExpr,
  130. startsExpr
  131. }),
  132. at: new TokenType("@"),
  133. hash: new TokenType("#", {
  134. startsExpr
  135. }),
  136. interpreterDirective: new TokenType("#!..."),
  137. eq: new TokenType("=", {
  138. beforeExpr,
  139. isAssign
  140. }),
  141. assign: new TokenType("_=", {
  142. beforeExpr,
  143. isAssign
  144. }),
  145. incDec: new TokenType("++/--", {
  146. prefix,
  147. postfix,
  148. startsExpr
  149. }),
  150. bang: new TokenType("!", {
  151. beforeExpr,
  152. prefix,
  153. startsExpr
  154. }),
  155. tilde: new TokenType("~", {
  156. beforeExpr,
  157. prefix,
  158. startsExpr
  159. }),
  160. pipeline: createBinop("|>", 0),
  161. nullishCoalescing: createBinop("??", 1),
  162. logicalOR: createBinop("||", 1),
  163. logicalAND: createBinop("&&", 2),
  164. bitwiseOR: createBinop("|", 3),
  165. bitwiseXOR: createBinop("^", 4),
  166. bitwiseAND: createBinop("&", 5),
  167. equality: createBinop("==/!=/===/!==", 6),
  168. relational: createBinop("</>/<=/>=", 7),
  169. bitShift: createBinop("<</>>/>>>", 8),
  170. plusMin: new TokenType("+/-", {
  171. beforeExpr,
  172. binop: 9,
  173. prefix,
  174. startsExpr
  175. }),
  176. modulo: new TokenType("%", {
  177. beforeExpr,
  178. binop: 10,
  179. startsExpr
  180. }),
  181. star: new TokenType("*", {
  182. binop: 10
  183. }),
  184. slash: createBinop("/", 10),
  185. exponent: new TokenType("**", {
  186. beforeExpr,
  187. binop: 11,
  188. rightAssociative: true
  189. }),
  190. _break: createKeyword("break"),
  191. _case: createKeyword("case", {
  192. beforeExpr
  193. }),
  194. _catch: createKeyword("catch"),
  195. _continue: createKeyword("continue"),
  196. _debugger: createKeyword("debugger"),
  197. _default: createKeyword("default", {
  198. beforeExpr
  199. }),
  200. _do: createKeyword("do", {
  201. isLoop,
  202. beforeExpr
  203. }),
  204. _else: createKeyword("else", {
  205. beforeExpr
  206. }),
  207. _finally: createKeyword("finally"),
  208. _for: createKeyword("for", {
  209. isLoop
  210. }),
  211. _function: createKeyword("function", {
  212. startsExpr
  213. }),
  214. _if: createKeyword("if"),
  215. _return: createKeyword("return", {
  216. beforeExpr
  217. }),
  218. _switch: createKeyword("switch"),
  219. _throw: createKeyword("throw", {
  220. beforeExpr,
  221. prefix,
  222. startsExpr
  223. }),
  224. _try: createKeyword("try"),
  225. _var: createKeyword("var"),
  226. _const: createKeyword("const"),
  227. _while: createKeyword("while", {
  228. isLoop
  229. }),
  230. _with: createKeyword("with"),
  231. _new: createKeyword("new", {
  232. beforeExpr,
  233. startsExpr
  234. }),
  235. _this: createKeyword("this", {
  236. startsExpr
  237. }),
  238. _super: createKeyword("super", {
  239. startsExpr
  240. }),
  241. _class: createKeyword("class", {
  242. startsExpr
  243. }),
  244. _extends: createKeyword("extends", {
  245. beforeExpr
  246. }),
  247. _export: createKeyword("export"),
  248. _import: createKeyword("import", {
  249. startsExpr
  250. }),
  251. _null: createKeyword("null", {
  252. startsExpr
  253. }),
  254. _true: createKeyword("true", {
  255. startsExpr
  256. }),
  257. _false: createKeyword("false", {
  258. startsExpr
  259. }),
  260. _in: createKeyword("in", {
  261. beforeExpr,
  262. binop: 7
  263. }),
  264. _instanceof: createKeyword("instanceof", {
  265. beforeExpr,
  266. binop: 7
  267. }),
  268. _typeof: createKeyword("typeof", {
  269. beforeExpr,
  270. prefix,
  271. startsExpr
  272. }),
  273. _void: createKeyword("void", {
  274. beforeExpr,
  275. prefix,
  276. startsExpr
  277. }),
  278. _delete: createKeyword("delete", {
  279. beforeExpr,
  280. prefix,
  281. startsExpr
  282. })
  283. };
  284. const lineBreak = /\r\n?|[\n\u2028\u2029]/;
  285. const lineBreakG = new RegExp(lineBreak.source, "g");
  286. function isNewLine(code) {
  287. switch (code) {
  288. case 10:
  289. case 13:
  290. case 8232:
  291. case 8233:
  292. return true;
  293. default:
  294. return false;
  295. }
  296. }
  297. const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  298. function isWhitespace(code) {
  299. switch (code) {
  300. case 0x0009:
  301. case 0x000b:
  302. case 0x000c:
  303. case 32:
  304. case 160:
  305. case 5760:
  306. case 0x2000:
  307. case 0x2001:
  308. case 0x2002:
  309. case 0x2003:
  310. case 0x2004:
  311. case 0x2005:
  312. case 0x2006:
  313. case 0x2007:
  314. case 0x2008:
  315. case 0x2009:
  316. case 0x200a:
  317. case 0x202f:
  318. case 0x205f:
  319. case 0x3000:
  320. case 0xfeff:
  321. return true;
  322. default:
  323. return false;
  324. }
  325. }
  326. class Position {
  327. constructor(line, col) {
  328. this.line = void 0;
  329. this.column = void 0;
  330. this.line = line;
  331. this.column = col;
  332. }
  333. }
  334. class SourceLocation {
  335. constructor(start, end) {
  336. this.start = void 0;
  337. this.end = void 0;
  338. this.filename = void 0;
  339. this.identifierName = void 0;
  340. this.start = start;
  341. this.end = end;
  342. }
  343. }
  344. function getLineInfo(input, offset) {
  345. let line = 1;
  346. let lineStart = 0;
  347. let match;
  348. lineBreakG.lastIndex = 0;
  349. while ((match = lineBreakG.exec(input)) && match.index < offset) {
  350. line++;
  351. lineStart = lineBreakG.lastIndex;
  352. }
  353. return new Position(line, offset - lineStart);
  354. }
  355. class BaseParser {
  356. constructor() {
  357. this.sawUnambiguousESM = false;
  358. this.ambiguousScriptDifferentAst = false;
  359. }
  360. hasPlugin(name) {
  361. return this.plugins.has(name);
  362. }
  363. getPluginOption(plugin, name) {
  364. if (this.hasPlugin(plugin)) return this.plugins.get(plugin)[name];
  365. }
  366. }
  367. function last(stack) {
  368. return stack[stack.length - 1];
  369. }
  370. class CommentsParser extends BaseParser {
  371. addComment(comment) {
  372. if (this.filename) comment.loc.filename = this.filename;
  373. this.state.trailingComments.push(comment);
  374. this.state.leadingComments.push(comment);
  375. }
  376. adjustCommentsAfterTrailingComma(node, elements, takeAllComments) {
  377. if (this.state.leadingComments.length === 0) {
  378. return;
  379. }
  380. let lastElement = null;
  381. let i = elements.length;
  382. while (lastElement === null && i > 0) {
  383. lastElement = elements[--i];
  384. }
  385. if (lastElement === null) {
  386. return;
  387. }
  388. for (let j = 0; j < this.state.leadingComments.length; j++) {
  389. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  390. this.state.leadingComments.splice(j, 1);
  391. j--;
  392. }
  393. }
  394. const newTrailingComments = [];
  395. for (let i = 0; i < this.state.leadingComments.length; i++) {
  396. const leadingComment = this.state.leadingComments[i];
  397. if (leadingComment.end < node.end) {
  398. newTrailingComments.push(leadingComment);
  399. if (!takeAllComments) {
  400. this.state.leadingComments.splice(i, 1);
  401. i--;
  402. }
  403. } else {
  404. if (node.trailingComments === undefined) {
  405. node.trailingComments = [];
  406. }
  407. node.trailingComments.push(leadingComment);
  408. }
  409. }
  410. if (takeAllComments) this.state.leadingComments = [];
  411. if (newTrailingComments.length > 0) {
  412. lastElement.trailingComments = newTrailingComments;
  413. } else if (lastElement.trailingComments !== undefined) {
  414. lastElement.trailingComments = [];
  415. }
  416. }
  417. processComment(node) {
  418. if (node.type === "Program" && node.body.length > 0) return;
  419. const stack = this.state.commentStack;
  420. let firstChild, lastChild, trailingComments, i, j;
  421. if (this.state.trailingComments.length > 0) {
  422. if (this.state.trailingComments[0].start >= node.end) {
  423. trailingComments = this.state.trailingComments;
  424. this.state.trailingComments = [];
  425. } else {
  426. this.state.trailingComments.length = 0;
  427. }
  428. } else if (stack.length > 0) {
  429. const lastInStack = last(stack);
  430. if (lastInStack.trailingComments && lastInStack.trailingComments[0].start >= node.end) {
  431. trailingComments = lastInStack.trailingComments;
  432. delete lastInStack.trailingComments;
  433. }
  434. }
  435. if (stack.length > 0 && last(stack).start >= node.start) {
  436. firstChild = stack.pop();
  437. }
  438. while (stack.length > 0 && last(stack).start >= node.start) {
  439. lastChild = stack.pop();
  440. }
  441. if (!lastChild && firstChild) lastChild = firstChild;
  442. if (firstChild) {
  443. switch (node.type) {
  444. case "ObjectExpression":
  445. this.adjustCommentsAfterTrailingComma(node, node.properties);
  446. break;
  447. case "ObjectPattern":
  448. this.adjustCommentsAfterTrailingComma(node, node.properties, true);
  449. break;
  450. case "CallExpression":
  451. this.adjustCommentsAfterTrailingComma(node, node.arguments);
  452. break;
  453. case "ArrayExpression":
  454. this.adjustCommentsAfterTrailingComma(node, node.elements);
  455. break;
  456. case "ArrayPattern":
  457. this.adjustCommentsAfterTrailingComma(node, node.elements, true);
  458. break;
  459. }
  460. } else if (this.state.commentPreviousNode && (this.state.commentPreviousNode.type === "ImportSpecifier" && node.type !== "ImportSpecifier" || this.state.commentPreviousNode.type === "ExportSpecifier" && node.type !== "ExportSpecifier")) {
  461. this.adjustCommentsAfterTrailingComma(node, [this.state.commentPreviousNode]);
  462. }
  463. if (lastChild) {
  464. if (lastChild.leadingComments) {
  465. if (lastChild !== node && lastChild.leadingComments.length > 0 && last(lastChild.leadingComments).end <= node.start) {
  466. node.leadingComments = lastChild.leadingComments;
  467. delete lastChild.leadingComments;
  468. } else {
  469. for (i = lastChild.leadingComments.length - 2; i >= 0; --i) {
  470. if (lastChild.leadingComments[i].end <= node.start) {
  471. node.leadingComments = lastChild.leadingComments.splice(0, i + 1);
  472. break;
  473. }
  474. }
  475. }
  476. }
  477. } else if (this.state.leadingComments.length > 0) {
  478. if (last(this.state.leadingComments).end <= node.start) {
  479. if (this.state.commentPreviousNode) {
  480. for (j = 0; j < this.state.leadingComments.length; j++) {
  481. if (this.state.leadingComments[j].end < this.state.commentPreviousNode.end) {
  482. this.state.leadingComments.splice(j, 1);
  483. j--;
  484. }
  485. }
  486. }
  487. if (this.state.leadingComments.length > 0) {
  488. node.leadingComments = this.state.leadingComments;
  489. this.state.leadingComments = [];
  490. }
  491. } else {
  492. for (i = 0; i < this.state.leadingComments.length; i++) {
  493. if (this.state.leadingComments[i].end > node.start) {
  494. break;
  495. }
  496. }
  497. const leadingComments = this.state.leadingComments.slice(0, i);
  498. if (leadingComments.length) {
  499. node.leadingComments = leadingComments;
  500. }
  501. trailingComments = this.state.leadingComments.slice(i);
  502. if (trailingComments.length === 0) {
  503. trailingComments = null;
  504. }
  505. }
  506. }
  507. this.state.commentPreviousNode = node;
  508. if (trailingComments) {
  509. if (trailingComments.length && trailingComments[0].start >= node.start && last(trailingComments).end <= node.end) {
  510. node.innerComments = trailingComments;
  511. } else {
  512. const firstTrailingCommentIndex = trailingComments.findIndex(comment => comment.end >= node.end);
  513. if (firstTrailingCommentIndex > 0) {
  514. node.innerComments = trailingComments.slice(0, firstTrailingCommentIndex);
  515. node.trailingComments = trailingComments.slice(firstTrailingCommentIndex);
  516. } else {
  517. node.trailingComments = trailingComments;
  518. }
  519. }
  520. }
  521. stack.push(node);
  522. }
  523. }
  524. const ErrorMessages = Object.freeze({
  525. AccessorIsGenerator: "A %0ter cannot be a generator",
  526. ArgumentsInClass: "'arguments' is only allowed in functions and class methods",
  527. AsyncFunctionInSingleStatementContext: "Async functions can only be declared at the top level or inside a block",
  528. AwaitBindingIdentifier: "Can not use 'await' as identifier inside an async function",
  529. AwaitBindingIdentifierInStaticBlock: "Can not use 'await' as identifier inside a static block",
  530. AwaitExpressionFormalParameter: "await is not allowed in async function parameters",
  531. AwaitNotInAsyncContext: "'await' is only allowed within async functions and at the top levels of modules",
  532. AwaitNotInAsyncFunction: "'await' is only allowed within async functions",
  533. BadGetterArity: "getter must not have any formal parameters",
  534. BadSetterArity: "setter must have exactly one formal parameter",
  535. BadSetterRestParameter: "setter function argument must not be a rest parameter",
  536. ConstructorClassField: "Classes may not have a field named 'constructor'",
  537. ConstructorClassPrivateField: "Classes may not have a private field named '#constructor'",
  538. ConstructorIsAccessor: "Class constructor may not be an accessor",
  539. ConstructorIsAsync: "Constructor can't be an async function",
  540. ConstructorIsGenerator: "Constructor can't be a generator",
  541. DeclarationMissingInitializer: "%0 require an initialization value",
  542. DecoratorBeforeExport: "Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",
  543. DecoratorConstructor: "Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",
  544. DecoratorExportClass: "Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",
  545. DecoratorSemicolon: "Decorators must not be followed by a semicolon",
  546. DecoratorStaticBlock: "Decorators can't be used with a static block",
  547. DeletePrivateField: "Deleting a private field is not allowed",
  548. DestructureNamedImport: "ES2015 named imports do not destructure. Use another statement for destructuring after the import.",
  549. DuplicateConstructor: "Duplicate constructor in the same class",
  550. DuplicateDefaultExport: "Only one default export allowed per module.",
  551. DuplicateExport: "`%0` has already been exported. Exported identifiers must be unique.",
  552. DuplicateProto: "Redefinition of __proto__ property",
  553. DuplicateRegExpFlags: "Duplicate regular expression flag",
  554. ElementAfterRest: "Rest element must be last element",
  555. EscapedCharNotAnIdentifier: "Invalid Unicode escape",
  556. ExportBindingIsString: "A string literal cannot be used as an exported binding without `from`.\n- Did you mean `export { '%0' as '%1' } from 'some-module'`?",
  557. ExportDefaultFromAsIdentifier: "'from' is not allowed as an identifier after 'export default'",
  558. ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
  559. ForOfLet: "The left-hand side of a for-of loop may not start with 'let'.",
  560. GeneratorInSingleStatementContext: "Generators can only be declared at the top level or inside a block",
  561. IllegalBreakContinue: "Unsyntactic %0",
  562. IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
  563. IllegalReturn: "'return' outside of function",
  564. ImportBindingIsString: 'A string literal cannot be used as an imported binding.\n- Did you mean `import { "%0" as foo }`?',
  565. ImportCallArgumentTrailingComma: "Trailing comma is disallowed inside import(...) arguments",
  566. ImportCallArity: "import() requires exactly %0",
  567. ImportCallNotNewExpression: "Cannot use new with import(...)",
  568. ImportCallSpreadArgument: "... is not allowed in import()",
  569. ImportMetaOutsideModule: `import.meta may appear only with 'sourceType: "module"'`,
  570. ImportOutsideModule: `'import' and 'export' may appear only with 'sourceType: "module"'`,
  571. InvalidBigIntLiteral: "Invalid BigIntLiteral",
  572. InvalidCodePoint: "Code point out of bounds",
  573. InvalidDecimal: "Invalid decimal",
  574. InvalidDigit: "Expected number in radix %0",
  575. InvalidEscapeSequence: "Bad character escape sequence",
  576. InvalidEscapeSequenceTemplate: "Invalid escape sequence in template",
  577. InvalidEscapedReservedWord: "Escape sequence in keyword %0",
  578. InvalidIdentifier: "Invalid identifier %0",
  579. InvalidLhs: "Invalid left-hand side in %0",
  580. InvalidLhsBinding: "Binding invalid left-hand side in %0",
  581. InvalidNumber: "Invalid number",
  582. InvalidOrMissingExponent: "Floating-point numbers require a valid exponent after the 'e'",
  583. InvalidOrUnexpectedToken: "Unexpected character '%0'",
  584. InvalidParenthesizedAssignment: "Invalid parenthesized assignment pattern",
  585. InvalidPrivateFieldResolution: "Private name #%0 is not defined",
  586. InvalidPropertyBindingPattern: "Binding member expression",
  587. InvalidRecordProperty: "Only properties and spread elements are allowed in record definitions",
  588. InvalidRestAssignmentPattern: "Invalid rest operator's argument",
  589. LabelRedeclaration: "Label '%0' is already declared",
  590. LetInLexicalBinding: "'let' is not allowed to be used as a name in 'let' or 'const' declarations.",
  591. LineTerminatorBeforeArrow: "No line break is allowed before '=>'",
  592. MalformedRegExpFlags: "Invalid regular expression flag",
  593. MissingClassName: "A class name is required",
  594. MissingEqInAssignment: "Only '=' operator can be used for specifying default value.",
  595. MissingSemicolon: "Missing semicolon",
  596. MissingUnicodeEscape: "Expecting Unicode escape sequence \\uXXXX",
  597. MixingCoalesceWithLogical: "Nullish coalescing operator(??) requires parens when mixing with logical operators",
  598. ModuleAttributeDifferentFromType: "The only accepted module attribute is `type`",
  599. ModuleAttributeInvalidValue: "Only string literals are allowed as module attribute values",
  600. ModuleAttributesWithDuplicateKeys: 'Duplicate key "%0" is not allowed in module attributes',
  601. ModuleExportNameHasLoneSurrogate: "An export name cannot include a lone surrogate, found '\\u%0'",
  602. ModuleExportUndefined: "Export '%0' is not defined",
  603. MultipleDefaultsInSwitch: "Multiple default clauses",
  604. NewlineAfterThrow: "Illegal newline after throw",
  605. NoCatchOrFinally: "Missing catch or finally clause",
  606. NumberIdentifier: "Identifier directly after number",
  607. NumericSeparatorInEscapeSequence: "Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",
  608. ObsoleteAwaitStar: "await* has been removed from the async functions proposal. Use Promise.all() instead.",
  609. OptionalChainingNoNew: "constructors in/after an Optional Chain are not allowed",
  610. OptionalChainingNoTemplate: "Tagged Template Literals are not allowed in optionalChain",
  611. ParamDupe: "Argument name clash",
  612. PatternHasAccessor: "Object pattern can't contain getter or setter",
  613. PatternHasMethod: "Object pattern can't contain methods",
  614. PipelineBodyNoArrow: 'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',
  615. PipelineBodySequenceExpression: "Pipeline body may not be a comma-separated sequence expression",
  616. PipelineHeadSequenceExpression: "Pipeline head should not be a comma-separated sequence expression",
  617. PipelineTopicUnused: "Pipeline is in topic style but does not use topic reference",
  618. PrimaryTopicNotAllowed: "Topic reference was used in a lexical context without topic binding",
  619. PrimaryTopicRequiresSmartPipeline: "Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",
  620. PrivateInExpectedIn: "Private names are only allowed in property accesses (`obj.#%0`) or in `in` expressions (`#%0 in obj`)",
  621. PrivateNameRedeclaration: "Duplicate private name #%0",
  622. RecordExpressionBarIncorrectEndSyntaxType: "Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  623. RecordExpressionBarIncorrectStartSyntaxType: "Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  624. RecordExpressionHashIncorrectStartSyntaxType: "Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  625. RecordNoProto: "'__proto__' is not allowed in Record expressions",
  626. RestTrailingComma: "Unexpected trailing comma after rest element",
  627. SloppyFunction: "In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement",
  628. StaticPrototype: "Classes may not have static property named prototype",
  629. StrictDelete: "Deleting local variable in strict mode",
  630. StrictEvalArguments: "Assigning to '%0' in strict mode",
  631. StrictEvalArgumentsBinding: "Binding '%0' in strict mode",
  632. StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
  633. StrictNumericEscape: "The only valid numeric escape in strict mode is '\\0'",
  634. StrictOctalLiteral: "Legacy octal literals are not allowed in strict mode",
  635. StrictWith: "'with' in strict mode",
  636. SuperNotAllowed: "super() is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",
  637. SuperPrivateField: "Private fields can't be accessed on super",
  638. TrailingDecorator: "Decorators must be attached to a class element",
  639. TupleExpressionBarIncorrectEndSyntaxType: "Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  640. TupleExpressionBarIncorrectStartSyntaxType: "Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",
  641. TupleExpressionHashIncorrectStartSyntaxType: "Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",
  642. UnexpectedArgumentPlaceholder: "Unexpected argument placeholder",
  643. UnexpectedAwaitAfterPipelineBody: 'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',
  644. UnexpectedDigitAfterHash: "Unexpected digit after hash token",
  645. UnexpectedImportExport: "'import' and 'export' may only appear at the top level",
  646. UnexpectedKeyword: "Unexpected keyword '%0'",
  647. UnexpectedLeadingDecorator: "Leading decorators must be attached to a class declaration",
  648. UnexpectedLexicalDeclaration: "Lexical declaration cannot appear in a single-statement context",
  649. UnexpectedNewTarget: "new.target can only be used in functions",
  650. UnexpectedNumericSeparator: "A numeric separator is only allowed between two digits",
  651. UnexpectedPrivateField: "Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",
  652. UnexpectedReservedWord: "Unexpected reserved word '%0'",
  653. UnexpectedSuper: "super is only allowed in object methods and classes",
  654. UnexpectedToken: "Unexpected token '%0'",
  655. UnexpectedTokenUnaryExponentiation: "Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",
  656. UnsupportedBind: "Binding should be performed on object property.",
  657. UnsupportedDecoratorExport: "A decorated export must export a class declaration",
  658. UnsupportedDefaultExport: "Only expressions, functions or classes are allowed as the `default` export.",
  659. UnsupportedImport: "import can only be used in import() or import.meta",
  660. UnsupportedMetaProperty: "The only valid meta property for %0 is %0.%1",
  661. UnsupportedParameterDecorator: "Decorators cannot be used to decorate parameters",
  662. UnsupportedPropertyDecorator: "Decorators cannot be used to decorate object literal properties",
  663. UnsupportedSuper: "super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",
  664. UnterminatedComment: "Unterminated comment",
  665. UnterminatedRegExp: "Unterminated regular expression",
  666. UnterminatedString: "Unterminated string constant",
  667. UnterminatedTemplate: "Unterminated template",
  668. VarRedeclaration: "Identifier '%0' has already been declared",
  669. YieldBindingIdentifier: "Can not use 'yield' as identifier inside a generator",
  670. YieldInParameter: "Yield expression is not allowed in formal parameters",
  671. ZeroDigitNumericSeparator: "Numeric separator can not be used after leading 0"
  672. });
  673. class ParserError extends CommentsParser {
  674. getLocationForPosition(pos) {
  675. let loc;
  676. if (pos === this.state.start) loc = this.state.startLoc;else if (pos === this.state.lastTokStart) loc = this.state.lastTokStartLoc;else if (pos === this.state.end) loc = this.state.endLoc;else if (pos === this.state.lastTokEnd) loc = this.state.lastTokEndLoc;else loc = getLineInfo(this.input, pos);
  677. return loc;
  678. }
  679. raise(pos, errorTemplate, ...params) {
  680. return this.raiseWithData(pos, undefined, errorTemplate, ...params);
  681. }
  682. raiseOverwrite(pos, errorTemplate, ...params) {
  683. const loc = this.getLocationForPosition(pos);
  684. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  685. if (this.options.errorRecovery) {
  686. const errors = this.state.errors;
  687. for (let i = errors.length - 1; i >= 0; i--) {
  688. const error = errors[i];
  689. if (error.pos === pos) {
  690. return Object.assign(error, {
  691. message
  692. });
  693. } else if (error.pos < pos) {
  694. break;
  695. }
  696. }
  697. }
  698. return this._raise({
  699. loc,
  700. pos
  701. }, message);
  702. }
  703. raiseWithData(pos, data, errorTemplate, ...params) {
  704. const loc = this.getLocationForPosition(pos);
  705. const message = errorTemplate.replace(/%(\d+)/g, (_, i) => params[i]) + ` (${loc.line}:${loc.column})`;
  706. return this._raise(Object.assign({
  707. loc,
  708. pos
  709. }, data), message);
  710. }
  711. _raise(errorContext, message) {
  712. const err = new SyntaxError(message);
  713. Object.assign(err, errorContext);
  714. if (this.options.errorRecovery) {
  715. if (!this.isLookahead) this.state.errors.push(err);
  716. return err;
  717. } else {
  718. throw err;
  719. }
  720. }
  721. }
  722. var estree = (superClass => class extends superClass {
  723. estreeParseRegExpLiteral({
  724. pattern,
  725. flags
  726. }) {
  727. let regex = null;
  728. try {
  729. regex = new RegExp(pattern, flags);
  730. } catch (e) {}
  731. const node = this.estreeParseLiteral(regex);
  732. node.regex = {
  733. pattern,
  734. flags
  735. };
  736. return node;
  737. }
  738. estreeParseBigIntLiteral(value) {
  739. let bigInt;
  740. try {
  741. bigInt = BigInt(value);
  742. } catch (_unused) {
  743. bigInt = null;
  744. }
  745. const node = this.estreeParseLiteral(bigInt);
  746. node.bigint = String(node.value || value);
  747. return node;
  748. }
  749. estreeParseDecimalLiteral(value) {
  750. const decimal = null;
  751. const node = this.estreeParseLiteral(decimal);
  752. node.decimal = String(node.value || value);
  753. return node;
  754. }
  755. estreeParseLiteral(value) {
  756. return this.parseLiteral(value, "Literal");
  757. }
  758. directiveToStmt(directive) {
  759. const directiveLiteral = directive.value;
  760. const stmt = this.startNodeAt(directive.start, directive.loc.start);
  761. const expression = this.startNodeAt(directiveLiteral.start, directiveLiteral.loc.start);
  762. expression.value = directiveLiteral.extra.expressionValue;
  763. expression.raw = directiveLiteral.extra.raw;
  764. stmt.expression = this.finishNodeAt(expression, "Literal", directiveLiteral.end, directiveLiteral.loc.end);
  765. stmt.directive = directiveLiteral.extra.raw.slice(1, -1);
  766. return this.finishNodeAt(stmt, "ExpressionStatement", directive.end, directive.loc.end);
  767. }
  768. initFunction(node, isAsync) {
  769. super.initFunction(node, isAsync);
  770. node.expression = false;
  771. }
  772. checkDeclaration(node) {
  773. if (node != null && this.isObjectProperty(node)) {
  774. this.checkDeclaration(node.value);
  775. } else {
  776. super.checkDeclaration(node);
  777. }
  778. }
  779. getObjectOrClassMethodParams(method) {
  780. return method.value.params;
  781. }
  782. isValidDirective(stmt) {
  783. var _stmt$expression$extr;
  784. return stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && typeof stmt.expression.value === "string" && !((_stmt$expression$extr = stmt.expression.extra) != null && _stmt$expression$extr.parenthesized);
  785. }
  786. stmtToDirective(stmt) {
  787. const directive = super.stmtToDirective(stmt);
  788. const value = stmt.expression.value;
  789. this.addExtra(directive.value, "expressionValue", value);
  790. return directive;
  791. }
  792. parseBlockBody(node, ...args) {
  793. super.parseBlockBody(node, ...args);
  794. const directiveStatements = node.directives.map(d => this.directiveToStmt(d));
  795. node.body = directiveStatements.concat(node.body);
  796. delete node.directives;
  797. }
  798. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  799. this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true);
  800. if (method.typeParameters) {
  801. method.value.typeParameters = method.typeParameters;
  802. delete method.typeParameters;
  803. }
  804. classBody.body.push(method);
  805. }
  806. parseExprAtom(refExpressionErrors) {
  807. switch (this.state.type) {
  808. case types.num:
  809. case types.string:
  810. return this.estreeParseLiteral(this.state.value);
  811. case types.regexp:
  812. return this.estreeParseRegExpLiteral(this.state.value);
  813. case types.bigint:
  814. return this.estreeParseBigIntLiteral(this.state.value);
  815. case types.decimal:
  816. return this.estreeParseDecimalLiteral(this.state.value);
  817. case types._null:
  818. return this.estreeParseLiteral(null);
  819. case types._true:
  820. return this.estreeParseLiteral(true);
  821. case types._false:
  822. return this.estreeParseLiteral(false);
  823. default:
  824. return super.parseExprAtom(refExpressionErrors);
  825. }
  826. }
  827. parseMaybePrivateName(...args) {
  828. const node = super.parseMaybePrivateName(...args);
  829. if (node.type === "PrivateName" && this.getPluginOption("estree", "classFeatures")) {
  830. return this.convertPrivateNameToPrivateIdentifier(node);
  831. }
  832. return node;
  833. }
  834. convertPrivateNameToPrivateIdentifier(node) {
  835. const name = super.getPrivateNameSV(node);
  836. node = node;
  837. delete node.id;
  838. node.name = name;
  839. node.type = "PrivateIdentifier";
  840. return node;
  841. }
  842. isPrivateName(node) {
  843. if (!this.getPluginOption("estree", "classFeatures")) {
  844. return super.isPrivateName(node);
  845. }
  846. return node.type === "PrivateIdentifier";
  847. }
  848. getPrivateNameSV(node) {
  849. if (!this.getPluginOption("estree", "classFeatures")) {
  850. return super.getPrivateNameSV(node);
  851. }
  852. return node.name;
  853. }
  854. parseLiteral(value, type, startPos, startLoc) {
  855. const node = super.parseLiteral(value, type, startPos, startLoc);
  856. node.raw = node.extra.raw;
  857. delete node.extra;
  858. return node;
  859. }
  860. parseFunctionBody(node, allowExpression, isMethod = false) {
  861. super.parseFunctionBody(node, allowExpression, isMethod);
  862. node.expression = node.body.type !== "BlockStatement";
  863. }
  864. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  865. let funcNode = this.startNode();
  866. funcNode.kind = node.kind;
  867. funcNode = super.parseMethod(funcNode, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope);
  868. funcNode.type = "FunctionExpression";
  869. delete funcNode.kind;
  870. node.value = funcNode;
  871. if (type === "ClassPrivateMethod") {
  872. node.computed = false;
  873. }
  874. type = "MethodDefinition";
  875. return this.finishNode(node, type);
  876. }
  877. parseClassProperty(...args) {
  878. const propertyNode = super.parseClassProperty(...args);
  879. if (this.getPluginOption("estree", "classFeatures")) {
  880. propertyNode.type = "PropertyDefinition";
  881. }
  882. return propertyNode;
  883. }
  884. parseClassPrivateProperty(...args) {
  885. const propertyNode = super.parseClassPrivateProperty(...args);
  886. if (this.getPluginOption("estree", "classFeatures")) {
  887. propertyNode.type = "PropertyDefinition";
  888. propertyNode.computed = false;
  889. }
  890. return propertyNode;
  891. }
  892. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  893. const node = super.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor);
  894. if (node) {
  895. node.type = "Property";
  896. if (node.kind === "method") node.kind = "init";
  897. node.shorthand = false;
  898. }
  899. return node;
  900. }
  901. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  902. const node = super.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  903. if (node) {
  904. node.kind = "init";
  905. node.type = "Property";
  906. }
  907. return node;
  908. }
  909. toAssignable(node, isLHS = false) {
  910. if (node != null && this.isObjectProperty(node)) {
  911. this.toAssignable(node.value, isLHS);
  912. return node;
  913. }
  914. return super.toAssignable(node, isLHS);
  915. }
  916. toAssignableObjectExpressionProp(prop, ...args) {
  917. if (prop.kind === "get" || prop.kind === "set") {
  918. this.raise(prop.key.start, ErrorMessages.PatternHasAccessor);
  919. } else if (prop.method) {
  920. this.raise(prop.key.start, ErrorMessages.PatternHasMethod);
  921. } else {
  922. super.toAssignableObjectExpressionProp(prop, ...args);
  923. }
  924. }
  925. finishCallExpression(node, optional) {
  926. super.finishCallExpression(node, optional);
  927. if (node.callee.type === "Import") {
  928. node.type = "ImportExpression";
  929. node.source = node.arguments[0];
  930. delete node.arguments;
  931. delete node.callee;
  932. }
  933. return node;
  934. }
  935. toReferencedArguments(node) {
  936. if (node.type === "ImportExpression") {
  937. return;
  938. }
  939. super.toReferencedArguments(node);
  940. }
  941. parseExport(node) {
  942. super.parseExport(node);
  943. switch (node.type) {
  944. case "ExportAllDeclaration":
  945. node.exported = null;
  946. break;
  947. case "ExportNamedDeclaration":
  948. if (node.specifiers.length === 1 && node.specifiers[0].type === "ExportNamespaceSpecifier") {
  949. node.type = "ExportAllDeclaration";
  950. node.exported = node.specifiers[0].exported;
  951. delete node.specifiers;
  952. }
  953. break;
  954. }
  955. return node;
  956. }
  957. parseSubscript(base, startPos, startLoc, noCalls, state) {
  958. const node = super.parseSubscript(base, startPos, startLoc, noCalls, state);
  959. if (state.optionalChainMember) {
  960. if (node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression") {
  961. node.type = node.type.substring(8);
  962. }
  963. if (state.stop) {
  964. const chain = this.startNodeAtNode(node);
  965. chain.expression = node;
  966. return this.finishNode(chain, "ChainExpression");
  967. }
  968. } else if (node.type === "MemberExpression" || node.type === "CallExpression") {
  969. node.optional = false;
  970. }
  971. return node;
  972. }
  973. hasPropertyAsPrivateName(node) {
  974. if (node.type === "ChainExpression") {
  975. node = node.expression;
  976. }
  977. return super.hasPropertyAsPrivateName(node);
  978. }
  979. isOptionalChain(node) {
  980. return node.type === "ChainExpression";
  981. }
  982. isObjectProperty(node) {
  983. return node.type === "Property" && node.kind === "init" && !node.method;
  984. }
  985. isObjectMethod(node) {
  986. return node.method || node.kind === "get" || node.kind === "set";
  987. }
  988. });
  989. class TokContext {
  990. constructor(token, isExpr, preserveSpace, override) {
  991. this.token = void 0;
  992. this.isExpr = void 0;
  993. this.preserveSpace = void 0;
  994. this.override = void 0;
  995. this.token = token;
  996. this.isExpr = !!isExpr;
  997. this.preserveSpace = !!preserveSpace;
  998. this.override = override;
  999. }
  1000. }
  1001. const types$1 = {
  1002. braceStatement: new TokContext("{", false),
  1003. braceExpression: new TokContext("{", true),
  1004. recordExpression: new TokContext("#{", true),
  1005. templateQuasi: new TokContext("${", false),
  1006. parenStatement: new TokContext("(", false),
  1007. parenExpression: new TokContext("(", true),
  1008. template: new TokContext("`", true, true, p => p.readTmplToken()),
  1009. functionExpression: new TokContext("function", true),
  1010. functionStatement: new TokContext("function", false)
  1011. };
  1012. types.parenR.updateContext = types.braceR.updateContext = function () {
  1013. if (this.state.context.length === 1) {
  1014. this.state.exprAllowed = true;
  1015. return;
  1016. }
  1017. let out = this.state.context.pop();
  1018. if (out === types$1.braceStatement && this.curContext().token === "function") {
  1019. out = this.state.context.pop();
  1020. }
  1021. this.state.exprAllowed = !out.isExpr;
  1022. };
  1023. types.name.updateContext = function (prevType) {
  1024. let allowed = false;
  1025. if (prevType !== types.dot) {
  1026. if (this.state.value === "of" && !this.state.exprAllowed && prevType !== types._function && prevType !== types._class) {
  1027. allowed = true;
  1028. }
  1029. }
  1030. this.state.exprAllowed = allowed;
  1031. if (this.state.isIterator) {
  1032. this.state.isIterator = false;
  1033. }
  1034. };
  1035. types.braceL.updateContext = function (prevType) {
  1036. this.state.context.push(this.braceIsBlock(prevType) ? types$1.braceStatement : types$1.braceExpression);
  1037. this.state.exprAllowed = true;
  1038. };
  1039. types.dollarBraceL.updateContext = function () {
  1040. this.state.context.push(types$1.templateQuasi);
  1041. this.state.exprAllowed = true;
  1042. };
  1043. types.parenL.updateContext = function (prevType) {
  1044. const statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
  1045. this.state.context.push(statementParens ? types$1.parenStatement : types$1.parenExpression);
  1046. this.state.exprAllowed = true;
  1047. };
  1048. types.incDec.updateContext = function () {};
  1049. types._function.updateContext = types._class.updateContext = function (prevType) {
  1050. if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && this.hasPrecedingLineBreak()) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) {
  1051. this.state.context.push(types$1.functionExpression);
  1052. } else {
  1053. this.state.context.push(types$1.functionStatement);
  1054. }
  1055. this.state.exprAllowed = false;
  1056. };
  1057. types.backQuote.updateContext = function () {
  1058. if (this.curContext() === types$1.template) {
  1059. this.state.context.pop();
  1060. } else {
  1061. this.state.context.push(types$1.template);
  1062. }
  1063. this.state.exprAllowed = false;
  1064. };
  1065. types.braceHashL.updateContext = function () {
  1066. this.state.context.push(types$1.recordExpression);
  1067. this.state.exprAllowed = true;
  1068. };
  1069. let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  1070. let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  1071. const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  1072. const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  1073. nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
  1074. const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
  1075. const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  1076. function isInAstralSet(code, set) {
  1077. let pos = 0x10000;
  1078. for (let i = 0, length = set.length; i < length; i += 2) {
  1079. pos += set[i];
  1080. if (pos > code) return false;
  1081. pos += set[i + 1];
  1082. if (pos >= code) return true;
  1083. }
  1084. return false;
  1085. }
  1086. function isIdentifierStart(code) {
  1087. if (code < 65) return code === 36;
  1088. if (code <= 90) return true;
  1089. if (code < 97) return code === 95;
  1090. if (code <= 122) return true;
  1091. if (code <= 0xffff) {
  1092. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  1093. }
  1094. return isInAstralSet(code, astralIdentifierStartCodes);
  1095. }
  1096. function isIdentifierChar(code) {
  1097. if (code < 48) return code === 36;
  1098. if (code < 58) return true;
  1099. if (code < 65) return false;
  1100. if (code <= 90) return true;
  1101. if (code < 97) return code === 95;
  1102. if (code <= 122) return true;
  1103. if (code <= 0xffff) {
  1104. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  1105. }
  1106. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
  1107. }
  1108. const reservedWords = {
  1109. keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
  1110. strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
  1111. strictBind: ["eval", "arguments"]
  1112. };
  1113. const keywords$1 = new Set(reservedWords.keyword);
  1114. const reservedWordsStrictSet = new Set(reservedWords.strict);
  1115. const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
  1116. function isReservedWord(word, inModule) {
  1117. return inModule && word === "await" || word === "enum";
  1118. }
  1119. function isStrictReservedWord(word, inModule) {
  1120. return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
  1121. }
  1122. function isStrictBindOnlyReservedWord(word) {
  1123. return reservedWordsStrictBindSet.has(word);
  1124. }
  1125. function isStrictBindReservedWord(word, inModule) {
  1126. return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
  1127. }
  1128. function isKeyword(word) {
  1129. return keywords$1.has(word);
  1130. }
  1131. const keywordRelationalOperator = /^in(stanceof)?$/;
  1132. function isIteratorStart(current, next) {
  1133. return current === 64 && next === 64;
  1134. }
  1135. const SCOPE_OTHER = 0b000000000,
  1136. SCOPE_PROGRAM = 0b000000001,
  1137. SCOPE_FUNCTION = 0b000000010,
  1138. SCOPE_ARROW = 0b000000100,
  1139. SCOPE_SIMPLE_CATCH = 0b000001000,
  1140. SCOPE_SUPER = 0b000010000,
  1141. SCOPE_DIRECT_SUPER = 0b000100000,
  1142. SCOPE_CLASS = 0b001000000,
  1143. SCOPE_STATIC_BLOCK = 0b010000000,
  1144. SCOPE_TS_MODULE = 0b100000000,
  1145. SCOPE_VAR = SCOPE_PROGRAM | SCOPE_FUNCTION | SCOPE_TS_MODULE;
  1146. const BIND_KIND_VALUE = 0b000000000001,
  1147. BIND_KIND_TYPE = 0b000000000010,
  1148. BIND_SCOPE_VAR = 0b000000000100,
  1149. BIND_SCOPE_LEXICAL = 0b000000001000,
  1150. BIND_SCOPE_FUNCTION = 0b000000010000,
  1151. BIND_FLAGS_NONE = 0b000001000000,
  1152. BIND_FLAGS_CLASS = 0b000010000000,
  1153. BIND_FLAGS_TS_ENUM = 0b000100000000,
  1154. BIND_FLAGS_TS_CONST_ENUM = 0b001000000000,
  1155. BIND_FLAGS_TS_EXPORT_ONLY = 0b010000000000,
  1156. BIND_FLAGS_FLOW_DECLARE_FN = 0b100000000000;
  1157. const BIND_CLASS = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_CLASS,
  1158. BIND_LEXICAL = BIND_KIND_VALUE | 0 | BIND_SCOPE_LEXICAL | 0,
  1159. BIND_VAR = BIND_KIND_VALUE | 0 | BIND_SCOPE_VAR | 0,
  1160. BIND_FUNCTION = BIND_KIND_VALUE | 0 | BIND_SCOPE_FUNCTION | 0,
  1161. BIND_TS_INTERFACE = 0 | BIND_KIND_TYPE | 0 | BIND_FLAGS_CLASS,
  1162. BIND_TS_TYPE = 0 | BIND_KIND_TYPE | 0 | 0,
  1163. BIND_TS_ENUM = BIND_KIND_VALUE | BIND_KIND_TYPE | BIND_SCOPE_LEXICAL | BIND_FLAGS_TS_ENUM,
  1164. BIND_TS_AMBIENT = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  1165. BIND_NONE = 0 | 0 | 0 | BIND_FLAGS_NONE,
  1166. BIND_OUTSIDE = BIND_KIND_VALUE | 0 | 0 | BIND_FLAGS_NONE,
  1167. BIND_TS_CONST_ENUM = BIND_TS_ENUM | BIND_FLAGS_TS_CONST_ENUM,
  1168. BIND_TS_NAMESPACE = 0 | 0 | 0 | BIND_FLAGS_TS_EXPORT_ONLY,
  1169. BIND_FLOW_DECLARE_FN = BIND_FLAGS_FLOW_DECLARE_FN;
  1170. const CLASS_ELEMENT_FLAG_STATIC = 0b100,
  1171. CLASS_ELEMENT_KIND_GETTER = 0b010,
  1172. CLASS_ELEMENT_KIND_SETTER = 0b001,
  1173. CLASS_ELEMENT_KIND_ACCESSOR = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_KIND_SETTER;
  1174. const CLASS_ELEMENT_STATIC_GETTER = CLASS_ELEMENT_KIND_GETTER | CLASS_ELEMENT_FLAG_STATIC,
  1175. CLASS_ELEMENT_STATIC_SETTER = CLASS_ELEMENT_KIND_SETTER | CLASS_ELEMENT_FLAG_STATIC,
  1176. CLASS_ELEMENT_INSTANCE_GETTER = CLASS_ELEMENT_KIND_GETTER,
  1177. CLASS_ELEMENT_INSTANCE_SETTER = CLASS_ELEMENT_KIND_SETTER,
  1178. CLASS_ELEMENT_OTHER = 0;
  1179. class Scope {
  1180. constructor(flags) {
  1181. this.flags = void 0;
  1182. this.var = [];
  1183. this.lexical = [];
  1184. this.functions = [];
  1185. this.flags = flags;
  1186. }
  1187. }
  1188. class ScopeHandler {
  1189. constructor(raise, inModule) {
  1190. this.scopeStack = [];
  1191. this.undefinedExports = new Map();
  1192. this.undefinedPrivateNames = new Map();
  1193. this.raise = raise;
  1194. this.inModule = inModule;
  1195. }
  1196. get inFunction() {
  1197. return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0;
  1198. }
  1199. get allowSuper() {
  1200. return (this.currentThisScope().flags & SCOPE_SUPER) > 0;
  1201. }
  1202. get allowDirectSuper() {
  1203. return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0;
  1204. }
  1205. get inClass() {
  1206. return (this.currentThisScope().flags & SCOPE_CLASS) > 0;
  1207. }
  1208. get inStaticBlock() {
  1209. return (this.currentThisScope().flags & SCOPE_STATIC_BLOCK) > 0;
  1210. }
  1211. get inNonArrowFunction() {
  1212. return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0;
  1213. }
  1214. get treatFunctionsAsVar() {
  1215. return this.treatFunctionsAsVarInScope(this.currentScope());
  1216. }
  1217. createScope(flags) {
  1218. return new Scope(flags);
  1219. }
  1220. enter(flags) {
  1221. this.scopeStack.push(this.createScope(flags));
  1222. }
  1223. exit() {
  1224. this.scopeStack.pop();
  1225. }
  1226. treatFunctionsAsVarInScope(scope) {
  1227. return !!(scope.flags & SCOPE_FUNCTION || !this.inModule && scope.flags & SCOPE_PROGRAM);
  1228. }
  1229. declareName(name, bindingType, pos) {
  1230. let scope = this.currentScope();
  1231. if (bindingType & BIND_SCOPE_LEXICAL || bindingType & BIND_SCOPE_FUNCTION) {
  1232. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  1233. if (bindingType & BIND_SCOPE_FUNCTION) {
  1234. scope.functions.push(name);
  1235. } else {
  1236. scope.lexical.push(name);
  1237. }
  1238. if (bindingType & BIND_SCOPE_LEXICAL) {
  1239. this.maybeExportDefined(scope, name);
  1240. }
  1241. } else if (bindingType & BIND_SCOPE_VAR) {
  1242. for (let i = this.scopeStack.length - 1; i >= 0; --i) {
  1243. scope = this.scopeStack[i];
  1244. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  1245. scope.var.push(name);
  1246. this.maybeExportDefined(scope, name);
  1247. if (scope.flags & SCOPE_VAR) break;
  1248. }
  1249. }
  1250. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  1251. this.undefinedExports.delete(name);
  1252. }
  1253. }
  1254. maybeExportDefined(scope, name) {
  1255. if (this.inModule && scope.flags & SCOPE_PROGRAM) {
  1256. this.undefinedExports.delete(name);
  1257. }
  1258. }
  1259. checkRedeclarationInScope(scope, name, bindingType, pos) {
  1260. if (this.isRedeclaredInScope(scope, name, bindingType)) {
  1261. this.raise(pos, ErrorMessages.VarRedeclaration, name);
  1262. }
  1263. }
  1264. isRedeclaredInScope(scope, name, bindingType) {
  1265. if (!(bindingType & BIND_KIND_VALUE)) return false;
  1266. if (bindingType & BIND_SCOPE_LEXICAL) {
  1267. return scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  1268. }
  1269. if (bindingType & BIND_SCOPE_FUNCTION) {
  1270. return scope.lexical.indexOf(name) > -1 || !this.treatFunctionsAsVarInScope(scope) && scope.var.indexOf(name) > -1;
  1271. }
  1272. return scope.lexical.indexOf(name) > -1 && !(scope.flags & SCOPE_SIMPLE_CATCH && scope.lexical[0] === name) || !this.treatFunctionsAsVarInScope(scope) && scope.functions.indexOf(name) > -1;
  1273. }
  1274. checkLocalExport(id) {
  1275. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1 && this.scopeStack[0].functions.indexOf(id.name) === -1) {
  1276. this.undefinedExports.set(id.name, id.start);
  1277. }
  1278. }
  1279. currentScope() {
  1280. return this.scopeStack[this.scopeStack.length - 1];
  1281. }
  1282. currentVarScope() {
  1283. for (let i = this.scopeStack.length - 1;; i--) {
  1284. const scope = this.scopeStack[i];
  1285. if (scope.flags & SCOPE_VAR) {
  1286. return scope;
  1287. }
  1288. }
  1289. }
  1290. currentThisScope() {
  1291. for (let i = this.scopeStack.length - 1;; i--) {
  1292. const scope = this.scopeStack[i];
  1293. if ((scope.flags & SCOPE_VAR || scope.flags & SCOPE_CLASS) && !(scope.flags & SCOPE_ARROW)) {
  1294. return scope;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. class FlowScope extends Scope {
  1300. constructor(...args) {
  1301. super(...args);
  1302. this.declareFunctions = [];
  1303. }
  1304. }
  1305. class FlowScopeHandler extends ScopeHandler {
  1306. createScope(flags) {
  1307. return new FlowScope(flags);
  1308. }
  1309. declareName(name, bindingType, pos) {
  1310. const scope = this.currentScope();
  1311. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  1312. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  1313. this.maybeExportDefined(scope, name);
  1314. scope.declareFunctions.push(name);
  1315. return;
  1316. }
  1317. super.declareName(...arguments);
  1318. }
  1319. isRedeclaredInScope(scope, name, bindingType) {
  1320. if (super.isRedeclaredInScope(...arguments)) return true;
  1321. if (bindingType & BIND_FLAGS_FLOW_DECLARE_FN) {
  1322. return !scope.declareFunctions.includes(name) && (scope.lexical.includes(name) || scope.functions.includes(name));
  1323. }
  1324. return false;
  1325. }
  1326. checkLocalExport(id) {
  1327. if (this.scopeStack[0].declareFunctions.indexOf(id.name) === -1) {
  1328. super.checkLocalExport(id);
  1329. }
  1330. }
  1331. }
  1332. const reservedTypes = new Set(["_", "any", "bool", "boolean", "empty", "extends", "false", "interface", "mixed", "null", "number", "static", "string", "true", "typeof", "void"]);
  1333. const FlowErrors = Object.freeze({
  1334. AmbiguousConditionalArrow: "Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",
  1335. AmbiguousDeclareModuleKind: "Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",
  1336. AssignReservedType: "Cannot overwrite reserved type %0",
  1337. DeclareClassElement: "The `declare` modifier can only appear on class fields.",
  1338. DeclareClassFieldInitializer: "Initializers are not allowed in fields with the `declare` modifier.",
  1339. DuplicateDeclareModuleExports: "Duplicate `declare module.exports` statement",
  1340. EnumBooleanMemberNotInitialized: "Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",
  1341. EnumDuplicateMemberName: "Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",
  1342. EnumInconsistentMemberValues: "Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",
  1343. EnumInvalidExplicitType: "Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1344. EnumInvalidExplicitTypeUnknownSupplied: "Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",
  1345. EnumInvalidMemberInitializerPrimaryType: "Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",
  1346. EnumInvalidMemberInitializerSymbolType: "Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",
  1347. EnumInvalidMemberInitializerUnknownType: "The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",
  1348. EnumInvalidMemberName: "Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",
  1349. EnumNumberMemberNotInitialized: "Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",
  1350. EnumStringMemberInconsistentlyInitailized: "String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",
  1351. GetterMayNotHaveThisParam: "A getter cannot have a `this` parameter.",
  1352. ImportTypeShorthandOnlyInPureImport: "The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",
  1353. InexactInsideExact: "Explicit inexact syntax cannot appear inside an explicit exact object type",
  1354. InexactInsideNonObject: "Explicit inexact syntax cannot appear in class or interface definitions",
  1355. InexactVariance: "Explicit inexact syntax cannot have variance",
  1356. InvalidNonTypeImportInDeclareModule: "Imports within a `declare module` body must always be `import type` or `import typeof`",
  1357. MissingTypeParamDefault: "Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",
  1358. NestedDeclareModule: "`declare module` cannot be used inside another `declare module`",
  1359. NestedFlowComment: "Cannot have a flow comment inside another flow comment",
  1360. OptionalBindingPattern: "A binding pattern parameter cannot be optional in an implementation signature.",
  1361. SetterMayNotHaveThisParam: "A setter cannot have a `this` parameter.",
  1362. SpreadVariance: "Spread properties cannot have variance",
  1363. ThisParamAnnotationRequired: "A type annotation is required for the `this` parameter.",
  1364. ThisParamBannedInConstructor: "Constructors cannot have a `this` parameter; constructors don't bind `this` like other functions.",
  1365. ThisParamMayNotBeOptional: "The `this` parameter cannot be optional.",
  1366. ThisParamMustBeFirst: "The `this` parameter must be the first function parameter.",
  1367. ThisParamNoDefault: "The `this` parameter may not have a default value.",
  1368. TypeBeforeInitializer: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  1369. TypeCastInPattern: "The type cast expression is expected to be wrapped with parenthesis",
  1370. UnexpectedExplicitInexactInObject: "Explicit inexact syntax must appear at the end of an inexact object",
  1371. UnexpectedReservedType: "Unexpected reserved type %0",
  1372. UnexpectedReservedUnderscore: "`_` is only allowed as a type argument to call or new",
  1373. UnexpectedSpaceBetweenModuloChecks: "Spaces between `%` and `checks` are not allowed here.",
  1374. UnexpectedSpreadType: "Spread operator cannot appear in class or interface definitions",
  1375. UnexpectedSubtractionOperand: 'Unexpected token, expected "number" or "bigint"',
  1376. UnexpectedTokenAfterTypeParameter: "Expected an arrow function after this type parameter declaration",
  1377. UnexpectedTypeParameterBeforeAsyncArrowFunction: "Type parameters must come after the async keyword, e.g. instead of `<T> async () => {}`, use `async <T>() => {}`",
  1378. UnsupportedDeclareExportKind: "`declare export %0` is not supported. Use `%1` instead",
  1379. UnsupportedStatementInDeclareModule: "Only declares and type imports are allowed inside declare module",
  1380. UnterminatedFlowComment: "Unterminated flow-comment"
  1381. });
  1382. function isEsModuleType(bodyElement) {
  1383. return bodyElement.type === "DeclareExportAllDeclaration" || bodyElement.type === "DeclareExportDeclaration" && (!bodyElement.declaration || bodyElement.declaration.type !== "TypeAlias" && bodyElement.declaration.type !== "InterfaceDeclaration");
  1384. }
  1385. function hasTypeImportKind(node) {
  1386. return node.importKind === "type" || node.importKind === "typeof";
  1387. }
  1388. function isMaybeDefaultImport(state) {
  1389. return (state.type === types.name || !!state.type.keyword) && state.value !== "from";
  1390. }
  1391. const exportSuggestions = {
  1392. const: "declare export var",
  1393. let: "declare export var",
  1394. type: "export type",
  1395. interface: "export interface"
  1396. };
  1397. function partition(list, test) {
  1398. const list1 = [];
  1399. const list2 = [];
  1400. for (let i = 0; i < list.length; i++) {
  1401. (test(list[i], i, list) ? list1 : list2).push(list[i]);
  1402. }
  1403. return [list1, list2];
  1404. }
  1405. const FLOW_PRAGMA_REGEX = /\*?\s*@((?:no)?flow)\b/;
  1406. var flow = (superClass => class extends superClass {
  1407. constructor(...args) {
  1408. super(...args);
  1409. this.flowPragma = undefined;
  1410. }
  1411. getScopeHandler() {
  1412. return FlowScopeHandler;
  1413. }
  1414. shouldParseTypes() {
  1415. return this.getPluginOption("flow", "all") || this.flowPragma === "flow";
  1416. }
  1417. shouldParseEnums() {
  1418. return !!this.getPluginOption("flow", "enums");
  1419. }
  1420. finishToken(type, val) {
  1421. if (type !== types.string && type !== types.semi && type !== types.interpreterDirective) {
  1422. if (this.flowPragma === undefined) {
  1423. this.flowPragma = null;
  1424. }
  1425. }
  1426. return super.finishToken(type, val);
  1427. }
  1428. addComment(comment) {
  1429. if (this.flowPragma === undefined) {
  1430. const matches = FLOW_PRAGMA_REGEX.exec(comment.value);
  1431. if (!matches) ; else if (matches[1] === "flow") {
  1432. this.flowPragma = "flow";
  1433. } else if (matches[1] === "noflow") {
  1434. this.flowPragma = "noflow";
  1435. } else {
  1436. throw new Error("Unexpected flow pragma");
  1437. }
  1438. }
  1439. return super.addComment(comment);
  1440. }
  1441. flowParseTypeInitialiser(tok) {
  1442. const oldInType = this.state.inType;
  1443. this.state.inType = true;
  1444. this.expect(tok || types.colon);
  1445. const type = this.flowParseType();
  1446. this.state.inType = oldInType;
  1447. return type;
  1448. }
  1449. flowParsePredicate() {
  1450. const node = this.startNode();
  1451. const moduloLoc = this.state.startLoc;
  1452. const moduloPos = this.state.start;
  1453. this.expect(types.modulo);
  1454. const checksLoc = this.state.startLoc;
  1455. this.expectContextual("checks");
  1456. if (moduloLoc.line !== checksLoc.line || moduloLoc.column !== checksLoc.column - 1) {
  1457. this.raise(moduloPos, FlowErrors.UnexpectedSpaceBetweenModuloChecks);
  1458. }
  1459. if (this.eat(types.parenL)) {
  1460. node.value = this.parseExpression();
  1461. this.expect(types.parenR);
  1462. return this.finishNode(node, "DeclaredPredicate");
  1463. } else {
  1464. return this.finishNode(node, "InferredPredicate");
  1465. }
  1466. }
  1467. flowParseTypeAndPredicateInitialiser() {
  1468. const oldInType = this.state.inType;
  1469. this.state.inType = true;
  1470. this.expect(types.colon);
  1471. let type = null;
  1472. let predicate = null;
  1473. if (this.match(types.modulo)) {
  1474. this.state.inType = oldInType;
  1475. predicate = this.flowParsePredicate();
  1476. } else {
  1477. type = this.flowParseType();
  1478. this.state.inType = oldInType;
  1479. if (this.match(types.modulo)) {
  1480. predicate = this.flowParsePredicate();
  1481. }
  1482. }
  1483. return [type, predicate];
  1484. }
  1485. flowParseDeclareClass(node) {
  1486. this.next();
  1487. this.flowParseInterfaceish(node, true);
  1488. return this.finishNode(node, "DeclareClass");
  1489. }
  1490. flowParseDeclareFunction(node) {
  1491. this.next();
  1492. const id = node.id = this.parseIdentifier();
  1493. const typeNode = this.startNode();
  1494. const typeContainer = this.startNode();
  1495. if (this.isRelational("<")) {
  1496. typeNode.typeParameters = this.flowParseTypeParameterDeclaration();
  1497. } else {
  1498. typeNode.typeParameters = null;
  1499. }
  1500. this.expect(types.parenL);
  1501. const tmp = this.flowParseFunctionTypeParams();
  1502. typeNode.params = tmp.params;
  1503. typeNode.rest = tmp.rest;
  1504. typeNode.this = tmp._this;
  1505. this.expect(types.parenR);
  1506. [typeNode.returnType, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  1507. typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation");
  1508. id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation");
  1509. this.resetEndLocation(id);
  1510. this.semicolon();
  1511. this.scope.declareName(node.id.name, BIND_FLOW_DECLARE_FN, node.id.start);
  1512. return this.finishNode(node, "DeclareFunction");
  1513. }
  1514. flowParseDeclare(node, insideModule) {
  1515. if (this.match(types._class)) {
  1516. return this.flowParseDeclareClass(node);
  1517. } else if (this.match(types._function)) {
  1518. return this.flowParseDeclareFunction(node);
  1519. } else if (this.match(types._var)) {
  1520. return this.flowParseDeclareVariable(node);
  1521. } else if (this.eatContextual("module")) {
  1522. if (this.match(types.dot)) {
  1523. return this.flowParseDeclareModuleExports(node);
  1524. } else {
  1525. if (insideModule) {
  1526. this.raise(this.state.lastTokStart, FlowErrors.NestedDeclareModule);
  1527. }
  1528. return this.flowParseDeclareModule(node);
  1529. }
  1530. } else if (this.isContextual("type")) {
  1531. return this.flowParseDeclareTypeAlias(node);
  1532. } else if (this.isContextual("opaque")) {
  1533. return this.flowParseDeclareOpaqueType(node);
  1534. } else if (this.isContextual("interface")) {
  1535. return this.flowParseDeclareInterface(node);
  1536. } else if (this.match(types._export)) {
  1537. return this.flowParseDeclareExportDeclaration(node, insideModule);
  1538. } else {
  1539. throw this.unexpected();
  1540. }
  1541. }
  1542. flowParseDeclareVariable(node) {
  1543. this.next();
  1544. node.id = this.flowParseTypeAnnotatableIdentifier(true);
  1545. this.scope.declareName(node.id.name, BIND_VAR, node.id.start);
  1546. this.semicolon();
  1547. return this.finishNode(node, "DeclareVariable");
  1548. }
  1549. flowParseDeclareModule(node) {
  1550. this.scope.enter(SCOPE_OTHER);
  1551. if (this.match(types.string)) {
  1552. node.id = this.parseExprAtom();
  1553. } else {
  1554. node.id = this.parseIdentifier();
  1555. }
  1556. const bodyNode = node.body = this.startNode();
  1557. const body = bodyNode.body = [];
  1558. this.expect(types.braceL);
  1559. while (!this.match(types.braceR)) {
  1560. let bodyNode = this.startNode();
  1561. if (this.match(types._import)) {
  1562. this.next();
  1563. if (!this.isContextual("type") && !this.match(types._typeof)) {
  1564. this.raise(this.state.lastTokStart, FlowErrors.InvalidNonTypeImportInDeclareModule);
  1565. }
  1566. this.parseImport(bodyNode);
  1567. } else {
  1568. this.expectContextual("declare", FlowErrors.UnsupportedStatementInDeclareModule);
  1569. bodyNode = this.flowParseDeclare(bodyNode, true);
  1570. }
  1571. body.push(bodyNode);
  1572. }
  1573. this.scope.exit();
  1574. this.expect(types.braceR);
  1575. this.finishNode(bodyNode, "BlockStatement");
  1576. let kind = null;
  1577. let hasModuleExport = false;
  1578. body.forEach(bodyElement => {
  1579. if (isEsModuleType(bodyElement)) {
  1580. if (kind === "CommonJS") {
  1581. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1582. }
  1583. kind = "ES";
  1584. } else if (bodyElement.type === "DeclareModuleExports") {
  1585. if (hasModuleExport) {
  1586. this.raise(bodyElement.start, FlowErrors.DuplicateDeclareModuleExports);
  1587. }
  1588. if (kind === "ES") {
  1589. this.raise(bodyElement.start, FlowErrors.AmbiguousDeclareModuleKind);
  1590. }
  1591. kind = "CommonJS";
  1592. hasModuleExport = true;
  1593. }
  1594. });
  1595. node.kind = kind || "CommonJS";
  1596. return this.finishNode(node, "DeclareModule");
  1597. }
  1598. flowParseDeclareExportDeclaration(node, insideModule) {
  1599. this.expect(types._export);
  1600. if (this.eat(types._default)) {
  1601. if (this.match(types._function) || this.match(types._class)) {
  1602. node.declaration = this.flowParseDeclare(this.startNode());
  1603. } else {
  1604. node.declaration = this.flowParseType();
  1605. this.semicolon();
  1606. }
  1607. node.default = true;
  1608. return this.finishNode(node, "DeclareExportDeclaration");
  1609. } else {
  1610. if (this.match(types._const) || this.isLet() || (this.isContextual("type") || this.isContextual("interface")) && !insideModule) {
  1611. const label = this.state.value;
  1612. const suggestion = exportSuggestions[label];
  1613. throw this.raise(this.state.start, FlowErrors.UnsupportedDeclareExportKind, label, suggestion);
  1614. }
  1615. if (this.match(types._var) || this.match(types._function) || this.match(types._class) || this.isContextual("opaque")) {
  1616. node.declaration = this.flowParseDeclare(this.startNode());
  1617. node.default = false;
  1618. return this.finishNode(node, "DeclareExportDeclaration");
  1619. } else if (this.match(types.star) || this.match(types.braceL) || this.isContextual("interface") || this.isContextual("type") || this.isContextual("opaque")) {
  1620. node = this.parseExport(node);
  1621. if (node.type === "ExportNamedDeclaration") {
  1622. node.type = "ExportDeclaration";
  1623. node.default = false;
  1624. delete node.exportKind;
  1625. }
  1626. node.type = "Declare" + node.type;
  1627. return node;
  1628. }
  1629. }
  1630. throw this.unexpected();
  1631. }
  1632. flowParseDeclareModuleExports(node) {
  1633. this.next();
  1634. this.expectContextual("exports");
  1635. node.typeAnnotation = this.flowParseTypeAnnotation();
  1636. this.semicolon();
  1637. return this.finishNode(node, "DeclareModuleExports");
  1638. }
  1639. flowParseDeclareTypeAlias(node) {
  1640. this.next();
  1641. this.flowParseTypeAlias(node);
  1642. node.type = "DeclareTypeAlias";
  1643. return node;
  1644. }
  1645. flowParseDeclareOpaqueType(node) {
  1646. this.next();
  1647. this.flowParseOpaqueType(node, true);
  1648. node.type = "DeclareOpaqueType";
  1649. return node;
  1650. }
  1651. flowParseDeclareInterface(node) {
  1652. this.next();
  1653. this.flowParseInterfaceish(node);
  1654. return this.finishNode(node, "DeclareInterface");
  1655. }
  1656. flowParseInterfaceish(node, isClass = false) {
  1657. node.id = this.flowParseRestrictedIdentifier(!isClass, true);
  1658. this.scope.declareName(node.id.name, isClass ? BIND_FUNCTION : BIND_LEXICAL, node.id.start);
  1659. if (this.isRelational("<")) {
  1660. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1661. } else {
  1662. node.typeParameters = null;
  1663. }
  1664. node.extends = [];
  1665. node.implements = [];
  1666. node.mixins = [];
  1667. if (this.eat(types._extends)) {
  1668. do {
  1669. node.extends.push(this.flowParseInterfaceExtends());
  1670. } while (!isClass && this.eat(types.comma));
  1671. }
  1672. if (this.isContextual("mixins")) {
  1673. this.next();
  1674. do {
  1675. node.mixins.push(this.flowParseInterfaceExtends());
  1676. } while (this.eat(types.comma));
  1677. }
  1678. if (this.isContextual("implements")) {
  1679. this.next();
  1680. do {
  1681. node.implements.push(this.flowParseInterfaceExtends());
  1682. } while (this.eat(types.comma));
  1683. }
  1684. node.body = this.flowParseObjectType({
  1685. allowStatic: isClass,
  1686. allowExact: false,
  1687. allowSpread: false,
  1688. allowProto: isClass,
  1689. allowInexact: false
  1690. });
  1691. }
  1692. flowParseInterfaceExtends() {
  1693. const node = this.startNode();
  1694. node.id = this.flowParseQualifiedTypeIdentifier();
  1695. if (this.isRelational("<")) {
  1696. node.typeParameters = this.flowParseTypeParameterInstantiation();
  1697. } else {
  1698. node.typeParameters = null;
  1699. }
  1700. return this.finishNode(node, "InterfaceExtends");
  1701. }
  1702. flowParseInterface(node) {
  1703. this.flowParseInterfaceish(node);
  1704. return this.finishNode(node, "InterfaceDeclaration");
  1705. }
  1706. checkNotUnderscore(word) {
  1707. if (word === "_") {
  1708. this.raise(this.state.start, FlowErrors.UnexpectedReservedUnderscore);
  1709. }
  1710. }
  1711. checkReservedType(word, startLoc, declaration) {
  1712. if (!reservedTypes.has(word)) return;
  1713. this.raise(startLoc, declaration ? FlowErrors.AssignReservedType : FlowErrors.UnexpectedReservedType, word);
  1714. }
  1715. flowParseRestrictedIdentifier(liberal, declaration) {
  1716. this.checkReservedType(this.state.value, this.state.start, declaration);
  1717. return this.parseIdentifier(liberal);
  1718. }
  1719. flowParseTypeAlias(node) {
  1720. node.id = this.flowParseRestrictedIdentifier(false, true);
  1721. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1722. if (this.isRelational("<")) {
  1723. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1724. } else {
  1725. node.typeParameters = null;
  1726. }
  1727. node.right = this.flowParseTypeInitialiser(types.eq);
  1728. this.semicolon();
  1729. return this.finishNode(node, "TypeAlias");
  1730. }
  1731. flowParseOpaqueType(node, declare) {
  1732. this.expectContextual("type");
  1733. node.id = this.flowParseRestrictedIdentifier(true, true);
  1734. this.scope.declareName(node.id.name, BIND_LEXICAL, node.id.start);
  1735. if (this.isRelational("<")) {
  1736. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1737. } else {
  1738. node.typeParameters = null;
  1739. }
  1740. node.supertype = null;
  1741. if (this.match(types.colon)) {
  1742. node.supertype = this.flowParseTypeInitialiser(types.colon);
  1743. }
  1744. node.impltype = null;
  1745. if (!declare) {
  1746. node.impltype = this.flowParseTypeInitialiser(types.eq);
  1747. }
  1748. this.semicolon();
  1749. return this.finishNode(node, "OpaqueType");
  1750. }
  1751. flowParseTypeParameter(requireDefault = false) {
  1752. const nodeStart = this.state.start;
  1753. const node = this.startNode();
  1754. const variance = this.flowParseVariance();
  1755. const ident = this.flowParseTypeAnnotatableIdentifier();
  1756. node.name = ident.name;
  1757. node.variance = variance;
  1758. node.bound = ident.typeAnnotation;
  1759. if (this.match(types.eq)) {
  1760. this.eat(types.eq);
  1761. node.default = this.flowParseType();
  1762. } else {
  1763. if (requireDefault) {
  1764. this.raise(nodeStart, FlowErrors.MissingTypeParamDefault);
  1765. }
  1766. }
  1767. return this.finishNode(node, "TypeParameter");
  1768. }
  1769. flowParseTypeParameterDeclaration() {
  1770. const oldInType = this.state.inType;
  1771. const node = this.startNode();
  1772. node.params = [];
  1773. this.state.inType = true;
  1774. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  1775. this.next();
  1776. } else {
  1777. this.unexpected();
  1778. }
  1779. let defaultRequired = false;
  1780. do {
  1781. const typeParameter = this.flowParseTypeParameter(defaultRequired);
  1782. node.params.push(typeParameter);
  1783. if (typeParameter.default) {
  1784. defaultRequired = true;
  1785. }
  1786. if (!this.isRelational(">")) {
  1787. this.expect(types.comma);
  1788. }
  1789. } while (!this.isRelational(">"));
  1790. this.expectRelational(">");
  1791. this.state.inType = oldInType;
  1792. return this.finishNode(node, "TypeParameterDeclaration");
  1793. }
  1794. flowParseTypeParameterInstantiation() {
  1795. const node = this.startNode();
  1796. const oldInType = this.state.inType;
  1797. node.params = [];
  1798. this.state.inType = true;
  1799. this.expectRelational("<");
  1800. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  1801. this.state.noAnonFunctionType = false;
  1802. while (!this.isRelational(">")) {
  1803. node.params.push(this.flowParseType());
  1804. if (!this.isRelational(">")) {
  1805. this.expect(types.comma);
  1806. }
  1807. }
  1808. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  1809. this.expectRelational(">");
  1810. this.state.inType = oldInType;
  1811. return this.finishNode(node, "TypeParameterInstantiation");
  1812. }
  1813. flowParseTypeParameterInstantiationCallOrNew() {
  1814. const node = this.startNode();
  1815. const oldInType = this.state.inType;
  1816. node.params = [];
  1817. this.state.inType = true;
  1818. this.expectRelational("<");
  1819. while (!this.isRelational(">")) {
  1820. node.params.push(this.flowParseTypeOrImplicitInstantiation());
  1821. if (!this.isRelational(">")) {
  1822. this.expect(types.comma);
  1823. }
  1824. }
  1825. this.expectRelational(">");
  1826. this.state.inType = oldInType;
  1827. return this.finishNode(node, "TypeParameterInstantiation");
  1828. }
  1829. flowParseInterfaceType() {
  1830. const node = this.startNode();
  1831. this.expectContextual("interface");
  1832. node.extends = [];
  1833. if (this.eat(types._extends)) {
  1834. do {
  1835. node.extends.push(this.flowParseInterfaceExtends());
  1836. } while (this.eat(types.comma));
  1837. }
  1838. node.body = this.flowParseObjectType({
  1839. allowStatic: false,
  1840. allowExact: false,
  1841. allowSpread: false,
  1842. allowProto: false,
  1843. allowInexact: false
  1844. });
  1845. return this.finishNode(node, "InterfaceTypeAnnotation");
  1846. }
  1847. flowParseObjectPropertyKey() {
  1848. return this.match(types.num) || this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  1849. }
  1850. flowParseObjectTypeIndexer(node, isStatic, variance) {
  1851. node.static = isStatic;
  1852. if (this.lookahead().type === types.colon) {
  1853. node.id = this.flowParseObjectPropertyKey();
  1854. node.key = this.flowParseTypeInitialiser();
  1855. } else {
  1856. node.id = null;
  1857. node.key = this.flowParseType();
  1858. }
  1859. this.expect(types.bracketR);
  1860. node.value = this.flowParseTypeInitialiser();
  1861. node.variance = variance;
  1862. return this.finishNode(node, "ObjectTypeIndexer");
  1863. }
  1864. flowParseObjectTypeInternalSlot(node, isStatic) {
  1865. node.static = isStatic;
  1866. node.id = this.flowParseObjectPropertyKey();
  1867. this.expect(types.bracketR);
  1868. this.expect(types.bracketR);
  1869. if (this.isRelational("<") || this.match(types.parenL)) {
  1870. node.method = true;
  1871. node.optional = false;
  1872. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  1873. } else {
  1874. node.method = false;
  1875. if (this.eat(types.question)) {
  1876. node.optional = true;
  1877. }
  1878. node.value = this.flowParseTypeInitialiser();
  1879. }
  1880. return this.finishNode(node, "ObjectTypeInternalSlot");
  1881. }
  1882. flowParseObjectTypeMethodish(node) {
  1883. node.params = [];
  1884. node.rest = null;
  1885. node.typeParameters = null;
  1886. node.this = null;
  1887. if (this.isRelational("<")) {
  1888. node.typeParameters = this.flowParseTypeParameterDeclaration();
  1889. }
  1890. this.expect(types.parenL);
  1891. if (this.match(types._this)) {
  1892. node.this = this.flowParseFunctionTypeParam(true);
  1893. node.this.name = null;
  1894. if (!this.match(types.parenR)) {
  1895. this.expect(types.comma);
  1896. }
  1897. }
  1898. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  1899. node.params.push(this.flowParseFunctionTypeParam(false));
  1900. if (!this.match(types.parenR)) {
  1901. this.expect(types.comma);
  1902. }
  1903. }
  1904. if (this.eat(types.ellipsis)) {
  1905. node.rest = this.flowParseFunctionTypeParam(false);
  1906. }
  1907. this.expect(types.parenR);
  1908. node.returnType = this.flowParseTypeInitialiser();
  1909. return this.finishNode(node, "FunctionTypeAnnotation");
  1910. }
  1911. flowParseObjectTypeCallProperty(node, isStatic) {
  1912. const valueNode = this.startNode();
  1913. node.static = isStatic;
  1914. node.value = this.flowParseObjectTypeMethodish(valueNode);
  1915. return this.finishNode(node, "ObjectTypeCallProperty");
  1916. }
  1917. flowParseObjectType({
  1918. allowStatic,
  1919. allowExact,
  1920. allowSpread,
  1921. allowProto,
  1922. allowInexact
  1923. }) {
  1924. const oldInType = this.state.inType;
  1925. this.state.inType = true;
  1926. const nodeStart = this.startNode();
  1927. nodeStart.callProperties = [];
  1928. nodeStart.properties = [];
  1929. nodeStart.indexers = [];
  1930. nodeStart.internalSlots = [];
  1931. let endDelim;
  1932. let exact;
  1933. let inexact = false;
  1934. if (allowExact && this.match(types.braceBarL)) {
  1935. this.expect(types.braceBarL);
  1936. endDelim = types.braceBarR;
  1937. exact = true;
  1938. } else {
  1939. this.expect(types.braceL);
  1940. endDelim = types.braceR;
  1941. exact = false;
  1942. }
  1943. nodeStart.exact = exact;
  1944. while (!this.match(endDelim)) {
  1945. let isStatic = false;
  1946. let protoStart = null;
  1947. let inexactStart = null;
  1948. const node = this.startNode();
  1949. if (allowProto && this.isContextual("proto")) {
  1950. const lookahead = this.lookahead();
  1951. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1952. this.next();
  1953. protoStart = this.state.start;
  1954. allowStatic = false;
  1955. }
  1956. }
  1957. if (allowStatic && this.isContextual("static")) {
  1958. const lookahead = this.lookahead();
  1959. if (lookahead.type !== types.colon && lookahead.type !== types.question) {
  1960. this.next();
  1961. isStatic = true;
  1962. }
  1963. }
  1964. const variance = this.flowParseVariance();
  1965. if (this.eat(types.bracketL)) {
  1966. if (protoStart != null) {
  1967. this.unexpected(protoStart);
  1968. }
  1969. if (this.eat(types.bracketL)) {
  1970. if (variance) {
  1971. this.unexpected(variance.start);
  1972. }
  1973. nodeStart.internalSlots.push(this.flowParseObjectTypeInternalSlot(node, isStatic));
  1974. } else {
  1975. nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic, variance));
  1976. }
  1977. } else if (this.match(types.parenL) || this.isRelational("<")) {
  1978. if (protoStart != null) {
  1979. this.unexpected(protoStart);
  1980. }
  1981. if (variance) {
  1982. this.unexpected(variance.start);
  1983. }
  1984. nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, isStatic));
  1985. } else {
  1986. let kind = "init";
  1987. if (this.isContextual("get") || this.isContextual("set")) {
  1988. const lookahead = this.lookahead();
  1989. if (lookahead.type === types.name || lookahead.type === types.string || lookahead.type === types.num) {
  1990. kind = this.state.value;
  1991. this.next();
  1992. }
  1993. }
  1994. const propOrInexact = this.flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact != null ? allowInexact : !exact);
  1995. if (propOrInexact === null) {
  1996. inexact = true;
  1997. inexactStart = this.state.lastTokStart;
  1998. } else {
  1999. nodeStart.properties.push(propOrInexact);
  2000. }
  2001. }
  2002. this.flowObjectTypeSemicolon();
  2003. if (inexactStart && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  2004. this.raise(inexactStart, FlowErrors.UnexpectedExplicitInexactInObject);
  2005. }
  2006. }
  2007. this.expect(endDelim);
  2008. if (allowSpread) {
  2009. nodeStart.inexact = inexact;
  2010. }
  2011. const out = this.finishNode(nodeStart, "ObjectTypeAnnotation");
  2012. this.state.inType = oldInType;
  2013. return out;
  2014. }
  2015. flowParseObjectTypeProperty(node, isStatic, protoStart, variance, kind, allowSpread, allowInexact) {
  2016. if (this.eat(types.ellipsis)) {
  2017. const isInexactToken = this.match(types.comma) || this.match(types.semi) || this.match(types.braceR) || this.match(types.braceBarR);
  2018. if (isInexactToken) {
  2019. if (!allowSpread) {
  2020. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideNonObject);
  2021. } else if (!allowInexact) {
  2022. this.raise(this.state.lastTokStart, FlowErrors.InexactInsideExact);
  2023. }
  2024. if (variance) {
  2025. this.raise(variance.start, FlowErrors.InexactVariance);
  2026. }
  2027. return null;
  2028. }
  2029. if (!allowSpread) {
  2030. this.raise(this.state.lastTokStart, FlowErrors.UnexpectedSpreadType);
  2031. }
  2032. if (protoStart != null) {
  2033. this.unexpected(protoStart);
  2034. }
  2035. if (variance) {
  2036. this.raise(variance.start, FlowErrors.SpreadVariance);
  2037. }
  2038. node.argument = this.flowParseType();
  2039. return this.finishNode(node, "ObjectTypeSpreadProperty");
  2040. } else {
  2041. node.key = this.flowParseObjectPropertyKey();
  2042. node.static = isStatic;
  2043. node.proto = protoStart != null;
  2044. node.kind = kind;
  2045. let optional = false;
  2046. if (this.isRelational("<") || this.match(types.parenL)) {
  2047. node.method = true;
  2048. if (protoStart != null) {
  2049. this.unexpected(protoStart);
  2050. }
  2051. if (variance) {
  2052. this.unexpected(variance.start);
  2053. }
  2054. node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(node.start, node.loc.start));
  2055. if (kind === "get" || kind === "set") {
  2056. this.flowCheckGetterSetterParams(node);
  2057. }
  2058. if (!allowSpread && node.key.name === "constructor" && node.value.this) {
  2059. this.raise(node.value.this.start, FlowErrors.ThisParamBannedInConstructor);
  2060. }
  2061. } else {
  2062. if (kind !== "init") this.unexpected();
  2063. node.method = false;
  2064. if (this.eat(types.question)) {
  2065. optional = true;
  2066. }
  2067. node.value = this.flowParseTypeInitialiser();
  2068. node.variance = variance;
  2069. }
  2070. node.optional = optional;
  2071. return this.finishNode(node, "ObjectTypeProperty");
  2072. }
  2073. }
  2074. flowCheckGetterSetterParams(property) {
  2075. const paramCount = property.kind === "get" ? 0 : 1;
  2076. const start = property.start;
  2077. const length = property.value.params.length + (property.value.rest ? 1 : 0);
  2078. if (property.value.this) {
  2079. this.raise(property.value.this.start, property.kind === "get" ? FlowErrors.GetterMayNotHaveThisParam : FlowErrors.SetterMayNotHaveThisParam);
  2080. }
  2081. if (length !== paramCount) {
  2082. if (property.kind === "get") {
  2083. this.raise(start, ErrorMessages.BadGetterArity);
  2084. } else {
  2085. this.raise(start, ErrorMessages.BadSetterArity);
  2086. }
  2087. }
  2088. if (property.kind === "set" && property.value.rest) {
  2089. this.raise(start, ErrorMessages.BadSetterRestParameter);
  2090. }
  2091. }
  2092. flowObjectTypeSemicolon() {
  2093. if (!this.eat(types.semi) && !this.eat(types.comma) && !this.match(types.braceR) && !this.match(types.braceBarR)) {
  2094. this.unexpected();
  2095. }
  2096. }
  2097. flowParseQualifiedTypeIdentifier(startPos, startLoc, id) {
  2098. startPos = startPos || this.state.start;
  2099. startLoc = startLoc || this.state.startLoc;
  2100. let node = id || this.flowParseRestrictedIdentifier(true);
  2101. while (this.eat(types.dot)) {
  2102. const node2 = this.startNodeAt(startPos, startLoc);
  2103. node2.qualification = node;
  2104. node2.id = this.flowParseRestrictedIdentifier(true);
  2105. node = this.finishNode(node2, "QualifiedTypeIdentifier");
  2106. }
  2107. return node;
  2108. }
  2109. flowParseGenericType(startPos, startLoc, id) {
  2110. const node = this.startNodeAt(startPos, startLoc);
  2111. node.typeParameters = null;
  2112. node.id = this.flowParseQualifiedTypeIdentifier(startPos, startLoc, id);
  2113. if (this.isRelational("<")) {
  2114. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2115. }
  2116. return this.finishNode(node, "GenericTypeAnnotation");
  2117. }
  2118. flowParseTypeofType() {
  2119. const node = this.startNode();
  2120. this.expect(types._typeof);
  2121. node.argument = this.flowParsePrimaryType();
  2122. return this.finishNode(node, "TypeofTypeAnnotation");
  2123. }
  2124. flowParseTupleType() {
  2125. const node = this.startNode();
  2126. node.types = [];
  2127. this.expect(types.bracketL);
  2128. while (this.state.pos < this.length && !this.match(types.bracketR)) {
  2129. node.types.push(this.flowParseType());
  2130. if (this.match(types.bracketR)) break;
  2131. this.expect(types.comma);
  2132. }
  2133. this.expect(types.bracketR);
  2134. return this.finishNode(node, "TupleTypeAnnotation");
  2135. }
  2136. flowParseFunctionTypeParam(first) {
  2137. let name = null;
  2138. let optional = false;
  2139. let typeAnnotation = null;
  2140. const node = this.startNode();
  2141. const lh = this.lookahead();
  2142. const isThis = this.state.type === types._this;
  2143. if (lh.type === types.colon || lh.type === types.question) {
  2144. if (isThis && !first) {
  2145. this.raise(node.start, FlowErrors.ThisParamMustBeFirst);
  2146. }
  2147. name = this.parseIdentifier(isThis);
  2148. if (this.eat(types.question)) {
  2149. optional = true;
  2150. if (isThis) {
  2151. this.raise(node.start, FlowErrors.ThisParamMayNotBeOptional);
  2152. }
  2153. }
  2154. typeAnnotation = this.flowParseTypeInitialiser();
  2155. } else {
  2156. typeAnnotation = this.flowParseType();
  2157. }
  2158. node.name = name;
  2159. node.optional = optional;
  2160. node.typeAnnotation = typeAnnotation;
  2161. return this.finishNode(node, "FunctionTypeParam");
  2162. }
  2163. reinterpretTypeAsFunctionTypeParam(type) {
  2164. const node = this.startNodeAt(type.start, type.loc.start);
  2165. node.name = null;
  2166. node.optional = false;
  2167. node.typeAnnotation = type;
  2168. return this.finishNode(node, "FunctionTypeParam");
  2169. }
  2170. flowParseFunctionTypeParams(params = []) {
  2171. let rest = null;
  2172. let _this = null;
  2173. if (this.match(types._this)) {
  2174. _this = this.flowParseFunctionTypeParam(true);
  2175. _this.name = null;
  2176. if (!this.match(types.parenR)) {
  2177. this.expect(types.comma);
  2178. }
  2179. }
  2180. while (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  2181. params.push(this.flowParseFunctionTypeParam(false));
  2182. if (!this.match(types.parenR)) {
  2183. this.expect(types.comma);
  2184. }
  2185. }
  2186. if (this.eat(types.ellipsis)) {
  2187. rest = this.flowParseFunctionTypeParam(false);
  2188. }
  2189. return {
  2190. params,
  2191. rest,
  2192. _this
  2193. };
  2194. }
  2195. flowIdentToTypeAnnotation(startPos, startLoc, node, id) {
  2196. switch (id.name) {
  2197. case "any":
  2198. return this.finishNode(node, "AnyTypeAnnotation");
  2199. case "bool":
  2200. case "boolean":
  2201. return this.finishNode(node, "BooleanTypeAnnotation");
  2202. case "mixed":
  2203. return this.finishNode(node, "MixedTypeAnnotation");
  2204. case "empty":
  2205. return this.finishNode(node, "EmptyTypeAnnotation");
  2206. case "number":
  2207. return this.finishNode(node, "NumberTypeAnnotation");
  2208. case "string":
  2209. return this.finishNode(node, "StringTypeAnnotation");
  2210. case "symbol":
  2211. return this.finishNode(node, "SymbolTypeAnnotation");
  2212. default:
  2213. this.checkNotUnderscore(id.name);
  2214. return this.flowParseGenericType(startPos, startLoc, id);
  2215. }
  2216. }
  2217. flowParsePrimaryType() {
  2218. const startPos = this.state.start;
  2219. const startLoc = this.state.startLoc;
  2220. const node = this.startNode();
  2221. let tmp;
  2222. let type;
  2223. let isGroupedType = false;
  2224. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  2225. switch (this.state.type) {
  2226. case types.name:
  2227. if (this.isContextual("interface")) {
  2228. return this.flowParseInterfaceType();
  2229. }
  2230. return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdentifier());
  2231. case types.braceL:
  2232. return this.flowParseObjectType({
  2233. allowStatic: false,
  2234. allowExact: false,
  2235. allowSpread: true,
  2236. allowProto: false,
  2237. allowInexact: true
  2238. });
  2239. case types.braceBarL:
  2240. return this.flowParseObjectType({
  2241. allowStatic: false,
  2242. allowExact: true,
  2243. allowSpread: true,
  2244. allowProto: false,
  2245. allowInexact: false
  2246. });
  2247. case types.bracketL:
  2248. this.state.noAnonFunctionType = false;
  2249. type = this.flowParseTupleType();
  2250. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2251. return type;
  2252. case types.relational:
  2253. if (this.state.value === "<") {
  2254. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2255. this.expect(types.parenL);
  2256. tmp = this.flowParseFunctionTypeParams();
  2257. node.params = tmp.params;
  2258. node.rest = tmp.rest;
  2259. node.this = tmp._this;
  2260. this.expect(types.parenR);
  2261. this.expect(types.arrow);
  2262. node.returnType = this.flowParseType();
  2263. return this.finishNode(node, "FunctionTypeAnnotation");
  2264. }
  2265. break;
  2266. case types.parenL:
  2267. this.next();
  2268. if (!this.match(types.parenR) && !this.match(types.ellipsis)) {
  2269. if (this.match(types.name) || this.match(types._this)) {
  2270. const token = this.lookahead().type;
  2271. isGroupedType = token !== types.question && token !== types.colon;
  2272. } else {
  2273. isGroupedType = true;
  2274. }
  2275. }
  2276. if (isGroupedType) {
  2277. this.state.noAnonFunctionType = false;
  2278. type = this.flowParseType();
  2279. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  2280. if (this.state.noAnonFunctionType || !(this.match(types.comma) || this.match(types.parenR) && this.lookahead().type === types.arrow)) {
  2281. this.expect(types.parenR);
  2282. return type;
  2283. } else {
  2284. this.eat(types.comma);
  2285. }
  2286. }
  2287. if (type) {
  2288. tmp = this.flowParseFunctionTypeParams([this.reinterpretTypeAsFunctionTypeParam(type)]);
  2289. } else {
  2290. tmp = this.flowParseFunctionTypeParams();
  2291. }
  2292. node.params = tmp.params;
  2293. node.rest = tmp.rest;
  2294. node.this = tmp._this;
  2295. this.expect(types.parenR);
  2296. this.expect(types.arrow);
  2297. node.returnType = this.flowParseType();
  2298. node.typeParameters = null;
  2299. return this.finishNode(node, "FunctionTypeAnnotation");
  2300. case types.string:
  2301. return this.parseLiteral(this.state.value, "StringLiteralTypeAnnotation");
  2302. case types._true:
  2303. case types._false:
  2304. node.value = this.match(types._true);
  2305. this.next();
  2306. return this.finishNode(node, "BooleanLiteralTypeAnnotation");
  2307. case types.plusMin:
  2308. if (this.state.value === "-") {
  2309. this.next();
  2310. if (this.match(types.num)) {
  2311. return this.parseLiteral(-this.state.value, "NumberLiteralTypeAnnotation", node.start, node.loc.start);
  2312. }
  2313. if (this.match(types.bigint)) {
  2314. return this.parseLiteral(-this.state.value, "BigIntLiteralTypeAnnotation", node.start, node.loc.start);
  2315. }
  2316. throw this.raise(this.state.start, FlowErrors.UnexpectedSubtractionOperand);
  2317. }
  2318. throw this.unexpected();
  2319. case types.num:
  2320. return this.parseLiteral(this.state.value, "NumberLiteralTypeAnnotation");
  2321. case types.bigint:
  2322. return this.parseLiteral(this.state.value, "BigIntLiteralTypeAnnotation");
  2323. case types._void:
  2324. this.next();
  2325. return this.finishNode(node, "VoidTypeAnnotation");
  2326. case types._null:
  2327. this.next();
  2328. return this.finishNode(node, "NullLiteralTypeAnnotation");
  2329. case types._this:
  2330. this.next();
  2331. return this.finishNode(node, "ThisTypeAnnotation");
  2332. case types.star:
  2333. this.next();
  2334. return this.finishNode(node, "ExistsTypeAnnotation");
  2335. default:
  2336. if (this.state.type.keyword === "typeof") {
  2337. return this.flowParseTypeofType();
  2338. } else if (this.state.type.keyword) {
  2339. const label = this.state.type.label;
  2340. this.next();
  2341. return super.createIdentifier(node, label);
  2342. }
  2343. }
  2344. throw this.unexpected();
  2345. }
  2346. flowParsePostfixType() {
  2347. const startPos = this.state.start,
  2348. startLoc = this.state.startLoc;
  2349. let type = this.flowParsePrimaryType();
  2350. while (this.match(types.bracketL) && !this.canInsertSemicolon()) {
  2351. const node = this.startNodeAt(startPos, startLoc);
  2352. node.elementType = type;
  2353. this.expect(types.bracketL);
  2354. this.expect(types.bracketR);
  2355. type = this.finishNode(node, "ArrayTypeAnnotation");
  2356. }
  2357. return type;
  2358. }
  2359. flowParsePrefixType() {
  2360. const node = this.startNode();
  2361. if (this.eat(types.question)) {
  2362. node.typeAnnotation = this.flowParsePrefixType();
  2363. return this.finishNode(node, "NullableTypeAnnotation");
  2364. } else {
  2365. return this.flowParsePostfixType();
  2366. }
  2367. }
  2368. flowParseAnonFunctionWithoutParens() {
  2369. const param = this.flowParsePrefixType();
  2370. if (!this.state.noAnonFunctionType && this.eat(types.arrow)) {
  2371. const node = this.startNodeAt(param.start, param.loc.start);
  2372. node.params = [this.reinterpretTypeAsFunctionTypeParam(param)];
  2373. node.rest = null;
  2374. node.this = null;
  2375. node.returnType = this.flowParseType();
  2376. node.typeParameters = null;
  2377. return this.finishNode(node, "FunctionTypeAnnotation");
  2378. }
  2379. return param;
  2380. }
  2381. flowParseIntersectionType() {
  2382. const node = this.startNode();
  2383. this.eat(types.bitwiseAND);
  2384. const type = this.flowParseAnonFunctionWithoutParens();
  2385. node.types = [type];
  2386. while (this.eat(types.bitwiseAND)) {
  2387. node.types.push(this.flowParseAnonFunctionWithoutParens());
  2388. }
  2389. return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation");
  2390. }
  2391. flowParseUnionType() {
  2392. const node = this.startNode();
  2393. this.eat(types.bitwiseOR);
  2394. const type = this.flowParseIntersectionType();
  2395. node.types = [type];
  2396. while (this.eat(types.bitwiseOR)) {
  2397. node.types.push(this.flowParseIntersectionType());
  2398. }
  2399. return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation");
  2400. }
  2401. flowParseType() {
  2402. const oldInType = this.state.inType;
  2403. this.state.inType = true;
  2404. const type = this.flowParseUnionType();
  2405. this.state.inType = oldInType;
  2406. this.state.exprAllowed = this.state.exprAllowed || this.state.noAnonFunctionType;
  2407. return type;
  2408. }
  2409. flowParseTypeOrImplicitInstantiation() {
  2410. if (this.state.type === types.name && this.state.value === "_") {
  2411. const startPos = this.state.start;
  2412. const startLoc = this.state.startLoc;
  2413. const node = this.parseIdentifier();
  2414. return this.flowParseGenericType(startPos, startLoc, node);
  2415. } else {
  2416. return this.flowParseType();
  2417. }
  2418. }
  2419. flowParseTypeAnnotation() {
  2420. const node = this.startNode();
  2421. node.typeAnnotation = this.flowParseTypeInitialiser();
  2422. return this.finishNode(node, "TypeAnnotation");
  2423. }
  2424. flowParseTypeAnnotatableIdentifier(allowPrimitiveOverride) {
  2425. const ident = allowPrimitiveOverride ? this.parseIdentifier() : this.flowParseRestrictedIdentifier();
  2426. if (this.match(types.colon)) {
  2427. ident.typeAnnotation = this.flowParseTypeAnnotation();
  2428. this.resetEndLocation(ident);
  2429. }
  2430. return ident;
  2431. }
  2432. typeCastToParameter(node) {
  2433. node.expression.typeAnnotation = node.typeAnnotation;
  2434. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  2435. return node.expression;
  2436. }
  2437. flowParseVariance() {
  2438. let variance = null;
  2439. if (this.match(types.plusMin)) {
  2440. variance = this.startNode();
  2441. if (this.state.value === "+") {
  2442. variance.kind = "plus";
  2443. } else {
  2444. variance.kind = "minus";
  2445. }
  2446. this.next();
  2447. this.finishNode(variance, "Variance");
  2448. }
  2449. return variance;
  2450. }
  2451. parseFunctionBody(node, allowExpressionBody, isMethod = false) {
  2452. if (allowExpressionBody) {
  2453. return this.forwardNoArrowParamsConversionAt(node, () => super.parseFunctionBody(node, true, isMethod));
  2454. }
  2455. return super.parseFunctionBody(node, false, isMethod);
  2456. }
  2457. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  2458. if (this.match(types.colon)) {
  2459. const typeNode = this.startNode();
  2460. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  2461. node.returnType = typeNode.typeAnnotation ? this.finishNode(typeNode, "TypeAnnotation") : null;
  2462. }
  2463. super.parseFunctionBodyAndFinish(node, type, isMethod);
  2464. }
  2465. parseStatement(context, topLevel) {
  2466. if (this.state.strict && this.match(types.name) && this.state.value === "interface") {
  2467. const lookahead = this.lookahead();
  2468. if (lookahead.type === types.name || isKeyword(lookahead.value)) {
  2469. const node = this.startNode();
  2470. this.next();
  2471. return this.flowParseInterface(node);
  2472. }
  2473. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2474. const node = this.startNode();
  2475. this.next();
  2476. return this.flowParseEnumDeclaration(node);
  2477. }
  2478. const stmt = super.parseStatement(context, topLevel);
  2479. if (this.flowPragma === undefined && !this.isValidDirective(stmt)) {
  2480. this.flowPragma = null;
  2481. }
  2482. return stmt;
  2483. }
  2484. parseExpressionStatement(node, expr) {
  2485. if (expr.type === "Identifier") {
  2486. if (expr.name === "declare") {
  2487. if (this.match(types._class) || this.match(types.name) || this.match(types._function) || this.match(types._var) || this.match(types._export)) {
  2488. return this.flowParseDeclare(node);
  2489. }
  2490. } else if (this.match(types.name)) {
  2491. if (expr.name === "interface") {
  2492. return this.flowParseInterface(node);
  2493. } else if (expr.name === "type") {
  2494. return this.flowParseTypeAlias(node);
  2495. } else if (expr.name === "opaque") {
  2496. return this.flowParseOpaqueType(node, false);
  2497. }
  2498. }
  2499. }
  2500. return super.parseExpressionStatement(node, expr);
  2501. }
  2502. shouldParseExportDeclaration() {
  2503. return this.isContextual("type") || this.isContextual("interface") || this.isContextual("opaque") || this.shouldParseEnums() && this.isContextual("enum") || super.shouldParseExportDeclaration();
  2504. }
  2505. isExportDefaultSpecifier() {
  2506. if (this.match(types.name) && (this.state.value === "type" || this.state.value === "interface" || this.state.value === "opaque" || this.shouldParseEnums() && this.state.value === "enum")) {
  2507. return false;
  2508. }
  2509. return super.isExportDefaultSpecifier();
  2510. }
  2511. parseExportDefaultExpression() {
  2512. if (this.shouldParseEnums() && this.isContextual("enum")) {
  2513. const node = this.startNode();
  2514. this.next();
  2515. return this.flowParseEnumDeclaration(node);
  2516. }
  2517. return super.parseExportDefaultExpression();
  2518. }
  2519. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  2520. if (!this.match(types.question)) return expr;
  2521. if (refNeedsArrowPos) {
  2522. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  2523. if (!result.node) {
  2524. refNeedsArrowPos.start = result.error.pos || this.state.start;
  2525. return expr;
  2526. }
  2527. if (result.error) this.state = result.failState;
  2528. return result.node;
  2529. }
  2530. this.expect(types.question);
  2531. const state = this.state.clone();
  2532. const originalNoArrowAt = this.state.noArrowAt;
  2533. const node = this.startNodeAt(startPos, startLoc);
  2534. let {
  2535. consequent,
  2536. failed
  2537. } = this.tryParseConditionalConsequent();
  2538. let [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2539. if (failed || invalid.length > 0) {
  2540. const noArrowAt = [...originalNoArrowAt];
  2541. if (invalid.length > 0) {
  2542. this.state = state;
  2543. this.state.noArrowAt = noArrowAt;
  2544. for (let i = 0; i < invalid.length; i++) {
  2545. noArrowAt.push(invalid[i].start);
  2546. }
  2547. ({
  2548. consequent,
  2549. failed
  2550. } = this.tryParseConditionalConsequent());
  2551. [valid, invalid] = this.getArrowLikeExpressions(consequent);
  2552. }
  2553. if (failed && valid.length > 1) {
  2554. this.raise(state.start, FlowErrors.AmbiguousConditionalArrow);
  2555. }
  2556. if (failed && valid.length === 1) {
  2557. this.state = state;
  2558. this.state.noArrowAt = noArrowAt.concat(valid[0].start);
  2559. ({
  2560. consequent,
  2561. failed
  2562. } = this.tryParseConditionalConsequent());
  2563. }
  2564. }
  2565. this.getArrowLikeExpressions(consequent, true);
  2566. this.state.noArrowAt = originalNoArrowAt;
  2567. this.expect(types.colon);
  2568. node.test = expr;
  2569. node.consequent = consequent;
  2570. node.alternate = this.forwardNoArrowParamsConversionAt(node, () => this.parseMaybeAssign(undefined, undefined, undefined));
  2571. return this.finishNode(node, "ConditionalExpression");
  2572. }
  2573. tryParseConditionalConsequent() {
  2574. this.state.noArrowParamsConversionAt.push(this.state.start);
  2575. const consequent = this.parseMaybeAssignAllowIn();
  2576. const failed = !this.match(types.colon);
  2577. this.state.noArrowParamsConversionAt.pop();
  2578. return {
  2579. consequent,
  2580. failed
  2581. };
  2582. }
  2583. getArrowLikeExpressions(node, disallowInvalid) {
  2584. const stack = [node];
  2585. const arrows = [];
  2586. while (stack.length !== 0) {
  2587. const node = stack.pop();
  2588. if (node.type === "ArrowFunctionExpression") {
  2589. if (node.typeParameters || !node.returnType) {
  2590. this.finishArrowValidation(node);
  2591. } else {
  2592. arrows.push(node);
  2593. }
  2594. stack.push(node.body);
  2595. } else if (node.type === "ConditionalExpression") {
  2596. stack.push(node.consequent);
  2597. stack.push(node.alternate);
  2598. }
  2599. }
  2600. if (disallowInvalid) {
  2601. arrows.forEach(node => this.finishArrowValidation(node));
  2602. return [arrows, []];
  2603. }
  2604. return partition(arrows, node => node.params.every(param => this.isAssignable(param, true)));
  2605. }
  2606. finishArrowValidation(node) {
  2607. var _node$extra;
  2608. this.toAssignableList(node.params, (_node$extra = node.extra) == null ? void 0 : _node$extra.trailingComma, false);
  2609. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  2610. super.checkParams(node, false, true);
  2611. this.scope.exit();
  2612. }
  2613. forwardNoArrowParamsConversionAt(node, parse) {
  2614. let result;
  2615. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  2616. this.state.noArrowParamsConversionAt.push(this.state.start);
  2617. result = parse();
  2618. this.state.noArrowParamsConversionAt.pop();
  2619. } else {
  2620. result = parse();
  2621. }
  2622. return result;
  2623. }
  2624. parseParenItem(node, startPos, startLoc) {
  2625. node = super.parseParenItem(node, startPos, startLoc);
  2626. if (this.eat(types.question)) {
  2627. node.optional = true;
  2628. this.resetEndLocation(node);
  2629. }
  2630. if (this.match(types.colon)) {
  2631. const typeCastNode = this.startNodeAt(startPos, startLoc);
  2632. typeCastNode.expression = node;
  2633. typeCastNode.typeAnnotation = this.flowParseTypeAnnotation();
  2634. return this.finishNode(typeCastNode, "TypeCastExpression");
  2635. }
  2636. return node;
  2637. }
  2638. assertModuleNodeAllowed(node) {
  2639. if (node.type === "ImportDeclaration" && (node.importKind === "type" || node.importKind === "typeof") || node.type === "ExportNamedDeclaration" && node.exportKind === "type" || node.type === "ExportAllDeclaration" && node.exportKind === "type") {
  2640. return;
  2641. }
  2642. super.assertModuleNodeAllowed(node);
  2643. }
  2644. parseExport(node) {
  2645. const decl = super.parseExport(node);
  2646. if (decl.type === "ExportNamedDeclaration" || decl.type === "ExportAllDeclaration") {
  2647. decl.exportKind = decl.exportKind || "value";
  2648. }
  2649. return decl;
  2650. }
  2651. parseExportDeclaration(node) {
  2652. if (this.isContextual("type")) {
  2653. node.exportKind = "type";
  2654. const declarationNode = this.startNode();
  2655. this.next();
  2656. if (this.match(types.braceL)) {
  2657. node.specifiers = this.parseExportSpecifiers();
  2658. this.parseExportFrom(node);
  2659. return null;
  2660. } else {
  2661. return this.flowParseTypeAlias(declarationNode);
  2662. }
  2663. } else if (this.isContextual("opaque")) {
  2664. node.exportKind = "type";
  2665. const declarationNode = this.startNode();
  2666. this.next();
  2667. return this.flowParseOpaqueType(declarationNode, false);
  2668. } else if (this.isContextual("interface")) {
  2669. node.exportKind = "type";
  2670. const declarationNode = this.startNode();
  2671. this.next();
  2672. return this.flowParseInterface(declarationNode);
  2673. } else if (this.shouldParseEnums() && this.isContextual("enum")) {
  2674. node.exportKind = "value";
  2675. const declarationNode = this.startNode();
  2676. this.next();
  2677. return this.flowParseEnumDeclaration(declarationNode);
  2678. } else {
  2679. return super.parseExportDeclaration(node);
  2680. }
  2681. }
  2682. eatExportStar(node) {
  2683. if (super.eatExportStar(...arguments)) return true;
  2684. if (this.isContextual("type") && this.lookahead().type === types.star) {
  2685. node.exportKind = "type";
  2686. this.next();
  2687. this.next();
  2688. return true;
  2689. }
  2690. return false;
  2691. }
  2692. maybeParseExportNamespaceSpecifier(node) {
  2693. const pos = this.state.start;
  2694. const hasNamespace = super.maybeParseExportNamespaceSpecifier(node);
  2695. if (hasNamespace && node.exportKind === "type") {
  2696. this.unexpected(pos);
  2697. }
  2698. return hasNamespace;
  2699. }
  2700. parseClassId(node, isStatement, optionalId) {
  2701. super.parseClassId(node, isStatement, optionalId);
  2702. if (this.isRelational("<")) {
  2703. node.typeParameters = this.flowParseTypeParameterDeclaration();
  2704. }
  2705. }
  2706. parseClassMember(classBody, member, state) {
  2707. const pos = this.state.start;
  2708. if (this.isContextual("declare")) {
  2709. if (this.parseClassMemberFromModifier(classBody, member)) {
  2710. return;
  2711. }
  2712. member.declare = true;
  2713. }
  2714. super.parseClassMember(classBody, member, state);
  2715. if (member.declare) {
  2716. if (member.type !== "ClassProperty" && member.type !== "ClassPrivateProperty" && member.type !== "PropertyDefinition") {
  2717. this.raise(pos, FlowErrors.DeclareClassElement);
  2718. } else if (member.value) {
  2719. this.raise(member.value.start, FlowErrors.DeclareClassFieldInitializer);
  2720. }
  2721. }
  2722. }
  2723. getTokenFromCode(code) {
  2724. const next = this.input.charCodeAt(this.state.pos + 1);
  2725. if (code === 123 && next === 124) {
  2726. return this.finishOp(types.braceBarL, 2);
  2727. } else if (this.state.inType && (code === 62 || code === 60)) {
  2728. return this.finishOp(types.relational, 1);
  2729. } else if (this.state.inType && code === 63) {
  2730. return this.finishOp(types.question, 1);
  2731. } else if (isIteratorStart(code, next)) {
  2732. this.state.isIterator = true;
  2733. return super.readWord();
  2734. } else {
  2735. return super.getTokenFromCode(code);
  2736. }
  2737. }
  2738. isAssignable(node, isBinding) {
  2739. switch (node.type) {
  2740. case "Identifier":
  2741. case "ObjectPattern":
  2742. case "ArrayPattern":
  2743. case "AssignmentPattern":
  2744. return true;
  2745. case "ObjectExpression":
  2746. {
  2747. const last = node.properties.length - 1;
  2748. return node.properties.every((prop, i) => {
  2749. return prop.type !== "ObjectMethod" && (i === last || prop.type === "SpreadElement") && this.isAssignable(prop);
  2750. });
  2751. }
  2752. case "ObjectProperty":
  2753. return this.isAssignable(node.value);
  2754. case "SpreadElement":
  2755. return this.isAssignable(node.argument);
  2756. case "ArrayExpression":
  2757. return node.elements.every(element => this.isAssignable(element));
  2758. case "AssignmentExpression":
  2759. return node.operator === "=";
  2760. case "ParenthesizedExpression":
  2761. case "TypeCastExpression":
  2762. return this.isAssignable(node.expression);
  2763. case "MemberExpression":
  2764. case "OptionalMemberExpression":
  2765. return !isBinding;
  2766. default:
  2767. return false;
  2768. }
  2769. }
  2770. toAssignable(node, isLHS = false) {
  2771. if (node.type === "TypeCastExpression") {
  2772. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  2773. } else {
  2774. return super.toAssignable(node, isLHS);
  2775. }
  2776. }
  2777. toAssignableList(exprList, trailingCommaPos, isLHS) {
  2778. for (let i = 0; i < exprList.length; i++) {
  2779. const expr = exprList[i];
  2780. if ((expr == null ? void 0 : expr.type) === "TypeCastExpression") {
  2781. exprList[i] = this.typeCastToParameter(expr);
  2782. }
  2783. }
  2784. return super.toAssignableList(exprList, trailingCommaPos, isLHS);
  2785. }
  2786. toReferencedList(exprList, isParenthesizedExpr) {
  2787. for (let i = 0; i < exprList.length; i++) {
  2788. var _expr$extra;
  2789. const expr = exprList[i];
  2790. if (expr && expr.type === "TypeCastExpression" && !((_expr$extra = expr.extra) != null && _expr$extra.parenthesized) && (exprList.length > 1 || !isParenthesizedExpr)) {
  2791. this.raise(expr.typeAnnotation.start, FlowErrors.TypeCastInPattern);
  2792. }
  2793. }
  2794. return exprList;
  2795. }
  2796. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  2797. const node = super.parseArrayLike(close, canBePattern, isTuple, refExpressionErrors);
  2798. if (canBePattern && !this.state.maybeInArrowParameters) {
  2799. this.toReferencedList(node.elements);
  2800. }
  2801. return node;
  2802. }
  2803. checkLVal(expr, ...args) {
  2804. if (expr.type !== "TypeCastExpression") {
  2805. return super.checkLVal(expr, ...args);
  2806. }
  2807. }
  2808. parseClassProperty(node) {
  2809. if (this.match(types.colon)) {
  2810. node.typeAnnotation = this.flowParseTypeAnnotation();
  2811. }
  2812. return super.parseClassProperty(node);
  2813. }
  2814. parseClassPrivateProperty(node) {
  2815. if (this.match(types.colon)) {
  2816. node.typeAnnotation = this.flowParseTypeAnnotation();
  2817. }
  2818. return super.parseClassPrivateProperty(node);
  2819. }
  2820. isClassMethod() {
  2821. return this.isRelational("<") || super.isClassMethod();
  2822. }
  2823. isClassProperty() {
  2824. return this.match(types.colon) || super.isClassProperty();
  2825. }
  2826. isNonstaticConstructor(method) {
  2827. return !this.match(types.colon) && super.isNonstaticConstructor(method);
  2828. }
  2829. isThisParam(param) {
  2830. return param.type === "Identifier" && param.name === "this";
  2831. }
  2832. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  2833. if (method.variance) {
  2834. this.unexpected(method.variance.start);
  2835. }
  2836. delete method.variance;
  2837. if (this.isRelational("<")) {
  2838. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2839. }
  2840. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  2841. if (method.params && isConstructor) {
  2842. const params = method.params;
  2843. if (params.length > 0 && this.isThisParam(params[0])) {
  2844. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  2845. }
  2846. } else if (method.type === "MethodDefinition" && isConstructor && method.value.params) {
  2847. const params = method.value.params;
  2848. if (params.length > 0 && this.isThisParam(params[0])) {
  2849. this.raise(method.start, FlowErrors.ThisParamBannedInConstructor);
  2850. }
  2851. }
  2852. }
  2853. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  2854. if (method.variance) {
  2855. this.unexpected(method.variance.start);
  2856. }
  2857. delete method.variance;
  2858. if (this.isRelational("<")) {
  2859. method.typeParameters = this.flowParseTypeParameterDeclaration();
  2860. }
  2861. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  2862. }
  2863. parseClassSuper(node) {
  2864. super.parseClassSuper(node);
  2865. if (node.superClass && this.isRelational("<")) {
  2866. node.superTypeParameters = this.flowParseTypeParameterInstantiation();
  2867. }
  2868. if (this.isContextual("implements")) {
  2869. this.next();
  2870. const implemented = node.implements = [];
  2871. do {
  2872. const node = this.startNode();
  2873. node.id = this.flowParseRestrictedIdentifier(true);
  2874. if (this.isRelational("<")) {
  2875. node.typeParameters = this.flowParseTypeParameterInstantiation();
  2876. } else {
  2877. node.typeParameters = null;
  2878. }
  2879. implemented.push(this.finishNode(node, "ClassImplements"));
  2880. } while (this.eat(types.comma));
  2881. }
  2882. }
  2883. checkGetterSetterParams(method) {
  2884. super.checkGetterSetterParams(method);
  2885. const params = this.getObjectOrClassMethodParams(method);
  2886. if (params.length > 0) {
  2887. const param = params[0];
  2888. if (this.isThisParam(param) && method.kind === "get") {
  2889. this.raise(param.start, FlowErrors.GetterMayNotHaveThisParam);
  2890. } else if (this.isThisParam(param)) {
  2891. this.raise(param.start, FlowErrors.SetterMayNotHaveThisParam);
  2892. }
  2893. }
  2894. }
  2895. parsePropertyName(node, isPrivateNameAllowed) {
  2896. const variance = this.flowParseVariance();
  2897. const key = super.parsePropertyName(node, isPrivateNameAllowed);
  2898. node.variance = variance;
  2899. return key;
  2900. }
  2901. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  2902. if (prop.variance) {
  2903. this.unexpected(prop.variance.start);
  2904. }
  2905. delete prop.variance;
  2906. let typeParameters;
  2907. if (this.isRelational("<") && !isAccessor) {
  2908. typeParameters = this.flowParseTypeParameterDeclaration();
  2909. if (!this.match(types.parenL)) this.unexpected();
  2910. }
  2911. super.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  2912. if (typeParameters) {
  2913. (prop.value || prop).typeParameters = typeParameters;
  2914. }
  2915. }
  2916. parseAssignableListItemTypes(param) {
  2917. if (this.eat(types.question)) {
  2918. if (param.type !== "Identifier") {
  2919. this.raise(param.start, FlowErrors.OptionalBindingPattern);
  2920. }
  2921. if (this.isThisParam(param)) {
  2922. this.raise(param.start, FlowErrors.ThisParamMayNotBeOptional);
  2923. }
  2924. param.optional = true;
  2925. }
  2926. if (this.match(types.colon)) {
  2927. param.typeAnnotation = this.flowParseTypeAnnotation();
  2928. } else if (this.isThisParam(param)) {
  2929. this.raise(param.start, FlowErrors.ThisParamAnnotationRequired);
  2930. }
  2931. if (this.match(types.eq) && this.isThisParam(param)) {
  2932. this.raise(param.start, FlowErrors.ThisParamNoDefault);
  2933. }
  2934. this.resetEndLocation(param);
  2935. return param;
  2936. }
  2937. parseMaybeDefault(startPos, startLoc, left) {
  2938. const node = super.parseMaybeDefault(startPos, startLoc, left);
  2939. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  2940. this.raise(node.typeAnnotation.start, FlowErrors.TypeBeforeInitializer);
  2941. }
  2942. return node;
  2943. }
  2944. shouldParseDefaultImport(node) {
  2945. if (!hasTypeImportKind(node)) {
  2946. return super.shouldParseDefaultImport(node);
  2947. }
  2948. return isMaybeDefaultImport(this.state);
  2949. }
  2950. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  2951. specifier.local = hasTypeImportKind(node) ? this.flowParseRestrictedIdentifier(true, true) : this.parseIdentifier();
  2952. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  2953. node.specifiers.push(this.finishNode(specifier, type));
  2954. }
  2955. maybeParseDefaultImportSpecifier(node) {
  2956. node.importKind = "value";
  2957. let kind = null;
  2958. if (this.match(types._typeof)) {
  2959. kind = "typeof";
  2960. } else if (this.isContextual("type")) {
  2961. kind = "type";
  2962. }
  2963. if (kind) {
  2964. const lh = this.lookahead();
  2965. if (kind === "type" && lh.type === types.star) {
  2966. this.unexpected(lh.start);
  2967. }
  2968. if (isMaybeDefaultImport(lh) || lh.type === types.braceL || lh.type === types.star) {
  2969. this.next();
  2970. node.importKind = kind;
  2971. }
  2972. }
  2973. return super.maybeParseDefaultImportSpecifier(node);
  2974. }
  2975. parseImportSpecifier(node) {
  2976. const specifier = this.startNode();
  2977. const firstIdentLoc = this.state.start;
  2978. const firstIdent = this.parseModuleExportName();
  2979. let specifierTypeKind = null;
  2980. if (firstIdent.type === "Identifier") {
  2981. if (firstIdent.name === "type") {
  2982. specifierTypeKind = "type";
  2983. } else if (firstIdent.name === "typeof") {
  2984. specifierTypeKind = "typeof";
  2985. }
  2986. }
  2987. let isBinding = false;
  2988. if (this.isContextual("as") && !this.isLookaheadContextual("as")) {
  2989. const as_ident = this.parseIdentifier(true);
  2990. if (specifierTypeKind !== null && !this.match(types.name) && !this.state.type.keyword) {
  2991. specifier.imported = as_ident;
  2992. specifier.importKind = specifierTypeKind;
  2993. specifier.local = as_ident.__clone();
  2994. } else {
  2995. specifier.imported = firstIdent;
  2996. specifier.importKind = null;
  2997. specifier.local = this.parseIdentifier();
  2998. }
  2999. } else if (specifierTypeKind !== null && (this.match(types.name) || this.state.type.keyword)) {
  3000. specifier.imported = this.parseIdentifier(true);
  3001. specifier.importKind = specifierTypeKind;
  3002. if (this.eatContextual("as")) {
  3003. specifier.local = this.parseIdentifier();
  3004. } else {
  3005. isBinding = true;
  3006. specifier.local = specifier.imported.__clone();
  3007. }
  3008. } else {
  3009. if (firstIdent.type === "StringLiteral") {
  3010. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, firstIdent.value);
  3011. }
  3012. isBinding = true;
  3013. specifier.imported = firstIdent;
  3014. specifier.importKind = null;
  3015. specifier.local = specifier.imported.__clone();
  3016. }
  3017. const nodeIsTypeImport = hasTypeImportKind(node);
  3018. const specifierIsTypeImport = hasTypeImportKind(specifier);
  3019. if (nodeIsTypeImport && specifierIsTypeImport) {
  3020. this.raise(firstIdentLoc, FlowErrors.ImportTypeShorthandOnlyInPureImport);
  3021. }
  3022. if (nodeIsTypeImport || specifierIsTypeImport) {
  3023. this.checkReservedType(specifier.local.name, specifier.local.start, true);
  3024. }
  3025. if (isBinding && !nodeIsTypeImport && !specifierIsTypeImport) {
  3026. this.checkReservedWord(specifier.local.name, specifier.start, true, true);
  3027. }
  3028. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  3029. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  3030. }
  3031. parseBindingAtom() {
  3032. switch (this.state.type) {
  3033. case types._this:
  3034. return this.parseIdentifier(true);
  3035. default:
  3036. return super.parseBindingAtom();
  3037. }
  3038. }
  3039. parseFunctionParams(node, allowModifiers) {
  3040. const kind = node.kind;
  3041. if (kind !== "get" && kind !== "set" && this.isRelational("<")) {
  3042. node.typeParameters = this.flowParseTypeParameterDeclaration();
  3043. }
  3044. super.parseFunctionParams(node, allowModifiers);
  3045. }
  3046. parseVarId(decl, kind) {
  3047. super.parseVarId(decl, kind);
  3048. if (this.match(types.colon)) {
  3049. decl.id.typeAnnotation = this.flowParseTypeAnnotation();
  3050. this.resetEndLocation(decl.id);
  3051. }
  3052. }
  3053. parseAsyncArrowFromCallExpression(node, call) {
  3054. if (this.match(types.colon)) {
  3055. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  3056. this.state.noAnonFunctionType = true;
  3057. node.returnType = this.flowParseTypeAnnotation();
  3058. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  3059. }
  3060. return super.parseAsyncArrowFromCallExpression(node, call);
  3061. }
  3062. shouldParseAsyncArrow() {
  3063. return this.match(types.colon) || super.shouldParseAsyncArrow();
  3064. }
  3065. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  3066. var _jsx;
  3067. let state = null;
  3068. let jsx;
  3069. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  3070. state = this.state.clone();
  3071. jsx = this.tryParse(() => super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos), state);
  3072. if (!jsx.error) return jsx.node;
  3073. const {
  3074. context
  3075. } = this.state;
  3076. if (context[context.length - 1] === types$1.j_oTag) {
  3077. context.length -= 2;
  3078. } else if (context[context.length - 1] === types$1.j_expr) {
  3079. context.length -= 1;
  3080. }
  3081. }
  3082. if ((_jsx = jsx) != null && _jsx.error || this.isRelational("<")) {
  3083. var _jsx2, _jsx3;
  3084. state = state || this.state.clone();
  3085. let typeParameters;
  3086. const arrow = this.tryParse(abort => {
  3087. var _arrowExpression$extr;
  3088. typeParameters = this.flowParseTypeParameterDeclaration();
  3089. const arrowExpression = this.forwardNoArrowParamsConversionAt(typeParameters, () => {
  3090. const result = super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  3091. this.resetStartLocationFromNode(result, typeParameters);
  3092. return result;
  3093. });
  3094. if (arrowExpression.type !== "ArrowFunctionExpression" && (_arrowExpression$extr = arrowExpression.extra) != null && _arrowExpression$extr.parenthesized) {
  3095. abort();
  3096. }
  3097. const expr = this.maybeUnwrapTypeCastExpression(arrowExpression);
  3098. expr.typeParameters = typeParameters;
  3099. this.resetStartLocationFromNode(expr, typeParameters);
  3100. return arrowExpression;
  3101. }, state);
  3102. let arrowExpression = null;
  3103. if (arrow.node && this.maybeUnwrapTypeCastExpression(arrow.node).type === "ArrowFunctionExpression") {
  3104. if (!arrow.error && !arrow.aborted) {
  3105. if (arrow.node.async) {
  3106. this.raise(typeParameters.start, FlowErrors.UnexpectedTypeParameterBeforeAsyncArrowFunction);
  3107. }
  3108. return arrow.node;
  3109. }
  3110. arrowExpression = arrow.node;
  3111. }
  3112. if ((_jsx2 = jsx) != null && _jsx2.node) {
  3113. this.state = jsx.failState;
  3114. return jsx.node;
  3115. }
  3116. if (arrowExpression) {
  3117. this.state = arrow.failState;
  3118. return arrowExpression;
  3119. }
  3120. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  3121. if (arrow.thrown) throw arrow.error;
  3122. throw this.raise(typeParameters.start, FlowErrors.UnexpectedTokenAfterTypeParameter);
  3123. }
  3124. return super.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos);
  3125. }
  3126. parseArrow(node) {
  3127. if (this.match(types.colon)) {
  3128. const result = this.tryParse(() => {
  3129. const oldNoAnonFunctionType = this.state.noAnonFunctionType;
  3130. this.state.noAnonFunctionType = true;
  3131. const typeNode = this.startNode();
  3132. [typeNode.typeAnnotation, node.predicate] = this.flowParseTypeAndPredicateInitialiser();
  3133. this.state.noAnonFunctionType = oldNoAnonFunctionType;
  3134. if (this.canInsertSemicolon()) this.unexpected();
  3135. if (!this.match(types.arrow)) this.unexpected();
  3136. return typeNode;
  3137. });
  3138. if (result.thrown) return null;
  3139. if (result.error) this.state = result.failState;
  3140. node.returnType = result.node.typeAnnotation ? this.finishNode(result.node, "TypeAnnotation") : null;
  3141. }
  3142. return super.parseArrow(node);
  3143. }
  3144. shouldParseArrow() {
  3145. return this.match(types.colon) || super.shouldParseArrow();
  3146. }
  3147. setArrowFunctionParameters(node, params) {
  3148. if (this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  3149. node.params = params;
  3150. } else {
  3151. super.setArrowFunctionParameters(node, params);
  3152. }
  3153. }
  3154. checkParams(node, allowDuplicates, isArrowFunction) {
  3155. if (isArrowFunction && this.state.noArrowParamsConversionAt.indexOf(node.start) !== -1) {
  3156. return;
  3157. }
  3158. for (let i = 0; i < node.params.length; i++) {
  3159. if (this.isThisParam(node.params[i]) && i > 0) {
  3160. this.raise(node.params[i].start, FlowErrors.ThisParamMustBeFirst);
  3161. }
  3162. }
  3163. return super.checkParams(...arguments);
  3164. }
  3165. parseParenAndDistinguishExpression(canBeArrow) {
  3166. return super.parseParenAndDistinguishExpression(canBeArrow && this.state.noArrowAt.indexOf(this.state.start) === -1);
  3167. }
  3168. parseSubscripts(base, startPos, startLoc, noCalls) {
  3169. if (base.type === "Identifier" && base.name === "async" && this.state.noArrowAt.indexOf(startPos) !== -1) {
  3170. this.next();
  3171. const node = this.startNodeAt(startPos, startLoc);
  3172. node.callee = base;
  3173. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  3174. base = this.finishNode(node, "CallExpression");
  3175. } else if (base.type === "Identifier" && base.name === "async" && this.isRelational("<")) {
  3176. const state = this.state.clone();
  3177. const arrow = this.tryParse(abort => this.parseAsyncArrowWithTypeParameters(startPos, startLoc) || abort(), state);
  3178. if (!arrow.error && !arrow.aborted) return arrow.node;
  3179. const result = this.tryParse(() => super.parseSubscripts(base, startPos, startLoc, noCalls), state);
  3180. if (result.node && !result.error) return result.node;
  3181. if (arrow.node) {
  3182. this.state = arrow.failState;
  3183. return arrow.node;
  3184. }
  3185. if (result.node) {
  3186. this.state = result.failState;
  3187. return result.node;
  3188. }
  3189. throw arrow.error || result.error;
  3190. }
  3191. return super.parseSubscripts(base, startPos, startLoc, noCalls);
  3192. }
  3193. parseSubscript(base, startPos, startLoc, noCalls, subscriptState) {
  3194. if (this.match(types.questionDot) && this.isLookaheadToken_lt()) {
  3195. subscriptState.optionalChainMember = true;
  3196. if (noCalls) {
  3197. subscriptState.stop = true;
  3198. return base;
  3199. }
  3200. this.next();
  3201. const node = this.startNodeAt(startPos, startLoc);
  3202. node.callee = base;
  3203. node.typeArguments = this.flowParseTypeParameterInstantiation();
  3204. this.expect(types.parenL);
  3205. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  3206. node.optional = true;
  3207. return this.finishCallExpression(node, true);
  3208. } else if (!noCalls && this.shouldParseTypes() && this.isRelational("<")) {
  3209. const node = this.startNodeAt(startPos, startLoc);
  3210. node.callee = base;
  3211. const result = this.tryParse(() => {
  3212. node.typeArguments = this.flowParseTypeParameterInstantiationCallOrNew();
  3213. this.expect(types.parenL);
  3214. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  3215. if (subscriptState.optionalChainMember) node.optional = false;
  3216. return this.finishCallExpression(node, subscriptState.optionalChainMember);
  3217. });
  3218. if (result.node) {
  3219. if (result.error) this.state = result.failState;
  3220. return result.node;
  3221. }
  3222. }
  3223. return super.parseSubscript(base, startPos, startLoc, noCalls, subscriptState);
  3224. }
  3225. parseNewArguments(node) {
  3226. let targs = null;
  3227. if (this.shouldParseTypes() && this.isRelational("<")) {
  3228. targs = this.tryParse(() => this.flowParseTypeParameterInstantiationCallOrNew()).node;
  3229. }
  3230. node.typeArguments = targs;
  3231. super.parseNewArguments(node);
  3232. }
  3233. parseAsyncArrowWithTypeParameters(startPos, startLoc) {
  3234. const node = this.startNodeAt(startPos, startLoc);
  3235. this.parseFunctionParams(node);
  3236. if (!this.parseArrow(node)) return;
  3237. return this.parseArrowExpression(node, undefined, true);
  3238. }
  3239. readToken_mult_modulo(code) {
  3240. const next = this.input.charCodeAt(this.state.pos + 1);
  3241. if (code === 42 && next === 47 && this.state.hasFlowComment) {
  3242. this.state.hasFlowComment = false;
  3243. this.state.pos += 2;
  3244. this.nextToken();
  3245. return;
  3246. }
  3247. super.readToken_mult_modulo(code);
  3248. }
  3249. readToken_pipe_amp(code) {
  3250. const next = this.input.charCodeAt(this.state.pos + 1);
  3251. if (code === 124 && next === 125) {
  3252. this.finishOp(types.braceBarR, 2);
  3253. return;
  3254. }
  3255. super.readToken_pipe_amp(code);
  3256. }
  3257. parseTopLevel(file, program) {
  3258. const fileNode = super.parseTopLevel(file, program);
  3259. if (this.state.hasFlowComment) {
  3260. this.raise(this.state.pos, FlowErrors.UnterminatedFlowComment);
  3261. }
  3262. return fileNode;
  3263. }
  3264. skipBlockComment() {
  3265. if (this.hasPlugin("flowComments") && this.skipFlowComment()) {
  3266. if (this.state.hasFlowComment) {
  3267. this.unexpected(null, FlowErrors.NestedFlowComment);
  3268. }
  3269. this.hasFlowCommentCompletion();
  3270. this.state.pos += this.skipFlowComment();
  3271. this.state.hasFlowComment = true;
  3272. return;
  3273. }
  3274. if (this.state.hasFlowComment) {
  3275. const end = this.input.indexOf("*-/", this.state.pos += 2);
  3276. if (end === -1) {
  3277. throw this.raise(this.state.pos - 2, ErrorMessages.UnterminatedComment);
  3278. }
  3279. this.state.pos = end + 3;
  3280. return;
  3281. }
  3282. super.skipBlockComment();
  3283. }
  3284. skipFlowComment() {
  3285. const {
  3286. pos
  3287. } = this.state;
  3288. let shiftToFirstNonWhiteSpace = 2;
  3289. while ([32, 9].includes(this.input.charCodeAt(pos + shiftToFirstNonWhiteSpace))) {
  3290. shiftToFirstNonWhiteSpace++;
  3291. }
  3292. const ch2 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos);
  3293. const ch3 = this.input.charCodeAt(shiftToFirstNonWhiteSpace + pos + 1);
  3294. if (ch2 === 58 && ch3 === 58) {
  3295. return shiftToFirstNonWhiteSpace + 2;
  3296. }
  3297. if (this.input.slice(shiftToFirstNonWhiteSpace + pos, shiftToFirstNonWhiteSpace + pos + 12) === "flow-include") {
  3298. return shiftToFirstNonWhiteSpace + 12;
  3299. }
  3300. if (ch2 === 58 && ch3 !== 58) {
  3301. return shiftToFirstNonWhiteSpace;
  3302. }
  3303. return false;
  3304. }
  3305. hasFlowCommentCompletion() {
  3306. const end = this.input.indexOf("*/", this.state.pos);
  3307. if (end === -1) {
  3308. throw this.raise(this.state.pos, ErrorMessages.UnterminatedComment);
  3309. }
  3310. }
  3311. flowEnumErrorBooleanMemberNotInitialized(pos, {
  3312. enumName,
  3313. memberName
  3314. }) {
  3315. this.raise(pos, FlowErrors.EnumBooleanMemberNotInitialized, memberName, enumName);
  3316. }
  3317. flowEnumErrorInvalidMemberName(pos, {
  3318. enumName,
  3319. memberName
  3320. }) {
  3321. const suggestion = memberName[0].toUpperCase() + memberName.slice(1);
  3322. this.raise(pos, FlowErrors.EnumInvalidMemberName, memberName, suggestion, enumName);
  3323. }
  3324. flowEnumErrorDuplicateMemberName(pos, {
  3325. enumName,
  3326. memberName
  3327. }) {
  3328. this.raise(pos, FlowErrors.EnumDuplicateMemberName, memberName, enumName);
  3329. }
  3330. flowEnumErrorInconsistentMemberValues(pos, {
  3331. enumName
  3332. }) {
  3333. this.raise(pos, FlowErrors.EnumInconsistentMemberValues, enumName);
  3334. }
  3335. flowEnumErrorInvalidExplicitType(pos, {
  3336. enumName,
  3337. suppliedType
  3338. }) {
  3339. return this.raise(pos, suppliedType === null ? FlowErrors.EnumInvalidExplicitTypeUnknownSupplied : FlowErrors.EnumInvalidExplicitType, enumName, suppliedType);
  3340. }
  3341. flowEnumErrorInvalidMemberInitializer(pos, {
  3342. enumName,
  3343. explicitType,
  3344. memberName
  3345. }) {
  3346. let message = null;
  3347. switch (explicitType) {
  3348. case "boolean":
  3349. case "number":
  3350. case "string":
  3351. message = FlowErrors.EnumInvalidMemberInitializerPrimaryType;
  3352. break;
  3353. case "symbol":
  3354. message = FlowErrors.EnumInvalidMemberInitializerSymbolType;
  3355. break;
  3356. default:
  3357. message = FlowErrors.EnumInvalidMemberInitializerUnknownType;
  3358. }
  3359. return this.raise(pos, message, enumName, memberName, explicitType);
  3360. }
  3361. flowEnumErrorNumberMemberNotInitialized(pos, {
  3362. enumName,
  3363. memberName
  3364. }) {
  3365. this.raise(pos, FlowErrors.EnumNumberMemberNotInitialized, enumName, memberName);
  3366. }
  3367. flowEnumErrorStringMemberInconsistentlyInitailized(pos, {
  3368. enumName
  3369. }) {
  3370. this.raise(pos, FlowErrors.EnumStringMemberInconsistentlyInitailized, enumName);
  3371. }
  3372. flowEnumMemberInit() {
  3373. const startPos = this.state.start;
  3374. const endOfInit = () => this.match(types.comma) || this.match(types.braceR);
  3375. switch (this.state.type) {
  3376. case types.num:
  3377. {
  3378. const literal = this.parseLiteral(this.state.value, "NumericLiteral");
  3379. if (endOfInit()) {
  3380. return {
  3381. type: "number",
  3382. pos: literal.start,
  3383. value: literal
  3384. };
  3385. }
  3386. return {
  3387. type: "invalid",
  3388. pos: startPos
  3389. };
  3390. }
  3391. case types.string:
  3392. {
  3393. const literal = this.parseLiteral(this.state.value, "StringLiteral");
  3394. if (endOfInit()) {
  3395. return {
  3396. type: "string",
  3397. pos: literal.start,
  3398. value: literal
  3399. };
  3400. }
  3401. return {
  3402. type: "invalid",
  3403. pos: startPos
  3404. };
  3405. }
  3406. case types._true:
  3407. case types._false:
  3408. {
  3409. const literal = this.parseBooleanLiteral();
  3410. if (endOfInit()) {
  3411. return {
  3412. type: "boolean",
  3413. pos: literal.start,
  3414. value: literal
  3415. };
  3416. }
  3417. return {
  3418. type: "invalid",
  3419. pos: startPos
  3420. };
  3421. }
  3422. default:
  3423. return {
  3424. type: "invalid",
  3425. pos: startPos
  3426. };
  3427. }
  3428. }
  3429. flowEnumMemberRaw() {
  3430. const pos = this.state.start;
  3431. const id = this.parseIdentifier(true);
  3432. const init = this.eat(types.eq) ? this.flowEnumMemberInit() : {
  3433. type: "none",
  3434. pos
  3435. };
  3436. return {
  3437. id,
  3438. init
  3439. };
  3440. }
  3441. flowEnumCheckExplicitTypeMismatch(pos, context, expectedType) {
  3442. const {
  3443. explicitType
  3444. } = context;
  3445. if (explicitType === null) {
  3446. return;
  3447. }
  3448. if (explicitType !== expectedType) {
  3449. this.flowEnumErrorInvalidMemberInitializer(pos, context);
  3450. }
  3451. }
  3452. flowEnumMembers({
  3453. enumName,
  3454. explicitType
  3455. }) {
  3456. const seenNames = new Set();
  3457. const members = {
  3458. booleanMembers: [],
  3459. numberMembers: [],
  3460. stringMembers: [],
  3461. defaultedMembers: []
  3462. };
  3463. let hasUnknownMembers = false;
  3464. while (!this.match(types.braceR)) {
  3465. if (this.eat(types.ellipsis)) {
  3466. hasUnknownMembers = true;
  3467. break;
  3468. }
  3469. const memberNode = this.startNode();
  3470. const {
  3471. id,
  3472. init
  3473. } = this.flowEnumMemberRaw();
  3474. const memberName = id.name;
  3475. if (memberName === "") {
  3476. continue;
  3477. }
  3478. if (/^[a-z]/.test(memberName)) {
  3479. this.flowEnumErrorInvalidMemberName(id.start, {
  3480. enumName,
  3481. memberName
  3482. });
  3483. }
  3484. if (seenNames.has(memberName)) {
  3485. this.flowEnumErrorDuplicateMemberName(id.start, {
  3486. enumName,
  3487. memberName
  3488. });
  3489. }
  3490. seenNames.add(memberName);
  3491. const context = {
  3492. enumName,
  3493. explicitType,
  3494. memberName
  3495. };
  3496. memberNode.id = id;
  3497. switch (init.type) {
  3498. case "boolean":
  3499. {
  3500. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "boolean");
  3501. memberNode.init = init.value;
  3502. members.booleanMembers.push(this.finishNode(memberNode, "EnumBooleanMember"));
  3503. break;
  3504. }
  3505. case "number":
  3506. {
  3507. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "number");
  3508. memberNode.init = init.value;
  3509. members.numberMembers.push(this.finishNode(memberNode, "EnumNumberMember"));
  3510. break;
  3511. }
  3512. case "string":
  3513. {
  3514. this.flowEnumCheckExplicitTypeMismatch(init.pos, context, "string");
  3515. memberNode.init = init.value;
  3516. members.stringMembers.push(this.finishNode(memberNode, "EnumStringMember"));
  3517. break;
  3518. }
  3519. case "invalid":
  3520. {
  3521. throw this.flowEnumErrorInvalidMemberInitializer(init.pos, context);
  3522. }
  3523. case "none":
  3524. {
  3525. switch (explicitType) {
  3526. case "boolean":
  3527. this.flowEnumErrorBooleanMemberNotInitialized(init.pos, context);
  3528. break;
  3529. case "number":
  3530. this.flowEnumErrorNumberMemberNotInitialized(init.pos, context);
  3531. break;
  3532. default:
  3533. members.defaultedMembers.push(this.finishNode(memberNode, "EnumDefaultedMember"));
  3534. }
  3535. }
  3536. }
  3537. if (!this.match(types.braceR)) {
  3538. this.expect(types.comma);
  3539. }
  3540. }
  3541. return {
  3542. members,
  3543. hasUnknownMembers
  3544. };
  3545. }
  3546. flowEnumStringMembers(initializedMembers, defaultedMembers, {
  3547. enumName
  3548. }) {
  3549. if (initializedMembers.length === 0) {
  3550. return defaultedMembers;
  3551. } else if (defaultedMembers.length === 0) {
  3552. return initializedMembers;
  3553. } else if (defaultedMembers.length > initializedMembers.length) {
  3554. for (const member of initializedMembers) {
  3555. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3556. enumName
  3557. });
  3558. }
  3559. return defaultedMembers;
  3560. } else {
  3561. for (const member of defaultedMembers) {
  3562. this.flowEnumErrorStringMemberInconsistentlyInitailized(member.start, {
  3563. enumName
  3564. });
  3565. }
  3566. return initializedMembers;
  3567. }
  3568. }
  3569. flowEnumParseExplicitType({
  3570. enumName
  3571. }) {
  3572. if (this.eatContextual("of")) {
  3573. if (!this.match(types.name)) {
  3574. throw this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3575. enumName,
  3576. suppliedType: null
  3577. });
  3578. }
  3579. const {
  3580. value
  3581. } = this.state;
  3582. this.next();
  3583. if (value !== "boolean" && value !== "number" && value !== "string" && value !== "symbol") {
  3584. this.flowEnumErrorInvalidExplicitType(this.state.start, {
  3585. enumName,
  3586. suppliedType: value
  3587. });
  3588. }
  3589. return value;
  3590. }
  3591. return null;
  3592. }
  3593. flowEnumBody(node, {
  3594. enumName,
  3595. nameLoc
  3596. }) {
  3597. const explicitType = this.flowEnumParseExplicitType({
  3598. enumName
  3599. });
  3600. this.expect(types.braceL);
  3601. const {
  3602. members,
  3603. hasUnknownMembers
  3604. } = this.flowEnumMembers({
  3605. enumName,
  3606. explicitType
  3607. });
  3608. node.hasUnknownMembers = hasUnknownMembers;
  3609. switch (explicitType) {
  3610. case "boolean":
  3611. node.explicitType = true;
  3612. node.members = members.booleanMembers;
  3613. this.expect(types.braceR);
  3614. return this.finishNode(node, "EnumBooleanBody");
  3615. case "number":
  3616. node.explicitType = true;
  3617. node.members = members.numberMembers;
  3618. this.expect(types.braceR);
  3619. return this.finishNode(node, "EnumNumberBody");
  3620. case "string":
  3621. node.explicitType = true;
  3622. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3623. enumName
  3624. });
  3625. this.expect(types.braceR);
  3626. return this.finishNode(node, "EnumStringBody");
  3627. case "symbol":
  3628. node.members = members.defaultedMembers;
  3629. this.expect(types.braceR);
  3630. return this.finishNode(node, "EnumSymbolBody");
  3631. default:
  3632. {
  3633. const empty = () => {
  3634. node.members = [];
  3635. this.expect(types.braceR);
  3636. return this.finishNode(node, "EnumStringBody");
  3637. };
  3638. node.explicitType = false;
  3639. const boolsLen = members.booleanMembers.length;
  3640. const numsLen = members.numberMembers.length;
  3641. const strsLen = members.stringMembers.length;
  3642. const defaultedLen = members.defaultedMembers.length;
  3643. if (!boolsLen && !numsLen && !strsLen && !defaultedLen) {
  3644. return empty();
  3645. } else if (!boolsLen && !numsLen) {
  3646. node.members = this.flowEnumStringMembers(members.stringMembers, members.defaultedMembers, {
  3647. enumName
  3648. });
  3649. this.expect(types.braceR);
  3650. return this.finishNode(node, "EnumStringBody");
  3651. } else if (!numsLen && !strsLen && boolsLen >= defaultedLen) {
  3652. for (const member of members.defaultedMembers) {
  3653. this.flowEnumErrorBooleanMemberNotInitialized(member.start, {
  3654. enumName,
  3655. memberName: member.id.name
  3656. });
  3657. }
  3658. node.members = members.booleanMembers;
  3659. this.expect(types.braceR);
  3660. return this.finishNode(node, "EnumBooleanBody");
  3661. } else if (!boolsLen && !strsLen && numsLen >= defaultedLen) {
  3662. for (const member of members.defaultedMembers) {
  3663. this.flowEnumErrorNumberMemberNotInitialized(member.start, {
  3664. enumName,
  3665. memberName: member.id.name
  3666. });
  3667. }
  3668. node.members = members.numberMembers;
  3669. this.expect(types.braceR);
  3670. return this.finishNode(node, "EnumNumberBody");
  3671. } else {
  3672. this.flowEnumErrorInconsistentMemberValues(nameLoc, {
  3673. enumName
  3674. });
  3675. return empty();
  3676. }
  3677. }
  3678. }
  3679. }
  3680. flowParseEnumDeclaration(node) {
  3681. const id = this.parseIdentifier();
  3682. node.id = id;
  3683. node.body = this.flowEnumBody(this.startNode(), {
  3684. enumName: id.name,
  3685. nameLoc: id.start
  3686. });
  3687. return this.finishNode(node, "EnumDeclaration");
  3688. }
  3689. updateContext(prevType) {
  3690. if (this.match(types.name) && this.state.value === "of" && prevType === types.name && this.input.slice(this.state.lastTokStart, this.state.lastTokEnd) === "interface") {
  3691. this.state.exprAllowed = false;
  3692. } else {
  3693. super.updateContext(prevType);
  3694. }
  3695. }
  3696. isLookaheadToken_lt() {
  3697. const next = this.nextTokenStart();
  3698. if (this.input.charCodeAt(next) === 60) {
  3699. const afterNext = this.input.charCodeAt(next + 1);
  3700. return afterNext !== 60 && afterNext !== 61;
  3701. }
  3702. return false;
  3703. }
  3704. maybeUnwrapTypeCastExpression(node) {
  3705. return node.type === "TypeCastExpression" ? node.expression : node;
  3706. }
  3707. });
  3708. const entities = {
  3709. quot: "\u0022",
  3710. amp: "&",
  3711. apos: "\u0027",
  3712. lt: "<",
  3713. gt: ">",
  3714. nbsp: "\u00A0",
  3715. iexcl: "\u00A1",
  3716. cent: "\u00A2",
  3717. pound: "\u00A3",
  3718. curren: "\u00A4",
  3719. yen: "\u00A5",
  3720. brvbar: "\u00A6",
  3721. sect: "\u00A7",
  3722. uml: "\u00A8",
  3723. copy: "\u00A9",
  3724. ordf: "\u00AA",
  3725. laquo: "\u00AB",
  3726. not: "\u00AC",
  3727. shy: "\u00AD",
  3728. reg: "\u00AE",
  3729. macr: "\u00AF",
  3730. deg: "\u00B0",
  3731. plusmn: "\u00B1",
  3732. sup2: "\u00B2",
  3733. sup3: "\u00B3",
  3734. acute: "\u00B4",
  3735. micro: "\u00B5",
  3736. para: "\u00B6",
  3737. middot: "\u00B7",
  3738. cedil: "\u00B8",
  3739. sup1: "\u00B9",
  3740. ordm: "\u00BA",
  3741. raquo: "\u00BB",
  3742. frac14: "\u00BC",
  3743. frac12: "\u00BD",
  3744. frac34: "\u00BE",
  3745. iquest: "\u00BF",
  3746. Agrave: "\u00C0",
  3747. Aacute: "\u00C1",
  3748. Acirc: "\u00C2",
  3749. Atilde: "\u00C3",
  3750. Auml: "\u00C4",
  3751. Aring: "\u00C5",
  3752. AElig: "\u00C6",
  3753. Ccedil: "\u00C7",
  3754. Egrave: "\u00C8",
  3755. Eacute: "\u00C9",
  3756. Ecirc: "\u00CA",
  3757. Euml: "\u00CB",
  3758. Igrave: "\u00CC",
  3759. Iacute: "\u00CD",
  3760. Icirc: "\u00CE",
  3761. Iuml: "\u00CF",
  3762. ETH: "\u00D0",
  3763. Ntilde: "\u00D1",
  3764. Ograve: "\u00D2",
  3765. Oacute: "\u00D3",
  3766. Ocirc: "\u00D4",
  3767. Otilde: "\u00D5",
  3768. Ouml: "\u00D6",
  3769. times: "\u00D7",
  3770. Oslash: "\u00D8",
  3771. Ugrave: "\u00D9",
  3772. Uacute: "\u00DA",
  3773. Ucirc: "\u00DB",
  3774. Uuml: "\u00DC",
  3775. Yacute: "\u00DD",
  3776. THORN: "\u00DE",
  3777. szlig: "\u00DF",
  3778. agrave: "\u00E0",
  3779. aacute: "\u00E1",
  3780. acirc: "\u00E2",
  3781. atilde: "\u00E3",
  3782. auml: "\u00E4",
  3783. aring: "\u00E5",
  3784. aelig: "\u00E6",
  3785. ccedil: "\u00E7",
  3786. egrave: "\u00E8",
  3787. eacute: "\u00E9",
  3788. ecirc: "\u00EA",
  3789. euml: "\u00EB",
  3790. igrave: "\u00EC",
  3791. iacute: "\u00ED",
  3792. icirc: "\u00EE",
  3793. iuml: "\u00EF",
  3794. eth: "\u00F0",
  3795. ntilde: "\u00F1",
  3796. ograve: "\u00F2",
  3797. oacute: "\u00F3",
  3798. ocirc: "\u00F4",
  3799. otilde: "\u00F5",
  3800. ouml: "\u00F6",
  3801. divide: "\u00F7",
  3802. oslash: "\u00F8",
  3803. ugrave: "\u00F9",
  3804. uacute: "\u00FA",
  3805. ucirc: "\u00FB",
  3806. uuml: "\u00FC",
  3807. yacute: "\u00FD",
  3808. thorn: "\u00FE",
  3809. yuml: "\u00FF",
  3810. OElig: "\u0152",
  3811. oelig: "\u0153",
  3812. Scaron: "\u0160",
  3813. scaron: "\u0161",
  3814. Yuml: "\u0178",
  3815. fnof: "\u0192",
  3816. circ: "\u02C6",
  3817. tilde: "\u02DC",
  3818. Alpha: "\u0391",
  3819. Beta: "\u0392",
  3820. Gamma: "\u0393",
  3821. Delta: "\u0394",
  3822. Epsilon: "\u0395",
  3823. Zeta: "\u0396",
  3824. Eta: "\u0397",
  3825. Theta: "\u0398",
  3826. Iota: "\u0399",
  3827. Kappa: "\u039A",
  3828. Lambda: "\u039B",
  3829. Mu: "\u039C",
  3830. Nu: "\u039D",
  3831. Xi: "\u039E",
  3832. Omicron: "\u039F",
  3833. Pi: "\u03A0",
  3834. Rho: "\u03A1",
  3835. Sigma: "\u03A3",
  3836. Tau: "\u03A4",
  3837. Upsilon: "\u03A5",
  3838. Phi: "\u03A6",
  3839. Chi: "\u03A7",
  3840. Psi: "\u03A8",
  3841. Omega: "\u03A9",
  3842. alpha: "\u03B1",
  3843. beta: "\u03B2",
  3844. gamma: "\u03B3",
  3845. delta: "\u03B4",
  3846. epsilon: "\u03B5",
  3847. zeta: "\u03B6",
  3848. eta: "\u03B7",
  3849. theta: "\u03B8",
  3850. iota: "\u03B9",
  3851. kappa: "\u03BA",
  3852. lambda: "\u03BB",
  3853. mu: "\u03BC",
  3854. nu: "\u03BD",
  3855. xi: "\u03BE",
  3856. omicron: "\u03BF",
  3857. pi: "\u03C0",
  3858. rho: "\u03C1",
  3859. sigmaf: "\u03C2",
  3860. sigma: "\u03C3",
  3861. tau: "\u03C4",
  3862. upsilon: "\u03C5",
  3863. phi: "\u03C6",
  3864. chi: "\u03C7",
  3865. psi: "\u03C8",
  3866. omega: "\u03C9",
  3867. thetasym: "\u03D1",
  3868. upsih: "\u03D2",
  3869. piv: "\u03D6",
  3870. ensp: "\u2002",
  3871. emsp: "\u2003",
  3872. thinsp: "\u2009",
  3873. zwnj: "\u200C",
  3874. zwj: "\u200D",
  3875. lrm: "\u200E",
  3876. rlm: "\u200F",
  3877. ndash: "\u2013",
  3878. mdash: "\u2014",
  3879. lsquo: "\u2018",
  3880. rsquo: "\u2019",
  3881. sbquo: "\u201A",
  3882. ldquo: "\u201C",
  3883. rdquo: "\u201D",
  3884. bdquo: "\u201E",
  3885. dagger: "\u2020",
  3886. Dagger: "\u2021",
  3887. bull: "\u2022",
  3888. hellip: "\u2026",
  3889. permil: "\u2030",
  3890. prime: "\u2032",
  3891. Prime: "\u2033",
  3892. lsaquo: "\u2039",
  3893. rsaquo: "\u203A",
  3894. oline: "\u203E",
  3895. frasl: "\u2044",
  3896. euro: "\u20AC",
  3897. image: "\u2111",
  3898. weierp: "\u2118",
  3899. real: "\u211C",
  3900. trade: "\u2122",
  3901. alefsym: "\u2135",
  3902. larr: "\u2190",
  3903. uarr: "\u2191",
  3904. rarr: "\u2192",
  3905. darr: "\u2193",
  3906. harr: "\u2194",
  3907. crarr: "\u21B5",
  3908. lArr: "\u21D0",
  3909. uArr: "\u21D1",
  3910. rArr: "\u21D2",
  3911. dArr: "\u21D3",
  3912. hArr: "\u21D4",
  3913. forall: "\u2200",
  3914. part: "\u2202",
  3915. exist: "\u2203",
  3916. empty: "\u2205",
  3917. nabla: "\u2207",
  3918. isin: "\u2208",
  3919. notin: "\u2209",
  3920. ni: "\u220B",
  3921. prod: "\u220F",
  3922. sum: "\u2211",
  3923. minus: "\u2212",
  3924. lowast: "\u2217",
  3925. radic: "\u221A",
  3926. prop: "\u221D",
  3927. infin: "\u221E",
  3928. ang: "\u2220",
  3929. and: "\u2227",
  3930. or: "\u2228",
  3931. cap: "\u2229",
  3932. cup: "\u222A",
  3933. int: "\u222B",
  3934. there4: "\u2234",
  3935. sim: "\u223C",
  3936. cong: "\u2245",
  3937. asymp: "\u2248",
  3938. ne: "\u2260",
  3939. equiv: "\u2261",
  3940. le: "\u2264",
  3941. ge: "\u2265",
  3942. sub: "\u2282",
  3943. sup: "\u2283",
  3944. nsub: "\u2284",
  3945. sube: "\u2286",
  3946. supe: "\u2287",
  3947. oplus: "\u2295",
  3948. otimes: "\u2297",
  3949. perp: "\u22A5",
  3950. sdot: "\u22C5",
  3951. lceil: "\u2308",
  3952. rceil: "\u2309",
  3953. lfloor: "\u230A",
  3954. rfloor: "\u230B",
  3955. lang: "\u2329",
  3956. rang: "\u232A",
  3957. loz: "\u25CA",
  3958. spades: "\u2660",
  3959. clubs: "\u2663",
  3960. hearts: "\u2665",
  3961. diams: "\u2666"
  3962. };
  3963. const HEX_NUMBER = /^[\da-fA-F]+$/;
  3964. const DECIMAL_NUMBER = /^\d+$/;
  3965. const JsxErrors = Object.freeze({
  3966. AttributeIsEmpty: "JSX attributes must only be assigned a non-empty expression",
  3967. MissingClosingTagElement: "Expected corresponding JSX closing tag for <%0>",
  3968. MissingClosingTagFragment: "Expected corresponding JSX closing tag for <>",
  3969. UnexpectedSequenceExpression: "Sequence expressions cannot be directly nested inside JSX. Did you mean to wrap it in parentheses (...)?",
  3970. UnsupportedJsxValue: "JSX value should be either an expression or a quoted JSX text",
  3971. UnterminatedJsxContent: "Unterminated JSX contents",
  3972. UnwrappedAdjacentJSXElements: "Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?"
  3973. });
  3974. types$1.j_oTag = new TokContext("<tag", false);
  3975. types$1.j_cTag = new TokContext("</tag", false);
  3976. types$1.j_expr = new TokContext("<tag>...</tag>", true, true);
  3977. types.jsxName = new TokenType("jsxName");
  3978. types.jsxText = new TokenType("jsxText", {
  3979. beforeExpr: true
  3980. });
  3981. types.jsxTagStart = new TokenType("jsxTagStart", {
  3982. startsExpr: true
  3983. });
  3984. types.jsxTagEnd = new TokenType("jsxTagEnd");
  3985. types.jsxTagStart.updateContext = function () {
  3986. this.state.context.push(types$1.j_expr);
  3987. this.state.context.push(types$1.j_oTag);
  3988. this.state.exprAllowed = false;
  3989. };
  3990. types.jsxTagEnd.updateContext = function (prevType) {
  3991. const out = this.state.context.pop();
  3992. if (out === types$1.j_oTag && prevType === types.slash || out === types$1.j_cTag) {
  3993. this.state.context.pop();
  3994. this.state.exprAllowed = this.curContext() === types$1.j_expr;
  3995. } else {
  3996. this.state.exprAllowed = true;
  3997. }
  3998. };
  3999. function isFragment(object) {
  4000. return object ? object.type === "JSXOpeningFragment" || object.type === "JSXClosingFragment" : false;
  4001. }
  4002. function getQualifiedJSXName(object) {
  4003. if (object.type === "JSXIdentifier") {
  4004. return object.name;
  4005. }
  4006. if (object.type === "JSXNamespacedName") {
  4007. return object.namespace.name + ":" + object.name.name;
  4008. }
  4009. if (object.type === "JSXMemberExpression") {
  4010. return getQualifiedJSXName(object.object) + "." + getQualifiedJSXName(object.property);
  4011. }
  4012. throw new Error("Node had unexpected type: " + object.type);
  4013. }
  4014. var jsx = (superClass => class extends superClass {
  4015. jsxReadToken() {
  4016. let out = "";
  4017. let chunkStart = this.state.pos;
  4018. for (;;) {
  4019. if (this.state.pos >= this.length) {
  4020. throw this.raise(this.state.start, JsxErrors.UnterminatedJsxContent);
  4021. }
  4022. const ch = this.input.charCodeAt(this.state.pos);
  4023. switch (ch) {
  4024. case 60:
  4025. case 123:
  4026. if (this.state.pos === this.state.start) {
  4027. if (ch === 60 && this.state.exprAllowed) {
  4028. ++this.state.pos;
  4029. return this.finishToken(types.jsxTagStart);
  4030. }
  4031. return super.getTokenFromCode(ch);
  4032. }
  4033. out += this.input.slice(chunkStart, this.state.pos);
  4034. return this.finishToken(types.jsxText, out);
  4035. case 38:
  4036. out += this.input.slice(chunkStart, this.state.pos);
  4037. out += this.jsxReadEntity();
  4038. chunkStart = this.state.pos;
  4039. break;
  4040. case 62:
  4041. case 125:
  4042. default:
  4043. if (isNewLine(ch)) {
  4044. out += this.input.slice(chunkStart, this.state.pos);
  4045. out += this.jsxReadNewLine(true);
  4046. chunkStart = this.state.pos;
  4047. } else {
  4048. ++this.state.pos;
  4049. }
  4050. }
  4051. }
  4052. }
  4053. jsxReadNewLine(normalizeCRLF) {
  4054. const ch = this.input.charCodeAt(this.state.pos);
  4055. let out;
  4056. ++this.state.pos;
  4057. if (ch === 13 && this.input.charCodeAt(this.state.pos) === 10) {
  4058. ++this.state.pos;
  4059. out = normalizeCRLF ? "\n" : "\r\n";
  4060. } else {
  4061. out = String.fromCharCode(ch);
  4062. }
  4063. ++this.state.curLine;
  4064. this.state.lineStart = this.state.pos;
  4065. return out;
  4066. }
  4067. jsxReadString(quote) {
  4068. let out = "";
  4069. let chunkStart = ++this.state.pos;
  4070. for (;;) {
  4071. if (this.state.pos >= this.length) {
  4072. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  4073. }
  4074. const ch = this.input.charCodeAt(this.state.pos);
  4075. if (ch === quote) break;
  4076. if (ch === 38) {
  4077. out += this.input.slice(chunkStart, this.state.pos);
  4078. out += this.jsxReadEntity();
  4079. chunkStart = this.state.pos;
  4080. } else if (isNewLine(ch)) {
  4081. out += this.input.slice(chunkStart, this.state.pos);
  4082. out += this.jsxReadNewLine(false);
  4083. chunkStart = this.state.pos;
  4084. } else {
  4085. ++this.state.pos;
  4086. }
  4087. }
  4088. out += this.input.slice(chunkStart, this.state.pos++);
  4089. return this.finishToken(types.string, out);
  4090. }
  4091. jsxReadEntity() {
  4092. let str = "";
  4093. let count = 0;
  4094. let entity;
  4095. let ch = this.input[this.state.pos];
  4096. const startPos = ++this.state.pos;
  4097. while (this.state.pos < this.length && count++ < 10) {
  4098. ch = this.input[this.state.pos++];
  4099. if (ch === ";") {
  4100. if (str[0] === "#") {
  4101. if (str[1] === "x") {
  4102. str = str.substr(2);
  4103. if (HEX_NUMBER.test(str)) {
  4104. entity = String.fromCodePoint(parseInt(str, 16));
  4105. }
  4106. } else {
  4107. str = str.substr(1);
  4108. if (DECIMAL_NUMBER.test(str)) {
  4109. entity = String.fromCodePoint(parseInt(str, 10));
  4110. }
  4111. }
  4112. } else {
  4113. entity = entities[str];
  4114. }
  4115. break;
  4116. }
  4117. str += ch;
  4118. }
  4119. if (!entity) {
  4120. this.state.pos = startPos;
  4121. return "&";
  4122. }
  4123. return entity;
  4124. }
  4125. jsxReadWord() {
  4126. let ch;
  4127. const start = this.state.pos;
  4128. do {
  4129. ch = this.input.charCodeAt(++this.state.pos);
  4130. } while (isIdentifierChar(ch) || ch === 45);
  4131. return this.finishToken(types.jsxName, this.input.slice(start, this.state.pos));
  4132. }
  4133. jsxParseIdentifier() {
  4134. const node = this.startNode();
  4135. if (this.match(types.jsxName)) {
  4136. node.name = this.state.value;
  4137. } else if (this.state.type.keyword) {
  4138. node.name = this.state.type.keyword;
  4139. } else {
  4140. this.unexpected();
  4141. }
  4142. this.next();
  4143. return this.finishNode(node, "JSXIdentifier");
  4144. }
  4145. jsxParseNamespacedName() {
  4146. const startPos = this.state.start;
  4147. const startLoc = this.state.startLoc;
  4148. const name = this.jsxParseIdentifier();
  4149. if (!this.eat(types.colon)) return name;
  4150. const node = this.startNodeAt(startPos, startLoc);
  4151. node.namespace = name;
  4152. node.name = this.jsxParseIdentifier();
  4153. return this.finishNode(node, "JSXNamespacedName");
  4154. }
  4155. jsxParseElementName() {
  4156. const startPos = this.state.start;
  4157. const startLoc = this.state.startLoc;
  4158. let node = this.jsxParseNamespacedName();
  4159. if (node.type === "JSXNamespacedName") {
  4160. return node;
  4161. }
  4162. while (this.eat(types.dot)) {
  4163. const newNode = this.startNodeAt(startPos, startLoc);
  4164. newNode.object = node;
  4165. newNode.property = this.jsxParseIdentifier();
  4166. node = this.finishNode(newNode, "JSXMemberExpression");
  4167. }
  4168. return node;
  4169. }
  4170. jsxParseAttributeValue() {
  4171. let node;
  4172. switch (this.state.type) {
  4173. case types.braceL:
  4174. node = this.startNode();
  4175. this.next();
  4176. node = this.jsxParseExpressionContainer(node);
  4177. if (node.expression.type === "JSXEmptyExpression") {
  4178. this.raise(node.start, JsxErrors.AttributeIsEmpty);
  4179. }
  4180. return node;
  4181. case types.jsxTagStart:
  4182. case types.string:
  4183. return this.parseExprAtom();
  4184. default:
  4185. throw this.raise(this.state.start, JsxErrors.UnsupportedJsxValue);
  4186. }
  4187. }
  4188. jsxParseEmptyExpression() {
  4189. const node = this.startNodeAt(this.state.lastTokEnd, this.state.lastTokEndLoc);
  4190. return this.finishNodeAt(node, "JSXEmptyExpression", this.state.start, this.state.startLoc);
  4191. }
  4192. jsxParseSpreadChild(node) {
  4193. this.next();
  4194. node.expression = this.parseExpression();
  4195. this.expect(types.braceR);
  4196. return this.finishNode(node, "JSXSpreadChild");
  4197. }
  4198. jsxParseExpressionContainer(node) {
  4199. if (this.match(types.braceR)) {
  4200. node.expression = this.jsxParseEmptyExpression();
  4201. } else {
  4202. const expression = this.parseExpression();
  4203. node.expression = expression;
  4204. }
  4205. this.expect(types.braceR);
  4206. return this.finishNode(node, "JSXExpressionContainer");
  4207. }
  4208. jsxParseAttribute() {
  4209. const node = this.startNode();
  4210. if (this.eat(types.braceL)) {
  4211. this.expect(types.ellipsis);
  4212. node.argument = this.parseMaybeAssignAllowIn();
  4213. this.expect(types.braceR);
  4214. return this.finishNode(node, "JSXSpreadAttribute");
  4215. }
  4216. node.name = this.jsxParseNamespacedName();
  4217. node.value = this.eat(types.eq) ? this.jsxParseAttributeValue() : null;
  4218. return this.finishNode(node, "JSXAttribute");
  4219. }
  4220. jsxParseOpeningElementAt(startPos, startLoc) {
  4221. const node = this.startNodeAt(startPos, startLoc);
  4222. if (this.match(types.jsxTagEnd)) {
  4223. this.expect(types.jsxTagEnd);
  4224. return this.finishNode(node, "JSXOpeningFragment");
  4225. }
  4226. node.name = this.jsxParseElementName();
  4227. return this.jsxParseOpeningElementAfterName(node);
  4228. }
  4229. jsxParseOpeningElementAfterName(node) {
  4230. const attributes = [];
  4231. while (!this.match(types.slash) && !this.match(types.jsxTagEnd)) {
  4232. attributes.push(this.jsxParseAttribute());
  4233. }
  4234. node.attributes = attributes;
  4235. node.selfClosing = this.eat(types.slash);
  4236. this.expect(types.jsxTagEnd);
  4237. return this.finishNode(node, "JSXOpeningElement");
  4238. }
  4239. jsxParseClosingElementAt(startPos, startLoc) {
  4240. const node = this.startNodeAt(startPos, startLoc);
  4241. if (this.match(types.jsxTagEnd)) {
  4242. this.expect(types.jsxTagEnd);
  4243. return this.finishNode(node, "JSXClosingFragment");
  4244. }
  4245. node.name = this.jsxParseElementName();
  4246. this.expect(types.jsxTagEnd);
  4247. return this.finishNode(node, "JSXClosingElement");
  4248. }
  4249. jsxParseElementAt(startPos, startLoc) {
  4250. const node = this.startNodeAt(startPos, startLoc);
  4251. const children = [];
  4252. const openingElement = this.jsxParseOpeningElementAt(startPos, startLoc);
  4253. let closingElement = null;
  4254. if (!openingElement.selfClosing) {
  4255. contents: for (;;) {
  4256. switch (this.state.type) {
  4257. case types.jsxTagStart:
  4258. startPos = this.state.start;
  4259. startLoc = this.state.startLoc;
  4260. this.next();
  4261. if (this.eat(types.slash)) {
  4262. closingElement = this.jsxParseClosingElementAt(startPos, startLoc);
  4263. break contents;
  4264. }
  4265. children.push(this.jsxParseElementAt(startPos, startLoc));
  4266. break;
  4267. case types.jsxText:
  4268. children.push(this.parseExprAtom());
  4269. break;
  4270. case types.braceL:
  4271. {
  4272. const node = this.startNode();
  4273. this.next();
  4274. if (this.match(types.ellipsis)) {
  4275. children.push(this.jsxParseSpreadChild(node));
  4276. } else {
  4277. children.push(this.jsxParseExpressionContainer(node));
  4278. }
  4279. break;
  4280. }
  4281. default:
  4282. throw this.unexpected();
  4283. }
  4284. }
  4285. if (isFragment(openingElement) && !isFragment(closingElement)) {
  4286. this.raise(closingElement.start, JsxErrors.MissingClosingTagFragment);
  4287. } else if (!isFragment(openingElement) && isFragment(closingElement)) {
  4288. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  4289. } else if (!isFragment(openingElement) && !isFragment(closingElement)) {
  4290. if (getQualifiedJSXName(closingElement.name) !== getQualifiedJSXName(openingElement.name)) {
  4291. this.raise(closingElement.start, JsxErrors.MissingClosingTagElement, getQualifiedJSXName(openingElement.name));
  4292. }
  4293. }
  4294. }
  4295. if (isFragment(openingElement)) {
  4296. node.openingFragment = openingElement;
  4297. node.closingFragment = closingElement;
  4298. } else {
  4299. node.openingElement = openingElement;
  4300. node.closingElement = closingElement;
  4301. }
  4302. node.children = children;
  4303. if (this.isRelational("<")) {
  4304. throw this.raise(this.state.start, JsxErrors.UnwrappedAdjacentJSXElements);
  4305. }
  4306. return isFragment(openingElement) ? this.finishNode(node, "JSXFragment") : this.finishNode(node, "JSXElement");
  4307. }
  4308. jsxParseElement() {
  4309. const startPos = this.state.start;
  4310. const startLoc = this.state.startLoc;
  4311. this.next();
  4312. return this.jsxParseElementAt(startPos, startLoc);
  4313. }
  4314. parseExprAtom(refExpressionErrors) {
  4315. if (this.match(types.jsxText)) {
  4316. return this.parseLiteral(this.state.value, "JSXText");
  4317. } else if (this.match(types.jsxTagStart)) {
  4318. return this.jsxParseElement();
  4319. } else if (this.isRelational("<") && this.input.charCodeAt(this.state.pos) !== 33) {
  4320. this.finishToken(types.jsxTagStart);
  4321. return this.jsxParseElement();
  4322. } else {
  4323. return super.parseExprAtom(refExpressionErrors);
  4324. }
  4325. }
  4326. getTokenFromCode(code) {
  4327. if (this.state.inPropertyName) return super.getTokenFromCode(code);
  4328. const context = this.curContext();
  4329. if (context === types$1.j_expr) {
  4330. return this.jsxReadToken();
  4331. }
  4332. if (context === types$1.j_oTag || context === types$1.j_cTag) {
  4333. if (isIdentifierStart(code)) {
  4334. return this.jsxReadWord();
  4335. }
  4336. if (code === 62) {
  4337. ++this.state.pos;
  4338. return this.finishToken(types.jsxTagEnd);
  4339. }
  4340. if ((code === 34 || code === 39) && context === types$1.j_oTag) {
  4341. return this.jsxReadString(code);
  4342. }
  4343. }
  4344. if (code === 60 && this.state.exprAllowed && this.input.charCodeAt(this.state.pos + 1) !== 33) {
  4345. ++this.state.pos;
  4346. return this.finishToken(types.jsxTagStart);
  4347. }
  4348. return super.getTokenFromCode(code);
  4349. }
  4350. updateContext(prevType) {
  4351. if (this.match(types.braceL)) {
  4352. const curContext = this.curContext();
  4353. if (curContext === types$1.j_oTag) {
  4354. this.state.context.push(types$1.braceExpression);
  4355. } else if (curContext === types$1.j_expr) {
  4356. this.state.context.push(types$1.templateQuasi);
  4357. } else {
  4358. super.updateContext(prevType);
  4359. }
  4360. this.state.exprAllowed = true;
  4361. } else if (this.match(types.slash) && prevType === types.jsxTagStart) {
  4362. this.state.context.length -= 2;
  4363. this.state.context.push(types$1.j_cTag);
  4364. this.state.exprAllowed = false;
  4365. } else {
  4366. return super.updateContext(prevType);
  4367. }
  4368. }
  4369. });
  4370. class TypeScriptScope extends Scope {
  4371. constructor(...args) {
  4372. super(...args);
  4373. this.types = [];
  4374. this.enums = [];
  4375. this.constEnums = [];
  4376. this.classes = [];
  4377. this.exportOnlyBindings = [];
  4378. }
  4379. }
  4380. class TypeScriptScopeHandler extends ScopeHandler {
  4381. createScope(flags) {
  4382. return new TypeScriptScope(flags);
  4383. }
  4384. declareName(name, bindingType, pos) {
  4385. const scope = this.currentScope();
  4386. if (bindingType & BIND_FLAGS_TS_EXPORT_ONLY) {
  4387. this.maybeExportDefined(scope, name);
  4388. scope.exportOnlyBindings.push(name);
  4389. return;
  4390. }
  4391. super.declareName(...arguments);
  4392. if (bindingType & BIND_KIND_TYPE) {
  4393. if (!(bindingType & BIND_KIND_VALUE)) {
  4394. this.checkRedeclarationInScope(scope, name, bindingType, pos);
  4395. this.maybeExportDefined(scope, name);
  4396. }
  4397. scope.types.push(name);
  4398. }
  4399. if (bindingType & BIND_FLAGS_TS_ENUM) scope.enums.push(name);
  4400. if (bindingType & BIND_FLAGS_TS_CONST_ENUM) scope.constEnums.push(name);
  4401. if (bindingType & BIND_FLAGS_CLASS) scope.classes.push(name);
  4402. }
  4403. isRedeclaredInScope(scope, name, bindingType) {
  4404. if (scope.enums.indexOf(name) > -1) {
  4405. if (bindingType & BIND_FLAGS_TS_ENUM) {
  4406. const isConst = !!(bindingType & BIND_FLAGS_TS_CONST_ENUM);
  4407. const wasConst = scope.constEnums.indexOf(name) > -1;
  4408. return isConst !== wasConst;
  4409. }
  4410. return true;
  4411. }
  4412. if (bindingType & BIND_FLAGS_CLASS && scope.classes.indexOf(name) > -1) {
  4413. if (scope.lexical.indexOf(name) > -1) {
  4414. return !!(bindingType & BIND_KIND_VALUE);
  4415. } else {
  4416. return false;
  4417. }
  4418. }
  4419. if (bindingType & BIND_KIND_TYPE && scope.types.indexOf(name) > -1) {
  4420. return true;
  4421. }
  4422. return super.isRedeclaredInScope(...arguments);
  4423. }
  4424. checkLocalExport(id) {
  4425. if (this.scopeStack[0].types.indexOf(id.name) === -1 && this.scopeStack[0].exportOnlyBindings.indexOf(id.name) === -1) {
  4426. super.checkLocalExport(id);
  4427. }
  4428. }
  4429. }
  4430. const PARAM = 0b0000,
  4431. PARAM_YIELD = 0b0001,
  4432. PARAM_AWAIT = 0b0010,
  4433. PARAM_RETURN = 0b0100,
  4434. PARAM_IN = 0b1000;
  4435. class ProductionParameterHandler {
  4436. constructor() {
  4437. this.stacks = [];
  4438. }
  4439. enter(flags) {
  4440. this.stacks.push(flags);
  4441. }
  4442. exit() {
  4443. this.stacks.pop();
  4444. }
  4445. currentFlags() {
  4446. return this.stacks[this.stacks.length - 1];
  4447. }
  4448. get hasAwait() {
  4449. return (this.currentFlags() & PARAM_AWAIT) > 0;
  4450. }
  4451. get hasYield() {
  4452. return (this.currentFlags() & PARAM_YIELD) > 0;
  4453. }
  4454. get hasReturn() {
  4455. return (this.currentFlags() & PARAM_RETURN) > 0;
  4456. }
  4457. get hasIn() {
  4458. return (this.currentFlags() & PARAM_IN) > 0;
  4459. }
  4460. }
  4461. function functionFlags(isAsync, isGenerator) {
  4462. return (isAsync ? PARAM_AWAIT : 0) | (isGenerator ? PARAM_YIELD : 0);
  4463. }
  4464. function nonNull(x) {
  4465. if (x == null) {
  4466. throw new Error(`Unexpected ${x} value.`);
  4467. }
  4468. return x;
  4469. }
  4470. function assert(x) {
  4471. if (!x) {
  4472. throw new Error("Assert fail");
  4473. }
  4474. }
  4475. const TSErrors = Object.freeze({
  4476. AbstractMethodHasImplementation: "Method '%0' cannot have an implementation because it is marked abstract.",
  4477. ClassMethodHasDeclare: "Class methods cannot have the 'declare' modifier",
  4478. ClassMethodHasReadonly: "Class methods cannot have the 'readonly' modifier",
  4479. ConstructorHasTypeParameters: "Type parameters cannot appear on a constructor declaration.",
  4480. DeclareAccessor: "'declare' is not allowed in %0ters.",
  4481. DeclareClassFieldHasInitializer: "Initializers are not allowed in ambient contexts.",
  4482. DeclareFunctionHasImplementation: "An implementation cannot be declared in ambient contexts.",
  4483. DuplicateAccessibilityModifier: "Accessibility modifier already seen.",
  4484. DuplicateModifier: "Duplicate modifier: '%0'",
  4485. EmptyHeritageClauseType: "'%0' list cannot be empty.",
  4486. EmptyTypeArguments: "Type argument list cannot be empty.",
  4487. EmptyTypeParameters: "Type parameter list cannot be empty.",
  4488. ExpectedAmbientAfterExportDeclare: "'export declare' must be followed by an ambient declaration.",
  4489. ImportAliasHasImportType: "An import alias can not use 'import type'",
  4490. IndexSignatureHasAbstract: "Index signatures cannot have the 'abstract' modifier",
  4491. IndexSignatureHasAccessibility: "Index signatures cannot have an accessibility modifier ('%0')",
  4492. IndexSignatureHasDeclare: "Index signatures cannot have the 'declare' modifier",
  4493. IndexSignatureHasStatic: "Index signatures cannot have the 'static' modifier",
  4494. InvalidModifierOnTypeMember: "'%0' modifier cannot appear on a type member.",
  4495. InvalidTupleMemberLabel: "Tuple members must be labeled with a simple identifier.",
  4496. MixedLabeledAndUnlabeledElements: "Tuple members must all have names or all not have names.",
  4497. NonAbstractClassHasAbstractMethod: "Abstract methods can only appear within an abstract class.",
  4498. NonClassMethodPropertyHasAbstractModifer: "'abstract' modifier can only appear on a class, method, or property declaration.",
  4499. OptionalTypeBeforeRequired: "A required element cannot follow an optional element.",
  4500. PatternIsOptional: "A binding pattern parameter cannot be optional in an implementation signature.",
  4501. PrivateElementHasAbstract: "Private elements cannot have the 'abstract' modifier.",
  4502. PrivateElementHasAccessibility: "Private elements cannot have an accessibility modifier ('%0')",
  4503. ReadonlyForMethodSignature: "'readonly' modifier can only appear on a property declaration or index signature.",
  4504. TypeAnnotationAfterAssign: "Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",
  4505. UnexpectedParameterModifier: "A parameter property is only allowed in a constructor implementation.",
  4506. UnexpectedReadonly: "'readonly' type modifier is only permitted on array and tuple literal types.",
  4507. UnexpectedTypeAnnotation: "Did not expect a type annotation here.",
  4508. UnexpectedTypeCastInParameter: "Unexpected type cast in parameter position.",
  4509. UnsupportedImportTypeArgument: "Argument in a type import must be a string literal",
  4510. UnsupportedParameterPropertyKind: "A parameter property may not be declared using a binding pattern.",
  4511. UnsupportedSignatureParameterKind: "Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"
  4512. });
  4513. function keywordTypeFromName(value) {
  4514. switch (value) {
  4515. case "any":
  4516. return "TSAnyKeyword";
  4517. case "boolean":
  4518. return "TSBooleanKeyword";
  4519. case "bigint":
  4520. return "TSBigIntKeyword";
  4521. case "never":
  4522. return "TSNeverKeyword";
  4523. case "number":
  4524. return "TSNumberKeyword";
  4525. case "object":
  4526. return "TSObjectKeyword";
  4527. case "string":
  4528. return "TSStringKeyword";
  4529. case "symbol":
  4530. return "TSSymbolKeyword";
  4531. case "undefined":
  4532. return "TSUndefinedKeyword";
  4533. case "unknown":
  4534. return "TSUnknownKeyword";
  4535. default:
  4536. return undefined;
  4537. }
  4538. }
  4539. function tsIsAccessModifier(modifier) {
  4540. return modifier === "private" || modifier === "public" || modifier === "protected";
  4541. }
  4542. var typescript = (superClass => class extends superClass {
  4543. getScopeHandler() {
  4544. return TypeScriptScopeHandler;
  4545. }
  4546. tsIsIdentifier() {
  4547. return this.match(types.name);
  4548. }
  4549. tsNextTokenCanFollowModifier() {
  4550. this.next();
  4551. return (this.match(types.bracketL) || this.match(types.braceL) || this.match(types.star) || this.match(types.ellipsis) || this.match(types.hash) || this.isLiteralPropertyName()) && !this.hasPrecedingLineBreak();
  4552. }
  4553. tsParseModifier(allowedModifiers) {
  4554. if (!this.match(types.name)) {
  4555. return undefined;
  4556. }
  4557. const modifier = this.state.value;
  4558. if (allowedModifiers.indexOf(modifier) !== -1 && this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))) {
  4559. return modifier;
  4560. }
  4561. return undefined;
  4562. }
  4563. tsParseModifiers(modified, allowedModifiers, disallowedModifiers, errorTemplate) {
  4564. for (;;) {
  4565. const startPos = this.state.start;
  4566. const modifier = this.tsParseModifier(allowedModifiers.concat(disallowedModifiers != null ? disallowedModifiers : []));
  4567. if (!modifier) break;
  4568. if (tsIsAccessModifier(modifier)) {
  4569. if (modified.accessibility) {
  4570. this.raise(startPos, TSErrors.DuplicateAccessibilityModifier);
  4571. } else {
  4572. modified.accessibility = modifier;
  4573. }
  4574. } else {
  4575. if (Object.hasOwnProperty.call(modified, modifier)) {
  4576. this.raise(startPos, TSErrors.DuplicateModifier, modifier);
  4577. }
  4578. modified[modifier] = true;
  4579. }
  4580. if (disallowedModifiers != null && disallowedModifiers.includes(modifier)) {
  4581. this.raise(startPos, errorTemplate, modifier);
  4582. }
  4583. }
  4584. }
  4585. tsIsListTerminator(kind) {
  4586. switch (kind) {
  4587. case "EnumMembers":
  4588. case "TypeMembers":
  4589. return this.match(types.braceR);
  4590. case "HeritageClauseElement":
  4591. return this.match(types.braceL);
  4592. case "TupleElementTypes":
  4593. return this.match(types.bracketR);
  4594. case "TypeParametersOrArguments":
  4595. return this.isRelational(">");
  4596. }
  4597. throw new Error("Unreachable");
  4598. }
  4599. tsParseList(kind, parseElement) {
  4600. const result = [];
  4601. while (!this.tsIsListTerminator(kind)) {
  4602. result.push(parseElement());
  4603. }
  4604. return result;
  4605. }
  4606. tsParseDelimitedList(kind, parseElement) {
  4607. return nonNull(this.tsParseDelimitedListWorker(kind, parseElement, true));
  4608. }
  4609. tsParseDelimitedListWorker(kind, parseElement, expectSuccess) {
  4610. const result = [];
  4611. for (;;) {
  4612. if (this.tsIsListTerminator(kind)) {
  4613. break;
  4614. }
  4615. const element = parseElement();
  4616. if (element == null) {
  4617. return undefined;
  4618. }
  4619. result.push(element);
  4620. if (this.eat(types.comma)) {
  4621. continue;
  4622. }
  4623. if (this.tsIsListTerminator(kind)) {
  4624. break;
  4625. }
  4626. if (expectSuccess) {
  4627. this.expect(types.comma);
  4628. }
  4629. return undefined;
  4630. }
  4631. return result;
  4632. }
  4633. tsParseBracketedList(kind, parseElement, bracket, skipFirstToken) {
  4634. if (!skipFirstToken) {
  4635. if (bracket) {
  4636. this.expect(types.bracketL);
  4637. } else {
  4638. this.expectRelational("<");
  4639. }
  4640. }
  4641. const result = this.tsParseDelimitedList(kind, parseElement);
  4642. if (bracket) {
  4643. this.expect(types.bracketR);
  4644. } else {
  4645. this.expectRelational(">");
  4646. }
  4647. return result;
  4648. }
  4649. tsParseImportType() {
  4650. const node = this.startNode();
  4651. this.expect(types._import);
  4652. this.expect(types.parenL);
  4653. if (!this.match(types.string)) {
  4654. this.raise(this.state.start, TSErrors.UnsupportedImportTypeArgument);
  4655. }
  4656. node.argument = this.parseExprAtom();
  4657. this.expect(types.parenR);
  4658. if (this.eat(types.dot)) {
  4659. node.qualifier = this.tsParseEntityName(true);
  4660. }
  4661. if (this.isRelational("<")) {
  4662. node.typeParameters = this.tsParseTypeArguments();
  4663. }
  4664. return this.finishNode(node, "TSImportType");
  4665. }
  4666. tsParseEntityName(allowReservedWords) {
  4667. let entity = this.parseIdentifier();
  4668. while (this.eat(types.dot)) {
  4669. const node = this.startNodeAtNode(entity);
  4670. node.left = entity;
  4671. node.right = this.parseIdentifier(allowReservedWords);
  4672. entity = this.finishNode(node, "TSQualifiedName");
  4673. }
  4674. return entity;
  4675. }
  4676. tsParseTypeReference() {
  4677. const node = this.startNode();
  4678. node.typeName = this.tsParseEntityName(false);
  4679. if (!this.hasPrecedingLineBreak() && this.isRelational("<")) {
  4680. node.typeParameters = this.tsParseTypeArguments();
  4681. }
  4682. return this.finishNode(node, "TSTypeReference");
  4683. }
  4684. tsParseThisTypePredicate(lhs) {
  4685. this.next();
  4686. const node = this.startNodeAtNode(lhs);
  4687. node.parameterName = lhs;
  4688. node.typeAnnotation = this.tsParseTypeAnnotation(false);
  4689. node.asserts = false;
  4690. return this.finishNode(node, "TSTypePredicate");
  4691. }
  4692. tsParseThisTypeNode() {
  4693. const node = this.startNode();
  4694. this.next();
  4695. return this.finishNode(node, "TSThisType");
  4696. }
  4697. tsParseTypeQuery() {
  4698. const node = this.startNode();
  4699. this.expect(types._typeof);
  4700. if (this.match(types._import)) {
  4701. node.exprName = this.tsParseImportType();
  4702. } else {
  4703. node.exprName = this.tsParseEntityName(true);
  4704. }
  4705. return this.finishNode(node, "TSTypeQuery");
  4706. }
  4707. tsParseTypeParameter() {
  4708. const node = this.startNode();
  4709. node.name = this.parseIdentifierName(node.start);
  4710. node.constraint = this.tsEatThenParseType(types._extends);
  4711. node.default = this.tsEatThenParseType(types.eq);
  4712. return this.finishNode(node, "TSTypeParameter");
  4713. }
  4714. tsTryParseTypeParameters() {
  4715. if (this.isRelational("<")) {
  4716. return this.tsParseTypeParameters();
  4717. }
  4718. }
  4719. tsParseTypeParameters() {
  4720. const node = this.startNode();
  4721. if (this.isRelational("<") || this.match(types.jsxTagStart)) {
  4722. this.next();
  4723. } else {
  4724. this.unexpected();
  4725. }
  4726. node.params = this.tsParseBracketedList("TypeParametersOrArguments", this.tsParseTypeParameter.bind(this), false, true);
  4727. if (node.params.length === 0) {
  4728. this.raise(node.start, TSErrors.EmptyTypeParameters);
  4729. }
  4730. return this.finishNode(node, "TSTypeParameterDeclaration");
  4731. }
  4732. tsTryNextParseConstantContext() {
  4733. if (this.lookahead().type === types._const) {
  4734. this.next();
  4735. return this.tsParseTypeReference();
  4736. }
  4737. return null;
  4738. }
  4739. tsFillSignature(returnToken, signature) {
  4740. const returnTokenRequired = returnToken === types.arrow;
  4741. signature.typeParameters = this.tsTryParseTypeParameters();
  4742. this.expect(types.parenL);
  4743. signature.parameters = this.tsParseBindingListForSignature();
  4744. if (returnTokenRequired) {
  4745. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4746. } else if (this.match(returnToken)) {
  4747. signature.typeAnnotation = this.tsParseTypeOrTypePredicateAnnotation(returnToken);
  4748. }
  4749. }
  4750. tsParseBindingListForSignature() {
  4751. return this.parseBindingList(types.parenR, 41).map(pattern => {
  4752. if (pattern.type !== "Identifier" && pattern.type !== "RestElement" && pattern.type !== "ObjectPattern" && pattern.type !== "ArrayPattern") {
  4753. this.raise(pattern.start, TSErrors.UnsupportedSignatureParameterKind, pattern.type);
  4754. }
  4755. return pattern;
  4756. });
  4757. }
  4758. tsParseTypeMemberSemicolon() {
  4759. if (!this.eat(types.comma)) {
  4760. this.semicolon();
  4761. }
  4762. }
  4763. tsParseSignatureMember(kind, node) {
  4764. this.tsFillSignature(types.colon, node);
  4765. this.tsParseTypeMemberSemicolon();
  4766. return this.finishNode(node, kind);
  4767. }
  4768. tsIsUnambiguouslyIndexSignature() {
  4769. this.next();
  4770. return this.eat(types.name) && this.match(types.colon);
  4771. }
  4772. tsTryParseIndexSignature(node) {
  4773. if (!(this.match(types.bracketL) && this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))) {
  4774. return undefined;
  4775. }
  4776. this.expect(types.bracketL);
  4777. const id = this.parseIdentifier();
  4778. id.typeAnnotation = this.tsParseTypeAnnotation();
  4779. this.resetEndLocation(id);
  4780. this.expect(types.bracketR);
  4781. node.parameters = [id];
  4782. const type = this.tsTryParseTypeAnnotation();
  4783. if (type) node.typeAnnotation = type;
  4784. this.tsParseTypeMemberSemicolon();
  4785. return this.finishNode(node, "TSIndexSignature");
  4786. }
  4787. tsParsePropertyOrMethodSignature(node, readonly) {
  4788. if (this.eat(types.question)) node.optional = true;
  4789. const nodeAny = node;
  4790. if (this.match(types.parenL) || this.isRelational("<")) {
  4791. if (readonly) {
  4792. this.raise(node.start, TSErrors.ReadonlyForMethodSignature);
  4793. }
  4794. const method = nodeAny;
  4795. this.tsFillSignature(types.colon, method);
  4796. this.tsParseTypeMemberSemicolon();
  4797. return this.finishNode(method, "TSMethodSignature");
  4798. } else {
  4799. const property = nodeAny;
  4800. if (readonly) property.readonly = true;
  4801. const type = this.tsTryParseTypeAnnotation();
  4802. if (type) property.typeAnnotation = type;
  4803. this.tsParseTypeMemberSemicolon();
  4804. return this.finishNode(property, "TSPropertySignature");
  4805. }
  4806. }
  4807. tsParseTypeMember() {
  4808. const node = this.startNode();
  4809. if (this.match(types.parenL) || this.isRelational("<")) {
  4810. return this.tsParseSignatureMember("TSCallSignatureDeclaration", node);
  4811. }
  4812. if (this.match(types._new)) {
  4813. const id = this.startNode();
  4814. this.next();
  4815. if (this.match(types.parenL) || this.isRelational("<")) {
  4816. return this.tsParseSignatureMember("TSConstructSignatureDeclaration", node);
  4817. } else {
  4818. node.key = this.createIdentifier(id, "new");
  4819. return this.tsParsePropertyOrMethodSignature(node, false);
  4820. }
  4821. }
  4822. this.tsParseModifiers(node, ["readonly"], ["declare", "abstract", "private", "protected", "public", "static"], TSErrors.InvalidModifierOnTypeMember);
  4823. const idx = this.tsTryParseIndexSignature(node);
  4824. if (idx) {
  4825. return idx;
  4826. }
  4827. this.parsePropertyName(node, false);
  4828. return this.tsParsePropertyOrMethodSignature(node, !!node.readonly);
  4829. }
  4830. tsParseTypeLiteral() {
  4831. const node = this.startNode();
  4832. node.members = this.tsParseObjectTypeMembers();
  4833. return this.finishNode(node, "TSTypeLiteral");
  4834. }
  4835. tsParseObjectTypeMembers() {
  4836. this.expect(types.braceL);
  4837. const members = this.tsParseList("TypeMembers", this.tsParseTypeMember.bind(this));
  4838. this.expect(types.braceR);
  4839. return members;
  4840. }
  4841. tsIsStartOfMappedType() {
  4842. this.next();
  4843. if (this.eat(types.plusMin)) {
  4844. return this.isContextual("readonly");
  4845. }
  4846. if (this.isContextual("readonly")) {
  4847. this.next();
  4848. }
  4849. if (!this.match(types.bracketL)) {
  4850. return false;
  4851. }
  4852. this.next();
  4853. if (!this.tsIsIdentifier()) {
  4854. return false;
  4855. }
  4856. this.next();
  4857. return this.match(types._in);
  4858. }
  4859. tsParseMappedTypeParameter() {
  4860. const node = this.startNode();
  4861. node.name = this.parseIdentifierName(node.start);
  4862. node.constraint = this.tsExpectThenParseType(types._in);
  4863. return this.finishNode(node, "TSTypeParameter");
  4864. }
  4865. tsParseMappedType() {
  4866. const node = this.startNode();
  4867. this.expect(types.braceL);
  4868. if (this.match(types.plusMin)) {
  4869. node.readonly = this.state.value;
  4870. this.next();
  4871. this.expectContextual("readonly");
  4872. } else if (this.eatContextual("readonly")) {
  4873. node.readonly = true;
  4874. }
  4875. this.expect(types.bracketL);
  4876. node.typeParameter = this.tsParseMappedTypeParameter();
  4877. node.nameType = this.eatContextual("as") ? this.tsParseType() : null;
  4878. this.expect(types.bracketR);
  4879. if (this.match(types.plusMin)) {
  4880. node.optional = this.state.value;
  4881. this.next();
  4882. this.expect(types.question);
  4883. } else if (this.eat(types.question)) {
  4884. node.optional = true;
  4885. }
  4886. node.typeAnnotation = this.tsTryParseType();
  4887. this.semicolon();
  4888. this.expect(types.braceR);
  4889. return this.finishNode(node, "TSMappedType");
  4890. }
  4891. tsParseTupleType() {
  4892. const node = this.startNode();
  4893. node.elementTypes = this.tsParseBracketedList("TupleElementTypes", this.tsParseTupleElementType.bind(this), true, false);
  4894. let seenOptionalElement = false;
  4895. let labeledElements = null;
  4896. node.elementTypes.forEach(elementNode => {
  4897. var _labeledElements;
  4898. let {
  4899. type
  4900. } = elementNode;
  4901. if (seenOptionalElement && type !== "TSRestType" && type !== "TSOptionalType" && !(type === "TSNamedTupleMember" && elementNode.optional)) {
  4902. this.raise(elementNode.start, TSErrors.OptionalTypeBeforeRequired);
  4903. }
  4904. seenOptionalElement = seenOptionalElement || type === "TSNamedTupleMember" && elementNode.optional || type === "TSOptionalType";
  4905. if (type === "TSRestType") {
  4906. elementNode = elementNode.typeAnnotation;
  4907. type = elementNode.type;
  4908. }
  4909. const isLabeled = type === "TSNamedTupleMember";
  4910. labeledElements = (_labeledElements = labeledElements) != null ? _labeledElements : isLabeled;
  4911. if (labeledElements !== isLabeled) {
  4912. this.raise(elementNode.start, TSErrors.MixedLabeledAndUnlabeledElements);
  4913. }
  4914. });
  4915. return this.finishNode(node, "TSTupleType");
  4916. }
  4917. tsParseTupleElementType() {
  4918. const {
  4919. start: startPos,
  4920. startLoc
  4921. } = this.state;
  4922. const rest = this.eat(types.ellipsis);
  4923. let type = this.tsParseType();
  4924. const optional = this.eat(types.question);
  4925. const labeled = this.eat(types.colon);
  4926. if (labeled) {
  4927. const labeledNode = this.startNodeAtNode(type);
  4928. labeledNode.optional = optional;
  4929. if (type.type === "TSTypeReference" && !type.typeParameters && type.typeName.type === "Identifier") {
  4930. labeledNode.label = type.typeName;
  4931. } else {
  4932. this.raise(type.start, TSErrors.InvalidTupleMemberLabel);
  4933. labeledNode.label = type;
  4934. }
  4935. labeledNode.elementType = this.tsParseType();
  4936. type = this.finishNode(labeledNode, "TSNamedTupleMember");
  4937. } else if (optional) {
  4938. const optionalTypeNode = this.startNodeAtNode(type);
  4939. optionalTypeNode.typeAnnotation = type;
  4940. type = this.finishNode(optionalTypeNode, "TSOptionalType");
  4941. }
  4942. if (rest) {
  4943. const restNode = this.startNodeAt(startPos, startLoc);
  4944. restNode.typeAnnotation = type;
  4945. type = this.finishNode(restNode, "TSRestType");
  4946. }
  4947. return type;
  4948. }
  4949. tsParseParenthesizedType() {
  4950. const node = this.startNode();
  4951. this.expect(types.parenL);
  4952. node.typeAnnotation = this.tsParseType();
  4953. this.expect(types.parenR);
  4954. return this.finishNode(node, "TSParenthesizedType");
  4955. }
  4956. tsParseFunctionOrConstructorType(type, abstract) {
  4957. const node = this.startNode();
  4958. if (type === "TSConstructorType") {
  4959. node.abstract = !!abstract;
  4960. if (abstract) this.next();
  4961. this.next();
  4962. }
  4963. this.tsFillSignature(types.arrow, node);
  4964. return this.finishNode(node, type);
  4965. }
  4966. tsParseLiteralTypeNode() {
  4967. const node = this.startNode();
  4968. node.literal = (() => {
  4969. switch (this.state.type) {
  4970. case types.num:
  4971. case types.bigint:
  4972. case types.string:
  4973. case types._true:
  4974. case types._false:
  4975. return this.parseExprAtom();
  4976. default:
  4977. throw this.unexpected();
  4978. }
  4979. })();
  4980. return this.finishNode(node, "TSLiteralType");
  4981. }
  4982. tsParseTemplateLiteralType() {
  4983. const node = this.startNode();
  4984. node.literal = this.parseTemplate(false);
  4985. return this.finishNode(node, "TSLiteralType");
  4986. }
  4987. parseTemplateSubstitution() {
  4988. if (this.state.inType) return this.tsParseType();
  4989. return super.parseTemplateSubstitution();
  4990. }
  4991. tsParseThisTypeOrThisTypePredicate() {
  4992. const thisKeyword = this.tsParseThisTypeNode();
  4993. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  4994. return this.tsParseThisTypePredicate(thisKeyword);
  4995. } else {
  4996. return thisKeyword;
  4997. }
  4998. }
  4999. tsParseNonArrayType() {
  5000. switch (this.state.type) {
  5001. case types.name:
  5002. case types._void:
  5003. case types._null:
  5004. {
  5005. const type = this.match(types._void) ? "TSVoidKeyword" : this.match(types._null) ? "TSNullKeyword" : keywordTypeFromName(this.state.value);
  5006. if (type !== undefined && this.lookaheadCharCode() !== 46) {
  5007. const node = this.startNode();
  5008. this.next();
  5009. return this.finishNode(node, type);
  5010. }
  5011. return this.tsParseTypeReference();
  5012. }
  5013. case types.string:
  5014. case types.num:
  5015. case types.bigint:
  5016. case types._true:
  5017. case types._false:
  5018. return this.tsParseLiteralTypeNode();
  5019. case types.plusMin:
  5020. if (this.state.value === "-") {
  5021. const node = this.startNode();
  5022. const nextToken = this.lookahead();
  5023. if (nextToken.type !== types.num && nextToken.type !== types.bigint) {
  5024. throw this.unexpected();
  5025. }
  5026. node.literal = this.parseMaybeUnary();
  5027. return this.finishNode(node, "TSLiteralType");
  5028. }
  5029. break;
  5030. case types._this:
  5031. return this.tsParseThisTypeOrThisTypePredicate();
  5032. case types._typeof:
  5033. return this.tsParseTypeQuery();
  5034. case types._import:
  5035. return this.tsParseImportType();
  5036. case types.braceL:
  5037. return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this)) ? this.tsParseMappedType() : this.tsParseTypeLiteral();
  5038. case types.bracketL:
  5039. return this.tsParseTupleType();
  5040. case types.parenL:
  5041. return this.tsParseParenthesizedType();
  5042. case types.backQuote:
  5043. return this.tsParseTemplateLiteralType();
  5044. }
  5045. throw this.unexpected();
  5046. }
  5047. tsParseArrayTypeOrHigher() {
  5048. let type = this.tsParseNonArrayType();
  5049. while (!this.hasPrecedingLineBreak() && this.eat(types.bracketL)) {
  5050. if (this.match(types.bracketR)) {
  5051. const node = this.startNodeAtNode(type);
  5052. node.elementType = type;
  5053. this.expect(types.bracketR);
  5054. type = this.finishNode(node, "TSArrayType");
  5055. } else {
  5056. const node = this.startNodeAtNode(type);
  5057. node.objectType = type;
  5058. node.indexType = this.tsParseType();
  5059. this.expect(types.bracketR);
  5060. type = this.finishNode(node, "TSIndexedAccessType");
  5061. }
  5062. }
  5063. return type;
  5064. }
  5065. tsParseTypeOperator(operator) {
  5066. const node = this.startNode();
  5067. this.expectContextual(operator);
  5068. node.operator = operator;
  5069. node.typeAnnotation = this.tsParseTypeOperatorOrHigher();
  5070. if (operator === "readonly") {
  5071. this.tsCheckTypeAnnotationForReadOnly(node);
  5072. }
  5073. return this.finishNode(node, "TSTypeOperator");
  5074. }
  5075. tsCheckTypeAnnotationForReadOnly(node) {
  5076. switch (node.typeAnnotation.type) {
  5077. case "TSTupleType":
  5078. case "TSArrayType":
  5079. return;
  5080. default:
  5081. this.raise(node.start, TSErrors.UnexpectedReadonly);
  5082. }
  5083. }
  5084. tsParseInferType() {
  5085. const node = this.startNode();
  5086. this.expectContextual("infer");
  5087. const typeParameter = this.startNode();
  5088. typeParameter.name = this.parseIdentifierName(typeParameter.start);
  5089. node.typeParameter = this.finishNode(typeParameter, "TSTypeParameter");
  5090. return this.finishNode(node, "TSInferType");
  5091. }
  5092. tsParseTypeOperatorOrHigher() {
  5093. const operator = ["keyof", "unique", "readonly"].find(kw => this.isContextual(kw));
  5094. return operator ? this.tsParseTypeOperator(operator) : this.isContextual("infer") ? this.tsParseInferType() : this.tsParseArrayTypeOrHigher();
  5095. }
  5096. tsParseUnionOrIntersectionType(kind, parseConstituentType, operator) {
  5097. const node = this.startNode();
  5098. const hasLeadingOperator = this.eat(operator);
  5099. const types = [];
  5100. do {
  5101. types.push(parseConstituentType());
  5102. } while (this.eat(operator));
  5103. if (types.length === 1 && !hasLeadingOperator) {
  5104. return types[0];
  5105. }
  5106. node.types = types;
  5107. return this.finishNode(node, kind);
  5108. }
  5109. tsParseIntersectionTypeOrHigher() {
  5110. return this.tsParseUnionOrIntersectionType("TSIntersectionType", this.tsParseTypeOperatorOrHigher.bind(this), types.bitwiseAND);
  5111. }
  5112. tsParseUnionTypeOrHigher() {
  5113. return this.tsParseUnionOrIntersectionType("TSUnionType", this.tsParseIntersectionTypeOrHigher.bind(this), types.bitwiseOR);
  5114. }
  5115. tsIsStartOfFunctionType() {
  5116. if (this.isRelational("<")) {
  5117. return true;
  5118. }
  5119. return this.match(types.parenL) && this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this));
  5120. }
  5121. tsSkipParameterStart() {
  5122. if (this.match(types.name) || this.match(types._this)) {
  5123. this.next();
  5124. return true;
  5125. }
  5126. if (this.match(types.braceL)) {
  5127. let braceStackCounter = 1;
  5128. this.next();
  5129. while (braceStackCounter > 0) {
  5130. if (this.match(types.braceL)) {
  5131. ++braceStackCounter;
  5132. } else if (this.match(types.braceR)) {
  5133. --braceStackCounter;
  5134. }
  5135. this.next();
  5136. }
  5137. return true;
  5138. }
  5139. if (this.match(types.bracketL)) {
  5140. let braceStackCounter = 1;
  5141. this.next();
  5142. while (braceStackCounter > 0) {
  5143. if (this.match(types.bracketL)) {
  5144. ++braceStackCounter;
  5145. } else if (this.match(types.bracketR)) {
  5146. --braceStackCounter;
  5147. }
  5148. this.next();
  5149. }
  5150. return true;
  5151. }
  5152. return false;
  5153. }
  5154. tsIsUnambiguouslyStartOfFunctionType() {
  5155. this.next();
  5156. if (this.match(types.parenR) || this.match(types.ellipsis)) {
  5157. return true;
  5158. }
  5159. if (this.tsSkipParameterStart()) {
  5160. if (this.match(types.colon) || this.match(types.comma) || this.match(types.question) || this.match(types.eq)) {
  5161. return true;
  5162. }
  5163. if (this.match(types.parenR)) {
  5164. this.next();
  5165. if (this.match(types.arrow)) {
  5166. return true;
  5167. }
  5168. }
  5169. }
  5170. return false;
  5171. }
  5172. tsParseTypeOrTypePredicateAnnotation(returnToken) {
  5173. return this.tsInType(() => {
  5174. const t = this.startNode();
  5175. this.expect(returnToken);
  5176. const node = this.startNode();
  5177. const asserts = !!this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));
  5178. if (asserts && this.match(types._this)) {
  5179. let thisTypePredicate = this.tsParseThisTypeOrThisTypePredicate();
  5180. if (thisTypePredicate.type === "TSThisType") {
  5181. node.parameterName = thisTypePredicate;
  5182. node.asserts = true;
  5183. thisTypePredicate = this.finishNode(node, "TSTypePredicate");
  5184. } else {
  5185. this.resetStartLocationFromNode(thisTypePredicate, node);
  5186. thisTypePredicate.asserts = true;
  5187. }
  5188. t.typeAnnotation = thisTypePredicate;
  5189. return this.finishNode(t, "TSTypeAnnotation");
  5190. }
  5191. const typePredicateVariable = this.tsIsIdentifier() && this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));
  5192. if (!typePredicateVariable) {
  5193. if (!asserts) {
  5194. return this.tsParseTypeAnnotation(false, t);
  5195. }
  5196. node.parameterName = this.parseIdentifier();
  5197. node.asserts = asserts;
  5198. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  5199. return this.finishNode(t, "TSTypeAnnotation");
  5200. }
  5201. const type = this.tsParseTypeAnnotation(false);
  5202. node.parameterName = typePredicateVariable;
  5203. node.typeAnnotation = type;
  5204. node.asserts = asserts;
  5205. t.typeAnnotation = this.finishNode(node, "TSTypePredicate");
  5206. return this.finishNode(t, "TSTypeAnnotation");
  5207. });
  5208. }
  5209. tsTryParseTypeOrTypePredicateAnnotation() {
  5210. return this.match(types.colon) ? this.tsParseTypeOrTypePredicateAnnotation(types.colon) : undefined;
  5211. }
  5212. tsTryParseTypeAnnotation() {
  5213. return this.match(types.colon) ? this.tsParseTypeAnnotation() : undefined;
  5214. }
  5215. tsTryParseType() {
  5216. return this.tsEatThenParseType(types.colon);
  5217. }
  5218. tsParseTypePredicatePrefix() {
  5219. const id = this.parseIdentifier();
  5220. if (this.isContextual("is") && !this.hasPrecedingLineBreak()) {
  5221. this.next();
  5222. return id;
  5223. }
  5224. }
  5225. tsParseTypePredicateAsserts() {
  5226. if (!this.match(types.name) || this.state.value !== "asserts" || this.hasPrecedingLineBreak()) {
  5227. return false;
  5228. }
  5229. const containsEsc = this.state.containsEsc;
  5230. this.next();
  5231. if (!this.match(types.name) && !this.match(types._this)) {
  5232. return false;
  5233. }
  5234. if (containsEsc) {
  5235. this.raise(this.state.lastTokStart, ErrorMessages.InvalidEscapedReservedWord, "asserts");
  5236. }
  5237. return true;
  5238. }
  5239. tsParseTypeAnnotation(eatColon = true, t = this.startNode()) {
  5240. this.tsInType(() => {
  5241. if (eatColon) this.expect(types.colon);
  5242. t.typeAnnotation = this.tsParseType();
  5243. });
  5244. return this.finishNode(t, "TSTypeAnnotation");
  5245. }
  5246. tsParseType() {
  5247. assert(this.state.inType);
  5248. const type = this.tsParseNonConditionalType();
  5249. if (this.hasPrecedingLineBreak() || !this.eat(types._extends)) {
  5250. return type;
  5251. }
  5252. const node = this.startNodeAtNode(type);
  5253. node.checkType = type;
  5254. node.extendsType = this.tsParseNonConditionalType();
  5255. this.expect(types.question);
  5256. node.trueType = this.tsParseType();
  5257. this.expect(types.colon);
  5258. node.falseType = this.tsParseType();
  5259. return this.finishNode(node, "TSConditionalType");
  5260. }
  5261. isAbstractConstructorSignature() {
  5262. return this.isContextual("abstract") && this.lookahead().type === types._new;
  5263. }
  5264. tsParseNonConditionalType() {
  5265. if (this.tsIsStartOfFunctionType()) {
  5266. return this.tsParseFunctionOrConstructorType("TSFunctionType");
  5267. }
  5268. if (this.match(types._new)) {
  5269. return this.tsParseFunctionOrConstructorType("TSConstructorType");
  5270. } else if (this.isAbstractConstructorSignature()) {
  5271. return this.tsParseFunctionOrConstructorType("TSConstructorType", true);
  5272. }
  5273. return this.tsParseUnionTypeOrHigher();
  5274. }
  5275. tsParseTypeAssertion() {
  5276. const node = this.startNode();
  5277. const _const = this.tsTryNextParseConstantContext();
  5278. node.typeAnnotation = _const || this.tsNextThenParseType();
  5279. this.expectRelational(">");
  5280. node.expression = this.parseMaybeUnary();
  5281. return this.finishNode(node, "TSTypeAssertion");
  5282. }
  5283. tsParseHeritageClause(descriptor) {
  5284. const originalStart = this.state.start;
  5285. const delimitedList = this.tsParseDelimitedList("HeritageClauseElement", this.tsParseExpressionWithTypeArguments.bind(this));
  5286. if (!delimitedList.length) {
  5287. this.raise(originalStart, TSErrors.EmptyHeritageClauseType, descriptor);
  5288. }
  5289. return delimitedList;
  5290. }
  5291. tsParseExpressionWithTypeArguments() {
  5292. const node = this.startNode();
  5293. node.expression = this.tsParseEntityName(false);
  5294. if (this.isRelational("<")) {
  5295. node.typeParameters = this.tsParseTypeArguments();
  5296. }
  5297. return this.finishNode(node, "TSExpressionWithTypeArguments");
  5298. }
  5299. tsParseInterfaceDeclaration(node) {
  5300. node.id = this.parseIdentifier();
  5301. this.checkLVal(node.id, "typescript interface declaration", BIND_TS_INTERFACE);
  5302. node.typeParameters = this.tsTryParseTypeParameters();
  5303. if (this.eat(types._extends)) {
  5304. node.extends = this.tsParseHeritageClause("extends");
  5305. }
  5306. const body = this.startNode();
  5307. body.body = this.tsInType(this.tsParseObjectTypeMembers.bind(this));
  5308. node.body = this.finishNode(body, "TSInterfaceBody");
  5309. return this.finishNode(node, "TSInterfaceDeclaration");
  5310. }
  5311. tsParseTypeAliasDeclaration(node) {
  5312. node.id = this.parseIdentifier();
  5313. this.checkLVal(node.id, "typescript type alias", BIND_TS_TYPE);
  5314. node.typeParameters = this.tsTryParseTypeParameters();
  5315. node.typeAnnotation = this.tsInType(() => {
  5316. this.expect(types.eq);
  5317. if (this.isContextual("intrinsic") && this.lookahead().type !== types.dot) {
  5318. const node = this.startNode();
  5319. this.next();
  5320. return this.finishNode(node, "TSIntrinsicKeyword");
  5321. }
  5322. return this.tsParseType();
  5323. });
  5324. this.semicolon();
  5325. return this.finishNode(node, "TSTypeAliasDeclaration");
  5326. }
  5327. tsInNoContext(cb) {
  5328. const oldContext = this.state.context;
  5329. this.state.context = [oldContext[0]];
  5330. try {
  5331. return cb();
  5332. } finally {
  5333. this.state.context = oldContext;
  5334. }
  5335. }
  5336. tsInType(cb) {
  5337. const oldInType = this.state.inType;
  5338. this.state.inType = true;
  5339. try {
  5340. return cb();
  5341. } finally {
  5342. this.state.inType = oldInType;
  5343. }
  5344. }
  5345. tsEatThenParseType(token) {
  5346. return !this.match(token) ? undefined : this.tsNextThenParseType();
  5347. }
  5348. tsExpectThenParseType(token) {
  5349. return this.tsDoThenParseType(() => this.expect(token));
  5350. }
  5351. tsNextThenParseType() {
  5352. return this.tsDoThenParseType(() => this.next());
  5353. }
  5354. tsDoThenParseType(cb) {
  5355. return this.tsInType(() => {
  5356. cb();
  5357. return this.tsParseType();
  5358. });
  5359. }
  5360. tsParseEnumMember() {
  5361. const node = this.startNode();
  5362. node.id = this.match(types.string) ? this.parseExprAtom() : this.parseIdentifier(true);
  5363. if (this.eat(types.eq)) {
  5364. node.initializer = this.parseMaybeAssignAllowIn();
  5365. }
  5366. return this.finishNode(node, "TSEnumMember");
  5367. }
  5368. tsParseEnumDeclaration(node, isConst) {
  5369. if (isConst) node.const = true;
  5370. node.id = this.parseIdentifier();
  5371. this.checkLVal(node.id, "typescript enum declaration", isConst ? BIND_TS_CONST_ENUM : BIND_TS_ENUM);
  5372. this.expect(types.braceL);
  5373. node.members = this.tsParseDelimitedList("EnumMembers", this.tsParseEnumMember.bind(this));
  5374. this.expect(types.braceR);
  5375. return this.finishNode(node, "TSEnumDeclaration");
  5376. }
  5377. tsParseModuleBlock() {
  5378. const node = this.startNode();
  5379. this.scope.enter(SCOPE_OTHER);
  5380. this.expect(types.braceL);
  5381. this.parseBlockOrModuleBlockBody(node.body = [], undefined, true, types.braceR);
  5382. this.scope.exit();
  5383. return this.finishNode(node, "TSModuleBlock");
  5384. }
  5385. tsParseModuleOrNamespaceDeclaration(node, nested = false) {
  5386. node.id = this.parseIdentifier();
  5387. if (!nested) {
  5388. this.checkLVal(node.id, "module or namespace declaration", BIND_TS_NAMESPACE);
  5389. }
  5390. if (this.eat(types.dot)) {
  5391. const inner = this.startNode();
  5392. this.tsParseModuleOrNamespaceDeclaration(inner, true);
  5393. node.body = inner;
  5394. } else {
  5395. this.scope.enter(SCOPE_TS_MODULE);
  5396. this.prodParam.enter(PARAM);
  5397. node.body = this.tsParseModuleBlock();
  5398. this.prodParam.exit();
  5399. this.scope.exit();
  5400. }
  5401. return this.finishNode(node, "TSModuleDeclaration");
  5402. }
  5403. tsParseAmbientExternalModuleDeclaration(node) {
  5404. if (this.isContextual("global")) {
  5405. node.global = true;
  5406. node.id = this.parseIdentifier();
  5407. } else if (this.match(types.string)) {
  5408. node.id = this.parseExprAtom();
  5409. } else {
  5410. this.unexpected();
  5411. }
  5412. if (this.match(types.braceL)) {
  5413. this.scope.enter(SCOPE_TS_MODULE);
  5414. this.prodParam.enter(PARAM);
  5415. node.body = this.tsParseModuleBlock();
  5416. this.prodParam.exit();
  5417. this.scope.exit();
  5418. } else {
  5419. this.semicolon();
  5420. }
  5421. return this.finishNode(node, "TSModuleDeclaration");
  5422. }
  5423. tsParseImportEqualsDeclaration(node, isExport) {
  5424. node.isExport = isExport || false;
  5425. node.id = this.parseIdentifier();
  5426. this.checkLVal(node.id, "import equals declaration", BIND_LEXICAL);
  5427. this.expect(types.eq);
  5428. const moduleReference = this.tsParseModuleReference();
  5429. if (node.importKind === "type" && moduleReference.type !== "TSExternalModuleReference") {
  5430. this.raise(moduleReference.start, TSErrors.ImportAliasHasImportType);
  5431. }
  5432. node.moduleReference = moduleReference;
  5433. this.semicolon();
  5434. return this.finishNode(node, "TSImportEqualsDeclaration");
  5435. }
  5436. tsIsExternalModuleReference() {
  5437. return this.isContextual("require") && this.lookaheadCharCode() === 40;
  5438. }
  5439. tsParseModuleReference() {
  5440. return this.tsIsExternalModuleReference() ? this.tsParseExternalModuleReference() : this.tsParseEntityName(false);
  5441. }
  5442. tsParseExternalModuleReference() {
  5443. const node = this.startNode();
  5444. this.expectContextual("require");
  5445. this.expect(types.parenL);
  5446. if (!this.match(types.string)) {
  5447. throw this.unexpected();
  5448. }
  5449. node.expression = this.parseExprAtom();
  5450. this.expect(types.parenR);
  5451. return this.finishNode(node, "TSExternalModuleReference");
  5452. }
  5453. tsLookAhead(f) {
  5454. const state = this.state.clone();
  5455. const res = f();
  5456. this.state = state;
  5457. return res;
  5458. }
  5459. tsTryParseAndCatch(f) {
  5460. const result = this.tryParse(abort => f() || abort());
  5461. if (result.aborted || !result.node) return undefined;
  5462. if (result.error) this.state = result.failState;
  5463. return result.node;
  5464. }
  5465. tsTryParse(f) {
  5466. const state = this.state.clone();
  5467. const result = f();
  5468. if (result !== undefined && result !== false) {
  5469. return result;
  5470. } else {
  5471. this.state = state;
  5472. return undefined;
  5473. }
  5474. }
  5475. tsTryParseDeclare(nany) {
  5476. if (this.isLineTerminator()) {
  5477. return;
  5478. }
  5479. let starttype = this.state.type;
  5480. let kind;
  5481. if (this.isContextual("let")) {
  5482. starttype = types._var;
  5483. kind = "let";
  5484. }
  5485. return this.tsInDeclareContext(() => {
  5486. switch (starttype) {
  5487. case types._function:
  5488. nany.declare = true;
  5489. return this.parseFunctionStatement(nany, false, true);
  5490. case types._class:
  5491. nany.declare = true;
  5492. return this.parseClass(nany, true, false);
  5493. case types._const:
  5494. if (this.match(types._const) && this.isLookaheadContextual("enum")) {
  5495. this.expect(types._const);
  5496. this.expectContextual("enum");
  5497. return this.tsParseEnumDeclaration(nany, true);
  5498. }
  5499. case types._var:
  5500. kind = kind || this.state.value;
  5501. return this.parseVarStatement(nany, kind);
  5502. case types.name:
  5503. {
  5504. const value = this.state.value;
  5505. if (value === "global") {
  5506. return this.tsParseAmbientExternalModuleDeclaration(nany);
  5507. } else {
  5508. return this.tsParseDeclaration(nany, value, true);
  5509. }
  5510. }
  5511. }
  5512. });
  5513. }
  5514. tsTryParseExportDeclaration() {
  5515. return this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5516. }
  5517. tsParseExpressionStatement(node, expr) {
  5518. switch (expr.name) {
  5519. case "declare":
  5520. {
  5521. const declaration = this.tsTryParseDeclare(node);
  5522. if (declaration) {
  5523. declaration.declare = true;
  5524. return declaration;
  5525. }
  5526. break;
  5527. }
  5528. case "global":
  5529. if (this.match(types.braceL)) {
  5530. this.scope.enter(SCOPE_TS_MODULE);
  5531. this.prodParam.enter(PARAM);
  5532. const mod = node;
  5533. mod.global = true;
  5534. mod.id = expr;
  5535. mod.body = this.tsParseModuleBlock();
  5536. this.scope.exit();
  5537. this.prodParam.exit();
  5538. return this.finishNode(mod, "TSModuleDeclaration");
  5539. }
  5540. break;
  5541. default:
  5542. return this.tsParseDeclaration(node, expr.name, false);
  5543. }
  5544. }
  5545. tsParseDeclaration(node, value, next) {
  5546. switch (value) {
  5547. case "abstract":
  5548. if (this.tsCheckLineTerminator(next) && (this.match(types._class) || this.match(types.name))) {
  5549. return this.tsParseAbstractDeclaration(node);
  5550. }
  5551. break;
  5552. case "enum":
  5553. if (next || this.match(types.name)) {
  5554. if (next) this.next();
  5555. return this.tsParseEnumDeclaration(node, false);
  5556. }
  5557. break;
  5558. case "interface":
  5559. if (this.tsCheckLineTerminator(next) && this.match(types.name)) {
  5560. return this.tsParseInterfaceDeclaration(node);
  5561. }
  5562. break;
  5563. case "module":
  5564. if (this.tsCheckLineTerminator(next)) {
  5565. if (this.match(types.string)) {
  5566. return this.tsParseAmbientExternalModuleDeclaration(node);
  5567. } else if (this.match(types.name)) {
  5568. return this.tsParseModuleOrNamespaceDeclaration(node);
  5569. }
  5570. }
  5571. break;
  5572. case "namespace":
  5573. if (this.tsCheckLineTerminator(next) && this.match(types.name)) {
  5574. return this.tsParseModuleOrNamespaceDeclaration(node);
  5575. }
  5576. break;
  5577. case "type":
  5578. if (this.tsCheckLineTerminator(next) && this.match(types.name)) {
  5579. return this.tsParseTypeAliasDeclaration(node);
  5580. }
  5581. break;
  5582. }
  5583. }
  5584. tsCheckLineTerminator(next) {
  5585. if (next) {
  5586. if (this.hasFollowingLineBreak()) return false;
  5587. this.next();
  5588. return true;
  5589. }
  5590. return !this.isLineTerminator();
  5591. }
  5592. tsTryParseGenericAsyncArrowFunction(startPos, startLoc) {
  5593. if (!this.isRelational("<")) {
  5594. return undefined;
  5595. }
  5596. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  5597. this.state.maybeInArrowParameters = true;
  5598. const res = this.tsTryParseAndCatch(() => {
  5599. const node = this.startNodeAt(startPos, startLoc);
  5600. node.typeParameters = this.tsParseTypeParameters();
  5601. super.parseFunctionParams(node);
  5602. node.returnType = this.tsTryParseTypeOrTypePredicateAnnotation();
  5603. this.expect(types.arrow);
  5604. return node;
  5605. });
  5606. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  5607. if (!res) {
  5608. return undefined;
  5609. }
  5610. return this.parseArrowExpression(res, null, true);
  5611. }
  5612. tsParseTypeArguments() {
  5613. const node = this.startNode();
  5614. node.params = this.tsInType(() => this.tsInNoContext(() => {
  5615. this.expectRelational("<");
  5616. return this.tsParseDelimitedList("TypeParametersOrArguments", this.tsParseType.bind(this));
  5617. }));
  5618. if (node.params.length === 0) {
  5619. this.raise(node.start, TSErrors.EmptyTypeArguments);
  5620. }
  5621. this.state.exprAllowed = false;
  5622. this.expectRelational(">");
  5623. return this.finishNode(node, "TSTypeParameterInstantiation");
  5624. }
  5625. tsIsDeclarationStart() {
  5626. if (this.match(types.name)) {
  5627. switch (this.state.value) {
  5628. case "abstract":
  5629. case "declare":
  5630. case "enum":
  5631. case "interface":
  5632. case "module":
  5633. case "namespace":
  5634. case "type":
  5635. return true;
  5636. }
  5637. }
  5638. return false;
  5639. }
  5640. isExportDefaultSpecifier() {
  5641. if (this.tsIsDeclarationStart()) return false;
  5642. return super.isExportDefaultSpecifier();
  5643. }
  5644. parseAssignableListItem(allowModifiers, decorators) {
  5645. const startPos = this.state.start;
  5646. const startLoc = this.state.startLoc;
  5647. let accessibility;
  5648. let readonly = false;
  5649. if (allowModifiers !== undefined) {
  5650. accessibility = this.parseAccessModifier();
  5651. readonly = !!this.tsParseModifier(["readonly"]);
  5652. if (allowModifiers === false && (accessibility || readonly)) {
  5653. this.raise(startPos, TSErrors.UnexpectedParameterModifier);
  5654. }
  5655. }
  5656. const left = this.parseMaybeDefault();
  5657. this.parseAssignableListItemTypes(left);
  5658. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  5659. if (accessibility || readonly) {
  5660. const pp = this.startNodeAt(startPos, startLoc);
  5661. if (decorators.length) {
  5662. pp.decorators = decorators;
  5663. }
  5664. if (accessibility) pp.accessibility = accessibility;
  5665. if (readonly) pp.readonly = readonly;
  5666. if (elt.type !== "Identifier" && elt.type !== "AssignmentPattern") {
  5667. this.raise(pp.start, TSErrors.UnsupportedParameterPropertyKind);
  5668. }
  5669. pp.parameter = elt;
  5670. return this.finishNode(pp, "TSParameterProperty");
  5671. }
  5672. if (decorators.length) {
  5673. left.decorators = decorators;
  5674. }
  5675. return elt;
  5676. }
  5677. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  5678. if (this.match(types.colon)) {
  5679. node.returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  5680. }
  5681. const bodilessType = type === "FunctionDeclaration" ? "TSDeclareFunction" : type === "ClassMethod" ? "TSDeclareMethod" : undefined;
  5682. if (bodilessType && !this.match(types.braceL) && this.isLineTerminator()) {
  5683. this.finishNode(node, bodilessType);
  5684. return;
  5685. }
  5686. if (bodilessType === "TSDeclareFunction" && this.state.isDeclareContext) {
  5687. this.raise(node.start, TSErrors.DeclareFunctionHasImplementation);
  5688. if (node.declare) {
  5689. super.parseFunctionBodyAndFinish(node, bodilessType, isMethod);
  5690. return;
  5691. }
  5692. }
  5693. super.parseFunctionBodyAndFinish(node, type, isMethod);
  5694. }
  5695. registerFunctionStatementId(node) {
  5696. if (!node.body && node.id) {
  5697. this.checkLVal(node.id, "function name", BIND_TS_AMBIENT);
  5698. } else {
  5699. super.registerFunctionStatementId(...arguments);
  5700. }
  5701. }
  5702. tsCheckForInvalidTypeCasts(items) {
  5703. items.forEach(node => {
  5704. if ((node == null ? void 0 : node.type) === "TSTypeCastExpression") {
  5705. this.raise(node.typeAnnotation.start, TSErrors.UnexpectedTypeAnnotation);
  5706. }
  5707. });
  5708. }
  5709. toReferencedList(exprList, isInParens) {
  5710. this.tsCheckForInvalidTypeCasts(exprList);
  5711. return exprList;
  5712. }
  5713. parseArrayLike(...args) {
  5714. const node = super.parseArrayLike(...args);
  5715. if (node.type === "ArrayExpression") {
  5716. this.tsCheckForInvalidTypeCasts(node.elements);
  5717. }
  5718. return node;
  5719. }
  5720. parseSubscript(base, startPos, startLoc, noCalls, state) {
  5721. if (!this.hasPrecedingLineBreak() && this.match(types.bang)) {
  5722. this.state.exprAllowed = false;
  5723. this.next();
  5724. const nonNullExpression = this.startNodeAt(startPos, startLoc);
  5725. nonNullExpression.expression = base;
  5726. return this.finishNode(nonNullExpression, "TSNonNullExpression");
  5727. }
  5728. if (this.isRelational("<")) {
  5729. const result = this.tsTryParseAndCatch(() => {
  5730. if (!noCalls && this.atPossibleAsyncArrow(base)) {
  5731. const asyncArrowFn = this.tsTryParseGenericAsyncArrowFunction(startPos, startLoc);
  5732. if (asyncArrowFn) {
  5733. return asyncArrowFn;
  5734. }
  5735. }
  5736. const node = this.startNodeAt(startPos, startLoc);
  5737. node.callee = base;
  5738. const typeArguments = this.tsParseTypeArguments();
  5739. if (typeArguments) {
  5740. if (!noCalls && this.eat(types.parenL)) {
  5741. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  5742. this.tsCheckForInvalidTypeCasts(node.arguments);
  5743. node.typeParameters = typeArguments;
  5744. if (state.optionalChainMember) {
  5745. node.optional = false;
  5746. }
  5747. return this.finishCallExpression(node, state.optionalChainMember);
  5748. } else if (this.match(types.backQuote)) {
  5749. const result = this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  5750. result.typeParameters = typeArguments;
  5751. return result;
  5752. }
  5753. }
  5754. this.unexpected();
  5755. });
  5756. if (result) return result;
  5757. }
  5758. return super.parseSubscript(base, startPos, startLoc, noCalls, state);
  5759. }
  5760. parseNewArguments(node) {
  5761. if (this.isRelational("<")) {
  5762. const typeParameters = this.tsTryParseAndCatch(() => {
  5763. const args = this.tsParseTypeArguments();
  5764. if (!this.match(types.parenL)) this.unexpected();
  5765. return args;
  5766. });
  5767. if (typeParameters) {
  5768. node.typeParameters = typeParameters;
  5769. }
  5770. }
  5771. super.parseNewArguments(node);
  5772. }
  5773. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  5774. if (nonNull(types._in.binop) > minPrec && !this.hasPrecedingLineBreak() && this.isContextual("as")) {
  5775. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  5776. node.expression = left;
  5777. const _const = this.tsTryNextParseConstantContext();
  5778. if (_const) {
  5779. node.typeAnnotation = _const;
  5780. } else {
  5781. node.typeAnnotation = this.tsNextThenParseType();
  5782. }
  5783. this.finishNode(node, "TSAsExpression");
  5784. this.reScan_lt_gt();
  5785. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  5786. }
  5787. return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec);
  5788. }
  5789. checkReservedWord(word, startLoc, checkKeywords, isBinding) {}
  5790. checkDuplicateExports() {}
  5791. parseImport(node) {
  5792. node.importKind = "value";
  5793. if (this.match(types.name) || this.match(types.star) || this.match(types.braceL)) {
  5794. let ahead = this.lookahead();
  5795. if (this.isContextual("type") && ahead.type !== types.comma && !(ahead.type === types.name && ahead.value === "from") && ahead.type !== types.eq) {
  5796. node.importKind = "type";
  5797. this.next();
  5798. ahead = this.lookahead();
  5799. }
  5800. if (this.match(types.name) && ahead.type === types.eq) {
  5801. return this.tsParseImportEqualsDeclaration(node);
  5802. }
  5803. }
  5804. const importNode = super.parseImport(node);
  5805. if (importNode.importKind === "type" && importNode.specifiers.length > 1 && importNode.specifiers[0].type === "ImportDefaultSpecifier") {
  5806. this.raise(importNode.start, "A type-only import can specify a default import or named bindings, but not both.");
  5807. }
  5808. return importNode;
  5809. }
  5810. parseExport(node) {
  5811. if (this.match(types._import)) {
  5812. this.next();
  5813. if (this.isContextual("type") && this.lookaheadCharCode() !== 61) {
  5814. node.importKind = "type";
  5815. this.next();
  5816. } else {
  5817. node.importKind = "value";
  5818. }
  5819. return this.tsParseImportEqualsDeclaration(node, true);
  5820. } else if (this.eat(types.eq)) {
  5821. const assign = node;
  5822. assign.expression = this.parseExpression();
  5823. this.semicolon();
  5824. return this.finishNode(assign, "TSExportAssignment");
  5825. } else if (this.eatContextual("as")) {
  5826. const decl = node;
  5827. this.expectContextual("namespace");
  5828. decl.id = this.parseIdentifier();
  5829. this.semicolon();
  5830. return this.finishNode(decl, "TSNamespaceExportDeclaration");
  5831. } else {
  5832. if (this.isContextual("type") && this.lookahead().type === types.braceL) {
  5833. this.next();
  5834. node.exportKind = "type";
  5835. } else {
  5836. node.exportKind = "value";
  5837. }
  5838. return super.parseExport(node);
  5839. }
  5840. }
  5841. isAbstractClass() {
  5842. return this.isContextual("abstract") && this.lookahead().type === types._class;
  5843. }
  5844. parseExportDefaultExpression() {
  5845. if (this.isAbstractClass()) {
  5846. const cls = this.startNode();
  5847. this.next();
  5848. cls.abstract = true;
  5849. this.parseClass(cls, true, true);
  5850. return cls;
  5851. }
  5852. if (this.state.value === "interface") {
  5853. const result = this.tsParseDeclaration(this.startNode(), this.state.value, true);
  5854. if (result) return result;
  5855. }
  5856. return super.parseExportDefaultExpression();
  5857. }
  5858. parseStatementContent(context, topLevel) {
  5859. if (this.state.type === types._const) {
  5860. const ahead = this.lookahead();
  5861. if (ahead.type === types.name && ahead.value === "enum") {
  5862. const node = this.startNode();
  5863. this.expect(types._const);
  5864. this.expectContextual("enum");
  5865. return this.tsParseEnumDeclaration(node, true);
  5866. }
  5867. }
  5868. return super.parseStatementContent(context, topLevel);
  5869. }
  5870. parseAccessModifier() {
  5871. return this.tsParseModifier(["public", "protected", "private"]);
  5872. }
  5873. parseClassMember(classBody, member, state) {
  5874. this.tsParseModifiers(member, ["declare", "private", "public", "protected"]);
  5875. const callParseClassMember = () => {
  5876. super.parseClassMember(classBody, member, state);
  5877. };
  5878. if (member.declare) {
  5879. this.tsInDeclareContext(callParseClassMember);
  5880. } else {
  5881. callParseClassMember();
  5882. }
  5883. }
  5884. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  5885. this.tsParseModifiers(member, ["abstract", "readonly", "declare"]);
  5886. const idx = this.tsTryParseIndexSignature(member);
  5887. if (idx) {
  5888. classBody.body.push(idx);
  5889. if (member.abstract) {
  5890. this.raise(member.start, TSErrors.IndexSignatureHasAbstract);
  5891. }
  5892. if (isStatic) {
  5893. this.raise(member.start, TSErrors.IndexSignatureHasStatic);
  5894. }
  5895. if (member.accessibility) {
  5896. this.raise(member.start, TSErrors.IndexSignatureHasAccessibility, member.accessibility);
  5897. }
  5898. if (member.declare) {
  5899. this.raise(member.start, TSErrors.IndexSignatureHasDeclare);
  5900. }
  5901. return;
  5902. }
  5903. if (!this.state.inAbstractClass && member.abstract) {
  5904. this.raise(member.start, TSErrors.NonAbstractClassHasAbstractMethod);
  5905. }
  5906. super.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  5907. }
  5908. parsePostMemberNameModifiers(methodOrProp) {
  5909. const optional = this.eat(types.question);
  5910. if (optional) methodOrProp.optional = true;
  5911. if (methodOrProp.readonly && this.match(types.parenL)) {
  5912. this.raise(methodOrProp.start, TSErrors.ClassMethodHasReadonly);
  5913. }
  5914. if (methodOrProp.declare && this.match(types.parenL)) {
  5915. this.raise(methodOrProp.start, TSErrors.ClassMethodHasDeclare);
  5916. }
  5917. }
  5918. parseExpressionStatement(node, expr) {
  5919. const decl = expr.type === "Identifier" ? this.tsParseExpressionStatement(node, expr) : undefined;
  5920. return decl || super.parseExpressionStatement(node, expr);
  5921. }
  5922. shouldParseExportDeclaration() {
  5923. if (this.tsIsDeclarationStart()) return true;
  5924. return super.shouldParseExportDeclaration();
  5925. }
  5926. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  5927. if (!refNeedsArrowPos || !this.match(types.question)) {
  5928. return super.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  5929. }
  5930. const result = this.tryParse(() => super.parseConditional(expr, startPos, startLoc));
  5931. if (!result.node) {
  5932. refNeedsArrowPos.start = result.error.pos || this.state.start;
  5933. return expr;
  5934. }
  5935. if (result.error) this.state = result.failState;
  5936. return result.node;
  5937. }
  5938. parseParenItem(node, startPos, startLoc) {
  5939. node = super.parseParenItem(node, startPos, startLoc);
  5940. if (this.eat(types.question)) {
  5941. node.optional = true;
  5942. this.resetEndLocation(node);
  5943. }
  5944. if (this.match(types.colon)) {
  5945. const typeCastNode = this.startNodeAt(startPos, startLoc);
  5946. typeCastNode.expression = node;
  5947. typeCastNode.typeAnnotation = this.tsParseTypeAnnotation();
  5948. return this.finishNode(typeCastNode, "TSTypeCastExpression");
  5949. }
  5950. return node;
  5951. }
  5952. parseExportDeclaration(node) {
  5953. const startPos = this.state.start;
  5954. const startLoc = this.state.startLoc;
  5955. const isDeclare = this.eatContextual("declare");
  5956. if (isDeclare && (this.isContextual("declare") || !this.shouldParseExportDeclaration())) {
  5957. throw this.raise(this.state.start, TSErrors.ExpectedAmbientAfterExportDeclare);
  5958. }
  5959. let declaration;
  5960. if (this.match(types.name)) {
  5961. declaration = this.tsTryParseExportDeclaration();
  5962. }
  5963. if (!declaration) {
  5964. declaration = super.parseExportDeclaration(node);
  5965. }
  5966. if (declaration && (declaration.type === "TSInterfaceDeclaration" || declaration.type === "TSTypeAliasDeclaration" || isDeclare)) {
  5967. node.exportKind = "type";
  5968. }
  5969. if (declaration && isDeclare) {
  5970. this.resetStartLocation(declaration, startPos, startLoc);
  5971. declaration.declare = true;
  5972. }
  5973. return declaration;
  5974. }
  5975. parseClassId(node, isStatement, optionalId) {
  5976. if ((!isStatement || optionalId) && this.isContextual("implements")) {
  5977. return;
  5978. }
  5979. super.parseClassId(node, isStatement, optionalId, node.declare ? BIND_TS_AMBIENT : BIND_CLASS);
  5980. const typeParameters = this.tsTryParseTypeParameters();
  5981. if (typeParameters) node.typeParameters = typeParameters;
  5982. }
  5983. parseClassPropertyAnnotation(node) {
  5984. if (!node.optional && this.eat(types.bang)) {
  5985. node.definite = true;
  5986. }
  5987. const type = this.tsTryParseTypeAnnotation();
  5988. if (type) node.typeAnnotation = type;
  5989. }
  5990. parseClassProperty(node) {
  5991. this.parseClassPropertyAnnotation(node);
  5992. if (this.state.isDeclareContext && this.match(types.eq)) {
  5993. this.raise(this.state.start, TSErrors.DeclareClassFieldHasInitializer);
  5994. }
  5995. return super.parseClassProperty(node);
  5996. }
  5997. parseClassPrivateProperty(node) {
  5998. if (node.abstract) {
  5999. this.raise(node.start, TSErrors.PrivateElementHasAbstract);
  6000. }
  6001. if (node.accessibility) {
  6002. this.raise(node.start, TSErrors.PrivateElementHasAccessibility, node.accessibility);
  6003. }
  6004. this.parseClassPropertyAnnotation(node);
  6005. return super.parseClassPrivateProperty(node);
  6006. }
  6007. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  6008. const typeParameters = this.tsTryParseTypeParameters();
  6009. if (typeParameters && isConstructor) {
  6010. this.raise(typeParameters.start, TSErrors.ConstructorHasTypeParameters);
  6011. }
  6012. if (method.declare && (method.kind === "get" || method.kind === "set")) {
  6013. this.raise(method.start, TSErrors.DeclareAccessor, method.kind);
  6014. }
  6015. if (typeParameters) method.typeParameters = typeParameters;
  6016. super.pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper);
  6017. }
  6018. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  6019. const typeParameters = this.tsTryParseTypeParameters();
  6020. if (typeParameters) method.typeParameters = typeParameters;
  6021. super.pushClassPrivateMethod(classBody, method, isGenerator, isAsync);
  6022. }
  6023. parseClassSuper(node) {
  6024. super.parseClassSuper(node);
  6025. if (node.superClass && this.isRelational("<")) {
  6026. node.superTypeParameters = this.tsParseTypeArguments();
  6027. }
  6028. if (this.eatContextual("implements")) {
  6029. node.implements = this.tsParseHeritageClause("implements");
  6030. }
  6031. }
  6032. parseObjPropValue(prop, ...args) {
  6033. const typeParameters = this.tsTryParseTypeParameters();
  6034. if (typeParameters) prop.typeParameters = typeParameters;
  6035. super.parseObjPropValue(prop, ...args);
  6036. }
  6037. parseFunctionParams(node, allowModifiers) {
  6038. const typeParameters = this.tsTryParseTypeParameters();
  6039. if (typeParameters) node.typeParameters = typeParameters;
  6040. super.parseFunctionParams(node, allowModifiers);
  6041. }
  6042. parseVarId(decl, kind) {
  6043. super.parseVarId(decl, kind);
  6044. if (decl.id.type === "Identifier" && this.eat(types.bang)) {
  6045. decl.definite = true;
  6046. }
  6047. const type = this.tsTryParseTypeAnnotation();
  6048. if (type) {
  6049. decl.id.typeAnnotation = type;
  6050. this.resetEndLocation(decl.id);
  6051. }
  6052. }
  6053. parseAsyncArrowFromCallExpression(node, call) {
  6054. if (this.match(types.colon)) {
  6055. node.returnType = this.tsParseTypeAnnotation();
  6056. }
  6057. return super.parseAsyncArrowFromCallExpression(node, call);
  6058. }
  6059. parseMaybeAssign(...args) {
  6060. var _jsx, _jsx2, _typeCast, _jsx3, _typeCast2, _jsx4, _typeCast3;
  6061. let state;
  6062. let jsx;
  6063. let typeCast;
  6064. if (this.hasPlugin("jsx") && (this.match(types.jsxTagStart) || this.isRelational("<"))) {
  6065. state = this.state.clone();
  6066. jsx = this.tryParse(() => super.parseMaybeAssign(...args), state);
  6067. if (!jsx.error) return jsx.node;
  6068. const {
  6069. context
  6070. } = this.state;
  6071. if (context[context.length - 1] === types$1.j_oTag) {
  6072. context.length -= 2;
  6073. } else if (context[context.length - 1] === types$1.j_expr) {
  6074. context.length -= 1;
  6075. }
  6076. }
  6077. if (!((_jsx = jsx) != null && _jsx.error) && !this.isRelational("<")) {
  6078. return super.parseMaybeAssign(...args);
  6079. }
  6080. let typeParameters;
  6081. state = state || this.state.clone();
  6082. const arrow = this.tryParse(abort => {
  6083. var _expr$extra, _typeParameters;
  6084. typeParameters = this.tsParseTypeParameters();
  6085. const expr = super.parseMaybeAssign(...args);
  6086. if (expr.type !== "ArrowFunctionExpression" || (_expr$extra = expr.extra) != null && _expr$extra.parenthesized) {
  6087. abort();
  6088. }
  6089. if (((_typeParameters = typeParameters) == null ? void 0 : _typeParameters.params.length) !== 0) {
  6090. this.resetStartLocationFromNode(expr, typeParameters);
  6091. }
  6092. expr.typeParameters = typeParameters;
  6093. return expr;
  6094. }, state);
  6095. if (!arrow.error && !arrow.aborted) return arrow.node;
  6096. if (!jsx) {
  6097. assert(!this.hasPlugin("jsx"));
  6098. typeCast = this.tryParse(() => super.parseMaybeAssign(...args), state);
  6099. if (!typeCast.error) return typeCast.node;
  6100. }
  6101. if ((_jsx2 = jsx) != null && _jsx2.node) {
  6102. this.state = jsx.failState;
  6103. return jsx.node;
  6104. }
  6105. if (arrow.node) {
  6106. this.state = arrow.failState;
  6107. return arrow.node;
  6108. }
  6109. if ((_typeCast = typeCast) != null && _typeCast.node) {
  6110. this.state = typeCast.failState;
  6111. return typeCast.node;
  6112. }
  6113. if ((_jsx3 = jsx) != null && _jsx3.thrown) throw jsx.error;
  6114. if (arrow.thrown) throw arrow.error;
  6115. if ((_typeCast2 = typeCast) != null && _typeCast2.thrown) throw typeCast.error;
  6116. throw ((_jsx4 = jsx) == null ? void 0 : _jsx4.error) || arrow.error || ((_typeCast3 = typeCast) == null ? void 0 : _typeCast3.error);
  6117. }
  6118. parseMaybeUnary(refExpressionErrors) {
  6119. if (!this.hasPlugin("jsx") && this.isRelational("<")) {
  6120. return this.tsParseTypeAssertion();
  6121. } else {
  6122. return super.parseMaybeUnary(refExpressionErrors);
  6123. }
  6124. }
  6125. parseArrow(node) {
  6126. if (this.match(types.colon)) {
  6127. const result = this.tryParse(abort => {
  6128. const returnType = this.tsParseTypeOrTypePredicateAnnotation(types.colon);
  6129. if (this.canInsertSemicolon() || !this.match(types.arrow)) abort();
  6130. return returnType;
  6131. });
  6132. if (result.aborted) return;
  6133. if (!result.thrown) {
  6134. if (result.error) this.state = result.failState;
  6135. node.returnType = result.node;
  6136. }
  6137. }
  6138. return super.parseArrow(node);
  6139. }
  6140. parseAssignableListItemTypes(param) {
  6141. if (this.eat(types.question)) {
  6142. if (param.type !== "Identifier" && !this.state.isDeclareContext && !this.state.inType) {
  6143. this.raise(param.start, TSErrors.PatternIsOptional);
  6144. }
  6145. param.optional = true;
  6146. }
  6147. const type = this.tsTryParseTypeAnnotation();
  6148. if (type) param.typeAnnotation = type;
  6149. this.resetEndLocation(param);
  6150. return param;
  6151. }
  6152. toAssignable(node, isLHS = false) {
  6153. switch (node.type) {
  6154. case "TSTypeCastExpression":
  6155. return super.toAssignable(this.typeCastToParameter(node), isLHS);
  6156. case "TSParameterProperty":
  6157. return super.toAssignable(node, isLHS);
  6158. case "ParenthesizedExpression":
  6159. return this.toAssignableParenthesizedExpression(node, isLHS);
  6160. case "TSAsExpression":
  6161. case "TSNonNullExpression":
  6162. case "TSTypeAssertion":
  6163. node.expression = this.toAssignable(node.expression, isLHS);
  6164. return node;
  6165. default:
  6166. return super.toAssignable(node, isLHS);
  6167. }
  6168. }
  6169. toAssignableParenthesizedExpression(node, isLHS) {
  6170. switch (node.expression.type) {
  6171. case "TSAsExpression":
  6172. case "TSNonNullExpression":
  6173. case "TSTypeAssertion":
  6174. case "ParenthesizedExpression":
  6175. node.expression = this.toAssignable(node.expression, isLHS);
  6176. return node;
  6177. default:
  6178. return super.toAssignable(node, isLHS);
  6179. }
  6180. }
  6181. checkLVal(expr, contextDescription, ...args) {
  6182. var _expr$extra2;
  6183. switch (expr.type) {
  6184. case "TSTypeCastExpression":
  6185. return;
  6186. case "TSParameterProperty":
  6187. this.checkLVal(expr.parameter, "parameter property", ...args);
  6188. return;
  6189. case "TSAsExpression":
  6190. case "TSTypeAssertion":
  6191. if (!args[0] && contextDescription !== "parenthesized expression" && !((_expr$extra2 = expr.extra) != null && _expr$extra2.parenthesized)) {
  6192. this.raise(expr.start, ErrorMessages.InvalidLhs, contextDescription);
  6193. break;
  6194. }
  6195. this.checkLVal(expr.expression, "parenthesized expression", ...args);
  6196. return;
  6197. case "TSNonNullExpression":
  6198. this.checkLVal(expr.expression, contextDescription, ...args);
  6199. return;
  6200. default:
  6201. super.checkLVal(expr, contextDescription, ...args);
  6202. return;
  6203. }
  6204. }
  6205. parseBindingAtom() {
  6206. switch (this.state.type) {
  6207. case types._this:
  6208. return this.parseIdentifier(true);
  6209. default:
  6210. return super.parseBindingAtom();
  6211. }
  6212. }
  6213. parseMaybeDecoratorArguments(expr) {
  6214. if (this.isRelational("<")) {
  6215. const typeArguments = this.tsParseTypeArguments();
  6216. if (this.match(types.parenL)) {
  6217. const call = super.parseMaybeDecoratorArguments(expr);
  6218. call.typeParameters = typeArguments;
  6219. return call;
  6220. }
  6221. this.unexpected(this.state.start, types.parenL);
  6222. }
  6223. return super.parseMaybeDecoratorArguments(expr);
  6224. }
  6225. checkCommaAfterRest(close) {
  6226. if (this.state.isDeclareContext && this.match(types.comma) && this.lookaheadCharCode() === close) {
  6227. this.next();
  6228. } else {
  6229. super.checkCommaAfterRest(close);
  6230. }
  6231. }
  6232. isClassMethod() {
  6233. return this.isRelational("<") || super.isClassMethod();
  6234. }
  6235. isClassProperty() {
  6236. return this.match(types.bang) || this.match(types.colon) || super.isClassProperty();
  6237. }
  6238. parseMaybeDefault(...args) {
  6239. const node = super.parseMaybeDefault(...args);
  6240. if (node.type === "AssignmentPattern" && node.typeAnnotation && node.right.start < node.typeAnnotation.start) {
  6241. this.raise(node.typeAnnotation.start, TSErrors.TypeAnnotationAfterAssign);
  6242. }
  6243. return node;
  6244. }
  6245. getTokenFromCode(code) {
  6246. if (this.state.inType && (code === 62 || code === 60)) {
  6247. return this.finishOp(types.relational, 1);
  6248. } else {
  6249. return super.getTokenFromCode(code);
  6250. }
  6251. }
  6252. reScan_lt_gt() {
  6253. if (this.match(types.relational)) {
  6254. const code = this.input.charCodeAt(this.state.start);
  6255. if (code === 60 || code === 62) {
  6256. this.state.pos -= 1;
  6257. this.readToken_lt_gt(code);
  6258. }
  6259. }
  6260. }
  6261. toAssignableList(exprList) {
  6262. for (let i = 0; i < exprList.length; i++) {
  6263. const expr = exprList[i];
  6264. if (!expr) continue;
  6265. switch (expr.type) {
  6266. case "TSTypeCastExpression":
  6267. exprList[i] = this.typeCastToParameter(expr);
  6268. break;
  6269. case "TSAsExpression":
  6270. case "TSTypeAssertion":
  6271. if (!this.state.maybeInArrowParameters) {
  6272. exprList[i] = this.typeCastToParameter(expr);
  6273. } else {
  6274. this.raise(expr.start, TSErrors.UnexpectedTypeCastInParameter);
  6275. }
  6276. break;
  6277. }
  6278. }
  6279. return super.toAssignableList(...arguments);
  6280. }
  6281. typeCastToParameter(node) {
  6282. node.expression.typeAnnotation = node.typeAnnotation;
  6283. this.resetEndLocation(node.expression, node.typeAnnotation.end, node.typeAnnotation.loc.end);
  6284. return node.expression;
  6285. }
  6286. shouldParseArrow() {
  6287. return this.match(types.colon) || super.shouldParseArrow();
  6288. }
  6289. shouldParseAsyncArrow() {
  6290. return this.match(types.colon) || super.shouldParseAsyncArrow();
  6291. }
  6292. canHaveLeadingDecorator() {
  6293. return super.canHaveLeadingDecorator() || this.isAbstractClass();
  6294. }
  6295. jsxParseOpeningElementAfterName(node) {
  6296. if (this.isRelational("<")) {
  6297. const typeArguments = this.tsTryParseAndCatch(() => this.tsParseTypeArguments());
  6298. if (typeArguments) node.typeParameters = typeArguments;
  6299. }
  6300. return super.jsxParseOpeningElementAfterName(node);
  6301. }
  6302. getGetterSetterExpectedParamCount(method) {
  6303. const baseCount = super.getGetterSetterExpectedParamCount(method);
  6304. const params = this.getObjectOrClassMethodParams(method);
  6305. const firstParam = params[0];
  6306. const hasContextParam = firstParam && firstParam.type === "Identifier" && firstParam.name === "this";
  6307. return hasContextParam ? baseCount + 1 : baseCount;
  6308. }
  6309. parseCatchClauseParam() {
  6310. const param = super.parseCatchClauseParam();
  6311. const type = this.tsTryParseTypeAnnotation();
  6312. if (type) {
  6313. param.typeAnnotation = type;
  6314. this.resetEndLocation(param);
  6315. }
  6316. return param;
  6317. }
  6318. tsInDeclareContext(cb) {
  6319. const oldIsDeclareContext = this.state.isDeclareContext;
  6320. this.state.isDeclareContext = true;
  6321. try {
  6322. return cb();
  6323. } finally {
  6324. this.state.isDeclareContext = oldIsDeclareContext;
  6325. }
  6326. }
  6327. parseClass(node, ...args) {
  6328. const oldInAbstractClass = this.state.inAbstractClass;
  6329. this.state.inAbstractClass = !!node.abstract;
  6330. try {
  6331. return super.parseClass(node, ...args);
  6332. } finally {
  6333. this.state.inAbstractClass = oldInAbstractClass;
  6334. }
  6335. }
  6336. tsParseAbstractDeclaration(node) {
  6337. if (this.match(types._class)) {
  6338. node.abstract = true;
  6339. return this.parseClass(node, true, false);
  6340. } else if (this.isContextual("interface")) {
  6341. if (!this.hasFollowingLineBreak()) {
  6342. node.abstract = true;
  6343. this.raise(node.start, TSErrors.NonClassMethodPropertyHasAbstractModifer);
  6344. this.next();
  6345. return this.tsParseInterfaceDeclaration(node);
  6346. }
  6347. } else {
  6348. this.unexpected(null, types._class);
  6349. }
  6350. }
  6351. parseMethod(...args) {
  6352. const method = super.parseMethod(...args);
  6353. if (method.abstract) {
  6354. const hasBody = this.hasPlugin("estree") ? !!method.value.body : !!method.body;
  6355. if (hasBody) {
  6356. const {
  6357. key
  6358. } = method;
  6359. this.raise(method.start, TSErrors.AbstractMethodHasImplementation, key.type === "Identifier" ? key.name : `[${this.input.slice(key.start, key.end)}]`);
  6360. }
  6361. }
  6362. return method;
  6363. }
  6364. });
  6365. types.placeholder = new TokenType("%%", {
  6366. startsExpr: true
  6367. });
  6368. var placeholders = (superClass => class extends superClass {
  6369. parsePlaceholder(expectedNode) {
  6370. if (this.match(types.placeholder)) {
  6371. const node = this.startNode();
  6372. this.next();
  6373. this.assertNoSpace("Unexpected space in placeholder.");
  6374. node.name = super.parseIdentifier(true);
  6375. this.assertNoSpace("Unexpected space in placeholder.");
  6376. this.expect(types.placeholder);
  6377. return this.finishPlaceholder(node, expectedNode);
  6378. }
  6379. }
  6380. finishPlaceholder(node, expectedNode) {
  6381. const isFinished = !!(node.expectedNode && node.type === "Placeholder");
  6382. node.expectedNode = expectedNode;
  6383. return isFinished ? node : this.finishNode(node, "Placeholder");
  6384. }
  6385. getTokenFromCode(code) {
  6386. if (code === 37 && this.input.charCodeAt(this.state.pos + 1) === 37) {
  6387. return this.finishOp(types.placeholder, 2);
  6388. }
  6389. return super.getTokenFromCode(...arguments);
  6390. }
  6391. parseExprAtom() {
  6392. return this.parsePlaceholder("Expression") || super.parseExprAtom(...arguments);
  6393. }
  6394. parseIdentifier() {
  6395. return this.parsePlaceholder("Identifier") || super.parseIdentifier(...arguments);
  6396. }
  6397. checkReservedWord(word) {
  6398. if (word !== undefined) super.checkReservedWord(...arguments);
  6399. }
  6400. parseBindingAtom() {
  6401. return this.parsePlaceholder("Pattern") || super.parseBindingAtom(...arguments);
  6402. }
  6403. checkLVal(expr) {
  6404. if (expr.type !== "Placeholder") super.checkLVal(...arguments);
  6405. }
  6406. toAssignable(node) {
  6407. if (node && node.type === "Placeholder" && node.expectedNode === "Expression") {
  6408. node.expectedNode = "Pattern";
  6409. return node;
  6410. }
  6411. return super.toAssignable(...arguments);
  6412. }
  6413. isLet(context) {
  6414. if (super.isLet(context)) {
  6415. return true;
  6416. }
  6417. if (!this.isContextual("let")) {
  6418. return false;
  6419. }
  6420. if (context) return false;
  6421. const nextToken = this.lookahead();
  6422. if (nextToken.type === types.placeholder) {
  6423. return true;
  6424. }
  6425. return false;
  6426. }
  6427. verifyBreakContinue(node) {
  6428. if (node.label && node.label.type === "Placeholder") return;
  6429. super.verifyBreakContinue(...arguments);
  6430. }
  6431. parseExpressionStatement(node, expr) {
  6432. if (expr.type !== "Placeholder" || expr.extra && expr.extra.parenthesized) {
  6433. return super.parseExpressionStatement(...arguments);
  6434. }
  6435. if (this.match(types.colon)) {
  6436. const stmt = node;
  6437. stmt.label = this.finishPlaceholder(expr, "Identifier");
  6438. this.next();
  6439. stmt.body = this.parseStatement("label");
  6440. return this.finishNode(stmt, "LabeledStatement");
  6441. }
  6442. this.semicolon();
  6443. node.name = expr.name;
  6444. return this.finishPlaceholder(node, "Statement");
  6445. }
  6446. parseBlock() {
  6447. return this.parsePlaceholder("BlockStatement") || super.parseBlock(...arguments);
  6448. }
  6449. parseFunctionId() {
  6450. return this.parsePlaceholder("Identifier") || super.parseFunctionId(...arguments);
  6451. }
  6452. parseClass(node, isStatement, optionalId) {
  6453. const type = isStatement ? "ClassDeclaration" : "ClassExpression";
  6454. this.next();
  6455. this.takeDecorators(node);
  6456. const oldStrict = this.state.strict;
  6457. const placeholder = this.parsePlaceholder("Identifier");
  6458. if (placeholder) {
  6459. if (this.match(types._extends) || this.match(types.placeholder) || this.match(types.braceL)) {
  6460. node.id = placeholder;
  6461. } else if (optionalId || !isStatement) {
  6462. node.id = null;
  6463. node.body = this.finishPlaceholder(placeholder, "ClassBody");
  6464. return this.finishNode(node, type);
  6465. } else {
  6466. this.unexpected(null, "A class name is required");
  6467. }
  6468. } else {
  6469. this.parseClassId(node, isStatement, optionalId);
  6470. }
  6471. this.parseClassSuper(node);
  6472. node.body = this.parsePlaceholder("ClassBody") || this.parseClassBody(!!node.superClass, oldStrict);
  6473. return this.finishNode(node, type);
  6474. }
  6475. parseExport(node) {
  6476. const placeholder = this.parsePlaceholder("Identifier");
  6477. if (!placeholder) return super.parseExport(...arguments);
  6478. if (!this.isContextual("from") && !this.match(types.comma)) {
  6479. node.specifiers = [];
  6480. node.source = null;
  6481. node.declaration = this.finishPlaceholder(placeholder, "Declaration");
  6482. return this.finishNode(node, "ExportNamedDeclaration");
  6483. }
  6484. this.expectPlugin("exportDefaultFrom");
  6485. const specifier = this.startNode();
  6486. specifier.exported = placeholder;
  6487. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  6488. return super.parseExport(node);
  6489. }
  6490. isExportDefaultSpecifier() {
  6491. if (this.match(types._default)) {
  6492. const next = this.nextTokenStart();
  6493. if (this.isUnparsedContextual(next, "from")) {
  6494. if (this.input.startsWith(types.placeholder.label, this.nextTokenStartSince(next + 4))) {
  6495. return true;
  6496. }
  6497. }
  6498. }
  6499. return super.isExportDefaultSpecifier();
  6500. }
  6501. maybeParseExportDefaultSpecifier(node) {
  6502. if (node.specifiers && node.specifiers.length > 0) {
  6503. return true;
  6504. }
  6505. return super.maybeParseExportDefaultSpecifier(...arguments);
  6506. }
  6507. checkExport(node) {
  6508. const {
  6509. specifiers
  6510. } = node;
  6511. if (specifiers != null && specifiers.length) {
  6512. node.specifiers = specifiers.filter(node => node.exported.type === "Placeholder");
  6513. }
  6514. super.checkExport(node);
  6515. node.specifiers = specifiers;
  6516. }
  6517. parseImport(node) {
  6518. const placeholder = this.parsePlaceholder("Identifier");
  6519. if (!placeholder) return super.parseImport(...arguments);
  6520. node.specifiers = [];
  6521. if (!this.isContextual("from") && !this.match(types.comma)) {
  6522. node.source = this.finishPlaceholder(placeholder, "StringLiteral");
  6523. this.semicolon();
  6524. return this.finishNode(node, "ImportDeclaration");
  6525. }
  6526. const specifier = this.startNodeAtNode(placeholder);
  6527. specifier.local = placeholder;
  6528. this.finishNode(specifier, "ImportDefaultSpecifier");
  6529. node.specifiers.push(specifier);
  6530. if (this.eat(types.comma)) {
  6531. const hasStarImport = this.maybeParseStarImportSpecifier(node);
  6532. if (!hasStarImport) this.parseNamedImportSpecifiers(node);
  6533. }
  6534. this.expectContextual("from");
  6535. node.source = this.parseImportSource();
  6536. this.semicolon();
  6537. return this.finishNode(node, "ImportDeclaration");
  6538. }
  6539. parseImportSource() {
  6540. return this.parsePlaceholder("StringLiteral") || super.parseImportSource(...arguments);
  6541. }
  6542. });
  6543. var v8intrinsic = (superClass => class extends superClass {
  6544. parseV8Intrinsic() {
  6545. if (this.match(types.modulo)) {
  6546. const v8IntrinsicStart = this.state.start;
  6547. const node = this.startNode();
  6548. this.eat(types.modulo);
  6549. if (this.match(types.name)) {
  6550. const name = this.parseIdentifierName(this.state.start);
  6551. const identifier = this.createIdentifier(node, name);
  6552. identifier.type = "V8IntrinsicIdentifier";
  6553. if (this.match(types.parenL)) {
  6554. return identifier;
  6555. }
  6556. }
  6557. this.unexpected(v8IntrinsicStart);
  6558. }
  6559. }
  6560. parseExprAtom() {
  6561. return this.parseV8Intrinsic() || super.parseExprAtom(...arguments);
  6562. }
  6563. });
  6564. function hasPlugin(plugins, name) {
  6565. return plugins.some(plugin => {
  6566. if (Array.isArray(plugin)) {
  6567. return plugin[0] === name;
  6568. } else {
  6569. return plugin === name;
  6570. }
  6571. });
  6572. }
  6573. function getPluginOption(plugins, name, option) {
  6574. const plugin = plugins.find(plugin => {
  6575. if (Array.isArray(plugin)) {
  6576. return plugin[0] === name;
  6577. } else {
  6578. return plugin === name;
  6579. }
  6580. });
  6581. if (plugin && Array.isArray(plugin)) {
  6582. return plugin[1][option];
  6583. }
  6584. return null;
  6585. }
  6586. const PIPELINE_PROPOSALS = ["minimal", "smart", "fsharp"];
  6587. const RECORD_AND_TUPLE_SYNTAX_TYPES = ["hash", "bar"];
  6588. function validatePlugins(plugins) {
  6589. if (hasPlugin(plugins, "decorators")) {
  6590. if (hasPlugin(plugins, "decorators-legacy")) {
  6591. throw new Error("Cannot use the decorators and decorators-legacy plugin together");
  6592. }
  6593. const decoratorsBeforeExport = getPluginOption(plugins, "decorators", "decoratorsBeforeExport");
  6594. if (decoratorsBeforeExport == null) {
  6595. throw new Error("The 'decorators' plugin requires a 'decoratorsBeforeExport' option," + " whose value must be a boolean. If you are migrating from" + " Babylon/Babel 6 or want to use the old decorators proposal, you" + " should use the 'decorators-legacy' plugin instead of 'decorators'.");
  6596. } else if (typeof decoratorsBeforeExport !== "boolean") {
  6597. throw new Error("'decoratorsBeforeExport' must be a boolean.");
  6598. }
  6599. }
  6600. if (hasPlugin(plugins, "flow") && hasPlugin(plugins, "typescript")) {
  6601. throw new Error("Cannot combine flow and typescript plugins.");
  6602. }
  6603. if (hasPlugin(plugins, "placeholders") && hasPlugin(plugins, "v8intrinsic")) {
  6604. throw new Error("Cannot combine placeholders and v8intrinsic plugins.");
  6605. }
  6606. if (hasPlugin(plugins, "pipelineOperator") && !PIPELINE_PROPOSALS.includes(getPluginOption(plugins, "pipelineOperator", "proposal"))) {
  6607. throw new Error("'pipelineOperator' requires 'proposal' option whose value should be one of: " + PIPELINE_PROPOSALS.map(p => `'${p}'`).join(", "));
  6608. }
  6609. if (hasPlugin(plugins, "moduleAttributes")) {
  6610. if (hasPlugin(plugins, "importAssertions")) {
  6611. throw new Error("Cannot combine importAssertions and moduleAttributes plugins.");
  6612. }
  6613. const moduleAttributesVerionPluginOption = getPluginOption(plugins, "moduleAttributes", "version");
  6614. if (moduleAttributesVerionPluginOption !== "may-2020") {
  6615. throw new Error("The 'moduleAttributes' plugin requires a 'version' option," + " representing the last proposal update. Currently, the" + " only supported value is 'may-2020'.");
  6616. }
  6617. }
  6618. if (hasPlugin(plugins, "recordAndTuple") && !RECORD_AND_TUPLE_SYNTAX_TYPES.includes(getPluginOption(plugins, "recordAndTuple", "syntaxType"))) {
  6619. throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: " + RECORD_AND_TUPLE_SYNTAX_TYPES.map(p => `'${p}'`).join(", "));
  6620. }
  6621. }
  6622. const mixinPlugins = {
  6623. estree,
  6624. jsx,
  6625. flow,
  6626. typescript,
  6627. v8intrinsic,
  6628. placeholders
  6629. };
  6630. const mixinPluginNames = Object.keys(mixinPlugins);
  6631. const defaultOptions = {
  6632. sourceType: "script",
  6633. sourceFilename: undefined,
  6634. startLine: 1,
  6635. allowAwaitOutsideFunction: false,
  6636. allowReturnOutsideFunction: false,
  6637. allowImportExportEverywhere: false,
  6638. allowSuperOutsideMethod: false,
  6639. allowUndeclaredExports: false,
  6640. plugins: [],
  6641. strictMode: null,
  6642. ranges: false,
  6643. tokens: false,
  6644. createParenthesizedExpressions: false,
  6645. errorRecovery: false
  6646. };
  6647. function getOptions(opts) {
  6648. const options = {};
  6649. for (const key of Object.keys(defaultOptions)) {
  6650. options[key] = opts && opts[key] != null ? opts[key] : defaultOptions[key];
  6651. }
  6652. return options;
  6653. }
  6654. class State {
  6655. constructor() {
  6656. this.strict = void 0;
  6657. this.curLine = void 0;
  6658. this.startLoc = void 0;
  6659. this.endLoc = void 0;
  6660. this.errors = [];
  6661. this.potentialArrowAt = -1;
  6662. this.noArrowAt = [];
  6663. this.noArrowParamsConversionAt = [];
  6664. this.maybeInArrowParameters = false;
  6665. this.inPipeline = false;
  6666. this.inType = false;
  6667. this.noAnonFunctionType = false;
  6668. this.inPropertyName = false;
  6669. this.hasFlowComment = false;
  6670. this.isIterator = false;
  6671. this.isDeclareContext = false;
  6672. this.inAbstractClass = false;
  6673. this.topicContext = {
  6674. maxNumOfResolvableTopics: 0,
  6675. maxTopicIndex: null
  6676. };
  6677. this.soloAwait = false;
  6678. this.inFSharpPipelineDirectBody = false;
  6679. this.labels = [];
  6680. this.decoratorStack = [[]];
  6681. this.comments = [];
  6682. this.trailingComments = [];
  6683. this.leadingComments = [];
  6684. this.commentStack = [];
  6685. this.commentPreviousNode = null;
  6686. this.pos = 0;
  6687. this.lineStart = 0;
  6688. this.type = types.eof;
  6689. this.value = null;
  6690. this.start = 0;
  6691. this.end = 0;
  6692. this.lastTokEndLoc = null;
  6693. this.lastTokStartLoc = null;
  6694. this.lastTokStart = 0;
  6695. this.lastTokEnd = 0;
  6696. this.context = [types$1.braceStatement];
  6697. this.exprAllowed = true;
  6698. this.containsEsc = false;
  6699. this.strictErrors = new Map();
  6700. this.exportedIdentifiers = [];
  6701. this.tokensLength = 0;
  6702. }
  6703. init(options) {
  6704. this.strict = options.strictMode === false ? false : options.sourceType === "module";
  6705. this.curLine = options.startLine;
  6706. this.startLoc = this.endLoc = this.curPosition();
  6707. }
  6708. curPosition() {
  6709. return new Position(this.curLine, this.pos - this.lineStart);
  6710. }
  6711. clone(skipArrays) {
  6712. const state = new State();
  6713. const keys = Object.keys(this);
  6714. for (let i = 0, length = keys.length; i < length; i++) {
  6715. const key = keys[i];
  6716. let val = this[key];
  6717. if (!skipArrays && Array.isArray(val)) {
  6718. val = val.slice();
  6719. }
  6720. state[key] = val;
  6721. }
  6722. return state;
  6723. }
  6724. }
  6725. var _isDigit = function isDigit(code) {
  6726. return code >= 48 && code <= 57;
  6727. };
  6728. const VALID_REGEX_FLAGS = new Set(["g", "m", "s", "i", "y", "u"]);
  6729. const forbiddenNumericSeparatorSiblings = {
  6730. decBinOct: [46, 66, 69, 79, 95, 98, 101, 111],
  6731. hex: [46, 88, 95, 120]
  6732. };
  6733. const allowedNumericSeparatorSiblings = {};
  6734. allowedNumericSeparatorSiblings.bin = [48, 49];
  6735. allowedNumericSeparatorSiblings.oct = [...allowedNumericSeparatorSiblings.bin, 50, 51, 52, 53, 54, 55];
  6736. allowedNumericSeparatorSiblings.dec = [...allowedNumericSeparatorSiblings.oct, 56, 57];
  6737. allowedNumericSeparatorSiblings.hex = [...allowedNumericSeparatorSiblings.dec, 65, 66, 67, 68, 69, 70, 97, 98, 99, 100, 101, 102];
  6738. class Token {
  6739. constructor(state) {
  6740. this.type = state.type;
  6741. this.value = state.value;
  6742. this.start = state.start;
  6743. this.end = state.end;
  6744. this.loc = new SourceLocation(state.startLoc, state.endLoc);
  6745. }
  6746. }
  6747. class Tokenizer extends ParserError {
  6748. constructor(options, input) {
  6749. super();
  6750. this.isLookahead = void 0;
  6751. this.tokens = [];
  6752. this.state = new State();
  6753. this.state.init(options);
  6754. this.input = input;
  6755. this.length = input.length;
  6756. this.isLookahead = false;
  6757. }
  6758. pushToken(token) {
  6759. this.tokens.length = this.state.tokensLength;
  6760. this.tokens.push(token);
  6761. ++this.state.tokensLength;
  6762. }
  6763. next() {
  6764. if (!this.isLookahead) {
  6765. this.checkKeywordEscapes();
  6766. if (this.options.tokens) {
  6767. this.pushToken(new Token(this.state));
  6768. }
  6769. }
  6770. this.state.lastTokEnd = this.state.end;
  6771. this.state.lastTokStart = this.state.start;
  6772. this.state.lastTokEndLoc = this.state.endLoc;
  6773. this.state.lastTokStartLoc = this.state.startLoc;
  6774. this.nextToken();
  6775. }
  6776. eat(type) {
  6777. if (this.match(type)) {
  6778. this.next();
  6779. return true;
  6780. } else {
  6781. return false;
  6782. }
  6783. }
  6784. match(type) {
  6785. return this.state.type === type;
  6786. }
  6787. lookahead() {
  6788. const old = this.state;
  6789. this.state = old.clone(true);
  6790. this.isLookahead = true;
  6791. this.next();
  6792. this.isLookahead = false;
  6793. const curr = this.state;
  6794. this.state = old;
  6795. return curr;
  6796. }
  6797. nextTokenStart() {
  6798. return this.nextTokenStartSince(this.state.pos);
  6799. }
  6800. nextTokenStartSince(pos) {
  6801. skipWhiteSpace.lastIndex = pos;
  6802. const skip = skipWhiteSpace.exec(this.input);
  6803. return pos + skip[0].length;
  6804. }
  6805. lookaheadCharCode() {
  6806. return this.input.charCodeAt(this.nextTokenStart());
  6807. }
  6808. setStrict(strict) {
  6809. this.state.strict = strict;
  6810. if (strict) {
  6811. this.state.strictErrors.forEach((message, pos) => this.raise(pos, message));
  6812. this.state.strictErrors.clear();
  6813. }
  6814. }
  6815. curContext() {
  6816. return this.state.context[this.state.context.length - 1];
  6817. }
  6818. nextToken() {
  6819. const curContext = this.curContext();
  6820. if (!(curContext != null && curContext.preserveSpace)) this.skipSpace();
  6821. this.state.start = this.state.pos;
  6822. this.state.startLoc = this.state.curPosition();
  6823. if (this.state.pos >= this.length) {
  6824. this.finishToken(types.eof);
  6825. return;
  6826. }
  6827. const override = curContext == null ? void 0 : curContext.override;
  6828. if (override) {
  6829. override(this);
  6830. } else {
  6831. this.getTokenFromCode(this.input.codePointAt(this.state.pos));
  6832. }
  6833. }
  6834. pushComment(block, text, start, end, startLoc, endLoc) {
  6835. const comment = {
  6836. type: block ? "CommentBlock" : "CommentLine",
  6837. value: text,
  6838. start: start,
  6839. end: end,
  6840. loc: new SourceLocation(startLoc, endLoc)
  6841. };
  6842. if (this.options.tokens) this.pushToken(comment);
  6843. this.state.comments.push(comment);
  6844. this.addComment(comment);
  6845. }
  6846. skipBlockComment() {
  6847. const startLoc = this.state.curPosition();
  6848. const start = this.state.pos;
  6849. const end = this.input.indexOf("*/", this.state.pos + 2);
  6850. if (end === -1) throw this.raise(start, ErrorMessages.UnterminatedComment);
  6851. this.state.pos = end + 2;
  6852. lineBreakG.lastIndex = start;
  6853. let match;
  6854. while ((match = lineBreakG.exec(this.input)) && match.index < this.state.pos) {
  6855. ++this.state.curLine;
  6856. this.state.lineStart = match.index + match[0].length;
  6857. }
  6858. if (this.isLookahead) return;
  6859. this.pushComment(true, this.input.slice(start + 2, end), start, this.state.pos, startLoc, this.state.curPosition());
  6860. }
  6861. skipLineComment(startSkip) {
  6862. const start = this.state.pos;
  6863. const startLoc = this.state.curPosition();
  6864. let ch = this.input.charCodeAt(this.state.pos += startSkip);
  6865. if (this.state.pos < this.length) {
  6866. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6867. ch = this.input.charCodeAt(this.state.pos);
  6868. }
  6869. }
  6870. if (this.isLookahead) return;
  6871. this.pushComment(false, this.input.slice(start + startSkip, this.state.pos), start, this.state.pos, startLoc, this.state.curPosition());
  6872. }
  6873. skipSpace() {
  6874. loop: while (this.state.pos < this.length) {
  6875. const ch = this.input.charCodeAt(this.state.pos);
  6876. switch (ch) {
  6877. case 32:
  6878. case 160:
  6879. case 9:
  6880. ++this.state.pos;
  6881. break;
  6882. case 13:
  6883. if (this.input.charCodeAt(this.state.pos + 1) === 10) {
  6884. ++this.state.pos;
  6885. }
  6886. case 10:
  6887. case 8232:
  6888. case 8233:
  6889. ++this.state.pos;
  6890. ++this.state.curLine;
  6891. this.state.lineStart = this.state.pos;
  6892. break;
  6893. case 47:
  6894. switch (this.input.charCodeAt(this.state.pos + 1)) {
  6895. case 42:
  6896. this.skipBlockComment();
  6897. break;
  6898. case 47:
  6899. this.skipLineComment(2);
  6900. break;
  6901. default:
  6902. break loop;
  6903. }
  6904. break;
  6905. default:
  6906. if (isWhitespace(ch)) {
  6907. ++this.state.pos;
  6908. } else {
  6909. break loop;
  6910. }
  6911. }
  6912. }
  6913. }
  6914. finishToken(type, val) {
  6915. this.state.end = this.state.pos;
  6916. this.state.endLoc = this.state.curPosition();
  6917. const prevType = this.state.type;
  6918. this.state.type = type;
  6919. this.state.value = val;
  6920. if (!this.isLookahead) this.updateContext(prevType);
  6921. }
  6922. readToken_numberSign() {
  6923. if (this.state.pos === 0 && this.readToken_interpreter()) {
  6924. return;
  6925. }
  6926. const nextPos = this.state.pos + 1;
  6927. const next = this.input.charCodeAt(nextPos);
  6928. if (next >= 48 && next <= 57) {
  6929. throw this.raise(this.state.pos, ErrorMessages.UnexpectedDigitAfterHash);
  6930. }
  6931. if (next === 123 || next === 91 && this.hasPlugin("recordAndTuple")) {
  6932. this.expectPlugin("recordAndTuple");
  6933. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "hash") {
  6934. throw this.raise(this.state.pos, next === 123 ? ErrorMessages.RecordExpressionHashIncorrectStartSyntaxType : ErrorMessages.TupleExpressionHashIncorrectStartSyntaxType);
  6935. }
  6936. if (next === 123) {
  6937. this.finishToken(types.braceHashL);
  6938. } else {
  6939. this.finishToken(types.bracketHashL);
  6940. }
  6941. this.state.pos += 2;
  6942. } else {
  6943. this.finishOp(types.hash, 1);
  6944. }
  6945. }
  6946. readToken_dot() {
  6947. const next = this.input.charCodeAt(this.state.pos + 1);
  6948. if (next >= 48 && next <= 57) {
  6949. this.readNumber(true);
  6950. return;
  6951. }
  6952. if (next === 46 && this.input.charCodeAt(this.state.pos + 2) === 46) {
  6953. this.state.pos += 3;
  6954. this.finishToken(types.ellipsis);
  6955. } else {
  6956. ++this.state.pos;
  6957. this.finishToken(types.dot);
  6958. }
  6959. }
  6960. readToken_slash() {
  6961. if (this.state.exprAllowed && !this.state.inType) {
  6962. ++this.state.pos;
  6963. this.readRegexp();
  6964. return;
  6965. }
  6966. const next = this.input.charCodeAt(this.state.pos + 1);
  6967. if (next === 61) {
  6968. this.finishOp(types.assign, 2);
  6969. } else {
  6970. this.finishOp(types.slash, 1);
  6971. }
  6972. }
  6973. readToken_interpreter() {
  6974. if (this.state.pos !== 0 || this.length < 2) return false;
  6975. let ch = this.input.charCodeAt(this.state.pos + 1);
  6976. if (ch !== 33) return false;
  6977. const start = this.state.pos;
  6978. this.state.pos += 1;
  6979. while (!isNewLine(ch) && ++this.state.pos < this.length) {
  6980. ch = this.input.charCodeAt(this.state.pos);
  6981. }
  6982. const value = this.input.slice(start + 2, this.state.pos);
  6983. this.finishToken(types.interpreterDirective, value);
  6984. return true;
  6985. }
  6986. readToken_mult_modulo(code) {
  6987. let type = code === 42 ? types.star : types.modulo;
  6988. let width = 1;
  6989. let next = this.input.charCodeAt(this.state.pos + 1);
  6990. const exprAllowed = this.state.exprAllowed;
  6991. if (code === 42 && next === 42) {
  6992. width++;
  6993. next = this.input.charCodeAt(this.state.pos + 2);
  6994. type = types.exponent;
  6995. }
  6996. if (next === 61 && !exprAllowed) {
  6997. width++;
  6998. type = types.assign;
  6999. }
  7000. this.finishOp(type, width);
  7001. }
  7002. readToken_pipe_amp(code) {
  7003. const next = this.input.charCodeAt(this.state.pos + 1);
  7004. if (next === code) {
  7005. if (this.input.charCodeAt(this.state.pos + 2) === 61) {
  7006. this.finishOp(types.assign, 3);
  7007. } else {
  7008. this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2);
  7009. }
  7010. return;
  7011. }
  7012. if (code === 124) {
  7013. if (next === 62) {
  7014. this.finishOp(types.pipeline, 2);
  7015. return;
  7016. }
  7017. if (this.hasPlugin("recordAndTuple") && next === 125) {
  7018. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  7019. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectEndSyntaxType);
  7020. }
  7021. this.finishOp(types.braceBarR, 2);
  7022. return;
  7023. }
  7024. if (this.hasPlugin("recordAndTuple") && next === 93) {
  7025. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  7026. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectEndSyntaxType);
  7027. }
  7028. this.finishOp(types.bracketBarR, 2);
  7029. return;
  7030. }
  7031. }
  7032. if (next === 61) {
  7033. this.finishOp(types.assign, 2);
  7034. return;
  7035. }
  7036. this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1);
  7037. }
  7038. readToken_caret() {
  7039. const next = this.input.charCodeAt(this.state.pos + 1);
  7040. if (next === 61) {
  7041. this.finishOp(types.assign, 2);
  7042. } else {
  7043. this.finishOp(types.bitwiseXOR, 1);
  7044. }
  7045. }
  7046. readToken_plus_min(code) {
  7047. const next = this.input.charCodeAt(this.state.pos + 1);
  7048. if (next === code) {
  7049. if (next === 45 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 62 && (this.state.lastTokEnd === 0 || this.hasPrecedingLineBreak())) {
  7050. this.skipLineComment(3);
  7051. this.skipSpace();
  7052. this.nextToken();
  7053. return;
  7054. }
  7055. this.finishOp(types.incDec, 2);
  7056. return;
  7057. }
  7058. if (next === 61) {
  7059. this.finishOp(types.assign, 2);
  7060. } else {
  7061. this.finishOp(types.plusMin, 1);
  7062. }
  7063. }
  7064. readToken_lt_gt(code) {
  7065. const next = this.input.charCodeAt(this.state.pos + 1);
  7066. let size = 1;
  7067. if (next === code) {
  7068. size = code === 62 && this.input.charCodeAt(this.state.pos + 2) === 62 ? 3 : 2;
  7069. if (this.input.charCodeAt(this.state.pos + size) === 61) {
  7070. this.finishOp(types.assign, size + 1);
  7071. return;
  7072. }
  7073. this.finishOp(types.bitShift, size);
  7074. return;
  7075. }
  7076. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.state.pos + 2) === 45 && this.input.charCodeAt(this.state.pos + 3) === 45) {
  7077. this.skipLineComment(4);
  7078. this.skipSpace();
  7079. this.nextToken();
  7080. return;
  7081. }
  7082. if (next === 61) {
  7083. size = 2;
  7084. }
  7085. this.finishOp(types.relational, size);
  7086. }
  7087. readToken_eq_excl(code) {
  7088. const next = this.input.charCodeAt(this.state.pos + 1);
  7089. if (next === 61) {
  7090. this.finishOp(types.equality, this.input.charCodeAt(this.state.pos + 2) === 61 ? 3 : 2);
  7091. return;
  7092. }
  7093. if (code === 61 && next === 62) {
  7094. this.state.pos += 2;
  7095. this.finishToken(types.arrow);
  7096. return;
  7097. }
  7098. this.finishOp(code === 61 ? types.eq : types.bang, 1);
  7099. }
  7100. readToken_question() {
  7101. const next = this.input.charCodeAt(this.state.pos + 1);
  7102. const next2 = this.input.charCodeAt(this.state.pos + 2);
  7103. if (next === 63) {
  7104. if (next2 === 61) {
  7105. this.finishOp(types.assign, 3);
  7106. } else {
  7107. this.finishOp(types.nullishCoalescing, 2);
  7108. }
  7109. } else if (next === 46 && !(next2 >= 48 && next2 <= 57)) {
  7110. this.state.pos += 2;
  7111. this.finishToken(types.questionDot);
  7112. } else {
  7113. ++this.state.pos;
  7114. this.finishToken(types.question);
  7115. }
  7116. }
  7117. getTokenFromCode(code) {
  7118. switch (code) {
  7119. case 46:
  7120. this.readToken_dot();
  7121. return;
  7122. case 40:
  7123. ++this.state.pos;
  7124. this.finishToken(types.parenL);
  7125. return;
  7126. case 41:
  7127. ++this.state.pos;
  7128. this.finishToken(types.parenR);
  7129. return;
  7130. case 59:
  7131. ++this.state.pos;
  7132. this.finishToken(types.semi);
  7133. return;
  7134. case 44:
  7135. ++this.state.pos;
  7136. this.finishToken(types.comma);
  7137. return;
  7138. case 91:
  7139. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  7140. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  7141. throw this.raise(this.state.pos, ErrorMessages.TupleExpressionBarIncorrectStartSyntaxType);
  7142. }
  7143. this.finishToken(types.bracketBarL);
  7144. this.state.pos += 2;
  7145. } else {
  7146. ++this.state.pos;
  7147. this.finishToken(types.bracketL);
  7148. }
  7149. return;
  7150. case 93:
  7151. ++this.state.pos;
  7152. this.finishToken(types.bracketR);
  7153. return;
  7154. case 123:
  7155. if (this.hasPlugin("recordAndTuple") && this.input.charCodeAt(this.state.pos + 1) === 124) {
  7156. if (this.getPluginOption("recordAndTuple", "syntaxType") !== "bar") {
  7157. throw this.raise(this.state.pos, ErrorMessages.RecordExpressionBarIncorrectStartSyntaxType);
  7158. }
  7159. this.finishToken(types.braceBarL);
  7160. this.state.pos += 2;
  7161. } else {
  7162. ++this.state.pos;
  7163. this.finishToken(types.braceL);
  7164. }
  7165. return;
  7166. case 125:
  7167. ++this.state.pos;
  7168. this.finishToken(types.braceR);
  7169. return;
  7170. case 58:
  7171. if (this.hasPlugin("functionBind") && this.input.charCodeAt(this.state.pos + 1) === 58) {
  7172. this.finishOp(types.doubleColon, 2);
  7173. } else {
  7174. ++this.state.pos;
  7175. this.finishToken(types.colon);
  7176. }
  7177. return;
  7178. case 63:
  7179. this.readToken_question();
  7180. return;
  7181. case 96:
  7182. ++this.state.pos;
  7183. this.finishToken(types.backQuote);
  7184. return;
  7185. case 48:
  7186. {
  7187. const next = this.input.charCodeAt(this.state.pos + 1);
  7188. if (next === 120 || next === 88) {
  7189. this.readRadixNumber(16);
  7190. return;
  7191. }
  7192. if (next === 111 || next === 79) {
  7193. this.readRadixNumber(8);
  7194. return;
  7195. }
  7196. if (next === 98 || next === 66) {
  7197. this.readRadixNumber(2);
  7198. return;
  7199. }
  7200. }
  7201. case 49:
  7202. case 50:
  7203. case 51:
  7204. case 52:
  7205. case 53:
  7206. case 54:
  7207. case 55:
  7208. case 56:
  7209. case 57:
  7210. this.readNumber(false);
  7211. return;
  7212. case 34:
  7213. case 39:
  7214. this.readString(code);
  7215. return;
  7216. case 47:
  7217. this.readToken_slash();
  7218. return;
  7219. case 37:
  7220. case 42:
  7221. this.readToken_mult_modulo(code);
  7222. return;
  7223. case 124:
  7224. case 38:
  7225. this.readToken_pipe_amp(code);
  7226. return;
  7227. case 94:
  7228. this.readToken_caret();
  7229. return;
  7230. case 43:
  7231. case 45:
  7232. this.readToken_plus_min(code);
  7233. return;
  7234. case 60:
  7235. case 62:
  7236. this.readToken_lt_gt(code);
  7237. return;
  7238. case 61:
  7239. case 33:
  7240. this.readToken_eq_excl(code);
  7241. return;
  7242. case 126:
  7243. this.finishOp(types.tilde, 1);
  7244. return;
  7245. case 64:
  7246. ++this.state.pos;
  7247. this.finishToken(types.at);
  7248. return;
  7249. case 35:
  7250. this.readToken_numberSign();
  7251. return;
  7252. case 92:
  7253. this.readWord();
  7254. return;
  7255. default:
  7256. if (isIdentifierStart(code)) {
  7257. this.readWord();
  7258. return;
  7259. }
  7260. }
  7261. throw this.raise(this.state.pos, ErrorMessages.InvalidOrUnexpectedToken, String.fromCodePoint(code));
  7262. }
  7263. finishOp(type, size) {
  7264. const str = this.input.slice(this.state.pos, this.state.pos + size);
  7265. this.state.pos += size;
  7266. this.finishToken(type, str);
  7267. }
  7268. readRegexp() {
  7269. const start = this.state.pos;
  7270. let escaped, inClass;
  7271. for (;;) {
  7272. if (this.state.pos >= this.length) {
  7273. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  7274. }
  7275. const ch = this.input.charAt(this.state.pos);
  7276. if (lineBreak.test(ch)) {
  7277. throw this.raise(start, ErrorMessages.UnterminatedRegExp);
  7278. }
  7279. if (escaped) {
  7280. escaped = false;
  7281. } else {
  7282. if (ch === "[") {
  7283. inClass = true;
  7284. } else if (ch === "]" && inClass) {
  7285. inClass = false;
  7286. } else if (ch === "/" && !inClass) {
  7287. break;
  7288. }
  7289. escaped = ch === "\\";
  7290. }
  7291. ++this.state.pos;
  7292. }
  7293. const content = this.input.slice(start, this.state.pos);
  7294. ++this.state.pos;
  7295. let mods = "";
  7296. while (this.state.pos < this.length) {
  7297. const char = this.input[this.state.pos];
  7298. const charCode = this.input.codePointAt(this.state.pos);
  7299. if (VALID_REGEX_FLAGS.has(char)) {
  7300. if (mods.indexOf(char) > -1) {
  7301. this.raise(this.state.pos + 1, ErrorMessages.DuplicateRegExpFlags);
  7302. }
  7303. } else if (isIdentifierChar(charCode) || charCode === 92) {
  7304. this.raise(this.state.pos + 1, ErrorMessages.MalformedRegExpFlags);
  7305. } else {
  7306. break;
  7307. }
  7308. ++this.state.pos;
  7309. mods += char;
  7310. }
  7311. this.finishToken(types.regexp, {
  7312. pattern: content,
  7313. flags: mods
  7314. });
  7315. }
  7316. readInt(radix, len, forceLen, allowNumSeparator = true) {
  7317. const start = this.state.pos;
  7318. const forbiddenSiblings = radix === 16 ? forbiddenNumericSeparatorSiblings.hex : forbiddenNumericSeparatorSiblings.decBinOct;
  7319. const allowedSiblings = radix === 16 ? allowedNumericSeparatorSiblings.hex : radix === 10 ? allowedNumericSeparatorSiblings.dec : radix === 8 ? allowedNumericSeparatorSiblings.oct : allowedNumericSeparatorSiblings.bin;
  7320. let invalid = false;
  7321. let total = 0;
  7322. for (let i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  7323. const code = this.input.charCodeAt(this.state.pos);
  7324. let val;
  7325. if (code === 95) {
  7326. const prev = this.input.charCodeAt(this.state.pos - 1);
  7327. const next = this.input.charCodeAt(this.state.pos + 1);
  7328. if (allowedSiblings.indexOf(next) === -1) {
  7329. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7330. } else if (forbiddenSiblings.indexOf(prev) > -1 || forbiddenSiblings.indexOf(next) > -1 || Number.isNaN(next)) {
  7331. this.raise(this.state.pos, ErrorMessages.UnexpectedNumericSeparator);
  7332. }
  7333. if (!allowNumSeparator) {
  7334. this.raise(this.state.pos, ErrorMessages.NumericSeparatorInEscapeSequence);
  7335. }
  7336. ++this.state.pos;
  7337. continue;
  7338. }
  7339. if (code >= 97) {
  7340. val = code - 97 + 10;
  7341. } else if (code >= 65) {
  7342. val = code - 65 + 10;
  7343. } else if (_isDigit(code)) {
  7344. val = code - 48;
  7345. } else {
  7346. val = Infinity;
  7347. }
  7348. if (val >= radix) {
  7349. if (this.options.errorRecovery && val <= 9) {
  7350. val = 0;
  7351. this.raise(this.state.start + i + 2, ErrorMessages.InvalidDigit, radix);
  7352. } else if (forceLen) {
  7353. val = 0;
  7354. invalid = true;
  7355. } else {
  7356. break;
  7357. }
  7358. }
  7359. ++this.state.pos;
  7360. total = total * radix + val;
  7361. }
  7362. if (this.state.pos === start || len != null && this.state.pos - start !== len || invalid) {
  7363. return null;
  7364. }
  7365. return total;
  7366. }
  7367. readRadixNumber(radix) {
  7368. const start = this.state.pos;
  7369. let isBigInt = false;
  7370. this.state.pos += 2;
  7371. const val = this.readInt(radix);
  7372. if (val == null) {
  7373. this.raise(this.state.start + 2, ErrorMessages.InvalidDigit, radix);
  7374. }
  7375. const next = this.input.charCodeAt(this.state.pos);
  7376. if (next === 110) {
  7377. ++this.state.pos;
  7378. isBigInt = true;
  7379. } else if (next === 109) {
  7380. throw this.raise(start, ErrorMessages.InvalidDecimal);
  7381. }
  7382. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7383. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7384. }
  7385. if (isBigInt) {
  7386. const str = this.input.slice(start, this.state.pos).replace(/[_n]/g, "");
  7387. this.finishToken(types.bigint, str);
  7388. return;
  7389. }
  7390. this.finishToken(types.num, val);
  7391. }
  7392. readNumber(startsWithDot) {
  7393. const start = this.state.pos;
  7394. let isFloat = false;
  7395. let isBigInt = false;
  7396. let isDecimal = false;
  7397. let hasExponent = false;
  7398. let isOctal = false;
  7399. if (!startsWithDot && this.readInt(10) === null) {
  7400. this.raise(start, ErrorMessages.InvalidNumber);
  7401. }
  7402. const hasLeadingZero = this.state.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  7403. if (hasLeadingZero) {
  7404. const integer = this.input.slice(start, this.state.pos);
  7405. this.recordStrictModeErrors(start, ErrorMessages.StrictOctalLiteral);
  7406. if (!this.state.strict) {
  7407. const underscorePos = integer.indexOf("_");
  7408. if (underscorePos > 0) {
  7409. this.raise(underscorePos + start, ErrorMessages.ZeroDigitNumericSeparator);
  7410. }
  7411. }
  7412. isOctal = hasLeadingZero && !/[89]/.test(integer);
  7413. }
  7414. let next = this.input.charCodeAt(this.state.pos);
  7415. if (next === 46 && !isOctal) {
  7416. ++this.state.pos;
  7417. this.readInt(10);
  7418. isFloat = true;
  7419. next = this.input.charCodeAt(this.state.pos);
  7420. }
  7421. if ((next === 69 || next === 101) && !isOctal) {
  7422. next = this.input.charCodeAt(++this.state.pos);
  7423. if (next === 43 || next === 45) {
  7424. ++this.state.pos;
  7425. }
  7426. if (this.readInt(10) === null) {
  7427. this.raise(start, ErrorMessages.InvalidOrMissingExponent);
  7428. }
  7429. isFloat = true;
  7430. hasExponent = true;
  7431. next = this.input.charCodeAt(this.state.pos);
  7432. }
  7433. if (next === 110) {
  7434. if (isFloat || hasLeadingZero) {
  7435. this.raise(start, ErrorMessages.InvalidBigIntLiteral);
  7436. }
  7437. ++this.state.pos;
  7438. isBigInt = true;
  7439. }
  7440. if (next === 109) {
  7441. this.expectPlugin("decimal", this.state.pos);
  7442. if (hasExponent || hasLeadingZero) {
  7443. this.raise(start, ErrorMessages.InvalidDecimal);
  7444. }
  7445. ++this.state.pos;
  7446. isDecimal = true;
  7447. }
  7448. if (isIdentifierStart(this.input.codePointAt(this.state.pos))) {
  7449. throw this.raise(this.state.pos, ErrorMessages.NumberIdentifier);
  7450. }
  7451. const str = this.input.slice(start, this.state.pos).replace(/[_mn]/g, "");
  7452. if (isBigInt) {
  7453. this.finishToken(types.bigint, str);
  7454. return;
  7455. }
  7456. if (isDecimal) {
  7457. this.finishToken(types.decimal, str);
  7458. return;
  7459. }
  7460. const val = isOctal ? parseInt(str, 8) : parseFloat(str);
  7461. this.finishToken(types.num, val);
  7462. }
  7463. readCodePoint(throwOnInvalid) {
  7464. const ch = this.input.charCodeAt(this.state.pos);
  7465. let code;
  7466. if (ch === 123) {
  7467. const codePos = ++this.state.pos;
  7468. code = this.readHexChar(this.input.indexOf("}", this.state.pos) - this.state.pos, true, throwOnInvalid);
  7469. ++this.state.pos;
  7470. if (code !== null && code > 0x10ffff) {
  7471. if (throwOnInvalid) {
  7472. this.raise(codePos, ErrorMessages.InvalidCodePoint);
  7473. } else {
  7474. return null;
  7475. }
  7476. }
  7477. } else {
  7478. code = this.readHexChar(4, false, throwOnInvalid);
  7479. }
  7480. return code;
  7481. }
  7482. readString(quote) {
  7483. let out = "",
  7484. chunkStart = ++this.state.pos;
  7485. for (;;) {
  7486. if (this.state.pos >= this.length) {
  7487. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7488. }
  7489. const ch = this.input.charCodeAt(this.state.pos);
  7490. if (ch === quote) break;
  7491. if (ch === 92) {
  7492. out += this.input.slice(chunkStart, this.state.pos);
  7493. out += this.readEscapedChar(false);
  7494. chunkStart = this.state.pos;
  7495. } else if (ch === 8232 || ch === 8233) {
  7496. ++this.state.pos;
  7497. ++this.state.curLine;
  7498. this.state.lineStart = this.state.pos;
  7499. } else if (isNewLine(ch)) {
  7500. throw this.raise(this.state.start, ErrorMessages.UnterminatedString);
  7501. } else {
  7502. ++this.state.pos;
  7503. }
  7504. }
  7505. out += this.input.slice(chunkStart, this.state.pos++);
  7506. this.finishToken(types.string, out);
  7507. }
  7508. readTmplToken() {
  7509. let out = "",
  7510. chunkStart = this.state.pos,
  7511. containsInvalid = false;
  7512. for (;;) {
  7513. if (this.state.pos >= this.length) {
  7514. throw this.raise(this.state.start, ErrorMessages.UnterminatedTemplate);
  7515. }
  7516. const ch = this.input.charCodeAt(this.state.pos);
  7517. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.state.pos + 1) === 123) {
  7518. if (this.state.pos === this.state.start && this.match(types.template)) {
  7519. if (ch === 36) {
  7520. this.state.pos += 2;
  7521. this.finishToken(types.dollarBraceL);
  7522. return;
  7523. } else {
  7524. ++this.state.pos;
  7525. this.finishToken(types.backQuote);
  7526. return;
  7527. }
  7528. }
  7529. out += this.input.slice(chunkStart, this.state.pos);
  7530. this.finishToken(types.template, containsInvalid ? null : out);
  7531. return;
  7532. }
  7533. if (ch === 92) {
  7534. out += this.input.slice(chunkStart, this.state.pos);
  7535. const escaped = this.readEscapedChar(true);
  7536. if (escaped === null) {
  7537. containsInvalid = true;
  7538. } else {
  7539. out += escaped;
  7540. }
  7541. chunkStart = this.state.pos;
  7542. } else if (isNewLine(ch)) {
  7543. out += this.input.slice(chunkStart, this.state.pos);
  7544. ++this.state.pos;
  7545. switch (ch) {
  7546. case 13:
  7547. if (this.input.charCodeAt(this.state.pos) === 10) {
  7548. ++this.state.pos;
  7549. }
  7550. case 10:
  7551. out += "\n";
  7552. break;
  7553. default:
  7554. out += String.fromCharCode(ch);
  7555. break;
  7556. }
  7557. ++this.state.curLine;
  7558. this.state.lineStart = this.state.pos;
  7559. chunkStart = this.state.pos;
  7560. } else {
  7561. ++this.state.pos;
  7562. }
  7563. }
  7564. }
  7565. recordStrictModeErrors(pos, message) {
  7566. if (this.state.strict && !this.state.strictErrors.has(pos)) {
  7567. this.raise(pos, message);
  7568. } else {
  7569. this.state.strictErrors.set(pos, message);
  7570. }
  7571. }
  7572. readEscapedChar(inTemplate) {
  7573. const throwOnInvalid = !inTemplate;
  7574. const ch = this.input.charCodeAt(++this.state.pos);
  7575. ++this.state.pos;
  7576. switch (ch) {
  7577. case 110:
  7578. return "\n";
  7579. case 114:
  7580. return "\r";
  7581. case 120:
  7582. {
  7583. const code = this.readHexChar(2, false, throwOnInvalid);
  7584. return code === null ? null : String.fromCharCode(code);
  7585. }
  7586. case 117:
  7587. {
  7588. const code = this.readCodePoint(throwOnInvalid);
  7589. return code === null ? null : String.fromCodePoint(code);
  7590. }
  7591. case 116:
  7592. return "\t";
  7593. case 98:
  7594. return "\b";
  7595. case 118:
  7596. return "\u000b";
  7597. case 102:
  7598. return "\f";
  7599. case 13:
  7600. if (this.input.charCodeAt(this.state.pos) === 10) {
  7601. ++this.state.pos;
  7602. }
  7603. case 10:
  7604. this.state.lineStart = this.state.pos;
  7605. ++this.state.curLine;
  7606. case 8232:
  7607. case 8233:
  7608. return "";
  7609. case 56:
  7610. case 57:
  7611. if (inTemplate) {
  7612. return null;
  7613. } else {
  7614. this.recordStrictModeErrors(this.state.pos - 1, ErrorMessages.StrictNumericEscape);
  7615. }
  7616. default:
  7617. if (ch >= 48 && ch <= 55) {
  7618. const codePos = this.state.pos - 1;
  7619. const match = this.input.substr(this.state.pos - 1, 3).match(/^[0-7]+/);
  7620. let octalStr = match[0];
  7621. let octal = parseInt(octalStr, 8);
  7622. if (octal > 255) {
  7623. octalStr = octalStr.slice(0, -1);
  7624. octal = parseInt(octalStr, 8);
  7625. }
  7626. this.state.pos += octalStr.length - 1;
  7627. const next = this.input.charCodeAt(this.state.pos);
  7628. if (octalStr !== "0" || next === 56 || next === 57) {
  7629. if (inTemplate) {
  7630. return null;
  7631. } else {
  7632. this.recordStrictModeErrors(codePos, ErrorMessages.StrictNumericEscape);
  7633. }
  7634. }
  7635. return String.fromCharCode(octal);
  7636. }
  7637. return String.fromCharCode(ch);
  7638. }
  7639. }
  7640. readHexChar(len, forceLen, throwOnInvalid) {
  7641. const codePos = this.state.pos;
  7642. const n = this.readInt(16, len, forceLen, false);
  7643. if (n === null) {
  7644. if (throwOnInvalid) {
  7645. this.raise(codePos, ErrorMessages.InvalidEscapeSequence);
  7646. } else {
  7647. this.state.pos = codePos - 1;
  7648. }
  7649. }
  7650. return n;
  7651. }
  7652. readWord1() {
  7653. let word = "";
  7654. this.state.containsEsc = false;
  7655. const start = this.state.pos;
  7656. let chunkStart = this.state.pos;
  7657. while (this.state.pos < this.length) {
  7658. const ch = this.input.codePointAt(this.state.pos);
  7659. if (isIdentifierChar(ch)) {
  7660. this.state.pos += ch <= 0xffff ? 1 : 2;
  7661. } else if (this.state.isIterator && ch === 64) {
  7662. ++this.state.pos;
  7663. } else if (ch === 92) {
  7664. this.state.containsEsc = true;
  7665. word += this.input.slice(chunkStart, this.state.pos);
  7666. const escStart = this.state.pos;
  7667. const identifierCheck = this.state.pos === start ? isIdentifierStart : isIdentifierChar;
  7668. if (this.input.charCodeAt(++this.state.pos) !== 117) {
  7669. this.raise(this.state.pos, ErrorMessages.MissingUnicodeEscape);
  7670. continue;
  7671. }
  7672. ++this.state.pos;
  7673. const esc = this.readCodePoint(true);
  7674. if (esc !== null) {
  7675. if (!identifierCheck(esc)) {
  7676. this.raise(escStart, ErrorMessages.EscapedCharNotAnIdentifier);
  7677. }
  7678. word += String.fromCodePoint(esc);
  7679. }
  7680. chunkStart = this.state.pos;
  7681. } else {
  7682. break;
  7683. }
  7684. }
  7685. return word + this.input.slice(chunkStart, this.state.pos);
  7686. }
  7687. isIterator(word) {
  7688. return word === "@@iterator" || word === "@@asyncIterator";
  7689. }
  7690. readWord() {
  7691. const word = this.readWord1();
  7692. const type = keywords.get(word) || types.name;
  7693. if (this.state.isIterator && (!this.isIterator(word) || !this.state.inType)) {
  7694. this.raise(this.state.pos, ErrorMessages.InvalidIdentifier, word);
  7695. }
  7696. this.finishToken(type, word);
  7697. }
  7698. checkKeywordEscapes() {
  7699. const kw = this.state.type.keyword;
  7700. if (kw && this.state.containsEsc) {
  7701. this.raise(this.state.start, ErrorMessages.InvalidEscapedReservedWord, kw);
  7702. }
  7703. }
  7704. braceIsBlock(prevType) {
  7705. const parent = this.curContext();
  7706. if (parent === types$1.functionExpression || parent === types$1.functionStatement) {
  7707. return true;
  7708. }
  7709. if (prevType === types.colon && (parent === types$1.braceStatement || parent === types$1.braceExpression)) {
  7710. return !parent.isExpr;
  7711. }
  7712. if (prevType === types._return || prevType === types.name && this.state.exprAllowed) {
  7713. return this.hasPrecedingLineBreak();
  7714. }
  7715. if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) {
  7716. return true;
  7717. }
  7718. if (prevType === types.braceL) {
  7719. return parent === types$1.braceStatement;
  7720. }
  7721. if (prevType === types._var || prevType === types._const || prevType === types.name) {
  7722. return false;
  7723. }
  7724. if (prevType === types.relational) {
  7725. return true;
  7726. }
  7727. return !this.state.exprAllowed;
  7728. }
  7729. updateContext(prevType) {
  7730. const type = this.state.type;
  7731. let update;
  7732. if (type.keyword && (prevType === types.dot || prevType === types.questionDot)) {
  7733. this.state.exprAllowed = false;
  7734. } else if (update = type.updateContext) {
  7735. update.call(this, prevType);
  7736. } else {
  7737. this.state.exprAllowed = type.beforeExpr;
  7738. }
  7739. }
  7740. }
  7741. class ClassScope {
  7742. constructor() {
  7743. this.privateNames = new Set();
  7744. this.loneAccessors = new Map();
  7745. this.undefinedPrivateNames = new Map();
  7746. }
  7747. }
  7748. class ClassScopeHandler {
  7749. constructor(raise) {
  7750. this.stack = [];
  7751. this.undefinedPrivateNames = new Map();
  7752. this.raise = raise;
  7753. }
  7754. current() {
  7755. return this.stack[this.stack.length - 1];
  7756. }
  7757. enter() {
  7758. this.stack.push(new ClassScope());
  7759. }
  7760. exit() {
  7761. const oldClassScope = this.stack.pop();
  7762. const current = this.current();
  7763. for (const [name, pos] of Array.from(oldClassScope.undefinedPrivateNames)) {
  7764. if (current) {
  7765. if (!current.undefinedPrivateNames.has(name)) {
  7766. current.undefinedPrivateNames.set(name, pos);
  7767. }
  7768. } else {
  7769. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  7770. }
  7771. }
  7772. }
  7773. declarePrivateName(name, elementType, pos) {
  7774. const classScope = this.current();
  7775. let redefined = classScope.privateNames.has(name);
  7776. if (elementType & CLASS_ELEMENT_KIND_ACCESSOR) {
  7777. const accessor = redefined && classScope.loneAccessors.get(name);
  7778. if (accessor) {
  7779. const oldStatic = accessor & CLASS_ELEMENT_FLAG_STATIC;
  7780. const newStatic = elementType & CLASS_ELEMENT_FLAG_STATIC;
  7781. const oldKind = accessor & CLASS_ELEMENT_KIND_ACCESSOR;
  7782. const newKind = elementType & CLASS_ELEMENT_KIND_ACCESSOR;
  7783. redefined = oldKind === newKind || oldStatic !== newStatic;
  7784. if (!redefined) classScope.loneAccessors.delete(name);
  7785. } else if (!redefined) {
  7786. classScope.loneAccessors.set(name, elementType);
  7787. }
  7788. }
  7789. if (redefined) {
  7790. this.raise(pos, ErrorMessages.PrivateNameRedeclaration, name);
  7791. }
  7792. classScope.privateNames.add(name);
  7793. classScope.undefinedPrivateNames.delete(name);
  7794. }
  7795. usePrivateName(name, pos) {
  7796. let classScope;
  7797. for (classScope of this.stack) {
  7798. if (classScope.privateNames.has(name)) return;
  7799. }
  7800. if (classScope) {
  7801. classScope.undefinedPrivateNames.set(name, pos);
  7802. } else {
  7803. this.raise(pos, ErrorMessages.InvalidPrivateFieldResolution, name);
  7804. }
  7805. }
  7806. }
  7807. const kExpression = 0,
  7808. kMaybeArrowParameterDeclaration = 1,
  7809. kMaybeAsyncArrowParameterDeclaration = 2,
  7810. kParameterDeclaration = 3;
  7811. class ExpressionScope {
  7812. constructor(type = kExpression) {
  7813. this.type = void 0;
  7814. this.type = type;
  7815. }
  7816. canBeArrowParameterDeclaration() {
  7817. return this.type === kMaybeAsyncArrowParameterDeclaration || this.type === kMaybeArrowParameterDeclaration;
  7818. }
  7819. isCertainlyParameterDeclaration() {
  7820. return this.type === kParameterDeclaration;
  7821. }
  7822. }
  7823. class ArrowHeadParsingScope extends ExpressionScope {
  7824. constructor(type) {
  7825. super(type);
  7826. this.errors = new Map();
  7827. }
  7828. recordDeclarationError(pos, message) {
  7829. this.errors.set(pos, message);
  7830. }
  7831. clearDeclarationError(pos) {
  7832. this.errors.delete(pos);
  7833. }
  7834. iterateErrors(iterator) {
  7835. this.errors.forEach(iterator);
  7836. }
  7837. }
  7838. class ExpressionScopeHandler {
  7839. constructor(raise) {
  7840. this.stack = [new ExpressionScope()];
  7841. this.raise = raise;
  7842. }
  7843. enter(scope) {
  7844. this.stack.push(scope);
  7845. }
  7846. exit() {
  7847. this.stack.pop();
  7848. }
  7849. recordParameterInitializerError(pos, message) {
  7850. const {
  7851. stack
  7852. } = this;
  7853. let i = stack.length - 1;
  7854. let scope = stack[i];
  7855. while (!scope.isCertainlyParameterDeclaration()) {
  7856. if (scope.canBeArrowParameterDeclaration()) {
  7857. scope.recordDeclarationError(pos, message);
  7858. } else {
  7859. return;
  7860. }
  7861. scope = stack[--i];
  7862. }
  7863. this.raise(pos, message);
  7864. }
  7865. recordParenthesizedIdentifierError(pos, message) {
  7866. const {
  7867. stack
  7868. } = this;
  7869. const scope = stack[stack.length - 1];
  7870. if (scope.isCertainlyParameterDeclaration()) {
  7871. this.raise(pos, message);
  7872. } else if (scope.canBeArrowParameterDeclaration()) {
  7873. scope.recordDeclarationError(pos, message);
  7874. } else {
  7875. return;
  7876. }
  7877. }
  7878. recordAsyncArrowParametersError(pos, message) {
  7879. const {
  7880. stack
  7881. } = this;
  7882. let i = stack.length - 1;
  7883. let scope = stack[i];
  7884. while (scope.canBeArrowParameterDeclaration()) {
  7885. if (scope.type === kMaybeAsyncArrowParameterDeclaration) {
  7886. scope.recordDeclarationError(pos, message);
  7887. }
  7888. scope = stack[--i];
  7889. }
  7890. }
  7891. validateAsPattern() {
  7892. const {
  7893. stack
  7894. } = this;
  7895. const currentScope = stack[stack.length - 1];
  7896. if (!currentScope.canBeArrowParameterDeclaration()) return;
  7897. currentScope.iterateErrors((message, pos) => {
  7898. this.raise(pos, message);
  7899. let i = stack.length - 2;
  7900. let scope = stack[i];
  7901. while (scope.canBeArrowParameterDeclaration()) {
  7902. scope.clearDeclarationError(pos);
  7903. scope = stack[--i];
  7904. }
  7905. });
  7906. }
  7907. }
  7908. function newParameterDeclarationScope() {
  7909. return new ExpressionScope(kParameterDeclaration);
  7910. }
  7911. function newArrowHeadScope() {
  7912. return new ArrowHeadParsingScope(kMaybeArrowParameterDeclaration);
  7913. }
  7914. function newAsyncArrowScope() {
  7915. return new ArrowHeadParsingScope(kMaybeAsyncArrowParameterDeclaration);
  7916. }
  7917. function newExpressionScope() {
  7918. return new ExpressionScope();
  7919. }
  7920. class UtilParser extends Tokenizer {
  7921. addExtra(node, key, val) {
  7922. if (!node) return;
  7923. const extra = node.extra = node.extra || {};
  7924. extra[key] = val;
  7925. }
  7926. isRelational(op) {
  7927. return this.match(types.relational) && this.state.value === op;
  7928. }
  7929. expectRelational(op) {
  7930. if (this.isRelational(op)) {
  7931. this.next();
  7932. } else {
  7933. this.unexpected(null, types.relational);
  7934. }
  7935. }
  7936. isContextual(name) {
  7937. return this.match(types.name) && this.state.value === name && !this.state.containsEsc;
  7938. }
  7939. isUnparsedContextual(nameStart, name) {
  7940. const nameEnd = nameStart + name.length;
  7941. return this.input.slice(nameStart, nameEnd) === name && (nameEnd === this.input.length || !isIdentifierChar(this.input.charCodeAt(nameEnd)));
  7942. }
  7943. isLookaheadContextual(name) {
  7944. const next = this.nextTokenStart();
  7945. return this.isUnparsedContextual(next, name);
  7946. }
  7947. eatContextual(name) {
  7948. return this.isContextual(name) && this.eat(types.name);
  7949. }
  7950. expectContextual(name, message) {
  7951. if (!this.eatContextual(name)) this.unexpected(null, message);
  7952. }
  7953. canInsertSemicolon() {
  7954. return this.match(types.eof) || this.match(types.braceR) || this.hasPrecedingLineBreak();
  7955. }
  7956. hasPrecedingLineBreak() {
  7957. return lineBreak.test(this.input.slice(this.state.lastTokEnd, this.state.start));
  7958. }
  7959. hasFollowingLineBreak() {
  7960. return lineBreak.test(this.input.slice(this.state.end, this.nextTokenStart()));
  7961. }
  7962. isLineTerminator() {
  7963. return this.eat(types.semi) || this.canInsertSemicolon();
  7964. }
  7965. semicolon(allowAsi = true) {
  7966. if (allowAsi ? this.isLineTerminator() : this.eat(types.semi)) return;
  7967. this.raise(this.state.lastTokEnd, ErrorMessages.MissingSemicolon);
  7968. }
  7969. expect(type, pos) {
  7970. this.eat(type) || this.unexpected(pos, type);
  7971. }
  7972. assertNoSpace(message = "Unexpected space.") {
  7973. if (this.state.start > this.state.lastTokEnd) {
  7974. this.raise(this.state.lastTokEnd, message);
  7975. }
  7976. }
  7977. unexpected(pos, messageOrType = "Unexpected token") {
  7978. if (typeof messageOrType !== "string") {
  7979. messageOrType = `Unexpected token, expected "${messageOrType.label}"`;
  7980. }
  7981. throw this.raise(pos != null ? pos : this.state.start, messageOrType);
  7982. }
  7983. expectPlugin(name, pos) {
  7984. if (!this.hasPlugin(name)) {
  7985. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7986. missingPlugin: [name]
  7987. }, `This experimental syntax requires enabling the parser plugin: '${name}'`);
  7988. }
  7989. return true;
  7990. }
  7991. expectOnePlugin(names, pos) {
  7992. if (!names.some(n => this.hasPlugin(n))) {
  7993. throw this.raiseWithData(pos != null ? pos : this.state.start, {
  7994. missingPlugin: names
  7995. }, `This experimental syntax requires enabling one of the following parser plugin(s): '${names.join(", ")}'`);
  7996. }
  7997. }
  7998. tryParse(fn, oldState = this.state.clone()) {
  7999. const abortSignal = {
  8000. node: null
  8001. };
  8002. try {
  8003. const node = fn((node = null) => {
  8004. abortSignal.node = node;
  8005. throw abortSignal;
  8006. });
  8007. if (this.state.errors.length > oldState.errors.length) {
  8008. const failState = this.state;
  8009. this.state = oldState;
  8010. return {
  8011. node,
  8012. error: failState.errors[oldState.errors.length],
  8013. thrown: false,
  8014. aborted: false,
  8015. failState
  8016. };
  8017. }
  8018. return {
  8019. node,
  8020. error: null,
  8021. thrown: false,
  8022. aborted: false,
  8023. failState: null
  8024. };
  8025. } catch (error) {
  8026. const failState = this.state;
  8027. this.state = oldState;
  8028. if (error instanceof SyntaxError) {
  8029. return {
  8030. node: null,
  8031. error,
  8032. thrown: true,
  8033. aborted: false,
  8034. failState
  8035. };
  8036. }
  8037. if (error === abortSignal) {
  8038. return {
  8039. node: abortSignal.node,
  8040. error: null,
  8041. thrown: false,
  8042. aborted: true,
  8043. failState
  8044. };
  8045. }
  8046. throw error;
  8047. }
  8048. }
  8049. checkExpressionErrors(refExpressionErrors, andThrow) {
  8050. if (!refExpressionErrors) return false;
  8051. const {
  8052. shorthandAssign,
  8053. doubleProto
  8054. } = refExpressionErrors;
  8055. if (!andThrow) return shorthandAssign >= 0 || doubleProto >= 0;
  8056. if (shorthandAssign >= 0) {
  8057. this.unexpected(shorthandAssign);
  8058. }
  8059. if (doubleProto >= 0) {
  8060. this.raise(doubleProto, ErrorMessages.DuplicateProto);
  8061. }
  8062. }
  8063. isLiteralPropertyName() {
  8064. return this.match(types.name) || !!this.state.type.keyword || this.match(types.string) || this.match(types.num) || this.match(types.bigint) || this.match(types.decimal);
  8065. }
  8066. isPrivateName(node) {
  8067. return node.type === "PrivateName";
  8068. }
  8069. getPrivateNameSV(node) {
  8070. return node.id.name;
  8071. }
  8072. hasPropertyAsPrivateName(node) {
  8073. return (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property);
  8074. }
  8075. isOptionalChain(node) {
  8076. return node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression";
  8077. }
  8078. isObjectProperty(node) {
  8079. return node.type === "ObjectProperty";
  8080. }
  8081. isObjectMethod(node) {
  8082. return node.type === "ObjectMethod";
  8083. }
  8084. initializeScopes(inModule = this.options.sourceType === "module") {
  8085. const oldLabels = this.state.labels;
  8086. this.state.labels = [];
  8087. const oldExportedIdentifiers = this.state.exportedIdentifiers;
  8088. this.state.exportedIdentifiers = [];
  8089. const oldInModule = this.inModule;
  8090. this.inModule = inModule;
  8091. const oldScope = this.scope;
  8092. const ScopeHandler = this.getScopeHandler();
  8093. this.scope = new ScopeHandler(this.raise.bind(this), this.inModule);
  8094. const oldProdParam = this.prodParam;
  8095. this.prodParam = new ProductionParameterHandler();
  8096. const oldClassScope = this.classScope;
  8097. this.classScope = new ClassScopeHandler(this.raise.bind(this));
  8098. const oldExpressionScope = this.expressionScope;
  8099. this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this));
  8100. return () => {
  8101. this.state.labels = oldLabels;
  8102. this.state.exportedIdentifiers = oldExportedIdentifiers;
  8103. this.inModule = oldInModule;
  8104. this.scope = oldScope;
  8105. this.prodParam = oldProdParam;
  8106. this.classScope = oldClassScope;
  8107. this.expressionScope = oldExpressionScope;
  8108. };
  8109. }
  8110. enterInitialScopes() {
  8111. let paramFlags = PARAM;
  8112. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  8113. paramFlags |= PARAM_AWAIT;
  8114. }
  8115. this.scope.enter(SCOPE_PROGRAM);
  8116. this.prodParam.enter(paramFlags);
  8117. }
  8118. }
  8119. class ExpressionErrors {
  8120. constructor() {
  8121. this.shorthandAssign = -1;
  8122. this.doubleProto = -1;
  8123. }
  8124. }
  8125. class Node {
  8126. constructor(parser, pos, loc) {
  8127. this.type = void 0;
  8128. this.start = void 0;
  8129. this.end = void 0;
  8130. this.loc = void 0;
  8131. this.range = void 0;
  8132. this.leadingComments = void 0;
  8133. this.trailingComments = void 0;
  8134. this.innerComments = void 0;
  8135. this.extra = void 0;
  8136. this.type = "";
  8137. this.start = pos;
  8138. this.end = 0;
  8139. this.loc = new SourceLocation(loc);
  8140. if (parser != null && parser.options.ranges) this.range = [pos, 0];
  8141. if (parser != null && parser.filename) this.loc.filename = parser.filename;
  8142. }
  8143. __clone() {
  8144. const newNode = new Node();
  8145. const keys = Object.keys(this);
  8146. for (let i = 0, length = keys.length; i < length; i++) {
  8147. const key = keys[i];
  8148. if (key !== "leadingComments" && key !== "trailingComments" && key !== "innerComments") {
  8149. newNode[key] = this[key];
  8150. }
  8151. }
  8152. return newNode;
  8153. }
  8154. }
  8155. class NodeUtils extends UtilParser {
  8156. startNode() {
  8157. return new Node(this, this.state.start, this.state.startLoc);
  8158. }
  8159. startNodeAt(pos, loc) {
  8160. return new Node(this, pos, loc);
  8161. }
  8162. startNodeAtNode(type) {
  8163. return this.startNodeAt(type.start, type.loc.start);
  8164. }
  8165. finishNode(node, type) {
  8166. return this.finishNodeAt(node, type, this.state.lastTokEnd, this.state.lastTokEndLoc);
  8167. }
  8168. finishNodeAt(node, type, pos, loc) {
  8169. node.type = type;
  8170. node.end = pos;
  8171. node.loc.end = loc;
  8172. if (this.options.ranges) node.range[1] = pos;
  8173. this.processComment(node);
  8174. return node;
  8175. }
  8176. resetStartLocation(node, start, startLoc) {
  8177. node.start = start;
  8178. node.loc.start = startLoc;
  8179. if (this.options.ranges) node.range[0] = start;
  8180. }
  8181. resetEndLocation(node, end = this.state.lastTokEnd, endLoc = this.state.lastTokEndLoc) {
  8182. node.end = end;
  8183. node.loc.end = endLoc;
  8184. if (this.options.ranges) node.range[1] = end;
  8185. }
  8186. resetStartLocationFromNode(node, locationNode) {
  8187. this.resetStartLocation(node, locationNode.start, locationNode.loc.start);
  8188. }
  8189. }
  8190. const unwrapParenthesizedExpression = node => {
  8191. return node.type === "ParenthesizedExpression" ? unwrapParenthesizedExpression(node.expression) : node;
  8192. };
  8193. class LValParser extends NodeUtils {
  8194. toAssignable(node, isLHS = false) {
  8195. var _node$extra, _node$extra3;
  8196. let parenthesized = undefined;
  8197. if (node.type === "ParenthesizedExpression" || (_node$extra = node.extra) != null && _node$extra.parenthesized) {
  8198. parenthesized = unwrapParenthesizedExpression(node);
  8199. if (isLHS) {
  8200. if (parenthesized.type === "Identifier") {
  8201. this.expressionScope.recordParenthesizedIdentifierError(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  8202. } else if (parenthesized.type !== "MemberExpression") {
  8203. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  8204. }
  8205. } else {
  8206. this.raise(node.start, ErrorMessages.InvalidParenthesizedAssignment);
  8207. }
  8208. }
  8209. switch (node.type) {
  8210. case "Identifier":
  8211. case "ObjectPattern":
  8212. case "ArrayPattern":
  8213. case "AssignmentPattern":
  8214. break;
  8215. case "ObjectExpression":
  8216. node.type = "ObjectPattern";
  8217. for (let i = 0, length = node.properties.length, last = length - 1; i < length; i++) {
  8218. var _node$extra2;
  8219. const prop = node.properties[i];
  8220. const isLast = i === last;
  8221. this.toAssignableObjectExpressionProp(prop, isLast, isLHS);
  8222. if (isLast && prop.type === "RestElement" && (_node$extra2 = node.extra) != null && _node$extra2.trailingComma) {
  8223. this.raiseRestNotLast(node.extra.trailingComma);
  8224. }
  8225. }
  8226. break;
  8227. case "ObjectProperty":
  8228. this.toAssignable(node.value, isLHS);
  8229. break;
  8230. case "SpreadElement":
  8231. {
  8232. this.checkToRestConversion(node);
  8233. node.type = "RestElement";
  8234. const arg = node.argument;
  8235. this.toAssignable(arg, isLHS);
  8236. break;
  8237. }
  8238. case "ArrayExpression":
  8239. node.type = "ArrayPattern";
  8240. this.toAssignableList(node.elements, (_node$extra3 = node.extra) == null ? void 0 : _node$extra3.trailingComma, isLHS);
  8241. break;
  8242. case "AssignmentExpression":
  8243. if (node.operator !== "=") {
  8244. this.raise(node.left.end, ErrorMessages.MissingEqInAssignment);
  8245. }
  8246. node.type = "AssignmentPattern";
  8247. delete node.operator;
  8248. this.toAssignable(node.left, isLHS);
  8249. break;
  8250. case "ParenthesizedExpression":
  8251. this.toAssignable(parenthesized, isLHS);
  8252. break;
  8253. }
  8254. return node;
  8255. }
  8256. toAssignableObjectExpressionProp(prop, isLast, isLHS) {
  8257. if (prop.type === "ObjectMethod") {
  8258. const error = prop.kind === "get" || prop.kind === "set" ? ErrorMessages.PatternHasAccessor : ErrorMessages.PatternHasMethod;
  8259. this.raise(prop.key.start, error);
  8260. } else if (prop.type === "SpreadElement" && !isLast) {
  8261. this.raiseRestNotLast(prop.start);
  8262. } else {
  8263. this.toAssignable(prop, isLHS);
  8264. }
  8265. }
  8266. toAssignableList(exprList, trailingCommaPos, isLHS) {
  8267. let end = exprList.length;
  8268. if (end) {
  8269. const last = exprList[end - 1];
  8270. if ((last == null ? void 0 : last.type) === "RestElement") {
  8271. --end;
  8272. } else if ((last == null ? void 0 : last.type) === "SpreadElement") {
  8273. last.type = "RestElement";
  8274. let arg = last.argument;
  8275. this.toAssignable(arg, isLHS);
  8276. arg = unwrapParenthesizedExpression(arg);
  8277. if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern" && arg.type !== "ObjectPattern") {
  8278. this.unexpected(arg.start);
  8279. }
  8280. if (trailingCommaPos) {
  8281. this.raiseTrailingCommaAfterRest(trailingCommaPos);
  8282. }
  8283. --end;
  8284. }
  8285. }
  8286. for (let i = 0; i < end; i++) {
  8287. const elt = exprList[i];
  8288. if (elt) {
  8289. this.toAssignable(elt, isLHS);
  8290. if (elt.type === "RestElement") {
  8291. this.raiseRestNotLast(elt.start);
  8292. }
  8293. }
  8294. }
  8295. return exprList;
  8296. }
  8297. toReferencedList(exprList, isParenthesizedExpr) {
  8298. return exprList;
  8299. }
  8300. toReferencedListDeep(exprList, isParenthesizedExpr) {
  8301. this.toReferencedList(exprList, isParenthesizedExpr);
  8302. for (const expr of exprList) {
  8303. if ((expr == null ? void 0 : expr.type) === "ArrayExpression") {
  8304. this.toReferencedListDeep(expr.elements);
  8305. }
  8306. }
  8307. }
  8308. parseSpread(refExpressionErrors, refNeedsArrowPos) {
  8309. const node = this.startNode();
  8310. this.next();
  8311. node.argument = this.parseMaybeAssignAllowIn(refExpressionErrors, undefined, refNeedsArrowPos);
  8312. return this.finishNode(node, "SpreadElement");
  8313. }
  8314. parseRestBinding() {
  8315. const node = this.startNode();
  8316. this.next();
  8317. node.argument = this.parseBindingAtom();
  8318. return this.finishNode(node, "RestElement");
  8319. }
  8320. parseBindingAtom() {
  8321. switch (this.state.type) {
  8322. case types.bracketL:
  8323. {
  8324. const node = this.startNode();
  8325. this.next();
  8326. node.elements = this.parseBindingList(types.bracketR, 93, true);
  8327. return this.finishNode(node, "ArrayPattern");
  8328. }
  8329. case types.braceL:
  8330. return this.parseObjectLike(types.braceR, true);
  8331. }
  8332. return this.parseIdentifier();
  8333. }
  8334. parseBindingList(close, closeCharCode, allowEmpty, allowModifiers) {
  8335. const elts = [];
  8336. let first = true;
  8337. while (!this.eat(close)) {
  8338. if (first) {
  8339. first = false;
  8340. } else {
  8341. this.expect(types.comma);
  8342. }
  8343. if (allowEmpty && this.match(types.comma)) {
  8344. elts.push(null);
  8345. } else if (this.eat(close)) {
  8346. break;
  8347. } else if (this.match(types.ellipsis)) {
  8348. elts.push(this.parseAssignableListItemTypes(this.parseRestBinding()));
  8349. this.checkCommaAfterRest(closeCharCode);
  8350. this.expect(close);
  8351. break;
  8352. } else {
  8353. const decorators = [];
  8354. if (this.match(types.at) && this.hasPlugin("decorators")) {
  8355. this.raise(this.state.start, ErrorMessages.UnsupportedParameterDecorator);
  8356. }
  8357. while (this.match(types.at)) {
  8358. decorators.push(this.parseDecorator());
  8359. }
  8360. elts.push(this.parseAssignableListItem(allowModifiers, decorators));
  8361. }
  8362. }
  8363. return elts;
  8364. }
  8365. parseAssignableListItem(allowModifiers, decorators) {
  8366. const left = this.parseMaybeDefault();
  8367. this.parseAssignableListItemTypes(left);
  8368. const elt = this.parseMaybeDefault(left.start, left.loc.start, left);
  8369. if (decorators.length) {
  8370. left.decorators = decorators;
  8371. }
  8372. return elt;
  8373. }
  8374. parseAssignableListItemTypes(param) {
  8375. return param;
  8376. }
  8377. parseMaybeDefault(startPos, startLoc, left) {
  8378. var _startLoc, _startPos, _left;
  8379. startLoc = (_startLoc = startLoc) != null ? _startLoc : this.state.startLoc;
  8380. startPos = (_startPos = startPos) != null ? _startPos : this.state.start;
  8381. left = (_left = left) != null ? _left : this.parseBindingAtom();
  8382. if (!this.eat(types.eq)) return left;
  8383. const node = this.startNodeAt(startPos, startLoc);
  8384. node.left = left;
  8385. node.right = this.parseMaybeAssignAllowIn();
  8386. return this.finishNode(node, "AssignmentPattern");
  8387. }
  8388. checkLVal(expr, contextDescription, bindingType = BIND_NONE, checkClashes, disallowLetBinding, strictModeChanged = false) {
  8389. switch (expr.type) {
  8390. case "Identifier":
  8391. {
  8392. const {
  8393. name
  8394. } = expr;
  8395. if (this.state.strict && (strictModeChanged ? isStrictBindReservedWord(name, this.inModule) : isStrictBindOnlyReservedWord(name))) {
  8396. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.StrictEvalArguments : ErrorMessages.StrictEvalArgumentsBinding, name);
  8397. }
  8398. if (checkClashes) {
  8399. if (checkClashes.has(name)) {
  8400. this.raise(expr.start, ErrorMessages.ParamDupe);
  8401. } else {
  8402. checkClashes.add(name);
  8403. }
  8404. }
  8405. if (disallowLetBinding && name === "let") {
  8406. this.raise(expr.start, ErrorMessages.LetInLexicalBinding);
  8407. }
  8408. if (!(bindingType & BIND_NONE)) {
  8409. this.scope.declareName(name, bindingType, expr.start);
  8410. }
  8411. break;
  8412. }
  8413. case "MemberExpression":
  8414. if (bindingType !== BIND_NONE) {
  8415. this.raise(expr.start, ErrorMessages.InvalidPropertyBindingPattern);
  8416. }
  8417. break;
  8418. case "ObjectPattern":
  8419. for (let prop of expr.properties) {
  8420. if (this.isObjectProperty(prop)) prop = prop.value;else if (this.isObjectMethod(prop)) continue;
  8421. this.checkLVal(prop, "object destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  8422. }
  8423. break;
  8424. case "ArrayPattern":
  8425. for (const elem of expr.elements) {
  8426. if (elem) {
  8427. this.checkLVal(elem, "array destructuring pattern", bindingType, checkClashes, disallowLetBinding);
  8428. }
  8429. }
  8430. break;
  8431. case "AssignmentPattern":
  8432. this.checkLVal(expr.left, "assignment pattern", bindingType, checkClashes);
  8433. break;
  8434. case "RestElement":
  8435. this.checkLVal(expr.argument, "rest element", bindingType, checkClashes);
  8436. break;
  8437. case "ParenthesizedExpression":
  8438. this.checkLVal(expr.expression, "parenthesized expression", bindingType, checkClashes);
  8439. break;
  8440. default:
  8441. {
  8442. this.raise(expr.start, bindingType === BIND_NONE ? ErrorMessages.InvalidLhs : ErrorMessages.InvalidLhsBinding, contextDescription);
  8443. }
  8444. }
  8445. }
  8446. checkToRestConversion(node) {
  8447. if (node.argument.type !== "Identifier" && node.argument.type !== "MemberExpression") {
  8448. this.raise(node.argument.start, ErrorMessages.InvalidRestAssignmentPattern);
  8449. }
  8450. }
  8451. checkCommaAfterRest(close) {
  8452. if (this.match(types.comma)) {
  8453. if (this.lookaheadCharCode() === close) {
  8454. this.raiseTrailingCommaAfterRest(this.state.start);
  8455. } else {
  8456. this.raiseRestNotLast(this.state.start);
  8457. }
  8458. }
  8459. }
  8460. raiseRestNotLast(pos) {
  8461. throw this.raise(pos, ErrorMessages.ElementAfterRest);
  8462. }
  8463. raiseTrailingCommaAfterRest(pos) {
  8464. this.raise(pos, ErrorMessages.RestTrailingComma);
  8465. }
  8466. }
  8467. class ExpressionParser extends LValParser {
  8468. checkProto(prop, isRecord, protoRef, refExpressionErrors) {
  8469. if (prop.type === "SpreadElement" || this.isObjectMethod(prop) || prop.computed || prop.shorthand) {
  8470. return;
  8471. }
  8472. const key = prop.key;
  8473. const name = key.type === "Identifier" ? key.name : key.value;
  8474. if (name === "__proto__") {
  8475. if (isRecord) {
  8476. this.raise(key.start, ErrorMessages.RecordNoProto);
  8477. return;
  8478. }
  8479. if (protoRef.used) {
  8480. if (refExpressionErrors) {
  8481. if (refExpressionErrors.doubleProto === -1) {
  8482. refExpressionErrors.doubleProto = key.start;
  8483. }
  8484. } else {
  8485. this.raise(key.start, ErrorMessages.DuplicateProto);
  8486. }
  8487. }
  8488. protoRef.used = true;
  8489. }
  8490. }
  8491. shouldExitDescending(expr, potentialArrowAt) {
  8492. return expr.type === "ArrowFunctionExpression" && expr.start === potentialArrowAt;
  8493. }
  8494. getExpression() {
  8495. let paramFlags = PARAM;
  8496. if (this.hasPlugin("topLevelAwait") && this.inModule) {
  8497. paramFlags |= PARAM_AWAIT;
  8498. }
  8499. this.scope.enter(SCOPE_PROGRAM);
  8500. this.prodParam.enter(paramFlags);
  8501. this.nextToken();
  8502. const expr = this.parseExpression();
  8503. if (!this.match(types.eof)) {
  8504. this.unexpected();
  8505. }
  8506. expr.comments = this.state.comments;
  8507. expr.errors = this.state.errors;
  8508. if (this.options.tokens) {
  8509. expr.tokens = this.tokens;
  8510. }
  8511. return expr;
  8512. }
  8513. parseExpression(disallowIn, refExpressionErrors) {
  8514. if (disallowIn) {
  8515. return this.disallowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8516. }
  8517. return this.allowInAnd(() => this.parseExpressionBase(refExpressionErrors));
  8518. }
  8519. parseExpressionBase(refExpressionErrors) {
  8520. const startPos = this.state.start;
  8521. const startLoc = this.state.startLoc;
  8522. const expr = this.parseMaybeAssign(refExpressionErrors);
  8523. if (this.match(types.comma)) {
  8524. const node = this.startNodeAt(startPos, startLoc);
  8525. node.expressions = [expr];
  8526. while (this.eat(types.comma)) {
  8527. node.expressions.push(this.parseMaybeAssign(refExpressionErrors));
  8528. }
  8529. this.toReferencedList(node.expressions);
  8530. return this.finishNode(node, "SequenceExpression");
  8531. }
  8532. return expr;
  8533. }
  8534. parseMaybeAssignDisallowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8535. return this.disallowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8536. }
  8537. parseMaybeAssignAllowIn(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8538. return this.allowInAnd(() => this.parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos));
  8539. }
  8540. parseMaybeAssign(refExpressionErrors, afterLeftParse, refNeedsArrowPos) {
  8541. const startPos = this.state.start;
  8542. const startLoc = this.state.startLoc;
  8543. if (this.isContextual("yield")) {
  8544. if (this.prodParam.hasYield) {
  8545. this.state.exprAllowed = true;
  8546. let left = this.parseYield();
  8547. if (afterLeftParse) {
  8548. left = afterLeftParse.call(this, left, startPos, startLoc);
  8549. }
  8550. return left;
  8551. }
  8552. }
  8553. let ownExpressionErrors;
  8554. if (refExpressionErrors) {
  8555. ownExpressionErrors = false;
  8556. } else {
  8557. refExpressionErrors = new ExpressionErrors();
  8558. ownExpressionErrors = true;
  8559. }
  8560. if (this.match(types.parenL) || this.match(types.name)) {
  8561. this.state.potentialArrowAt = this.state.start;
  8562. }
  8563. let left = this.parseMaybeConditional(refExpressionErrors, refNeedsArrowPos);
  8564. if (afterLeftParse) {
  8565. left = afterLeftParse.call(this, left, startPos, startLoc);
  8566. }
  8567. if (this.state.type.isAssign) {
  8568. const node = this.startNodeAt(startPos, startLoc);
  8569. const operator = this.state.value;
  8570. node.operator = operator;
  8571. if (this.match(types.eq)) {
  8572. node.left = this.toAssignable(left, true);
  8573. refExpressionErrors.doubleProto = -1;
  8574. } else {
  8575. node.left = left;
  8576. }
  8577. if (refExpressionErrors.shorthandAssign >= node.left.start) {
  8578. refExpressionErrors.shorthandAssign = -1;
  8579. }
  8580. this.checkLVal(left, "assignment expression");
  8581. this.next();
  8582. node.right = this.parseMaybeAssign();
  8583. return this.finishNode(node, "AssignmentExpression");
  8584. } else if (ownExpressionErrors) {
  8585. this.checkExpressionErrors(refExpressionErrors, true);
  8586. }
  8587. return left;
  8588. }
  8589. parseMaybeConditional(refExpressionErrors, refNeedsArrowPos) {
  8590. const startPos = this.state.start;
  8591. const startLoc = this.state.startLoc;
  8592. const potentialArrowAt = this.state.potentialArrowAt;
  8593. const expr = this.parseExprOps(refExpressionErrors);
  8594. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8595. return expr;
  8596. }
  8597. return this.parseConditional(expr, startPos, startLoc, refNeedsArrowPos);
  8598. }
  8599. parseConditional(expr, startPos, startLoc, refNeedsArrowPos) {
  8600. if (this.eat(types.question)) {
  8601. const node = this.startNodeAt(startPos, startLoc);
  8602. node.test = expr;
  8603. node.consequent = this.parseMaybeAssignAllowIn();
  8604. this.expect(types.colon);
  8605. node.alternate = this.parseMaybeAssign();
  8606. return this.finishNode(node, "ConditionalExpression");
  8607. }
  8608. return expr;
  8609. }
  8610. parseExprOps(refExpressionErrors) {
  8611. const startPos = this.state.start;
  8612. const startLoc = this.state.startLoc;
  8613. const potentialArrowAt = this.state.potentialArrowAt;
  8614. const expr = this.parseMaybeUnary(refExpressionErrors);
  8615. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8616. return expr;
  8617. }
  8618. return this.parseExprOp(expr, startPos, startLoc, -1);
  8619. }
  8620. parseExprOp(left, leftStartPos, leftStartLoc, minPrec) {
  8621. let prec = this.state.type.binop;
  8622. if (prec != null && (this.prodParam.hasIn || !this.match(types._in))) {
  8623. if (prec > minPrec) {
  8624. const op = this.state.type;
  8625. if (op === types.pipeline) {
  8626. this.expectPlugin("pipelineOperator");
  8627. if (this.state.inFSharpPipelineDirectBody) {
  8628. return left;
  8629. }
  8630. this.state.inPipeline = true;
  8631. this.checkPipelineAtInfixOperator(left, leftStartPos);
  8632. }
  8633. const node = this.startNodeAt(leftStartPos, leftStartLoc);
  8634. node.left = left;
  8635. node.operator = this.state.value;
  8636. const logical = op === types.logicalOR || op === types.logicalAND;
  8637. const coalesce = op === types.nullishCoalescing;
  8638. if (coalesce) {
  8639. prec = types.logicalAND.binop;
  8640. }
  8641. this.next();
  8642. if (op === types.pipeline && this.getPluginOption("pipelineOperator", "proposal") === "minimal") {
  8643. if (this.match(types.name) && this.state.value === "await" && this.prodParam.hasAwait) {
  8644. throw this.raise(this.state.start, ErrorMessages.UnexpectedAwaitAfterPipelineBody);
  8645. }
  8646. }
  8647. node.right = this.parseExprOpRightExpr(op, prec);
  8648. this.finishNode(node, logical || coalesce ? "LogicalExpression" : "BinaryExpression");
  8649. const nextOp = this.state.type;
  8650. if (coalesce && (nextOp === types.logicalOR || nextOp === types.logicalAND) || logical && nextOp === types.nullishCoalescing) {
  8651. throw this.raise(this.state.start, ErrorMessages.MixingCoalesceWithLogical);
  8652. }
  8653. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec);
  8654. }
  8655. }
  8656. return left;
  8657. }
  8658. parseExprOpRightExpr(op, prec) {
  8659. const startPos = this.state.start;
  8660. const startLoc = this.state.startLoc;
  8661. switch (op) {
  8662. case types.pipeline:
  8663. switch (this.getPluginOption("pipelineOperator", "proposal")) {
  8664. case "smart":
  8665. return this.withTopicPermittingContext(() => {
  8666. return this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(op, prec), startPos, startLoc);
  8667. });
  8668. case "fsharp":
  8669. return this.withSoloAwaitPermittingContext(() => {
  8670. return this.parseFSharpPipelineBody(prec);
  8671. });
  8672. }
  8673. default:
  8674. return this.parseExprOpBaseRightExpr(op, prec);
  8675. }
  8676. }
  8677. parseExprOpBaseRightExpr(op, prec) {
  8678. const startPos = this.state.start;
  8679. const startLoc = this.state.startLoc;
  8680. return this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, op.rightAssociative ? prec - 1 : prec);
  8681. }
  8682. checkExponentialAfterUnary(node) {
  8683. if (this.match(types.exponent)) {
  8684. this.raise(node.argument.start, ErrorMessages.UnexpectedTokenUnaryExponentiation);
  8685. }
  8686. }
  8687. parseMaybeUnary(refExpressionErrors, sawUnary) {
  8688. const startPos = this.state.start;
  8689. const startLoc = this.state.startLoc;
  8690. const isAwait = this.isContextual("await");
  8691. if (isAwait && this.isAwaitAllowed()) {
  8692. this.next();
  8693. const expr = this.parseAwait(startPos, startLoc);
  8694. if (!sawUnary) this.checkExponentialAfterUnary(expr);
  8695. return expr;
  8696. }
  8697. if (this.isContextual("module") && this.lookaheadCharCode() === 123 && !this.hasFollowingLineBreak()) {
  8698. return this.parseModuleExpression();
  8699. }
  8700. const update = this.match(types.incDec);
  8701. const node = this.startNode();
  8702. if (this.state.type.prefix) {
  8703. node.operator = this.state.value;
  8704. node.prefix = true;
  8705. if (this.match(types._throw)) {
  8706. this.expectPlugin("throwExpressions");
  8707. }
  8708. const isDelete = this.match(types._delete);
  8709. this.next();
  8710. node.argument = this.parseMaybeUnary(null, true);
  8711. this.checkExpressionErrors(refExpressionErrors, true);
  8712. if (this.state.strict && isDelete) {
  8713. const arg = node.argument;
  8714. if (arg.type === "Identifier") {
  8715. this.raise(node.start, ErrorMessages.StrictDelete);
  8716. } else if (this.hasPropertyAsPrivateName(arg)) {
  8717. this.raise(node.start, ErrorMessages.DeletePrivateField);
  8718. }
  8719. }
  8720. if (!update) {
  8721. if (!sawUnary) this.checkExponentialAfterUnary(node);
  8722. return this.finishNode(node, "UnaryExpression");
  8723. }
  8724. }
  8725. const expr = this.parseUpdate(node, update, refExpressionErrors);
  8726. if (isAwait) {
  8727. const startsExpr = this.hasPlugin("v8intrinsic") ? this.state.type.startsExpr : this.state.type.startsExpr && !this.match(types.modulo);
  8728. if (startsExpr && !this.isAmbiguousAwait()) {
  8729. this.raiseOverwrite(startPos, this.hasPlugin("topLevelAwait") ? ErrorMessages.AwaitNotInAsyncContext : ErrorMessages.AwaitNotInAsyncFunction);
  8730. return this.parseAwait(startPos, startLoc);
  8731. }
  8732. }
  8733. return expr;
  8734. }
  8735. parseUpdate(node, update, refExpressionErrors) {
  8736. if (update) {
  8737. this.checkLVal(node.argument, "prefix operation");
  8738. return this.finishNode(node, "UpdateExpression");
  8739. }
  8740. const startPos = this.state.start;
  8741. const startLoc = this.state.startLoc;
  8742. let expr = this.parseExprSubscripts(refExpressionErrors);
  8743. if (this.checkExpressionErrors(refExpressionErrors, false)) return expr;
  8744. while (this.state.type.postfix && !this.canInsertSemicolon()) {
  8745. const node = this.startNodeAt(startPos, startLoc);
  8746. node.operator = this.state.value;
  8747. node.prefix = false;
  8748. node.argument = expr;
  8749. this.checkLVal(expr, "postfix operation");
  8750. this.next();
  8751. expr = this.finishNode(node, "UpdateExpression");
  8752. }
  8753. return expr;
  8754. }
  8755. parseExprSubscripts(refExpressionErrors) {
  8756. const startPos = this.state.start;
  8757. const startLoc = this.state.startLoc;
  8758. const potentialArrowAt = this.state.potentialArrowAt;
  8759. const expr = this.parseExprAtom(refExpressionErrors);
  8760. if (this.shouldExitDescending(expr, potentialArrowAt)) {
  8761. return expr;
  8762. }
  8763. return this.parseSubscripts(expr, startPos, startLoc);
  8764. }
  8765. parseSubscripts(base, startPos, startLoc, noCalls) {
  8766. const state = {
  8767. optionalChainMember: false,
  8768. maybeAsyncArrow: this.atPossibleAsyncArrow(base),
  8769. stop: false
  8770. };
  8771. do {
  8772. base = this.parseSubscript(base, startPos, startLoc, noCalls, state);
  8773. state.maybeAsyncArrow = false;
  8774. } while (!state.stop);
  8775. return base;
  8776. }
  8777. parseSubscript(base, startPos, startLoc, noCalls, state) {
  8778. if (!noCalls && this.eat(types.doubleColon)) {
  8779. return this.parseBind(base, startPos, startLoc, noCalls, state);
  8780. } else if (this.match(types.backQuote)) {
  8781. return this.parseTaggedTemplateExpression(base, startPos, startLoc, state);
  8782. }
  8783. let optional = false;
  8784. if (this.match(types.questionDot)) {
  8785. if (noCalls && this.lookaheadCharCode() === 40) {
  8786. state.stop = true;
  8787. return base;
  8788. }
  8789. state.optionalChainMember = optional = true;
  8790. this.next();
  8791. }
  8792. if (!noCalls && this.match(types.parenL)) {
  8793. return this.parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional);
  8794. } else if (optional || this.match(types.bracketL) || this.eat(types.dot)) {
  8795. return this.parseMember(base, startPos, startLoc, state, optional);
  8796. } else {
  8797. state.stop = true;
  8798. return base;
  8799. }
  8800. }
  8801. parseMember(base, startPos, startLoc, state, optional) {
  8802. const node = this.startNodeAt(startPos, startLoc);
  8803. const computed = this.eat(types.bracketL);
  8804. node.object = base;
  8805. node.computed = computed;
  8806. const property = computed ? this.parseExpression() : this.parseMaybePrivateName(true);
  8807. if (this.isPrivateName(property)) {
  8808. if (node.object.type === "Super") {
  8809. this.raise(startPos, ErrorMessages.SuperPrivateField);
  8810. }
  8811. this.classScope.usePrivateName(this.getPrivateNameSV(property), property.start);
  8812. }
  8813. node.property = property;
  8814. if (computed) {
  8815. this.expect(types.bracketR);
  8816. }
  8817. if (state.optionalChainMember) {
  8818. node.optional = optional;
  8819. return this.finishNode(node, "OptionalMemberExpression");
  8820. } else {
  8821. return this.finishNode(node, "MemberExpression");
  8822. }
  8823. }
  8824. parseBind(base, startPos, startLoc, noCalls, state) {
  8825. const node = this.startNodeAt(startPos, startLoc);
  8826. node.object = base;
  8827. node.callee = this.parseNoCallExpr();
  8828. state.stop = true;
  8829. return this.parseSubscripts(this.finishNode(node, "BindExpression"), startPos, startLoc, noCalls);
  8830. }
  8831. parseCoverCallAndAsyncArrowHead(base, startPos, startLoc, state, optional) {
  8832. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  8833. this.state.maybeInArrowParameters = true;
  8834. this.next();
  8835. let node = this.startNodeAt(startPos, startLoc);
  8836. node.callee = base;
  8837. if (state.maybeAsyncArrow) {
  8838. this.expressionScope.enter(newAsyncArrowScope());
  8839. }
  8840. if (state.optionalChainMember) {
  8841. node.optional = optional;
  8842. }
  8843. if (optional) {
  8844. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  8845. } else {
  8846. node.arguments = this.parseCallExpressionArguments(types.parenR, state.maybeAsyncArrow, base.type === "Import", base.type !== "Super", node);
  8847. }
  8848. this.finishCallExpression(node, state.optionalChainMember);
  8849. if (state.maybeAsyncArrow && this.shouldParseAsyncArrow() && !optional) {
  8850. state.stop = true;
  8851. this.expressionScope.validateAsPattern();
  8852. this.expressionScope.exit();
  8853. node = this.parseAsyncArrowFromCallExpression(this.startNodeAt(startPos, startLoc), node);
  8854. } else {
  8855. if (state.maybeAsyncArrow) {
  8856. this.expressionScope.exit();
  8857. }
  8858. this.toReferencedArguments(node);
  8859. }
  8860. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  8861. return node;
  8862. }
  8863. toReferencedArguments(node, isParenthesizedExpr) {
  8864. this.toReferencedListDeep(node.arguments, isParenthesizedExpr);
  8865. }
  8866. parseTaggedTemplateExpression(base, startPos, startLoc, state) {
  8867. const node = this.startNodeAt(startPos, startLoc);
  8868. node.tag = base;
  8869. node.quasi = this.parseTemplate(true);
  8870. if (state.optionalChainMember) {
  8871. this.raise(startPos, ErrorMessages.OptionalChainingNoTemplate);
  8872. }
  8873. return this.finishNode(node, "TaggedTemplateExpression");
  8874. }
  8875. atPossibleAsyncArrow(base) {
  8876. return base.type === "Identifier" && base.name === "async" && this.state.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && base.start === this.state.potentialArrowAt;
  8877. }
  8878. finishCallExpression(node, optional) {
  8879. if (node.callee.type === "Import") {
  8880. if (node.arguments.length === 2) {
  8881. if (!this.hasPlugin("moduleAttributes")) {
  8882. this.expectPlugin("importAssertions");
  8883. }
  8884. }
  8885. if (node.arguments.length === 0 || node.arguments.length > 2) {
  8886. this.raise(node.start, ErrorMessages.ImportCallArity, this.hasPlugin("importAssertions") || this.hasPlugin("moduleAttributes") ? "one or two arguments" : "one argument");
  8887. } else {
  8888. for (const arg of node.arguments) {
  8889. if (arg.type === "SpreadElement") {
  8890. this.raise(arg.start, ErrorMessages.ImportCallSpreadArgument);
  8891. }
  8892. }
  8893. }
  8894. }
  8895. return this.finishNode(node, optional ? "OptionalCallExpression" : "CallExpression");
  8896. }
  8897. parseCallExpressionArguments(close, possibleAsyncArrow, dynamicImport, allowPlaceholder, nodeForExtra) {
  8898. const elts = [];
  8899. let first = true;
  8900. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  8901. this.state.inFSharpPipelineDirectBody = false;
  8902. while (!this.eat(close)) {
  8903. if (first) {
  8904. first = false;
  8905. } else {
  8906. this.expect(types.comma);
  8907. if (this.match(close)) {
  8908. if (dynamicImport && !this.hasPlugin("importAssertions") && !this.hasPlugin("moduleAttributes")) {
  8909. this.raise(this.state.lastTokStart, ErrorMessages.ImportCallArgumentTrailingComma);
  8910. }
  8911. if (nodeForExtra) {
  8912. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  8913. }
  8914. this.next();
  8915. break;
  8916. }
  8917. }
  8918. elts.push(this.parseExprListItem(false, possibleAsyncArrow ? new ExpressionErrors() : undefined, possibleAsyncArrow ? {
  8919. start: 0
  8920. } : undefined, allowPlaceholder));
  8921. }
  8922. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  8923. return elts;
  8924. }
  8925. shouldParseAsyncArrow() {
  8926. return this.match(types.arrow) && !this.canInsertSemicolon();
  8927. }
  8928. parseAsyncArrowFromCallExpression(node, call) {
  8929. var _call$extra;
  8930. this.expect(types.arrow);
  8931. this.parseArrowExpression(node, call.arguments, true, (_call$extra = call.extra) == null ? void 0 : _call$extra.trailingComma);
  8932. return node;
  8933. }
  8934. parseNoCallExpr() {
  8935. const startPos = this.state.start;
  8936. const startLoc = this.state.startLoc;
  8937. return this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
  8938. }
  8939. parseExprAtom(refExpressionErrors) {
  8940. if (this.state.type === types.slash) this.readRegexp();
  8941. const canBeArrow = this.state.potentialArrowAt === this.state.start;
  8942. let node;
  8943. switch (this.state.type) {
  8944. case types._super:
  8945. return this.parseSuper();
  8946. case types._import:
  8947. node = this.startNode();
  8948. this.next();
  8949. if (this.match(types.dot)) {
  8950. return this.parseImportMetaProperty(node);
  8951. }
  8952. if (!this.match(types.parenL)) {
  8953. this.raise(this.state.lastTokStart, ErrorMessages.UnsupportedImport);
  8954. }
  8955. return this.finishNode(node, "Import");
  8956. case types._this:
  8957. node = this.startNode();
  8958. this.next();
  8959. return this.finishNode(node, "ThisExpression");
  8960. case types.name:
  8961. {
  8962. const containsEsc = this.state.containsEsc;
  8963. const id = this.parseIdentifier();
  8964. if (!containsEsc && id.name === "async" && !this.canInsertSemicolon()) {
  8965. if (this.match(types._function)) {
  8966. const last = this.state.context.length - 1;
  8967. if (this.state.context[last] !== types$1.functionStatement) {
  8968. throw new Error("Internal error");
  8969. }
  8970. this.state.context[last] = types$1.functionExpression;
  8971. this.next();
  8972. return this.parseFunction(this.startNodeAtNode(id), undefined, true);
  8973. } else if (this.match(types.name)) {
  8974. return this.parseAsyncArrowUnaryFunction(id);
  8975. }
  8976. }
  8977. if (canBeArrow && this.match(types.arrow) && !this.canInsertSemicolon()) {
  8978. this.next();
  8979. return this.parseArrowExpression(this.startNodeAtNode(id), [id], false);
  8980. }
  8981. return id;
  8982. }
  8983. case types._do:
  8984. {
  8985. return this.parseDo();
  8986. }
  8987. case types.regexp:
  8988. {
  8989. const value = this.state.value;
  8990. node = this.parseLiteral(value.value, "RegExpLiteral");
  8991. node.pattern = value.pattern;
  8992. node.flags = value.flags;
  8993. return node;
  8994. }
  8995. case types.num:
  8996. return this.parseLiteral(this.state.value, "NumericLiteral");
  8997. case types.bigint:
  8998. return this.parseLiteral(this.state.value, "BigIntLiteral");
  8999. case types.decimal:
  9000. return this.parseLiteral(this.state.value, "DecimalLiteral");
  9001. case types.string:
  9002. return this.parseLiteral(this.state.value, "StringLiteral");
  9003. case types._null:
  9004. node = this.startNode();
  9005. this.next();
  9006. return this.finishNode(node, "NullLiteral");
  9007. case types._true:
  9008. case types._false:
  9009. return this.parseBooleanLiteral();
  9010. case types.parenL:
  9011. return this.parseParenAndDistinguishExpression(canBeArrow);
  9012. case types.bracketBarL:
  9013. case types.bracketHashL:
  9014. {
  9015. return this.parseArrayLike(this.state.type === types.bracketBarL ? types.bracketBarR : types.bracketR, false, true, refExpressionErrors);
  9016. }
  9017. case types.bracketL:
  9018. {
  9019. return this.parseArrayLike(types.bracketR, true, false, refExpressionErrors);
  9020. }
  9021. case types.braceBarL:
  9022. case types.braceHashL:
  9023. {
  9024. return this.parseObjectLike(this.state.type === types.braceBarL ? types.braceBarR : types.braceR, false, true, refExpressionErrors);
  9025. }
  9026. case types.braceL:
  9027. {
  9028. return this.parseObjectLike(types.braceR, false, false, refExpressionErrors);
  9029. }
  9030. case types._function:
  9031. return this.parseFunctionOrFunctionSent();
  9032. case types.at:
  9033. this.parseDecorators();
  9034. case types._class:
  9035. node = this.startNode();
  9036. this.takeDecorators(node);
  9037. return this.parseClass(node, false);
  9038. case types._new:
  9039. return this.parseNewOrNewTarget();
  9040. case types.backQuote:
  9041. return this.parseTemplate(false);
  9042. case types.doubleColon:
  9043. {
  9044. node = this.startNode();
  9045. this.next();
  9046. node.object = null;
  9047. const callee = node.callee = this.parseNoCallExpr();
  9048. if (callee.type === "MemberExpression") {
  9049. return this.finishNode(node, "BindExpression");
  9050. } else {
  9051. throw this.raise(callee.start, ErrorMessages.UnsupportedBind);
  9052. }
  9053. }
  9054. case types.hash:
  9055. {
  9056. if (this.state.inPipeline) {
  9057. node = this.startNode();
  9058. if (this.getPluginOption("pipelineOperator", "proposal") !== "smart") {
  9059. this.raise(node.start, ErrorMessages.PrimaryTopicRequiresSmartPipeline);
  9060. }
  9061. this.next();
  9062. if (!this.primaryTopicReferenceIsAllowedInCurrentTopicContext()) {
  9063. this.raise(node.start, ErrorMessages.PrimaryTopicNotAllowed);
  9064. }
  9065. this.registerTopicReference();
  9066. return this.finishNode(node, "PipelinePrimaryTopicReference");
  9067. }
  9068. const nextCh = this.input.codePointAt(this.state.end);
  9069. if (isIdentifierStart(nextCh) || nextCh === 92) {
  9070. const start = this.state.start;
  9071. node = this.parseMaybePrivateName(true);
  9072. if (this.match(types._in)) {
  9073. this.expectPlugin("privateIn");
  9074. this.classScope.usePrivateName(this.getPrivateNameSV(node), node.start);
  9075. } else if (this.hasPlugin("privateIn")) {
  9076. this.raise(this.state.start, ErrorMessages.PrivateInExpectedIn, this.getPrivateNameSV(node));
  9077. } else {
  9078. throw this.unexpected(start);
  9079. }
  9080. return node;
  9081. }
  9082. }
  9083. case types.relational:
  9084. {
  9085. if (this.state.value === "<") {
  9086. const lookaheadCh = this.input.codePointAt(this.nextTokenStart());
  9087. if (isIdentifierStart(lookaheadCh) || lookaheadCh === 62) {
  9088. this.expectOnePlugin(["jsx", "flow", "typescript"]);
  9089. }
  9090. }
  9091. }
  9092. default:
  9093. throw this.unexpected();
  9094. }
  9095. }
  9096. parseAsyncArrowUnaryFunction(id) {
  9097. const node = this.startNodeAtNode(id);
  9098. this.prodParam.enter(functionFlags(true, this.prodParam.hasYield));
  9099. const params = [this.parseIdentifier()];
  9100. this.prodParam.exit();
  9101. if (this.hasPrecedingLineBreak()) {
  9102. this.raise(this.state.pos, ErrorMessages.LineTerminatorBeforeArrow);
  9103. }
  9104. this.expect(types.arrow);
  9105. this.parseArrowExpression(node, params, true);
  9106. return node;
  9107. }
  9108. parseDo() {
  9109. this.expectPlugin("doExpressions");
  9110. const node = this.startNode();
  9111. this.next();
  9112. const oldLabels = this.state.labels;
  9113. this.state.labels = [];
  9114. node.body = this.parseBlock();
  9115. this.state.labels = oldLabels;
  9116. return this.finishNode(node, "DoExpression");
  9117. }
  9118. parseSuper() {
  9119. const node = this.startNode();
  9120. this.next();
  9121. if (this.match(types.parenL) && !this.scope.allowDirectSuper && !this.options.allowSuperOutsideMethod) {
  9122. this.raise(node.start, ErrorMessages.SuperNotAllowed);
  9123. } else if (!this.scope.allowSuper && !this.options.allowSuperOutsideMethod) {
  9124. this.raise(node.start, ErrorMessages.UnexpectedSuper);
  9125. }
  9126. if (!this.match(types.parenL) && !this.match(types.bracketL) && !this.match(types.dot)) {
  9127. this.raise(node.start, ErrorMessages.UnsupportedSuper);
  9128. }
  9129. return this.finishNode(node, "Super");
  9130. }
  9131. parseBooleanLiteral() {
  9132. const node = this.startNode();
  9133. node.value = this.match(types._true);
  9134. this.next();
  9135. return this.finishNode(node, "BooleanLiteral");
  9136. }
  9137. parseMaybePrivateName(isPrivateNameAllowed) {
  9138. const isPrivate = this.match(types.hash);
  9139. if (isPrivate) {
  9140. this.expectOnePlugin(["classPrivateProperties", "classPrivateMethods"]);
  9141. if (!isPrivateNameAllowed) {
  9142. this.raise(this.state.pos, ErrorMessages.UnexpectedPrivateField);
  9143. }
  9144. const node = this.startNode();
  9145. this.next();
  9146. this.assertNoSpace("Unexpected space between # and identifier");
  9147. node.id = this.parseIdentifier(true);
  9148. return this.finishNode(node, "PrivateName");
  9149. } else {
  9150. return this.parseIdentifier(true);
  9151. }
  9152. }
  9153. parseFunctionOrFunctionSent() {
  9154. const node = this.startNode();
  9155. this.next();
  9156. if (this.prodParam.hasYield && this.match(types.dot)) {
  9157. const meta = this.createIdentifier(this.startNodeAtNode(node), "function");
  9158. this.next();
  9159. return this.parseMetaProperty(node, meta, "sent");
  9160. }
  9161. return this.parseFunction(node);
  9162. }
  9163. parseMetaProperty(node, meta, propertyName) {
  9164. node.meta = meta;
  9165. if (meta.name === "function" && propertyName === "sent") {
  9166. if (this.isContextual(propertyName)) {
  9167. this.expectPlugin("functionSent");
  9168. } else if (!this.hasPlugin("functionSent")) {
  9169. this.unexpected();
  9170. }
  9171. }
  9172. const containsEsc = this.state.containsEsc;
  9173. node.property = this.parseIdentifier(true);
  9174. if (node.property.name !== propertyName || containsEsc) {
  9175. this.raise(node.property.start, ErrorMessages.UnsupportedMetaProperty, meta.name, propertyName);
  9176. }
  9177. return this.finishNode(node, "MetaProperty");
  9178. }
  9179. parseImportMetaProperty(node) {
  9180. const id = this.createIdentifier(this.startNodeAtNode(node), "import");
  9181. this.next();
  9182. if (this.isContextual("meta")) {
  9183. if (!this.inModule) {
  9184. this.raiseWithData(id.start, {
  9185. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  9186. }, ErrorMessages.ImportMetaOutsideModule);
  9187. }
  9188. this.sawUnambiguousESM = true;
  9189. }
  9190. return this.parseMetaProperty(node, id, "meta");
  9191. }
  9192. parseLiteral(value, type, startPos, startLoc) {
  9193. startPos = startPos || this.state.start;
  9194. startLoc = startLoc || this.state.startLoc;
  9195. const node = this.startNodeAt(startPos, startLoc);
  9196. this.addExtra(node, "rawValue", value);
  9197. this.addExtra(node, "raw", this.input.slice(startPos, this.state.end));
  9198. node.value = value;
  9199. this.next();
  9200. return this.finishNode(node, type);
  9201. }
  9202. parseParenAndDistinguishExpression(canBeArrow) {
  9203. const startPos = this.state.start;
  9204. const startLoc = this.state.startLoc;
  9205. let val;
  9206. this.next();
  9207. this.expressionScope.enter(newArrowHeadScope());
  9208. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9209. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9210. this.state.maybeInArrowParameters = true;
  9211. this.state.inFSharpPipelineDirectBody = false;
  9212. const innerStartPos = this.state.start;
  9213. const innerStartLoc = this.state.startLoc;
  9214. const exprList = [];
  9215. const refExpressionErrors = new ExpressionErrors();
  9216. const refNeedsArrowPos = {
  9217. start: 0
  9218. };
  9219. let first = true;
  9220. let spreadStart;
  9221. let optionalCommaStart;
  9222. while (!this.match(types.parenR)) {
  9223. if (first) {
  9224. first = false;
  9225. } else {
  9226. this.expect(types.comma, refNeedsArrowPos.start || null);
  9227. if (this.match(types.parenR)) {
  9228. optionalCommaStart = this.state.start;
  9229. break;
  9230. }
  9231. }
  9232. if (this.match(types.ellipsis)) {
  9233. const spreadNodeStartPos = this.state.start;
  9234. const spreadNodeStartLoc = this.state.startLoc;
  9235. spreadStart = this.state.start;
  9236. exprList.push(this.parseParenItem(this.parseRestBinding(), spreadNodeStartPos, spreadNodeStartLoc));
  9237. this.checkCommaAfterRest(41);
  9238. break;
  9239. } else {
  9240. exprList.push(this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos));
  9241. }
  9242. }
  9243. const innerEndPos = this.state.lastTokEnd;
  9244. const innerEndLoc = this.state.lastTokEndLoc;
  9245. this.expect(types.parenR);
  9246. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9247. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9248. let arrowNode = this.startNodeAt(startPos, startLoc);
  9249. if (canBeArrow && this.shouldParseArrow() && (arrowNode = this.parseArrow(arrowNode))) {
  9250. this.expressionScope.validateAsPattern();
  9251. this.expressionScope.exit();
  9252. this.parseArrowExpression(arrowNode, exprList, false);
  9253. return arrowNode;
  9254. }
  9255. this.expressionScope.exit();
  9256. if (!exprList.length) {
  9257. this.unexpected(this.state.lastTokStart);
  9258. }
  9259. if (optionalCommaStart) this.unexpected(optionalCommaStart);
  9260. if (spreadStart) this.unexpected(spreadStart);
  9261. this.checkExpressionErrors(refExpressionErrors, true);
  9262. if (refNeedsArrowPos.start) this.unexpected(refNeedsArrowPos.start);
  9263. this.toReferencedListDeep(exprList, true);
  9264. if (exprList.length > 1) {
  9265. val = this.startNodeAt(innerStartPos, innerStartLoc);
  9266. val.expressions = exprList;
  9267. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  9268. } else {
  9269. val = exprList[0];
  9270. }
  9271. if (!this.options.createParenthesizedExpressions) {
  9272. this.addExtra(val, "parenthesized", true);
  9273. this.addExtra(val, "parenStart", startPos);
  9274. return val;
  9275. }
  9276. const parenExpression = this.startNodeAt(startPos, startLoc);
  9277. parenExpression.expression = val;
  9278. this.finishNode(parenExpression, "ParenthesizedExpression");
  9279. return parenExpression;
  9280. }
  9281. shouldParseArrow() {
  9282. return !this.canInsertSemicolon();
  9283. }
  9284. parseArrow(node) {
  9285. if (this.eat(types.arrow)) {
  9286. return node;
  9287. }
  9288. }
  9289. parseParenItem(node, startPos, startLoc) {
  9290. return node;
  9291. }
  9292. parseNewOrNewTarget() {
  9293. const node = this.startNode();
  9294. this.next();
  9295. if (this.match(types.dot)) {
  9296. const meta = this.createIdentifier(this.startNodeAtNode(node), "new");
  9297. this.next();
  9298. const metaProp = this.parseMetaProperty(node, meta, "target");
  9299. if (!this.scope.inNonArrowFunction && !this.scope.inClass) {
  9300. let error = ErrorMessages.UnexpectedNewTarget;
  9301. if (this.hasPlugin("classProperties")) {
  9302. error += " or class properties";
  9303. }
  9304. this.raise(metaProp.start, error);
  9305. }
  9306. return metaProp;
  9307. }
  9308. return this.parseNew(node);
  9309. }
  9310. parseNew(node) {
  9311. node.callee = this.parseNoCallExpr();
  9312. if (node.callee.type === "Import") {
  9313. this.raise(node.callee.start, ErrorMessages.ImportCallNotNewExpression);
  9314. } else if (this.isOptionalChain(node.callee)) {
  9315. this.raise(this.state.lastTokEnd, ErrorMessages.OptionalChainingNoNew);
  9316. } else if (this.eat(types.questionDot)) {
  9317. this.raise(this.state.start, ErrorMessages.OptionalChainingNoNew);
  9318. }
  9319. this.parseNewArguments(node);
  9320. return this.finishNode(node, "NewExpression");
  9321. }
  9322. parseNewArguments(node) {
  9323. if (this.eat(types.parenL)) {
  9324. const args = this.parseExprList(types.parenR);
  9325. this.toReferencedList(args);
  9326. node.arguments = args;
  9327. } else {
  9328. node.arguments = [];
  9329. }
  9330. }
  9331. parseTemplateElement(isTagged) {
  9332. const elem = this.startNode();
  9333. if (this.state.value === null) {
  9334. if (!isTagged) {
  9335. this.raise(this.state.start + 1, ErrorMessages.InvalidEscapeSequenceTemplate);
  9336. }
  9337. }
  9338. elem.value = {
  9339. raw: this.input.slice(this.state.start, this.state.end).replace(/\r\n?/g, "\n"),
  9340. cooked: this.state.value
  9341. };
  9342. this.next();
  9343. elem.tail = this.match(types.backQuote);
  9344. return this.finishNode(elem, "TemplateElement");
  9345. }
  9346. parseTemplate(isTagged) {
  9347. const node = this.startNode();
  9348. this.next();
  9349. node.expressions = [];
  9350. let curElt = this.parseTemplateElement(isTagged);
  9351. node.quasis = [curElt];
  9352. while (!curElt.tail) {
  9353. this.expect(types.dollarBraceL);
  9354. node.expressions.push(this.parseTemplateSubstitution());
  9355. this.expect(types.braceR);
  9356. node.quasis.push(curElt = this.parseTemplateElement(isTagged));
  9357. }
  9358. this.next();
  9359. return this.finishNode(node, "TemplateLiteral");
  9360. }
  9361. parseTemplateSubstitution() {
  9362. return this.parseExpression();
  9363. }
  9364. parseObjectLike(close, isPattern, isRecord, refExpressionErrors) {
  9365. if (isRecord) {
  9366. this.expectPlugin("recordAndTuple");
  9367. }
  9368. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9369. this.state.inFSharpPipelineDirectBody = false;
  9370. const propHash = Object.create(null);
  9371. let first = true;
  9372. const node = this.startNode();
  9373. node.properties = [];
  9374. this.next();
  9375. while (!this.match(close)) {
  9376. if (first) {
  9377. first = false;
  9378. } else {
  9379. this.expect(types.comma);
  9380. if (this.match(close)) {
  9381. this.addExtra(node, "trailingComma", this.state.lastTokStart);
  9382. break;
  9383. }
  9384. }
  9385. const prop = this.parsePropertyDefinition(isPattern, refExpressionErrors);
  9386. if (!isPattern) {
  9387. this.checkProto(prop, isRecord, propHash, refExpressionErrors);
  9388. }
  9389. if (isRecord && !this.isObjectProperty(prop) && prop.type !== "SpreadElement") {
  9390. this.raise(prop.start, ErrorMessages.InvalidRecordProperty);
  9391. }
  9392. if (prop.shorthand) {
  9393. this.addExtra(prop, "shorthand", true);
  9394. }
  9395. node.properties.push(prop);
  9396. }
  9397. this.state.exprAllowed = false;
  9398. this.next();
  9399. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9400. let type = "ObjectExpression";
  9401. if (isPattern) {
  9402. type = "ObjectPattern";
  9403. } else if (isRecord) {
  9404. type = "RecordExpression";
  9405. }
  9406. return this.finishNode(node, type);
  9407. }
  9408. maybeAsyncOrAccessorProp(prop) {
  9409. return !prop.computed && prop.key.type === "Identifier" && (this.isLiteralPropertyName() || this.match(types.bracketL) || this.match(types.star));
  9410. }
  9411. parsePropertyDefinition(isPattern, refExpressionErrors) {
  9412. let decorators = [];
  9413. if (this.match(types.at)) {
  9414. if (this.hasPlugin("decorators")) {
  9415. this.raise(this.state.start, ErrorMessages.UnsupportedPropertyDecorator);
  9416. }
  9417. while (this.match(types.at)) {
  9418. decorators.push(this.parseDecorator());
  9419. }
  9420. }
  9421. const prop = this.startNode();
  9422. let isGenerator = false;
  9423. let isAsync = false;
  9424. let isAccessor = false;
  9425. let startPos;
  9426. let startLoc;
  9427. if (this.match(types.ellipsis)) {
  9428. if (decorators.length) this.unexpected();
  9429. if (isPattern) {
  9430. this.next();
  9431. prop.argument = this.parseIdentifier();
  9432. this.checkCommaAfterRest(125);
  9433. return this.finishNode(prop, "RestElement");
  9434. }
  9435. return this.parseSpread();
  9436. }
  9437. if (decorators.length) {
  9438. prop.decorators = decorators;
  9439. decorators = [];
  9440. }
  9441. prop.method = false;
  9442. if (isPattern || refExpressionErrors) {
  9443. startPos = this.state.start;
  9444. startLoc = this.state.startLoc;
  9445. }
  9446. if (!isPattern) {
  9447. isGenerator = this.eat(types.star);
  9448. }
  9449. const containsEsc = this.state.containsEsc;
  9450. const key = this.parsePropertyName(prop, false);
  9451. if (!isPattern && !isGenerator && !containsEsc && this.maybeAsyncOrAccessorProp(prop)) {
  9452. const keyName = key.name;
  9453. if (keyName === "async" && !this.hasPrecedingLineBreak()) {
  9454. isAsync = true;
  9455. isGenerator = this.eat(types.star);
  9456. this.parsePropertyName(prop, false);
  9457. }
  9458. if (keyName === "get" || keyName === "set") {
  9459. isAccessor = true;
  9460. prop.kind = keyName;
  9461. if (this.match(types.star)) {
  9462. isGenerator = true;
  9463. this.raise(this.state.pos, ErrorMessages.AccessorIsGenerator, keyName);
  9464. this.next();
  9465. }
  9466. this.parsePropertyName(prop, false);
  9467. }
  9468. }
  9469. this.parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors);
  9470. return prop;
  9471. }
  9472. getGetterSetterExpectedParamCount(method) {
  9473. return method.kind === "get" ? 0 : 1;
  9474. }
  9475. getObjectOrClassMethodParams(method) {
  9476. return method.params;
  9477. }
  9478. checkGetterSetterParams(method) {
  9479. var _params;
  9480. const paramCount = this.getGetterSetterExpectedParamCount(method);
  9481. const params = this.getObjectOrClassMethodParams(method);
  9482. const start = method.start;
  9483. if (params.length !== paramCount) {
  9484. if (method.kind === "get") {
  9485. this.raise(start, ErrorMessages.BadGetterArity);
  9486. } else {
  9487. this.raise(start, ErrorMessages.BadSetterArity);
  9488. }
  9489. }
  9490. if (method.kind === "set" && ((_params = params[params.length - 1]) == null ? void 0 : _params.type) === "RestElement") {
  9491. this.raise(start, ErrorMessages.BadSetterRestParameter);
  9492. }
  9493. }
  9494. parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) {
  9495. if (isAccessor) {
  9496. this.parseMethod(prop, isGenerator, false, false, false, "ObjectMethod");
  9497. this.checkGetterSetterParams(prop);
  9498. return prop;
  9499. }
  9500. if (isAsync || isGenerator || this.match(types.parenL)) {
  9501. if (isPattern) this.unexpected();
  9502. prop.kind = "method";
  9503. prop.method = true;
  9504. return this.parseMethod(prop, isGenerator, isAsync, false, false, "ObjectMethod");
  9505. }
  9506. }
  9507. parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors) {
  9508. prop.shorthand = false;
  9509. if (this.eat(types.colon)) {
  9510. prop.value = isPattern ? this.parseMaybeDefault(this.state.start, this.state.startLoc) : this.parseMaybeAssignAllowIn(refExpressionErrors);
  9511. return this.finishNode(prop, "ObjectProperty");
  9512. }
  9513. if (!prop.computed && prop.key.type === "Identifier") {
  9514. this.checkReservedWord(prop.key.name, prop.key.start, true, false);
  9515. if (isPattern) {
  9516. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9517. } else if (this.match(types.eq) && refExpressionErrors) {
  9518. if (refExpressionErrors.shorthandAssign === -1) {
  9519. refExpressionErrors.shorthandAssign = this.state.start;
  9520. }
  9521. prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key.__clone());
  9522. } else {
  9523. prop.value = prop.key.__clone();
  9524. }
  9525. prop.shorthand = true;
  9526. return this.finishNode(prop, "ObjectProperty");
  9527. }
  9528. }
  9529. parseObjPropValue(prop, startPos, startLoc, isGenerator, isAsync, isPattern, isAccessor, refExpressionErrors) {
  9530. const node = this.parseObjectMethod(prop, isGenerator, isAsync, isPattern, isAccessor) || this.parseObjectProperty(prop, startPos, startLoc, isPattern, refExpressionErrors);
  9531. if (!node) this.unexpected();
  9532. return node;
  9533. }
  9534. parsePropertyName(prop, isPrivateNameAllowed) {
  9535. if (this.eat(types.bracketL)) {
  9536. prop.computed = true;
  9537. prop.key = this.parseMaybeAssignAllowIn();
  9538. this.expect(types.bracketR);
  9539. } else {
  9540. const oldInPropertyName = this.state.inPropertyName;
  9541. this.state.inPropertyName = true;
  9542. prop.key = this.match(types.num) || this.match(types.string) || this.match(types.bigint) || this.match(types.decimal) ? this.parseExprAtom() : this.parseMaybePrivateName(isPrivateNameAllowed);
  9543. if (!this.isPrivateName(prop.key)) {
  9544. prop.computed = false;
  9545. }
  9546. this.state.inPropertyName = oldInPropertyName;
  9547. }
  9548. return prop.key;
  9549. }
  9550. initFunction(node, isAsync) {
  9551. node.id = null;
  9552. node.generator = false;
  9553. node.async = !!isAsync;
  9554. }
  9555. parseMethod(node, isGenerator, isAsync, isConstructor, allowDirectSuper, type, inClassScope = false) {
  9556. this.initFunction(node, isAsync);
  9557. node.generator = !!isGenerator;
  9558. const allowModifiers = isConstructor;
  9559. this.scope.enter(SCOPE_FUNCTION | SCOPE_SUPER | (inClassScope ? SCOPE_CLASS : 0) | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  9560. this.prodParam.enter(functionFlags(isAsync, node.generator));
  9561. this.parseFunctionParams(node, allowModifiers);
  9562. this.parseFunctionBodyAndFinish(node, type, true);
  9563. this.prodParam.exit();
  9564. this.scope.exit();
  9565. return node;
  9566. }
  9567. parseArrayLike(close, canBePattern, isTuple, refExpressionErrors) {
  9568. if (isTuple) {
  9569. this.expectPlugin("recordAndTuple");
  9570. }
  9571. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9572. this.state.inFSharpPipelineDirectBody = false;
  9573. const node = this.startNode();
  9574. this.next();
  9575. node.elements = this.parseExprList(close, !isTuple, refExpressionErrors, node);
  9576. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9577. return this.finishNode(node, isTuple ? "TupleExpression" : "ArrayExpression");
  9578. }
  9579. parseArrowExpression(node, params, isAsync, trailingCommaPos) {
  9580. this.scope.enter(SCOPE_FUNCTION | SCOPE_ARROW);
  9581. let flags = functionFlags(isAsync, false);
  9582. if (!this.match(types.bracketL) && this.prodParam.hasIn) {
  9583. flags |= PARAM_IN;
  9584. }
  9585. this.prodParam.enter(flags);
  9586. this.initFunction(node, isAsync);
  9587. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  9588. if (params) {
  9589. this.state.maybeInArrowParameters = true;
  9590. this.setArrowFunctionParameters(node, params, trailingCommaPos);
  9591. }
  9592. this.state.maybeInArrowParameters = false;
  9593. this.parseFunctionBody(node, true);
  9594. this.prodParam.exit();
  9595. this.scope.exit();
  9596. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  9597. return this.finishNode(node, "ArrowFunctionExpression");
  9598. }
  9599. setArrowFunctionParameters(node, params, trailingCommaPos) {
  9600. node.params = this.toAssignableList(params, trailingCommaPos, false);
  9601. }
  9602. parseFunctionBodyAndFinish(node, type, isMethod = false) {
  9603. this.parseFunctionBody(node, false, isMethod);
  9604. this.finishNode(node, type);
  9605. }
  9606. parseFunctionBody(node, allowExpression, isMethod = false) {
  9607. const isExpression = allowExpression && !this.match(types.braceL);
  9608. this.expressionScope.enter(newExpressionScope());
  9609. if (isExpression) {
  9610. node.body = this.parseMaybeAssign();
  9611. this.checkParams(node, false, allowExpression, false);
  9612. } else {
  9613. const oldStrict = this.state.strict;
  9614. const oldLabels = this.state.labels;
  9615. this.state.labels = [];
  9616. this.prodParam.enter(this.prodParam.currentFlags() | PARAM_RETURN);
  9617. node.body = this.parseBlock(true, false, hasStrictModeDirective => {
  9618. const nonSimple = !this.isSimpleParamList(node.params);
  9619. if (hasStrictModeDirective && nonSimple) {
  9620. const errorPos = (node.kind === "method" || node.kind === "constructor") && !!node.key ? node.key.end : node.start;
  9621. this.raise(errorPos, ErrorMessages.IllegalLanguageModeDirective);
  9622. }
  9623. const strictModeChanged = !oldStrict && this.state.strict;
  9624. this.checkParams(node, !this.state.strict && !allowExpression && !isMethod && !nonSimple, allowExpression, strictModeChanged);
  9625. if (this.state.strict && node.id) {
  9626. this.checkLVal(node.id, "function name", BIND_OUTSIDE, undefined, undefined, strictModeChanged);
  9627. }
  9628. });
  9629. this.prodParam.exit();
  9630. this.expressionScope.exit();
  9631. this.state.labels = oldLabels;
  9632. }
  9633. }
  9634. isSimpleParamList(params) {
  9635. for (let i = 0, len = params.length; i < len; i++) {
  9636. if (params[i].type !== "Identifier") return false;
  9637. }
  9638. return true;
  9639. }
  9640. checkParams(node, allowDuplicates, isArrowFunction, strictModeChanged = true) {
  9641. const checkClashes = new Set();
  9642. for (const param of node.params) {
  9643. this.checkLVal(param, "function parameter list", BIND_VAR, allowDuplicates ? null : checkClashes, undefined, strictModeChanged);
  9644. }
  9645. }
  9646. parseExprList(close, allowEmpty, refExpressionErrors, nodeForExtra) {
  9647. const elts = [];
  9648. let first = true;
  9649. while (!this.eat(close)) {
  9650. if (first) {
  9651. first = false;
  9652. } else {
  9653. this.expect(types.comma);
  9654. if (this.match(close)) {
  9655. if (nodeForExtra) {
  9656. this.addExtra(nodeForExtra, "trailingComma", this.state.lastTokStart);
  9657. }
  9658. this.next();
  9659. break;
  9660. }
  9661. }
  9662. elts.push(this.parseExprListItem(allowEmpty, refExpressionErrors));
  9663. }
  9664. return elts;
  9665. }
  9666. parseExprListItem(allowEmpty, refExpressionErrors, refNeedsArrowPos, allowPlaceholder) {
  9667. let elt;
  9668. if (this.match(types.comma)) {
  9669. if (!allowEmpty) {
  9670. this.raise(this.state.pos, ErrorMessages.UnexpectedToken, ",");
  9671. }
  9672. elt = null;
  9673. } else if (this.match(types.ellipsis)) {
  9674. const spreadNodeStartPos = this.state.start;
  9675. const spreadNodeStartLoc = this.state.startLoc;
  9676. elt = this.parseParenItem(this.parseSpread(refExpressionErrors, refNeedsArrowPos), spreadNodeStartPos, spreadNodeStartLoc);
  9677. } else if (this.match(types.question)) {
  9678. this.expectPlugin("partialApplication");
  9679. if (!allowPlaceholder) {
  9680. this.raise(this.state.start, ErrorMessages.UnexpectedArgumentPlaceholder);
  9681. }
  9682. const node = this.startNode();
  9683. this.next();
  9684. elt = this.finishNode(node, "ArgumentPlaceholder");
  9685. } else {
  9686. elt = this.parseMaybeAssignAllowIn(refExpressionErrors, this.parseParenItem, refNeedsArrowPos);
  9687. }
  9688. return elt;
  9689. }
  9690. parseIdentifier(liberal) {
  9691. const node = this.startNode();
  9692. const name = this.parseIdentifierName(node.start, liberal);
  9693. return this.createIdentifier(node, name);
  9694. }
  9695. createIdentifier(node, name) {
  9696. node.name = name;
  9697. node.loc.identifierName = name;
  9698. return this.finishNode(node, "Identifier");
  9699. }
  9700. parseIdentifierName(pos, liberal) {
  9701. let name;
  9702. const {
  9703. start,
  9704. type
  9705. } = this.state;
  9706. if (type === types.name) {
  9707. name = this.state.value;
  9708. } else if (type.keyword) {
  9709. name = type.keyword;
  9710. const curContext = this.curContext();
  9711. if ((type === types._class || type === types._function) && (curContext === types$1.functionStatement || curContext === types$1.functionExpression)) {
  9712. this.state.context.pop();
  9713. }
  9714. } else {
  9715. throw this.unexpected();
  9716. }
  9717. if (liberal) {
  9718. this.state.type = types.name;
  9719. } else {
  9720. this.checkReservedWord(name, start, !!type.keyword, false);
  9721. }
  9722. this.next();
  9723. return name;
  9724. }
  9725. checkReservedWord(word, startLoc, checkKeywords, isBinding) {
  9726. if (this.prodParam.hasYield && word === "yield") {
  9727. this.raise(startLoc, ErrorMessages.YieldBindingIdentifier);
  9728. return;
  9729. }
  9730. if (word === "await") {
  9731. if (this.prodParam.hasAwait) {
  9732. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9733. return;
  9734. } else if (this.scope.inStaticBlock && !this.scope.inNonArrowFunction) {
  9735. this.raise(startLoc, ErrorMessages.AwaitBindingIdentifierInStaticBlock);
  9736. return;
  9737. } else {
  9738. this.expressionScope.recordAsyncArrowParametersError(startLoc, ErrorMessages.AwaitBindingIdentifier);
  9739. }
  9740. }
  9741. if (this.scope.inClass && !this.scope.inNonArrowFunction && word === "arguments") {
  9742. this.raise(startLoc, ErrorMessages.ArgumentsInClass);
  9743. return;
  9744. }
  9745. if (checkKeywords && isKeyword(word)) {
  9746. this.raise(startLoc, ErrorMessages.UnexpectedKeyword, word);
  9747. return;
  9748. }
  9749. const reservedTest = !this.state.strict ? isReservedWord : isBinding ? isStrictBindReservedWord : isStrictReservedWord;
  9750. if (reservedTest(word, this.inModule)) {
  9751. this.raise(startLoc, ErrorMessages.UnexpectedReservedWord, word);
  9752. }
  9753. }
  9754. isAwaitAllowed() {
  9755. if (this.prodParam.hasAwait) return true;
  9756. if (this.options.allowAwaitOutsideFunction && !this.scope.inFunction) {
  9757. return true;
  9758. }
  9759. return false;
  9760. }
  9761. parseAwait(startPos, startLoc) {
  9762. const node = this.startNodeAt(startPos, startLoc);
  9763. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.AwaitExpressionFormalParameter);
  9764. if (this.eat(types.star)) {
  9765. this.raise(node.start, ErrorMessages.ObsoleteAwaitStar);
  9766. }
  9767. if (!this.scope.inFunction && !this.options.allowAwaitOutsideFunction) {
  9768. if (this.isAmbiguousAwait()) {
  9769. this.ambiguousScriptDifferentAst = true;
  9770. } else {
  9771. this.sawUnambiguousESM = true;
  9772. }
  9773. }
  9774. if (!this.state.soloAwait) {
  9775. node.argument = this.parseMaybeUnary(null, true);
  9776. }
  9777. return this.finishNode(node, "AwaitExpression");
  9778. }
  9779. isAmbiguousAwait() {
  9780. return this.hasPrecedingLineBreak() || this.match(types.plusMin) || this.match(types.parenL) || this.match(types.bracketL) || this.match(types.backQuote) || this.match(types.regexp) || this.match(types.slash) || this.hasPlugin("v8intrinsic") && this.match(types.modulo);
  9781. }
  9782. parseYield() {
  9783. const node = this.startNode();
  9784. this.expressionScope.recordParameterInitializerError(node.start, ErrorMessages.YieldInParameter);
  9785. this.next();
  9786. if (this.match(types.semi) || !this.match(types.star) && !this.state.type.startsExpr || this.hasPrecedingLineBreak()) {
  9787. node.delegate = false;
  9788. node.argument = null;
  9789. } else {
  9790. node.delegate = this.eat(types.star);
  9791. node.argument = this.parseMaybeAssign();
  9792. }
  9793. return this.finishNode(node, "YieldExpression");
  9794. }
  9795. checkPipelineAtInfixOperator(left, leftStartPos) {
  9796. if (this.getPluginOption("pipelineOperator", "proposal") === "smart") {
  9797. if (left.type === "SequenceExpression") {
  9798. this.raise(leftStartPos, ErrorMessages.PipelineHeadSequenceExpression);
  9799. }
  9800. }
  9801. }
  9802. parseSmartPipelineBody(childExpression, startPos, startLoc) {
  9803. this.checkSmartPipelineBodyEarlyErrors(childExpression, startPos);
  9804. return this.parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc);
  9805. }
  9806. checkSmartPipelineBodyEarlyErrors(childExpression, startPos) {
  9807. if (this.match(types.arrow)) {
  9808. throw this.raise(this.state.start, ErrorMessages.PipelineBodyNoArrow);
  9809. } else if (childExpression.type === "SequenceExpression") {
  9810. this.raise(startPos, ErrorMessages.PipelineBodySequenceExpression);
  9811. }
  9812. }
  9813. parseSmartPipelineBodyInStyle(childExpression, startPos, startLoc) {
  9814. const bodyNode = this.startNodeAt(startPos, startLoc);
  9815. const isSimpleReference = this.isSimpleReference(childExpression);
  9816. if (isSimpleReference) {
  9817. bodyNode.callee = childExpression;
  9818. } else {
  9819. if (!this.topicReferenceWasUsedInCurrentTopicContext()) {
  9820. this.raise(startPos, ErrorMessages.PipelineTopicUnused);
  9821. }
  9822. bodyNode.expression = childExpression;
  9823. }
  9824. return this.finishNode(bodyNode, isSimpleReference ? "PipelineBareFunction" : "PipelineTopicExpression");
  9825. }
  9826. isSimpleReference(expression) {
  9827. switch (expression.type) {
  9828. case "MemberExpression":
  9829. return !expression.computed && this.isSimpleReference(expression.object);
  9830. case "Identifier":
  9831. return true;
  9832. default:
  9833. return false;
  9834. }
  9835. }
  9836. withTopicPermittingContext(callback) {
  9837. const outerContextTopicState = this.state.topicContext;
  9838. this.state.topicContext = {
  9839. maxNumOfResolvableTopics: 1,
  9840. maxTopicIndex: null
  9841. };
  9842. try {
  9843. return callback();
  9844. } finally {
  9845. this.state.topicContext = outerContextTopicState;
  9846. }
  9847. }
  9848. withTopicForbiddingContext(callback) {
  9849. const outerContextTopicState = this.state.topicContext;
  9850. this.state.topicContext = {
  9851. maxNumOfResolvableTopics: 0,
  9852. maxTopicIndex: null
  9853. };
  9854. try {
  9855. return callback();
  9856. } finally {
  9857. this.state.topicContext = outerContextTopicState;
  9858. }
  9859. }
  9860. withSoloAwaitPermittingContext(callback) {
  9861. const outerContextSoloAwaitState = this.state.soloAwait;
  9862. this.state.soloAwait = true;
  9863. try {
  9864. return callback();
  9865. } finally {
  9866. this.state.soloAwait = outerContextSoloAwaitState;
  9867. }
  9868. }
  9869. allowInAnd(callback) {
  9870. const flags = this.prodParam.currentFlags();
  9871. const prodParamToSet = PARAM_IN & ~flags;
  9872. if (prodParamToSet) {
  9873. this.prodParam.enter(flags | PARAM_IN);
  9874. try {
  9875. return callback();
  9876. } finally {
  9877. this.prodParam.exit();
  9878. }
  9879. }
  9880. return callback();
  9881. }
  9882. disallowInAnd(callback) {
  9883. const flags = this.prodParam.currentFlags();
  9884. const prodParamToClear = PARAM_IN & flags;
  9885. if (prodParamToClear) {
  9886. this.prodParam.enter(flags & ~PARAM_IN);
  9887. try {
  9888. return callback();
  9889. } finally {
  9890. this.prodParam.exit();
  9891. }
  9892. }
  9893. return callback();
  9894. }
  9895. registerTopicReference() {
  9896. this.state.topicContext.maxTopicIndex = 0;
  9897. }
  9898. primaryTopicReferenceIsAllowedInCurrentTopicContext() {
  9899. return this.state.topicContext.maxNumOfResolvableTopics >= 1;
  9900. }
  9901. topicReferenceWasUsedInCurrentTopicContext() {
  9902. return this.state.topicContext.maxTopicIndex != null && this.state.topicContext.maxTopicIndex >= 0;
  9903. }
  9904. parseFSharpPipelineBody(prec) {
  9905. const startPos = this.state.start;
  9906. const startLoc = this.state.startLoc;
  9907. this.state.potentialArrowAt = this.state.start;
  9908. const oldInFSharpPipelineDirectBody = this.state.inFSharpPipelineDirectBody;
  9909. this.state.inFSharpPipelineDirectBody = true;
  9910. const ret = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec);
  9911. this.state.inFSharpPipelineDirectBody = oldInFSharpPipelineDirectBody;
  9912. return ret;
  9913. }
  9914. parseModuleExpression() {
  9915. this.expectPlugin("moduleBlocks");
  9916. const node = this.startNode();
  9917. this.next();
  9918. this.eat(types.braceL);
  9919. const revertScopes = this.initializeScopes(true);
  9920. this.enterInitialScopes();
  9921. const program = this.startNode();
  9922. try {
  9923. node.body = this.parseProgram(program, types.braceR, "module");
  9924. } finally {
  9925. revertScopes();
  9926. }
  9927. this.eat(types.braceR);
  9928. return this.finishNode(node, "ModuleExpression");
  9929. }
  9930. }
  9931. const loopLabel = {
  9932. kind: "loop"
  9933. },
  9934. switchLabel = {
  9935. kind: "switch"
  9936. };
  9937. const FUNC_NO_FLAGS = 0b000,
  9938. FUNC_STATEMENT = 0b001,
  9939. FUNC_HANGING_STATEMENT = 0b010,
  9940. FUNC_NULLABLE_ID = 0b100;
  9941. const loneSurrogate = /[\uD800-\uDFFF]/u;
  9942. class StatementParser extends ExpressionParser {
  9943. parseTopLevel(file, program) {
  9944. file.program = this.parseProgram(program);
  9945. file.comments = this.state.comments;
  9946. if (this.options.tokens) file.tokens = this.tokens;
  9947. return this.finishNode(file, "File");
  9948. }
  9949. parseProgram(program, end = types.eof, sourceType = this.options.sourceType) {
  9950. program.sourceType = sourceType;
  9951. program.interpreter = this.parseInterpreterDirective();
  9952. this.parseBlockBody(program, true, true, end);
  9953. if (this.inModule && !this.options.allowUndeclaredExports && this.scope.undefinedExports.size > 0) {
  9954. for (const [name] of Array.from(this.scope.undefinedExports)) {
  9955. const pos = this.scope.undefinedExports.get(name);
  9956. this.raise(pos, ErrorMessages.ModuleExportUndefined, name);
  9957. }
  9958. }
  9959. return this.finishNode(program, "Program");
  9960. }
  9961. stmtToDirective(stmt) {
  9962. const expr = stmt.expression;
  9963. const directiveLiteral = this.startNodeAt(expr.start, expr.loc.start);
  9964. const directive = this.startNodeAt(stmt.start, stmt.loc.start);
  9965. const raw = this.input.slice(expr.start, expr.end);
  9966. const val = directiveLiteral.value = raw.slice(1, -1);
  9967. this.addExtra(directiveLiteral, "raw", raw);
  9968. this.addExtra(directiveLiteral, "rawValue", val);
  9969. directive.value = this.finishNodeAt(directiveLiteral, "DirectiveLiteral", expr.end, expr.loc.end);
  9970. return this.finishNodeAt(directive, "Directive", stmt.end, stmt.loc.end);
  9971. }
  9972. parseInterpreterDirective() {
  9973. if (!this.match(types.interpreterDirective)) {
  9974. return null;
  9975. }
  9976. const node = this.startNode();
  9977. node.value = this.state.value;
  9978. this.next();
  9979. return this.finishNode(node, "InterpreterDirective");
  9980. }
  9981. isLet(context) {
  9982. if (!this.isContextual("let")) {
  9983. return false;
  9984. }
  9985. return this.isLetKeyword(context);
  9986. }
  9987. isLetKeyword(context) {
  9988. const next = this.nextTokenStart();
  9989. const nextCh = this.input.charCodeAt(next);
  9990. if (nextCh === 91) return true;
  9991. if (context) return false;
  9992. if (nextCh === 123) return true;
  9993. if (isIdentifierStart(nextCh)) {
  9994. let pos = next + 1;
  9995. while (isIdentifierChar(this.input.charCodeAt(pos))) {
  9996. ++pos;
  9997. }
  9998. const ident = this.input.slice(next, pos);
  9999. if (!keywordRelationalOperator.test(ident)) return true;
  10000. }
  10001. return false;
  10002. }
  10003. parseStatement(context, topLevel) {
  10004. if (this.match(types.at)) {
  10005. this.parseDecorators(true);
  10006. }
  10007. return this.parseStatementContent(context, topLevel);
  10008. }
  10009. parseStatementContent(context, topLevel) {
  10010. let starttype = this.state.type;
  10011. const node = this.startNode();
  10012. let kind;
  10013. if (this.isLet(context)) {
  10014. starttype = types._var;
  10015. kind = "let";
  10016. }
  10017. switch (starttype) {
  10018. case types._break:
  10019. case types._continue:
  10020. return this.parseBreakContinueStatement(node, starttype.keyword);
  10021. case types._debugger:
  10022. return this.parseDebuggerStatement(node);
  10023. case types._do:
  10024. return this.parseDoStatement(node);
  10025. case types._for:
  10026. return this.parseForStatement(node);
  10027. case types._function:
  10028. if (this.lookaheadCharCode() === 46) break;
  10029. if (context) {
  10030. if (this.state.strict) {
  10031. this.raise(this.state.start, ErrorMessages.StrictFunction);
  10032. } else if (context !== "if" && context !== "label") {
  10033. this.raise(this.state.start, ErrorMessages.SloppyFunction);
  10034. }
  10035. }
  10036. return this.parseFunctionStatement(node, false, !context);
  10037. case types._class:
  10038. if (context) this.unexpected();
  10039. return this.parseClass(node, true);
  10040. case types._if:
  10041. return this.parseIfStatement(node);
  10042. case types._return:
  10043. return this.parseReturnStatement(node);
  10044. case types._switch:
  10045. return this.parseSwitchStatement(node);
  10046. case types._throw:
  10047. return this.parseThrowStatement(node);
  10048. case types._try:
  10049. return this.parseTryStatement(node);
  10050. case types._const:
  10051. case types._var:
  10052. kind = kind || this.state.value;
  10053. if (context && kind !== "var") {
  10054. this.raise(this.state.start, ErrorMessages.UnexpectedLexicalDeclaration);
  10055. }
  10056. return this.parseVarStatement(node, kind);
  10057. case types._while:
  10058. return this.parseWhileStatement(node);
  10059. case types._with:
  10060. return this.parseWithStatement(node);
  10061. case types.braceL:
  10062. return this.parseBlock();
  10063. case types.semi:
  10064. return this.parseEmptyStatement(node);
  10065. case types._import:
  10066. {
  10067. const nextTokenCharCode = this.lookaheadCharCode();
  10068. if (nextTokenCharCode === 40 || nextTokenCharCode === 46) {
  10069. break;
  10070. }
  10071. }
  10072. case types._export:
  10073. {
  10074. if (!this.options.allowImportExportEverywhere && !topLevel) {
  10075. this.raise(this.state.start, ErrorMessages.UnexpectedImportExport);
  10076. }
  10077. this.next();
  10078. let result;
  10079. if (starttype === types._import) {
  10080. result = this.parseImport(node);
  10081. if (result.type === "ImportDeclaration" && (!result.importKind || result.importKind === "value")) {
  10082. this.sawUnambiguousESM = true;
  10083. }
  10084. } else {
  10085. result = this.parseExport(node);
  10086. if (result.type === "ExportNamedDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportAllDeclaration" && (!result.exportKind || result.exportKind === "value") || result.type === "ExportDefaultDeclaration") {
  10087. this.sawUnambiguousESM = true;
  10088. }
  10089. }
  10090. this.assertModuleNodeAllowed(node);
  10091. return result;
  10092. }
  10093. default:
  10094. {
  10095. if (this.isAsyncFunction()) {
  10096. if (context) {
  10097. this.raise(this.state.start, ErrorMessages.AsyncFunctionInSingleStatementContext);
  10098. }
  10099. this.next();
  10100. return this.parseFunctionStatement(node, true, !context);
  10101. }
  10102. }
  10103. }
  10104. const maybeName = this.state.value;
  10105. const expr = this.parseExpression();
  10106. if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) {
  10107. return this.parseLabeledStatement(node, maybeName, expr, context);
  10108. } else {
  10109. return this.parseExpressionStatement(node, expr);
  10110. }
  10111. }
  10112. assertModuleNodeAllowed(node) {
  10113. if (!this.options.allowImportExportEverywhere && !this.inModule) {
  10114. this.raiseWithData(node.start, {
  10115. code: "BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"
  10116. }, ErrorMessages.ImportOutsideModule);
  10117. }
  10118. }
  10119. takeDecorators(node) {
  10120. const decorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10121. if (decorators.length) {
  10122. node.decorators = decorators;
  10123. this.resetStartLocationFromNode(node, decorators[0]);
  10124. this.state.decoratorStack[this.state.decoratorStack.length - 1] = [];
  10125. }
  10126. }
  10127. canHaveLeadingDecorator() {
  10128. return this.match(types._class);
  10129. }
  10130. parseDecorators(allowExport) {
  10131. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  10132. while (this.match(types.at)) {
  10133. const decorator = this.parseDecorator();
  10134. currentContextDecorators.push(decorator);
  10135. }
  10136. if (this.match(types._export)) {
  10137. if (!allowExport) {
  10138. this.unexpected();
  10139. }
  10140. if (this.hasPlugin("decorators") && !this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10141. this.raise(this.state.start, ErrorMessages.DecoratorExportClass);
  10142. }
  10143. } else if (!this.canHaveLeadingDecorator()) {
  10144. throw this.raise(this.state.start, ErrorMessages.UnexpectedLeadingDecorator);
  10145. }
  10146. }
  10147. parseDecorator() {
  10148. this.expectOnePlugin(["decorators-legacy", "decorators"]);
  10149. const node = this.startNode();
  10150. this.next();
  10151. if (this.hasPlugin("decorators")) {
  10152. this.state.decoratorStack.push([]);
  10153. const startPos = this.state.start;
  10154. const startLoc = this.state.startLoc;
  10155. let expr;
  10156. if (this.eat(types.parenL)) {
  10157. expr = this.parseExpression();
  10158. this.expect(types.parenR);
  10159. } else {
  10160. expr = this.parseIdentifier(false);
  10161. while (this.eat(types.dot)) {
  10162. const node = this.startNodeAt(startPos, startLoc);
  10163. node.object = expr;
  10164. node.property = this.parseIdentifier(true);
  10165. node.computed = false;
  10166. expr = this.finishNode(node, "MemberExpression");
  10167. }
  10168. }
  10169. node.expression = this.parseMaybeDecoratorArguments(expr);
  10170. this.state.decoratorStack.pop();
  10171. } else {
  10172. node.expression = this.parseExprSubscripts();
  10173. }
  10174. return this.finishNode(node, "Decorator");
  10175. }
  10176. parseMaybeDecoratorArguments(expr) {
  10177. if (this.eat(types.parenL)) {
  10178. const node = this.startNodeAtNode(expr);
  10179. node.callee = expr;
  10180. node.arguments = this.parseCallExpressionArguments(types.parenR, false);
  10181. this.toReferencedList(node.arguments);
  10182. return this.finishNode(node, "CallExpression");
  10183. }
  10184. return expr;
  10185. }
  10186. parseBreakContinueStatement(node, keyword) {
  10187. const isBreak = keyword === "break";
  10188. this.next();
  10189. if (this.isLineTerminator()) {
  10190. node.label = null;
  10191. } else {
  10192. node.label = this.parseIdentifier();
  10193. this.semicolon();
  10194. }
  10195. this.verifyBreakContinue(node, keyword);
  10196. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  10197. }
  10198. verifyBreakContinue(node, keyword) {
  10199. const isBreak = keyword === "break";
  10200. let i;
  10201. for (i = 0; i < this.state.labels.length; ++i) {
  10202. const lab = this.state.labels[i];
  10203. if (node.label == null || lab.name === node.label.name) {
  10204. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  10205. if (node.label && isBreak) break;
  10206. }
  10207. }
  10208. if (i === this.state.labels.length) {
  10209. this.raise(node.start, ErrorMessages.IllegalBreakContinue, keyword);
  10210. }
  10211. }
  10212. parseDebuggerStatement(node) {
  10213. this.next();
  10214. this.semicolon();
  10215. return this.finishNode(node, "DebuggerStatement");
  10216. }
  10217. parseHeaderExpression() {
  10218. this.expect(types.parenL);
  10219. const val = this.parseExpression();
  10220. this.expect(types.parenR);
  10221. return val;
  10222. }
  10223. parseDoStatement(node) {
  10224. this.next();
  10225. this.state.labels.push(loopLabel);
  10226. node.body = this.withTopicForbiddingContext(() => this.parseStatement("do"));
  10227. this.state.labels.pop();
  10228. this.expect(types._while);
  10229. node.test = this.parseHeaderExpression();
  10230. this.eat(types.semi);
  10231. return this.finishNode(node, "DoWhileStatement");
  10232. }
  10233. parseForStatement(node) {
  10234. this.next();
  10235. this.state.labels.push(loopLabel);
  10236. let awaitAt = -1;
  10237. if (this.isAwaitAllowed() && this.eatContextual("await")) {
  10238. awaitAt = this.state.lastTokStart;
  10239. }
  10240. this.scope.enter(SCOPE_OTHER);
  10241. this.expect(types.parenL);
  10242. if (this.match(types.semi)) {
  10243. if (awaitAt > -1) {
  10244. this.unexpected(awaitAt);
  10245. }
  10246. return this.parseFor(node, null);
  10247. }
  10248. const startsWithLet = this.isContextual("let");
  10249. const isLet = startsWithLet && this.isLetKeyword();
  10250. if (this.match(types._var) || this.match(types._const) || isLet) {
  10251. const init = this.startNode();
  10252. const kind = isLet ? "let" : this.state.value;
  10253. this.next();
  10254. this.parseVar(init, true, kind);
  10255. this.finishNode(init, "VariableDeclaration");
  10256. if ((this.match(types._in) || this.isContextual("of")) && init.declarations.length === 1) {
  10257. return this.parseForIn(node, init, awaitAt);
  10258. }
  10259. if (awaitAt > -1) {
  10260. this.unexpected(awaitAt);
  10261. }
  10262. return this.parseFor(node, init);
  10263. }
  10264. const refExpressionErrors = new ExpressionErrors();
  10265. const init = this.parseExpression(true, refExpressionErrors);
  10266. const isForOf = this.isContextual("of");
  10267. if (isForOf || this.match(types._in)) {
  10268. if (isForOf && startsWithLet) {
  10269. this.raise(init.start, ErrorMessages.ForOfLet);
  10270. }
  10271. this.toAssignable(init, true);
  10272. const description = isForOf ? "for-of statement" : "for-in statement";
  10273. this.checkLVal(init, description);
  10274. return this.parseForIn(node, init, awaitAt);
  10275. } else {
  10276. this.checkExpressionErrors(refExpressionErrors, true);
  10277. }
  10278. if (awaitAt > -1) {
  10279. this.unexpected(awaitAt);
  10280. }
  10281. return this.parseFor(node, init);
  10282. }
  10283. parseFunctionStatement(node, isAsync, declarationPosition) {
  10284. this.next();
  10285. return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), isAsync);
  10286. }
  10287. parseIfStatement(node) {
  10288. this.next();
  10289. node.test = this.parseHeaderExpression();
  10290. node.consequent = this.parseStatement("if");
  10291. node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
  10292. return this.finishNode(node, "IfStatement");
  10293. }
  10294. parseReturnStatement(node) {
  10295. if (!this.prodParam.hasReturn && !this.options.allowReturnOutsideFunction) {
  10296. this.raise(this.state.start, ErrorMessages.IllegalReturn);
  10297. }
  10298. this.next();
  10299. if (this.isLineTerminator()) {
  10300. node.argument = null;
  10301. } else {
  10302. node.argument = this.parseExpression();
  10303. this.semicolon();
  10304. }
  10305. return this.finishNode(node, "ReturnStatement");
  10306. }
  10307. parseSwitchStatement(node) {
  10308. this.next();
  10309. node.discriminant = this.parseHeaderExpression();
  10310. const cases = node.cases = [];
  10311. this.expect(types.braceL);
  10312. this.state.labels.push(switchLabel);
  10313. this.scope.enter(SCOPE_OTHER);
  10314. let cur;
  10315. for (let sawDefault; !this.match(types.braceR);) {
  10316. if (this.match(types._case) || this.match(types._default)) {
  10317. const isCase = this.match(types._case);
  10318. if (cur) this.finishNode(cur, "SwitchCase");
  10319. cases.push(cur = this.startNode());
  10320. cur.consequent = [];
  10321. this.next();
  10322. if (isCase) {
  10323. cur.test = this.parseExpression();
  10324. } else {
  10325. if (sawDefault) {
  10326. this.raise(this.state.lastTokStart, ErrorMessages.MultipleDefaultsInSwitch);
  10327. }
  10328. sawDefault = true;
  10329. cur.test = null;
  10330. }
  10331. this.expect(types.colon);
  10332. } else {
  10333. if (cur) {
  10334. cur.consequent.push(this.parseStatement(null));
  10335. } else {
  10336. this.unexpected();
  10337. }
  10338. }
  10339. }
  10340. this.scope.exit();
  10341. if (cur) this.finishNode(cur, "SwitchCase");
  10342. this.next();
  10343. this.state.labels.pop();
  10344. return this.finishNode(node, "SwitchStatement");
  10345. }
  10346. parseThrowStatement(node) {
  10347. this.next();
  10348. if (this.hasPrecedingLineBreak()) {
  10349. this.raise(this.state.lastTokEnd, ErrorMessages.NewlineAfterThrow);
  10350. }
  10351. node.argument = this.parseExpression();
  10352. this.semicolon();
  10353. return this.finishNode(node, "ThrowStatement");
  10354. }
  10355. parseCatchClauseParam() {
  10356. const param = this.parseBindingAtom();
  10357. const simple = param.type === "Identifier";
  10358. this.scope.enter(simple ? SCOPE_SIMPLE_CATCH : 0);
  10359. this.checkLVal(param, "catch clause", BIND_LEXICAL);
  10360. return param;
  10361. }
  10362. parseTryStatement(node) {
  10363. this.next();
  10364. node.block = this.parseBlock();
  10365. node.handler = null;
  10366. if (this.match(types._catch)) {
  10367. const clause = this.startNode();
  10368. this.next();
  10369. if (this.match(types.parenL)) {
  10370. this.expect(types.parenL);
  10371. clause.param = this.parseCatchClauseParam();
  10372. this.expect(types.parenR);
  10373. } else {
  10374. clause.param = null;
  10375. this.scope.enter(SCOPE_OTHER);
  10376. }
  10377. clause.body = this.withTopicForbiddingContext(() => this.parseBlock(false, false));
  10378. this.scope.exit();
  10379. node.handler = this.finishNode(clause, "CatchClause");
  10380. }
  10381. node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
  10382. if (!node.handler && !node.finalizer) {
  10383. this.raise(node.start, ErrorMessages.NoCatchOrFinally);
  10384. }
  10385. return this.finishNode(node, "TryStatement");
  10386. }
  10387. parseVarStatement(node, kind) {
  10388. this.next();
  10389. this.parseVar(node, false, kind);
  10390. this.semicolon();
  10391. return this.finishNode(node, "VariableDeclaration");
  10392. }
  10393. parseWhileStatement(node) {
  10394. this.next();
  10395. node.test = this.parseHeaderExpression();
  10396. this.state.labels.push(loopLabel);
  10397. node.body = this.withTopicForbiddingContext(() => this.parseStatement("while"));
  10398. this.state.labels.pop();
  10399. return this.finishNode(node, "WhileStatement");
  10400. }
  10401. parseWithStatement(node) {
  10402. if (this.state.strict) {
  10403. this.raise(this.state.start, ErrorMessages.StrictWith);
  10404. }
  10405. this.next();
  10406. node.object = this.parseHeaderExpression();
  10407. node.body = this.withTopicForbiddingContext(() => this.parseStatement("with"));
  10408. return this.finishNode(node, "WithStatement");
  10409. }
  10410. parseEmptyStatement(node) {
  10411. this.next();
  10412. return this.finishNode(node, "EmptyStatement");
  10413. }
  10414. parseLabeledStatement(node, maybeName, expr, context) {
  10415. for (const label of this.state.labels) {
  10416. if (label.name === maybeName) {
  10417. this.raise(expr.start, ErrorMessages.LabelRedeclaration, maybeName);
  10418. }
  10419. }
  10420. const kind = this.state.type.isLoop ? "loop" : this.match(types._switch) ? "switch" : null;
  10421. for (let i = this.state.labels.length - 1; i >= 0; i--) {
  10422. const label = this.state.labels[i];
  10423. if (label.statementStart === node.start) {
  10424. label.statementStart = this.state.start;
  10425. label.kind = kind;
  10426. } else {
  10427. break;
  10428. }
  10429. }
  10430. this.state.labels.push({
  10431. name: maybeName,
  10432. kind: kind,
  10433. statementStart: this.state.start
  10434. });
  10435. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  10436. this.state.labels.pop();
  10437. node.label = expr;
  10438. return this.finishNode(node, "LabeledStatement");
  10439. }
  10440. parseExpressionStatement(node, expr) {
  10441. node.expression = expr;
  10442. this.semicolon();
  10443. return this.finishNode(node, "ExpressionStatement");
  10444. }
  10445. parseBlock(allowDirectives = false, createNewLexicalScope = true, afterBlockParse) {
  10446. const node = this.startNode();
  10447. if (allowDirectives) {
  10448. this.state.strictErrors.clear();
  10449. }
  10450. this.expect(types.braceL);
  10451. if (createNewLexicalScope) {
  10452. this.scope.enter(SCOPE_OTHER);
  10453. }
  10454. this.parseBlockBody(node, allowDirectives, false, types.braceR, afterBlockParse);
  10455. if (createNewLexicalScope) {
  10456. this.scope.exit();
  10457. }
  10458. return this.finishNode(node, "BlockStatement");
  10459. }
  10460. isValidDirective(stmt) {
  10461. return stmt.type === "ExpressionStatement" && stmt.expression.type === "StringLiteral" && !stmt.expression.extra.parenthesized;
  10462. }
  10463. parseBlockBody(node, allowDirectives, topLevel, end, afterBlockParse) {
  10464. const body = node.body = [];
  10465. const directives = node.directives = [];
  10466. this.parseBlockOrModuleBlockBody(body, allowDirectives ? directives : undefined, topLevel, end, afterBlockParse);
  10467. }
  10468. parseBlockOrModuleBlockBody(body, directives, topLevel, end, afterBlockParse) {
  10469. const oldStrict = this.state.strict;
  10470. let hasStrictModeDirective = false;
  10471. let parsedNonDirective = false;
  10472. while (!this.match(end)) {
  10473. const stmt = this.parseStatement(null, topLevel);
  10474. if (directives && !parsedNonDirective) {
  10475. if (this.isValidDirective(stmt)) {
  10476. const directive = this.stmtToDirective(stmt);
  10477. directives.push(directive);
  10478. if (!hasStrictModeDirective && directive.value.value === "use strict") {
  10479. hasStrictModeDirective = true;
  10480. this.setStrict(true);
  10481. }
  10482. continue;
  10483. }
  10484. parsedNonDirective = true;
  10485. this.state.strictErrors.clear();
  10486. }
  10487. body.push(stmt);
  10488. }
  10489. if (afterBlockParse) {
  10490. afterBlockParse.call(this, hasStrictModeDirective);
  10491. }
  10492. if (!oldStrict) {
  10493. this.setStrict(false);
  10494. }
  10495. this.next();
  10496. }
  10497. parseFor(node, init) {
  10498. node.init = init;
  10499. this.semicolon(false);
  10500. node.test = this.match(types.semi) ? null : this.parseExpression();
  10501. this.semicolon(false);
  10502. node.update = this.match(types.parenR) ? null : this.parseExpression();
  10503. this.expect(types.parenR);
  10504. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10505. this.scope.exit();
  10506. this.state.labels.pop();
  10507. return this.finishNode(node, "ForStatement");
  10508. }
  10509. parseForIn(node, init, awaitAt) {
  10510. const isForIn = this.match(types._in);
  10511. this.next();
  10512. if (isForIn) {
  10513. if (awaitAt > -1) this.unexpected(awaitAt);
  10514. } else {
  10515. node.await = awaitAt > -1;
  10516. }
  10517. if (init.type === "VariableDeclaration" && init.declarations[0].init != null && (!isForIn || this.state.strict || init.kind !== "var" || init.declarations[0].id.type !== "Identifier")) {
  10518. this.raise(init.start, ErrorMessages.ForInOfLoopInitializer, isForIn ? "for-in" : "for-of");
  10519. } else if (init.type === "AssignmentPattern") {
  10520. this.raise(init.start, ErrorMessages.InvalidLhs, "for-loop");
  10521. }
  10522. node.left = init;
  10523. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssignAllowIn();
  10524. this.expect(types.parenR);
  10525. node.body = this.withTopicForbiddingContext(() => this.parseStatement("for"));
  10526. this.scope.exit();
  10527. this.state.labels.pop();
  10528. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement");
  10529. }
  10530. parseVar(node, isFor, kind) {
  10531. const declarations = node.declarations = [];
  10532. const isTypescript = this.hasPlugin("typescript");
  10533. node.kind = kind;
  10534. for (;;) {
  10535. const decl = this.startNode();
  10536. this.parseVarId(decl, kind);
  10537. if (this.eat(types.eq)) {
  10538. decl.init = isFor ? this.parseMaybeAssignDisallowIn() : this.parseMaybeAssignAllowIn();
  10539. } else {
  10540. if (kind === "const" && !(this.match(types._in) || this.isContextual("of"))) {
  10541. if (!isTypescript) {
  10542. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Const declarations");
  10543. }
  10544. } else if (decl.id.type !== "Identifier" && !(isFor && (this.match(types._in) || this.isContextual("of")))) {
  10545. this.raise(this.state.lastTokEnd, ErrorMessages.DeclarationMissingInitializer, "Complex binding patterns");
  10546. }
  10547. decl.init = null;
  10548. }
  10549. declarations.push(this.finishNode(decl, "VariableDeclarator"));
  10550. if (!this.eat(types.comma)) break;
  10551. }
  10552. return node;
  10553. }
  10554. parseVarId(decl, kind) {
  10555. decl.id = this.parseBindingAtom();
  10556. this.checkLVal(decl.id, "variable declaration", kind === "var" ? BIND_VAR : BIND_LEXICAL, undefined, kind !== "var");
  10557. }
  10558. parseFunction(node, statement = FUNC_NO_FLAGS, isAsync = false) {
  10559. const isStatement = statement & FUNC_STATEMENT;
  10560. const isHangingStatement = statement & FUNC_HANGING_STATEMENT;
  10561. const requireId = !!isStatement && !(statement & FUNC_NULLABLE_ID);
  10562. this.initFunction(node, isAsync);
  10563. if (this.match(types.star) && isHangingStatement) {
  10564. this.raise(this.state.start, ErrorMessages.GeneratorInSingleStatementContext);
  10565. }
  10566. node.generator = this.eat(types.star);
  10567. if (isStatement) {
  10568. node.id = this.parseFunctionId(requireId);
  10569. }
  10570. const oldMaybeInArrowParameters = this.state.maybeInArrowParameters;
  10571. this.state.maybeInArrowParameters = false;
  10572. this.scope.enter(SCOPE_FUNCTION);
  10573. this.prodParam.enter(functionFlags(isAsync, node.generator));
  10574. if (!isStatement) {
  10575. node.id = this.parseFunctionId();
  10576. }
  10577. this.parseFunctionParams(node, false);
  10578. this.withTopicForbiddingContext(() => {
  10579. this.parseFunctionBodyAndFinish(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  10580. });
  10581. this.prodParam.exit();
  10582. this.scope.exit();
  10583. if (isStatement && !isHangingStatement) {
  10584. this.registerFunctionStatementId(node);
  10585. }
  10586. this.state.maybeInArrowParameters = oldMaybeInArrowParameters;
  10587. return node;
  10588. }
  10589. parseFunctionId(requireId) {
  10590. return requireId || this.match(types.name) ? this.parseIdentifier() : null;
  10591. }
  10592. parseFunctionParams(node, allowModifiers) {
  10593. this.expect(types.parenL);
  10594. this.expressionScope.enter(newParameterDeclarationScope());
  10595. node.params = this.parseBindingList(types.parenR, 41, false, allowModifiers);
  10596. this.expressionScope.exit();
  10597. }
  10598. registerFunctionStatementId(node) {
  10599. if (!node.id) return;
  10600. this.scope.declareName(node.id.name, this.state.strict || node.generator || node.async ? this.scope.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION, node.id.start);
  10601. }
  10602. parseClass(node, isStatement, optionalId) {
  10603. this.next();
  10604. this.takeDecorators(node);
  10605. const oldStrict = this.state.strict;
  10606. this.state.strict = true;
  10607. this.parseClassId(node, isStatement, optionalId);
  10608. this.parseClassSuper(node);
  10609. node.body = this.parseClassBody(!!node.superClass, oldStrict);
  10610. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
  10611. }
  10612. isClassProperty() {
  10613. return this.match(types.eq) || this.match(types.semi) || this.match(types.braceR);
  10614. }
  10615. isClassMethod() {
  10616. return this.match(types.parenL);
  10617. }
  10618. isNonstaticConstructor(method) {
  10619. return !method.computed && !method.static && (method.key.name === "constructor" || method.key.value === "constructor");
  10620. }
  10621. parseClassBody(constructorAllowsSuper, oldStrict) {
  10622. this.classScope.enter();
  10623. const state = {
  10624. constructorAllowsSuper,
  10625. hadConstructor: false
  10626. };
  10627. let decorators = [];
  10628. const classBody = this.startNode();
  10629. classBody.body = [];
  10630. this.expect(types.braceL);
  10631. this.withTopicForbiddingContext(() => {
  10632. while (!this.match(types.braceR)) {
  10633. if (this.eat(types.semi)) {
  10634. if (decorators.length > 0) {
  10635. throw this.raise(this.state.lastTokEnd, ErrorMessages.DecoratorSemicolon);
  10636. }
  10637. continue;
  10638. }
  10639. if (this.match(types.at)) {
  10640. decorators.push(this.parseDecorator());
  10641. continue;
  10642. }
  10643. const member = this.startNode();
  10644. if (decorators.length) {
  10645. member.decorators = decorators;
  10646. this.resetStartLocationFromNode(member, decorators[0]);
  10647. decorators = [];
  10648. }
  10649. this.parseClassMember(classBody, member, state);
  10650. if (member.kind === "constructor" && member.decorators && member.decorators.length > 0) {
  10651. this.raise(member.start, ErrorMessages.DecoratorConstructor);
  10652. }
  10653. }
  10654. });
  10655. this.state.strict = oldStrict;
  10656. this.next();
  10657. if (decorators.length) {
  10658. throw this.raise(this.state.start, ErrorMessages.TrailingDecorator);
  10659. }
  10660. this.classScope.exit();
  10661. return this.finishNode(classBody, "ClassBody");
  10662. }
  10663. parseClassMemberFromModifier(classBody, member) {
  10664. const key = this.parseIdentifier(true);
  10665. if (this.isClassMethod()) {
  10666. const method = member;
  10667. method.kind = "method";
  10668. method.computed = false;
  10669. method.key = key;
  10670. method.static = false;
  10671. this.pushClassMethod(classBody, method, false, false, false, false);
  10672. return true;
  10673. } else if (this.isClassProperty()) {
  10674. const prop = member;
  10675. prop.computed = false;
  10676. prop.key = key;
  10677. prop.static = false;
  10678. classBody.body.push(this.parseClassProperty(prop));
  10679. return true;
  10680. }
  10681. return false;
  10682. }
  10683. parseClassMember(classBody, member, state) {
  10684. const isStatic = this.isContextual("static");
  10685. if (isStatic) {
  10686. if (this.parseClassMemberFromModifier(classBody, member)) {
  10687. return;
  10688. }
  10689. if (this.eat(types.braceL)) {
  10690. this.parseClassStaticBlock(classBody, member);
  10691. return;
  10692. }
  10693. }
  10694. this.parseClassMemberWithIsStatic(classBody, member, state, isStatic);
  10695. }
  10696. parseClassMemberWithIsStatic(classBody, member, state, isStatic) {
  10697. const publicMethod = member;
  10698. const privateMethod = member;
  10699. const publicProp = member;
  10700. const privateProp = member;
  10701. const method = publicMethod;
  10702. const publicMember = publicMethod;
  10703. member.static = isStatic;
  10704. if (this.eat(types.star)) {
  10705. method.kind = "method";
  10706. this.parseClassElementName(method);
  10707. if (this.isPrivateName(method.key)) {
  10708. this.pushClassPrivateMethod(classBody, privateMethod, true, false);
  10709. return;
  10710. }
  10711. if (this.isNonstaticConstructor(publicMethod)) {
  10712. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsGenerator);
  10713. }
  10714. this.pushClassMethod(classBody, publicMethod, true, false, false, false);
  10715. return;
  10716. }
  10717. const containsEsc = this.state.containsEsc;
  10718. const key = this.parseClassElementName(member);
  10719. const isPrivate = this.isPrivateName(key);
  10720. const isSimple = key.type === "Identifier";
  10721. const maybeQuestionTokenStart = this.state.start;
  10722. this.parsePostMemberNameModifiers(publicMember);
  10723. if (this.isClassMethod()) {
  10724. method.kind = "method";
  10725. if (isPrivate) {
  10726. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10727. return;
  10728. }
  10729. const isConstructor = this.isNonstaticConstructor(publicMethod);
  10730. let allowsDirectSuper = false;
  10731. if (isConstructor) {
  10732. publicMethod.kind = "constructor";
  10733. if (state.hadConstructor && !this.hasPlugin("typescript")) {
  10734. this.raise(key.start, ErrorMessages.DuplicateConstructor);
  10735. }
  10736. state.hadConstructor = true;
  10737. allowsDirectSuper = state.constructorAllowsSuper;
  10738. }
  10739. this.pushClassMethod(classBody, publicMethod, false, false, isConstructor, allowsDirectSuper);
  10740. } else if (this.isClassProperty()) {
  10741. if (isPrivate) {
  10742. this.pushClassPrivateProperty(classBody, privateProp);
  10743. } else {
  10744. this.pushClassProperty(classBody, publicProp);
  10745. }
  10746. } else if (isSimple && key.name === "async" && !containsEsc && !this.isLineTerminator()) {
  10747. const isGenerator = this.eat(types.star);
  10748. if (publicMember.optional) {
  10749. this.unexpected(maybeQuestionTokenStart);
  10750. }
  10751. method.kind = "method";
  10752. this.parseClassElementName(method);
  10753. this.parsePostMemberNameModifiers(publicMember);
  10754. if (this.isPrivateName(method.key)) {
  10755. this.pushClassPrivateMethod(classBody, privateMethod, isGenerator, true);
  10756. } else {
  10757. if (this.isNonstaticConstructor(publicMethod)) {
  10758. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAsync);
  10759. }
  10760. this.pushClassMethod(classBody, publicMethod, isGenerator, true, false, false);
  10761. }
  10762. } else if (isSimple && (key.name === "get" || key.name === "set") && !containsEsc && !(this.match(types.star) && this.isLineTerminator())) {
  10763. method.kind = key.name;
  10764. this.parseClassElementName(publicMethod);
  10765. if (this.isPrivateName(method.key)) {
  10766. this.pushClassPrivateMethod(classBody, privateMethod, false, false);
  10767. } else {
  10768. if (this.isNonstaticConstructor(publicMethod)) {
  10769. this.raise(publicMethod.key.start, ErrorMessages.ConstructorIsAccessor);
  10770. }
  10771. this.pushClassMethod(classBody, publicMethod, false, false, false, false);
  10772. }
  10773. this.checkGetterSetterParams(publicMethod);
  10774. } else if (this.isLineTerminator()) {
  10775. if (isPrivate) {
  10776. this.pushClassPrivateProperty(classBody, privateProp);
  10777. } else {
  10778. this.pushClassProperty(classBody, publicProp);
  10779. }
  10780. } else {
  10781. this.unexpected();
  10782. }
  10783. }
  10784. parseClassElementName(member) {
  10785. const key = this.parsePropertyName(member, true);
  10786. if (!member.computed && member.static && (key.name === "prototype" || key.value === "prototype")) {
  10787. this.raise(key.start, ErrorMessages.StaticPrototype);
  10788. }
  10789. if (this.isPrivateName(key) && this.getPrivateNameSV(key) === "constructor") {
  10790. this.raise(key.start, ErrorMessages.ConstructorClassPrivateField);
  10791. }
  10792. return key;
  10793. }
  10794. parseClassStaticBlock(classBody, member) {
  10795. var _member$decorators;
  10796. this.expectPlugin("classStaticBlock", member.start);
  10797. this.scope.enter(SCOPE_CLASS | SCOPE_STATIC_BLOCK | SCOPE_SUPER);
  10798. const oldLabels = this.state.labels;
  10799. this.state.labels = [];
  10800. this.prodParam.enter(PARAM);
  10801. const body = member.body = [];
  10802. this.parseBlockOrModuleBlockBody(body, undefined, false, types.braceR);
  10803. this.prodParam.exit();
  10804. this.scope.exit();
  10805. this.state.labels = oldLabels;
  10806. classBody.body.push(this.finishNode(member, "StaticBlock"));
  10807. if ((_member$decorators = member.decorators) != null && _member$decorators.length) {
  10808. this.raise(member.start, ErrorMessages.DecoratorStaticBlock);
  10809. }
  10810. }
  10811. pushClassProperty(classBody, prop) {
  10812. if (!prop.computed && (prop.key.name === "constructor" || prop.key.value === "constructor")) {
  10813. this.raise(prop.key.start, ErrorMessages.ConstructorClassField);
  10814. }
  10815. classBody.body.push(this.parseClassProperty(prop));
  10816. }
  10817. pushClassPrivateProperty(classBody, prop) {
  10818. this.expectPlugin("classPrivateProperties", prop.key.start);
  10819. const node = this.parseClassPrivateProperty(prop);
  10820. classBody.body.push(node);
  10821. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), CLASS_ELEMENT_OTHER, node.key.start);
  10822. }
  10823. pushClassMethod(classBody, method, isGenerator, isAsync, isConstructor, allowsDirectSuper) {
  10824. classBody.body.push(this.parseMethod(method, isGenerator, isAsync, isConstructor, allowsDirectSuper, "ClassMethod", true));
  10825. }
  10826. pushClassPrivateMethod(classBody, method, isGenerator, isAsync) {
  10827. this.expectPlugin("classPrivateMethods", method.key.start);
  10828. const node = this.parseMethod(method, isGenerator, isAsync, false, false, "ClassPrivateMethod", true);
  10829. classBody.body.push(node);
  10830. const kind = node.kind === "get" ? node.static ? CLASS_ELEMENT_STATIC_GETTER : CLASS_ELEMENT_INSTANCE_GETTER : node.kind === "set" ? node.static ? CLASS_ELEMENT_STATIC_SETTER : CLASS_ELEMENT_INSTANCE_SETTER : CLASS_ELEMENT_OTHER;
  10831. this.classScope.declarePrivateName(this.getPrivateNameSV(node.key), kind, node.key.start);
  10832. }
  10833. parsePostMemberNameModifiers(methodOrProp) {}
  10834. parseClassPrivateProperty(node) {
  10835. this.parseInitializer(node);
  10836. this.semicolon();
  10837. return this.finishNode(node, "ClassPrivateProperty");
  10838. }
  10839. parseClassProperty(node) {
  10840. if (!node.typeAnnotation || this.match(types.eq)) {
  10841. this.expectPlugin("classProperties");
  10842. }
  10843. this.parseInitializer(node);
  10844. this.semicolon();
  10845. return this.finishNode(node, "ClassProperty");
  10846. }
  10847. parseInitializer(node) {
  10848. this.scope.enter(SCOPE_CLASS | SCOPE_SUPER);
  10849. this.expressionScope.enter(newExpressionScope());
  10850. this.prodParam.enter(PARAM);
  10851. node.value = this.eat(types.eq) ? this.parseMaybeAssignAllowIn() : null;
  10852. this.expressionScope.exit();
  10853. this.prodParam.exit();
  10854. this.scope.exit();
  10855. }
  10856. parseClassId(node, isStatement, optionalId, bindingType = BIND_CLASS) {
  10857. if (this.match(types.name)) {
  10858. node.id = this.parseIdentifier();
  10859. if (isStatement) {
  10860. this.checkLVal(node.id, "class name", bindingType);
  10861. }
  10862. } else {
  10863. if (optionalId || !isStatement) {
  10864. node.id = null;
  10865. } else {
  10866. this.unexpected(null, ErrorMessages.MissingClassName);
  10867. }
  10868. }
  10869. }
  10870. parseClassSuper(node) {
  10871. node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
  10872. }
  10873. parseExport(node) {
  10874. const hasDefault = this.maybeParseExportDefaultSpecifier(node);
  10875. const parseAfterDefault = !hasDefault || this.eat(types.comma);
  10876. const hasStar = parseAfterDefault && this.eatExportStar(node);
  10877. const hasNamespace = hasStar && this.maybeParseExportNamespaceSpecifier(node);
  10878. const parseAfterNamespace = parseAfterDefault && (!hasNamespace || this.eat(types.comma));
  10879. const isFromRequired = hasDefault || hasStar;
  10880. if (hasStar && !hasNamespace) {
  10881. if (hasDefault) this.unexpected();
  10882. this.parseExportFrom(node, true);
  10883. return this.finishNode(node, "ExportAllDeclaration");
  10884. }
  10885. const hasSpecifiers = this.maybeParseExportNamedSpecifiers(node);
  10886. if (hasDefault && parseAfterDefault && !hasStar && !hasSpecifiers || hasNamespace && parseAfterNamespace && !hasSpecifiers) {
  10887. throw this.unexpected(null, types.braceL);
  10888. }
  10889. let hasDeclaration;
  10890. if (isFromRequired || hasSpecifiers) {
  10891. hasDeclaration = false;
  10892. this.parseExportFrom(node, isFromRequired);
  10893. } else {
  10894. hasDeclaration = this.maybeParseExportDeclaration(node);
  10895. }
  10896. if (isFromRequired || hasSpecifiers || hasDeclaration) {
  10897. this.checkExport(node, true, false, !!node.source);
  10898. return this.finishNode(node, "ExportNamedDeclaration");
  10899. }
  10900. if (this.eat(types._default)) {
  10901. node.declaration = this.parseExportDefaultExpression();
  10902. this.checkExport(node, true, true);
  10903. return this.finishNode(node, "ExportDefaultDeclaration");
  10904. }
  10905. throw this.unexpected(null, types.braceL);
  10906. }
  10907. eatExportStar(node) {
  10908. return this.eat(types.star);
  10909. }
  10910. maybeParseExportDefaultSpecifier(node) {
  10911. if (this.isExportDefaultSpecifier()) {
  10912. this.expectPlugin("exportDefaultFrom");
  10913. const specifier = this.startNode();
  10914. specifier.exported = this.parseIdentifier(true);
  10915. node.specifiers = [this.finishNode(specifier, "ExportDefaultSpecifier")];
  10916. return true;
  10917. }
  10918. return false;
  10919. }
  10920. maybeParseExportNamespaceSpecifier(node) {
  10921. if (this.isContextual("as")) {
  10922. if (!node.specifiers) node.specifiers = [];
  10923. const specifier = this.startNodeAt(this.state.lastTokStart, this.state.lastTokStartLoc);
  10924. this.next();
  10925. specifier.exported = this.parseModuleExportName();
  10926. node.specifiers.push(this.finishNode(specifier, "ExportNamespaceSpecifier"));
  10927. return true;
  10928. }
  10929. return false;
  10930. }
  10931. maybeParseExportNamedSpecifiers(node) {
  10932. if (this.match(types.braceL)) {
  10933. if (!node.specifiers) node.specifiers = [];
  10934. node.specifiers.push(...this.parseExportSpecifiers());
  10935. node.source = null;
  10936. node.declaration = null;
  10937. return true;
  10938. }
  10939. return false;
  10940. }
  10941. maybeParseExportDeclaration(node) {
  10942. if (this.shouldParseExportDeclaration()) {
  10943. node.specifiers = [];
  10944. node.source = null;
  10945. node.declaration = this.parseExportDeclaration(node);
  10946. return true;
  10947. }
  10948. return false;
  10949. }
  10950. isAsyncFunction() {
  10951. if (!this.isContextual("async")) return false;
  10952. const next = this.nextTokenStart();
  10953. return !lineBreak.test(this.input.slice(this.state.pos, next)) && this.isUnparsedContextual(next, "function");
  10954. }
  10955. parseExportDefaultExpression() {
  10956. const expr = this.startNode();
  10957. const isAsync = this.isAsyncFunction();
  10958. if (this.match(types._function) || isAsync) {
  10959. this.next();
  10960. if (isAsync) {
  10961. this.next();
  10962. }
  10963. return this.parseFunction(expr, FUNC_STATEMENT | FUNC_NULLABLE_ID, isAsync);
  10964. } else if (this.match(types._class)) {
  10965. return this.parseClass(expr, true, true);
  10966. } else if (this.match(types.at)) {
  10967. if (this.hasPlugin("decorators") && this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  10968. this.raise(this.state.start, ErrorMessages.DecoratorBeforeExport);
  10969. }
  10970. this.parseDecorators(false);
  10971. return this.parseClass(expr, true, true);
  10972. } else if (this.match(types._const) || this.match(types._var) || this.isLet()) {
  10973. throw this.raise(this.state.start, ErrorMessages.UnsupportedDefaultExport);
  10974. } else {
  10975. const res = this.parseMaybeAssignAllowIn();
  10976. this.semicolon();
  10977. return res;
  10978. }
  10979. }
  10980. parseExportDeclaration(node) {
  10981. return this.parseStatement(null);
  10982. }
  10983. isExportDefaultSpecifier() {
  10984. if (this.match(types.name)) {
  10985. const value = this.state.value;
  10986. if (value === "async" && !this.state.containsEsc || value === "let") {
  10987. return false;
  10988. }
  10989. if ((value === "type" || value === "interface") && !this.state.containsEsc) {
  10990. const l = this.lookahead();
  10991. if (l.type === types.name && l.value !== "from" || l.type === types.braceL) {
  10992. this.expectOnePlugin(["flow", "typescript"]);
  10993. return false;
  10994. }
  10995. }
  10996. } else if (!this.match(types._default)) {
  10997. return false;
  10998. }
  10999. const next = this.nextTokenStart();
  11000. const hasFrom = this.isUnparsedContextual(next, "from");
  11001. if (this.input.charCodeAt(next) === 44 || this.match(types.name) && hasFrom) {
  11002. return true;
  11003. }
  11004. if (this.match(types._default) && hasFrom) {
  11005. const nextAfterFrom = this.input.charCodeAt(this.nextTokenStartSince(next + 4));
  11006. return nextAfterFrom === 34 || nextAfterFrom === 39;
  11007. }
  11008. return false;
  11009. }
  11010. parseExportFrom(node, expect) {
  11011. if (this.eatContextual("from")) {
  11012. node.source = this.parseImportSource();
  11013. this.checkExport(node);
  11014. const assertions = this.maybeParseImportAssertions();
  11015. if (assertions) {
  11016. node.assertions = assertions;
  11017. }
  11018. } else {
  11019. if (expect) {
  11020. this.unexpected();
  11021. } else {
  11022. node.source = null;
  11023. }
  11024. }
  11025. this.semicolon();
  11026. }
  11027. shouldParseExportDeclaration() {
  11028. if (this.match(types.at)) {
  11029. this.expectOnePlugin(["decorators", "decorators-legacy"]);
  11030. if (this.hasPlugin("decorators")) {
  11031. if (this.getPluginOption("decorators", "decoratorsBeforeExport")) {
  11032. this.unexpected(this.state.start, ErrorMessages.DecoratorBeforeExport);
  11033. } else {
  11034. return true;
  11035. }
  11036. }
  11037. }
  11038. return this.state.type.keyword === "var" || this.state.type.keyword === "const" || this.state.type.keyword === "function" || this.state.type.keyword === "class" || this.isLet() || this.isAsyncFunction();
  11039. }
  11040. checkExport(node, checkNames, isDefault, isFrom) {
  11041. if (checkNames) {
  11042. if (isDefault) {
  11043. this.checkDuplicateExports(node, "default");
  11044. if (this.hasPlugin("exportDefaultFrom")) {
  11045. var _declaration$extra;
  11046. const declaration = node.declaration;
  11047. if (declaration.type === "Identifier" && declaration.name === "from" && declaration.end - declaration.start === 4 && !((_declaration$extra = declaration.extra) != null && _declaration$extra.parenthesized)) {
  11048. this.raise(declaration.start, ErrorMessages.ExportDefaultFromAsIdentifier);
  11049. }
  11050. }
  11051. } else if (node.specifiers && node.specifiers.length) {
  11052. for (const specifier of node.specifiers) {
  11053. const {
  11054. exported
  11055. } = specifier;
  11056. const exportedName = exported.type === "Identifier" ? exported.name : exported.value;
  11057. this.checkDuplicateExports(specifier, exportedName);
  11058. if (!isFrom && specifier.local) {
  11059. const {
  11060. local
  11061. } = specifier;
  11062. if (local.type === "StringLiteral") {
  11063. this.raise(specifier.start, ErrorMessages.ExportBindingIsString, local.value, exportedName);
  11064. } else {
  11065. this.checkReservedWord(local.name, local.start, true, false);
  11066. this.scope.checkLocalExport(local);
  11067. }
  11068. }
  11069. }
  11070. } else if (node.declaration) {
  11071. if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") {
  11072. const id = node.declaration.id;
  11073. if (!id) throw new Error("Assertion failure");
  11074. this.checkDuplicateExports(node, id.name);
  11075. } else if (node.declaration.type === "VariableDeclaration") {
  11076. for (const declaration of node.declaration.declarations) {
  11077. this.checkDeclaration(declaration.id);
  11078. }
  11079. }
  11080. }
  11081. }
  11082. const currentContextDecorators = this.state.decoratorStack[this.state.decoratorStack.length - 1];
  11083. if (currentContextDecorators.length) {
  11084. throw this.raise(node.start, ErrorMessages.UnsupportedDecoratorExport);
  11085. }
  11086. }
  11087. checkDeclaration(node) {
  11088. if (node.type === "Identifier") {
  11089. this.checkDuplicateExports(node, node.name);
  11090. } else if (node.type === "ObjectPattern") {
  11091. for (const prop of node.properties) {
  11092. this.checkDeclaration(prop);
  11093. }
  11094. } else if (node.type === "ArrayPattern") {
  11095. for (const elem of node.elements) {
  11096. if (elem) {
  11097. this.checkDeclaration(elem);
  11098. }
  11099. }
  11100. } else if (node.type === "ObjectProperty") {
  11101. this.checkDeclaration(node.value);
  11102. } else if (node.type === "RestElement") {
  11103. this.checkDeclaration(node.argument);
  11104. } else if (node.type === "AssignmentPattern") {
  11105. this.checkDeclaration(node.left);
  11106. }
  11107. }
  11108. checkDuplicateExports(node, name) {
  11109. if (this.state.exportedIdentifiers.indexOf(name) > -1) {
  11110. this.raise(node.start, name === "default" ? ErrorMessages.DuplicateDefaultExport : ErrorMessages.DuplicateExport, name);
  11111. }
  11112. this.state.exportedIdentifiers.push(name);
  11113. }
  11114. parseExportSpecifiers() {
  11115. const nodes = [];
  11116. let first = true;
  11117. this.expect(types.braceL);
  11118. while (!this.eat(types.braceR)) {
  11119. if (first) {
  11120. first = false;
  11121. } else {
  11122. this.expect(types.comma);
  11123. if (this.eat(types.braceR)) break;
  11124. }
  11125. const node = this.startNode();
  11126. node.local = this.parseModuleExportName();
  11127. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local.__clone();
  11128. nodes.push(this.finishNode(node, "ExportSpecifier"));
  11129. }
  11130. return nodes;
  11131. }
  11132. parseModuleExportName() {
  11133. if (this.match(types.string)) {
  11134. this.expectPlugin("moduleStringNames");
  11135. const result = this.parseLiteral(this.state.value, "StringLiteral");
  11136. const surrogate = result.value.match(loneSurrogate);
  11137. if (surrogate) {
  11138. this.raise(result.start, ErrorMessages.ModuleExportNameHasLoneSurrogate, surrogate[0].charCodeAt(0).toString(16));
  11139. }
  11140. return result;
  11141. }
  11142. return this.parseIdentifier(true);
  11143. }
  11144. parseImport(node) {
  11145. node.specifiers = [];
  11146. if (!this.match(types.string)) {
  11147. const hasDefault = this.maybeParseDefaultImportSpecifier(node);
  11148. const parseNext = !hasDefault || this.eat(types.comma);
  11149. const hasStar = parseNext && this.maybeParseStarImportSpecifier(node);
  11150. if (parseNext && !hasStar) this.parseNamedImportSpecifiers(node);
  11151. this.expectContextual("from");
  11152. }
  11153. node.source = this.parseImportSource();
  11154. const assertions = this.maybeParseImportAssertions();
  11155. if (assertions) {
  11156. node.assertions = assertions;
  11157. } else {
  11158. const attributes = this.maybeParseModuleAttributes();
  11159. if (attributes) {
  11160. node.attributes = attributes;
  11161. }
  11162. }
  11163. this.semicolon();
  11164. return this.finishNode(node, "ImportDeclaration");
  11165. }
  11166. parseImportSource() {
  11167. if (!this.match(types.string)) this.unexpected();
  11168. return this.parseExprAtom();
  11169. }
  11170. shouldParseDefaultImport(node) {
  11171. return this.match(types.name);
  11172. }
  11173. parseImportSpecifierLocal(node, specifier, type, contextDescription) {
  11174. specifier.local = this.parseIdentifier();
  11175. this.checkLVal(specifier.local, contextDescription, BIND_LEXICAL);
  11176. node.specifiers.push(this.finishNode(specifier, type));
  11177. }
  11178. parseAssertEntries() {
  11179. const attrs = [];
  11180. const attrNames = new Set();
  11181. do {
  11182. if (this.match(types.braceR)) {
  11183. break;
  11184. }
  11185. const node = this.startNode();
  11186. const keyName = this.state.value;
  11187. if (this.match(types.string)) {
  11188. node.key = this.parseLiteral(keyName, "StringLiteral");
  11189. } else {
  11190. node.key = this.parseIdentifier(true);
  11191. }
  11192. this.expect(types.colon);
  11193. if (keyName !== "type") {
  11194. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, keyName);
  11195. }
  11196. if (attrNames.has(keyName)) {
  11197. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, keyName);
  11198. }
  11199. attrNames.add(keyName);
  11200. if (!this.match(types.string)) {
  11201. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  11202. }
  11203. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  11204. this.finishNode(node, "ImportAttribute");
  11205. attrs.push(node);
  11206. } while (this.eat(types.comma));
  11207. return attrs;
  11208. }
  11209. maybeParseModuleAttributes() {
  11210. if (this.match(types._with) && !this.hasPrecedingLineBreak()) {
  11211. this.expectPlugin("moduleAttributes");
  11212. this.next();
  11213. } else {
  11214. if (this.hasPlugin("moduleAttributes")) return [];
  11215. return null;
  11216. }
  11217. const attrs = [];
  11218. const attributes = new Set();
  11219. do {
  11220. const node = this.startNode();
  11221. node.key = this.parseIdentifier(true);
  11222. if (node.key.name !== "type") {
  11223. this.raise(node.key.start, ErrorMessages.ModuleAttributeDifferentFromType, node.key.name);
  11224. }
  11225. if (attributes.has(node.key.name)) {
  11226. this.raise(node.key.start, ErrorMessages.ModuleAttributesWithDuplicateKeys, node.key.name);
  11227. }
  11228. attributes.add(node.key.name);
  11229. this.expect(types.colon);
  11230. if (!this.match(types.string)) {
  11231. throw this.unexpected(this.state.start, ErrorMessages.ModuleAttributeInvalidValue);
  11232. }
  11233. node.value = this.parseLiteral(this.state.value, "StringLiteral");
  11234. this.finishNode(node, "ImportAttribute");
  11235. attrs.push(node);
  11236. } while (this.eat(types.comma));
  11237. return attrs;
  11238. }
  11239. maybeParseImportAssertions() {
  11240. if (this.isContextual("assert") && !this.hasPrecedingLineBreak()) {
  11241. this.expectPlugin("importAssertions");
  11242. this.next();
  11243. } else {
  11244. if (this.hasPlugin("importAssertions")) return [];
  11245. return null;
  11246. }
  11247. this.eat(types.braceL);
  11248. const attrs = this.parseAssertEntries();
  11249. this.eat(types.braceR);
  11250. return attrs;
  11251. }
  11252. maybeParseDefaultImportSpecifier(node) {
  11253. if (this.shouldParseDefaultImport(node)) {
  11254. this.parseImportSpecifierLocal(node, this.startNode(), "ImportDefaultSpecifier", "default import specifier");
  11255. return true;
  11256. }
  11257. return false;
  11258. }
  11259. maybeParseStarImportSpecifier(node) {
  11260. if (this.match(types.star)) {
  11261. const specifier = this.startNode();
  11262. this.next();
  11263. this.expectContextual("as");
  11264. this.parseImportSpecifierLocal(node, specifier, "ImportNamespaceSpecifier", "import namespace specifier");
  11265. return true;
  11266. }
  11267. return false;
  11268. }
  11269. parseNamedImportSpecifiers(node) {
  11270. let first = true;
  11271. this.expect(types.braceL);
  11272. while (!this.eat(types.braceR)) {
  11273. if (first) {
  11274. first = false;
  11275. } else {
  11276. if (this.eat(types.colon)) {
  11277. throw this.raise(this.state.start, ErrorMessages.DestructureNamedImport);
  11278. }
  11279. this.expect(types.comma);
  11280. if (this.eat(types.braceR)) break;
  11281. }
  11282. this.parseImportSpecifier(node);
  11283. }
  11284. }
  11285. parseImportSpecifier(node) {
  11286. const specifier = this.startNode();
  11287. specifier.imported = this.parseModuleExportName();
  11288. if (this.eatContextual("as")) {
  11289. specifier.local = this.parseIdentifier();
  11290. } else {
  11291. const {
  11292. imported
  11293. } = specifier;
  11294. if (imported.type === "StringLiteral") {
  11295. throw this.raise(specifier.start, ErrorMessages.ImportBindingIsString, imported.value);
  11296. }
  11297. this.checkReservedWord(imported.name, specifier.start, true, true);
  11298. specifier.local = imported.__clone();
  11299. }
  11300. this.checkLVal(specifier.local, "import specifier", BIND_LEXICAL);
  11301. node.specifiers.push(this.finishNode(specifier, "ImportSpecifier"));
  11302. }
  11303. }
  11304. class Parser extends StatementParser {
  11305. constructor(options, input) {
  11306. options = getOptions(options);
  11307. super(options, input);
  11308. this.options = options;
  11309. this.initializeScopes();
  11310. this.plugins = pluginsMap(this.options.plugins);
  11311. this.filename = options.sourceFilename;
  11312. }
  11313. getScopeHandler() {
  11314. return ScopeHandler;
  11315. }
  11316. parse() {
  11317. this.enterInitialScopes();
  11318. const file = this.startNode();
  11319. const program = this.startNode();
  11320. this.nextToken();
  11321. file.errors = null;
  11322. this.parseTopLevel(file, program);
  11323. file.errors = this.state.errors;
  11324. return file;
  11325. }
  11326. }
  11327. function pluginsMap(plugins) {
  11328. const pluginMap = new Map();
  11329. for (const plugin of plugins) {
  11330. const [name, options] = Array.isArray(plugin) ? plugin : [plugin, {}];
  11331. if (!pluginMap.has(name)) pluginMap.set(name, options || {});
  11332. }
  11333. return pluginMap;
  11334. }
  11335. function parse(input, options) {
  11336. var _options;
  11337. if (((_options = options) == null ? void 0 : _options.sourceType) === "unambiguous") {
  11338. options = Object.assign({}, options);
  11339. try {
  11340. options.sourceType = "module";
  11341. const parser = getParser(options, input);
  11342. const ast = parser.parse();
  11343. if (parser.sawUnambiguousESM) {
  11344. return ast;
  11345. }
  11346. if (parser.ambiguousScriptDifferentAst) {
  11347. try {
  11348. options.sourceType = "script";
  11349. return getParser(options, input).parse();
  11350. } catch (_unused) {}
  11351. } else {
  11352. ast.program.sourceType = "script";
  11353. }
  11354. return ast;
  11355. } catch (moduleError) {
  11356. try {
  11357. options.sourceType = "script";
  11358. return getParser(options, input).parse();
  11359. } catch (_unused2) {}
  11360. throw moduleError;
  11361. }
  11362. } else {
  11363. return getParser(options, input).parse();
  11364. }
  11365. }
  11366. function parseExpression(input, options) {
  11367. const parser = getParser(options, input);
  11368. if (parser.options.strictMode) {
  11369. parser.state.strict = true;
  11370. }
  11371. return parser.getExpression();
  11372. }
  11373. function getParser(options, input) {
  11374. let cls = Parser;
  11375. if (options != null && options.plugins) {
  11376. validatePlugins(options.plugins);
  11377. cls = getParserClass(options.plugins);
  11378. }
  11379. return new cls(options, input);
  11380. }
  11381. const parserClassCache = {};
  11382. function getParserClass(pluginsFromOptions) {
  11383. const pluginList = mixinPluginNames.filter(name => hasPlugin(pluginsFromOptions, name));
  11384. const key = pluginList.join("/");
  11385. let cls = parserClassCache[key];
  11386. if (!cls) {
  11387. cls = Parser;
  11388. for (const plugin of pluginList) {
  11389. cls = mixinPlugins[plugin](cls);
  11390. }
  11391. parserClassCache[key] = cls;
  11392. }
  11393. return cls;
  11394. }
  11395. exports.parse = parse;
  11396. exports.parseExpression = parseExpression;
  11397. exports.tokTypes = types;
  11398. //# sourceMappingURL=index.js.map